Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1114, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MipsISelLowering.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/lib/Target/Mips -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/lib/Target/Mips -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/lib/Target/Mips -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c=. -ferror-limit 19 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-07-26-235520-9401-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp

1//===- MipsISelLowering.cpp - Mips 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 defines the interfaces that Mips uses to lower LLVM code into a
10// selection DAG.
11//
12//===----------------------------------------------------------------------===//
13
14#include "MipsISelLowering.h"
15#include "MCTargetDesc/MipsBaseInfo.h"
16#include "MCTargetDesc/MipsInstPrinter.h"
17#include "MCTargetDesc/MipsMCTargetDesc.h"
18#include "MipsCCState.h"
19#include "MipsInstrInfo.h"
20#include "MipsMachineFunction.h"
21#include "MipsRegisterInfo.h"
22#include "MipsSubtarget.h"
23#include "MipsTargetMachine.h"
24#include "MipsTargetObjectFile.h"
25#include "llvm/ADT/APFloat.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/ADT/StringRef.h"
30#include "llvm/ADT/StringSwitch.h"
31#include "llvm/CodeGen/CallingConvLower.h"
32#include "llvm/CodeGen/FunctionLoweringInfo.h"
33#include "llvm/CodeGen/ISDOpcodes.h"
34#include "llvm/CodeGen/MachineBasicBlock.h"
35#include "llvm/CodeGen/MachineFrameInfo.h"
36#include "llvm/CodeGen/MachineFunction.h"
37#include "llvm/CodeGen/MachineInstr.h"
38#include "llvm/CodeGen/MachineInstrBuilder.h"
39#include "llvm/CodeGen/MachineJumpTableInfo.h"
40#include "llvm/CodeGen/MachineMemOperand.h"
41#include "llvm/CodeGen/MachineOperand.h"
42#include "llvm/CodeGen/MachineRegisterInfo.h"
43#include "llvm/CodeGen/RuntimeLibcalls.h"
44#include "llvm/CodeGen/SelectionDAG.h"
45#include "llvm/CodeGen/SelectionDAGNodes.h"
46#include "llvm/CodeGen/TargetFrameLowering.h"
47#include "llvm/CodeGen/TargetInstrInfo.h"
48#include "llvm/CodeGen/TargetRegisterInfo.h"
49#include "llvm/CodeGen/ValueTypes.h"
50#include "llvm/IR/CallingConv.h"
51#include "llvm/IR/Constants.h"
52#include "llvm/IR/DataLayout.h"
53#include "llvm/IR/DebugLoc.h"
54#include "llvm/IR/DerivedTypes.h"
55#include "llvm/IR/Function.h"
56#include "llvm/IR/GlobalValue.h"
57#include "llvm/IR/Type.h"
58#include "llvm/IR/Value.h"
59#include "llvm/MC/MCContext.h"
60#include "llvm/MC/MCRegisterInfo.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/CodeGen.h"
63#include "llvm/Support/CommandLine.h"
64#include "llvm/Support/Compiler.h"
65#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MachineValueType.h"
67#include "llvm/Support/MathExtras.h"
68#include "llvm/Target/TargetMachine.h"
69#include "llvm/Target/TargetOptions.h"
70#include <algorithm>
71#include <cassert>
72#include <cctype>
73#include <cstdint>
74#include <deque>
75#include <iterator>
76#include <utility>
77#include <vector>
78
79using namespace llvm;
80
81#define DEBUG_TYPE"mips-lower" "mips-lower"
82
83STATISTIC(NumTailCalls, "Number of tail calls")static llvm::Statistic NumTailCalls = {"mips-lower", "NumTailCalls"
, "Number of tail calls"}
;
84
85static cl::opt<bool>
86NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
87 cl::desc("MIPS: Don't trap on integer division by zero."),
88 cl::init(false));
89
90extern cl::opt<bool> EmitJalrReloc;
91
92static const MCPhysReg Mips64DPRegs[8] = {
93 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
94 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
95};
96
97// If I is a shifted mask, set the size (Size) and the first bit of the
98// mask (Pos), and return true.
99// For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
100static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
101 if (!isShiftedMask_64(I))
102 return false;
103
104 Size = countPopulation(I);
105 Pos = countTrailingZeros(I);
106 return true;
107}
108
109// The MIPS MSA ABI passes vector arguments in the integer register set.
110// The number of integer registers used is dependant on the ABI used.
111MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
112 CallingConv::ID CC,
113 EVT VT) const {
114 if (!VT.isVector())
115 return getRegisterType(Context, VT);
116
117 return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32
118 : MVT::i64;
119}
120
121unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
122 CallingConv::ID CC,
123 EVT VT) const {
124 if (VT.isVector())
125 return divideCeil(VT.getSizeInBits(), Subtarget.isABI_O32() ? 32 : 64);
126 return MipsTargetLowering::getNumRegisters(Context, VT);
127}
128
129unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv(
130 LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
131 unsigned &NumIntermediates, MVT &RegisterVT) const {
132 // Break down vector types to either 2 i64s or 4 i32s.
133 RegisterVT = getRegisterTypeForCallingConv(Context, CC, VT);
134 IntermediateVT = RegisterVT;
135 NumIntermediates =
136 VT.getFixedSizeInBits() < RegisterVT.getFixedSizeInBits()
137 ? VT.getVectorNumElements()
138 : divideCeil(VT.getSizeInBits(), RegisterVT.getSizeInBits());
139 return NumIntermediates;
140}
141
142SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
143 MachineFunction &MF = DAG.getMachineFunction();
144 MipsFunctionInfo *FI = MF.getInfo<MipsFunctionInfo>();
145 return DAG.getRegister(FI->getGlobalBaseReg(MF), Ty);
146}
147
148SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
149 SelectionDAG &DAG,
150 unsigned Flag) const {
151 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
152}
153
154SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
155 SelectionDAG &DAG,
156 unsigned Flag) const {
157 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
158}
159
160SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
161 SelectionDAG &DAG,
162 unsigned Flag) const {
163 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
164}
165
166SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
167 SelectionDAG &DAG,
168 unsigned Flag) const {
169 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
170}
171
172SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
173 SelectionDAG &DAG,
174 unsigned Flag) const {
175 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
176 N->getOffset(), Flag);
177}
178
179const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
180 switch ((MipsISD::NodeType)Opcode) {
181 case MipsISD::FIRST_NUMBER: break;
182 case MipsISD::JmpLink: return "MipsISD::JmpLink";
183 case MipsISD::TailCall: return "MipsISD::TailCall";
184 case MipsISD::Highest: return "MipsISD::Highest";
185 case MipsISD::Higher: return "MipsISD::Higher";
186 case MipsISD::Hi: return "MipsISD::Hi";
187 case MipsISD::Lo: return "MipsISD::Lo";
188 case MipsISD::GotHi: return "MipsISD::GotHi";
189 case MipsISD::TlsHi: return "MipsISD::TlsHi";
190 case MipsISD::GPRel: return "MipsISD::GPRel";
191 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
192 case MipsISD::Ret: return "MipsISD::Ret";
193 case MipsISD::ERet: return "MipsISD::ERet";
194 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
195 case MipsISD::FMS: return "MipsISD::FMS";
196 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
197 case MipsISD::FPCmp: return "MipsISD::FPCmp";
198 case MipsISD::FSELECT: return "MipsISD::FSELECT";
199 case MipsISD::MTC1_D64: return "MipsISD::MTC1_D64";
200 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
201 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
202 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
203 case MipsISD::MFHI: return "MipsISD::MFHI";
204 case MipsISD::MFLO: return "MipsISD::MFLO";
205 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
206 case MipsISD::Mult: return "MipsISD::Mult";
207 case MipsISD::Multu: return "MipsISD::Multu";
208 case MipsISD::MAdd: return "MipsISD::MAdd";
209 case MipsISD::MAddu: return "MipsISD::MAddu";
210 case MipsISD::MSub: return "MipsISD::MSub";
211 case MipsISD::MSubu: return "MipsISD::MSubu";
212 case MipsISD::DivRem: return "MipsISD::DivRem";
213 case MipsISD::DivRemU: return "MipsISD::DivRemU";
214 case MipsISD::DivRem16: return "MipsISD::DivRem16";
215 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
216 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
217 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
218 case MipsISD::Wrapper: return "MipsISD::Wrapper";
219 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
220 case MipsISD::Sync: return "MipsISD::Sync";
221 case MipsISD::Ext: return "MipsISD::Ext";
222 case MipsISD::Ins: return "MipsISD::Ins";
223 case MipsISD::CIns: return "MipsISD::CIns";
224 case MipsISD::LWL: return "MipsISD::LWL";
225 case MipsISD::LWR: return "MipsISD::LWR";
226 case MipsISD::SWL: return "MipsISD::SWL";
227 case MipsISD::SWR: return "MipsISD::SWR";
228 case MipsISD::LDL: return "MipsISD::LDL";
229 case MipsISD::LDR: return "MipsISD::LDR";
230 case MipsISD::SDL: return "MipsISD::SDL";
231 case MipsISD::SDR: return "MipsISD::SDR";
232 case MipsISD::EXTP: return "MipsISD::EXTP";
233 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
234 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
235 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
236 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
237 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
238 case MipsISD::SHILO: return "MipsISD::SHILO";
239 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
240 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
241 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
242 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
243 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
244 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
245 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
246 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
247 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
248 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
249 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
250 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
251 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
252 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
253 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
254 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
255 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
256 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
257 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
258 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
259 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
260 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
261 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
262 case MipsISD::MULT: return "MipsISD::MULT";
263 case MipsISD::MULTU: return "MipsISD::MULTU";
264 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
265 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
266 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
267 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
268 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
269 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
270 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
271 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
272 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
273 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
274 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
275 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
276 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
277 case MipsISD::VCEQ: return "MipsISD::VCEQ";
278 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
279 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
280 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
281 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
282 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
283 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
284 case MipsISD::VNOR: return "MipsISD::VNOR";
285 case MipsISD::VSHF: return "MipsISD::VSHF";
286 case MipsISD::SHF: return "MipsISD::SHF";
287 case MipsISD::ILVEV: return "MipsISD::ILVEV";
288 case MipsISD::ILVOD: return "MipsISD::ILVOD";
289 case MipsISD::ILVL: return "MipsISD::ILVL";
290 case MipsISD::ILVR: return "MipsISD::ILVR";
291 case MipsISD::PCKEV: return "MipsISD::PCKEV";
292 case MipsISD::PCKOD: return "MipsISD::PCKOD";
293 case MipsISD::INSVE: return "MipsISD::INSVE";
294 }
295 return nullptr;
296}
297
298MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
299 const MipsSubtarget &STI)
300 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
301 // Mips does not have i1 type, so use i32 for
302 // setcc operations results (slt, sgt, ...).
303 setBooleanContents(ZeroOrOneBooleanContent);
304 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
305 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
306 // does. Integer booleans still use 0 and 1.
307 if (Subtarget.hasMips32r6())
308 setBooleanContents(ZeroOrOneBooleanContent,
309 ZeroOrNegativeOneBooleanContent);
310
311 // Load extented operations for i1 types must be promoted
312 for (MVT VT : MVT::integer_valuetypes()) {
313 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
314 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
315 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
316 }
317
318 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
319 // for f32, f16
320 for (MVT VT : MVT::fp_valuetypes()) {
321 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
322 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
323 }
324
325 // Set LoadExtAction for f16 vectors to Expand
326 for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
327 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
328 if (F16VT.isValid())
329 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
330 }
331
332 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
333 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
334
335 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
336
337 // Used by legalize types to correctly generate the setcc result.
338 // Without this, every float setcc comes with a AND/OR with the result,
339 // we don't want this, since the fpcmp result goes to a flag register,
340 // which is used implicitly by brcond and select operations.
341 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
342
343 // Mips Custom Operations
344 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
345 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
346 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
347 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
348 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
349 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
350 setOperationAction(ISD::SELECT, MVT::f32, Custom);
351 setOperationAction(ISD::SELECT, MVT::f64, Custom);
352 setOperationAction(ISD::SELECT, MVT::i32, Custom);
353 setOperationAction(ISD::SETCC, MVT::f32, Custom);
354 setOperationAction(ISD::SETCC, MVT::f64, Custom);
355 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
356 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
357 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
358 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
359
360 if (!(TM.Options.NoNaNsFPMath || Subtarget.inAbs2008Mode())) {
361 setOperationAction(ISD::FABS, MVT::f32, Custom);
362 setOperationAction(ISD::FABS, MVT::f64, Custom);
363 }
364
365 if (Subtarget.isGP64bit()) {
366 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
367 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
368 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
369 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
370 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
371 setOperationAction(ISD::SELECT, MVT::i64, Custom);
372 setOperationAction(ISD::LOAD, MVT::i64, Custom);
373 setOperationAction(ISD::STORE, MVT::i64, Custom);
374 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
375 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
376 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
377 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
378 }
379
380 if (!Subtarget.isGP64bit()) {
381 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
382 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
383 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
384 }
385
386 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
387 if (Subtarget.isGP64bit())
388 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
389
390 setOperationAction(ISD::SDIV, MVT::i32, Expand);
391 setOperationAction(ISD::SREM, MVT::i32, Expand);
392 setOperationAction(ISD::UDIV, MVT::i32, Expand);
393 setOperationAction(ISD::UREM, MVT::i32, Expand);
394 setOperationAction(ISD::SDIV, MVT::i64, Expand);
395 setOperationAction(ISD::SREM, MVT::i64, Expand);
396 setOperationAction(ISD::UDIV, MVT::i64, Expand);
397 setOperationAction(ISD::UREM, MVT::i64, Expand);
398
399 // Operations not directly supported by Mips.
400 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
401 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
402 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
403 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
404 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
405 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
406 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
407 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
408 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
409 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
410 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
411 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
412 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
413 if (Subtarget.hasCnMips()) {
414 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
415 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
416 } else {
417 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
418 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
419 }
420 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
421 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
422 setOperationAction(ISD::ROTL, MVT::i32, Expand);
423 setOperationAction(ISD::ROTL, MVT::i64, Expand);
424 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
425 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
426
427 if (!Subtarget.hasMips32r2())
428 setOperationAction(ISD::ROTR, MVT::i32, Expand);
429
430 if (!Subtarget.hasMips64r2())
431 setOperationAction(ISD::ROTR, MVT::i64, Expand);
432
433 setOperationAction(ISD::FSIN, MVT::f32, Expand);
434 setOperationAction(ISD::FSIN, MVT::f64, Expand);
435 setOperationAction(ISD::FCOS, MVT::f32, Expand);
436 setOperationAction(ISD::FCOS, MVT::f64, Expand);
437 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
438 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
439 setOperationAction(ISD::FPOW, MVT::f32, Expand);
440 setOperationAction(ISD::FPOW, MVT::f64, Expand);
441 setOperationAction(ISD::FLOG, MVT::f32, Expand);
442 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
443 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
444 setOperationAction(ISD::FEXP, MVT::f32, Expand);
445 setOperationAction(ISD::FMA, MVT::f32, Expand);
446 setOperationAction(ISD::FMA, MVT::f64, Expand);
447 setOperationAction(ISD::FREM, MVT::f32, Expand);
448 setOperationAction(ISD::FREM, MVT::f64, Expand);
449
450 // Lower f16 conversion operations into library calls
451 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
452 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
453 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
454 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
455
456 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
457
458 setOperationAction(ISD::VASTART, MVT::Other, Custom);
459 setOperationAction(ISD::VAARG, MVT::Other, Custom);
460 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
461 setOperationAction(ISD::VAEND, MVT::Other, Expand);
462
463 // Use the default for now
464 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
465 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
466
467 if (!Subtarget.isGP64bit()) {
468 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
469 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
470 }
471
472 if (!Subtarget.hasMips32r2()) {
473 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
474 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
475 }
476
477 // MIPS16 lacks MIPS32's clz and clo instructions.
478 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
479 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
480 if (!Subtarget.hasMips64())
481 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
482
483 if (!Subtarget.hasMips32r2())
484 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
485 if (!Subtarget.hasMips64r2())
486 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
487
488 if (Subtarget.isGP64bit()) {
489 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
490 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
491 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
492 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
493 }
494
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496
497 setTargetDAGCombine(ISD::SDIVREM);
498 setTargetDAGCombine(ISD::UDIVREM);
499 setTargetDAGCombine(ISD::SELECT);
500 setTargetDAGCombine(ISD::AND);
501 setTargetDAGCombine(ISD::OR);
502 setTargetDAGCombine(ISD::ADD);
503 setTargetDAGCombine(ISD::SUB);
504 setTargetDAGCombine(ISD::AssertZext);
505 setTargetDAGCombine(ISD::SHL);
506
507 if (ABI.IsO32()) {
508 // These libcalls are not available in 32-bit.
509 setLibcallName(RTLIB::SHL_I128, nullptr);
510 setLibcallName(RTLIB::SRL_I128, nullptr);
511 setLibcallName(RTLIB::SRA_I128, nullptr);
512 }
513
514 setMinFunctionAlignment(Subtarget.isGP64bit() ? Align(8) : Align(4));
515
516 // The arguments on the stack are defined in terms of 4-byte slots on O32
517 // and 8-byte slots on N32/N64.
518 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? Align(8)
519 : Align(4));
520
521 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
522
523 MaxStoresPerMemcpy = 16;
524
525 isMicroMips = Subtarget.inMicroMipsMode();
526}
527
528const MipsTargetLowering *
529MipsTargetLowering::create(const MipsTargetMachine &TM,
530 const MipsSubtarget &STI) {
531 if (STI.inMips16Mode())
532 return createMips16TargetLowering(TM, STI);
533
534 return createMipsSETargetLowering(TM, STI);
535}
536
537// Create a fast isel object.
538FastISel *
539MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
540 const TargetLibraryInfo *libInfo) const {
541 const MipsTargetMachine &TM =
542 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
543
544 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
545 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
546 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
547 !Subtarget.inMicroMipsMode();
548
549 // Disable if either of the following is true:
550 // We do not generate PIC, the ABI is not O32, XGOT is being used.
551 if (!TM.isPositionIndependent() || !TM.getABI().IsO32() ||
552 Subtarget.useXGOT())
553 UseFastISel = false;
554
555 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
556}
557
558EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
559 EVT VT) const {
560 if (!VT.isVector())
561 return MVT::i32;
562 return VT.changeVectorElementTypeToInteger();
563}
564
565static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
566 TargetLowering::DAGCombinerInfo &DCI,
567 const MipsSubtarget &Subtarget) {
568 if (DCI.isBeforeLegalizeOps())
569 return SDValue();
570
571 EVT Ty = N->getValueType(0);
572 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
573 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
574 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
575 MipsISD::DivRemU16;
576 SDLoc DL(N);
577
578 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
579 N->getOperand(0), N->getOperand(1));
580 SDValue InChain = DAG.getEntryNode();
581 SDValue InGlue = DivRem;
582
583 // insert MFLO
584 if (N->hasAnyUseOfValue(0)) {
585 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
586 InGlue);
587 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
588 InChain = CopyFromLo.getValue(1);
589 InGlue = CopyFromLo.getValue(2);
590 }
591
592 // insert MFHI
593 if (N->hasAnyUseOfValue(1)) {
594 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
595 HI, Ty, InGlue);
596 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
597 }
598
599 return SDValue();
600}
601
602static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
603 switch (CC) {
604 default: llvm_unreachable("Unknown fp condition code!")::llvm::llvm_unreachable_internal("Unknown fp condition code!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 604)
;
605 case ISD::SETEQ:
606 case ISD::SETOEQ: return Mips::FCOND_OEQ;
607 case ISD::SETUNE: return Mips::FCOND_UNE;
608 case ISD::SETLT:
609 case ISD::SETOLT: return Mips::FCOND_OLT;
610 case ISD::SETGT:
611 case ISD::SETOGT: return Mips::FCOND_OGT;
612 case ISD::SETLE:
613 case ISD::SETOLE: return Mips::FCOND_OLE;
614 case ISD::SETGE:
615 case ISD::SETOGE: return Mips::FCOND_OGE;
616 case ISD::SETULT: return Mips::FCOND_ULT;
617 case ISD::SETULE: return Mips::FCOND_ULE;
618 case ISD::SETUGT: return Mips::FCOND_UGT;
619 case ISD::SETUGE: return Mips::FCOND_UGE;
620 case ISD::SETUO: return Mips::FCOND_UN;
621 case ISD::SETO: return Mips::FCOND_OR;
622 case ISD::SETNE:
623 case ISD::SETONE: return Mips::FCOND_ONE;
624 case ISD::SETUEQ: return Mips::FCOND_UEQ;
625 }
626}
627
628/// This function returns true if the floating point conditional branches and
629/// conditional moves which use condition code CC should be inverted.
630static bool invertFPCondCodeUser(Mips::CondCode CC) {
631 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
632 return false;
633
634 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&(static_cast <bool> ((CC >= Mips::FCOND_T &&
CC <= Mips::FCOND_GT) && "Illegal Condition Code"
) ? void (0) : __assert_fail ("(CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) && \"Illegal Condition Code\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 635, __extension__ __PRETTY_FUNCTION__))
635 "Illegal Condition Code")(static_cast <bool> ((CC >= Mips::FCOND_T &&
CC <= Mips::FCOND_GT) && "Illegal Condition Code"
) ? void (0) : __assert_fail ("(CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) && \"Illegal Condition Code\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 635, __extension__ __PRETTY_FUNCTION__))
;
636
637 return true;
638}
639
640// Creates and returns an FPCmp node from a setcc node.
641// Returns Op if setcc is not a floating point comparison.
642static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
643 // must be a SETCC node
644 if (Op.getOpcode() != ISD::SETCC)
645 return Op;
646
647 SDValue LHS = Op.getOperand(0);
648
649 if (!LHS.getValueType().isFloatingPoint())
650 return Op;
651
652 SDValue RHS = Op.getOperand(1);
653 SDLoc DL(Op);
654
655 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
656 // node if necessary.
657 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
658
659 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
660 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
661}
662
663// Creates and returns a CMovFPT/F node.
664static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
665 SDValue False, const SDLoc &DL) {
666 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
667 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
668 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
669
670 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
671 True.getValueType(), True, FCC0, False, Cond);
672}
673
674static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
675 TargetLowering::DAGCombinerInfo &DCI,
676 const MipsSubtarget &Subtarget) {
677 if (DCI.isBeforeLegalizeOps())
678 return SDValue();
679
680 SDValue SetCC = N->getOperand(0);
681
682 if ((SetCC.getOpcode() != ISD::SETCC) ||
683 !SetCC.getOperand(0).getValueType().isInteger())
684 return SDValue();
685
686 SDValue False = N->getOperand(2);
687 EVT FalseTy = False.getValueType();
688
689 if (!FalseTy.isInteger())
690 return SDValue();
691
692 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
693
694 // If the RHS (False) is 0, we swap the order of the operands
695 // of ISD::SELECT (obviously also inverting the condition) so that we can
696 // take advantage of conditional moves using the $0 register.
697 // Example:
698 // return (a != 0) ? x : 0;
699 // load $reg, x
700 // movz $reg, $0, a
701 if (!FalseC)
702 return SDValue();
703
704 const SDLoc DL(N);
705
706 if (!FalseC->getZExtValue()) {
707 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
708 SDValue True = N->getOperand(1);
709
710 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
711 SetCC.getOperand(1),
712 ISD::getSetCCInverse(CC, SetCC.getValueType()));
713
714 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
715 }
716
717 // If both operands are integer constants there's a possibility that we
718 // can do some interesting optimizations.
719 SDValue True = N->getOperand(1);
720 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
721
722 if (!TrueC || !True.getValueType().isInteger())
723 return SDValue();
724
725 // We'll also ignore MVT::i64 operands as this optimizations proves
726 // to be ineffective because of the required sign extensions as the result
727 // of a SETCC operator is always MVT::i32 for non-vector types.
728 if (True.getValueType() == MVT::i64)
729 return SDValue();
730
731 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
732
733 // 1) (a < x) ? y : y-1
734 // slti $reg1, a, x
735 // addiu $reg2, $reg1, y-1
736 if (Diff == 1)
737 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
738
739 // 2) (a < x) ? y-1 : y
740 // slti $reg1, a, x
741 // xor $reg1, $reg1, 1
742 // addiu $reg2, $reg1, y-1
743 if (Diff == -1) {
744 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
745 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
746 SetCC.getOperand(1),
747 ISD::getSetCCInverse(CC, SetCC.getValueType()));
748 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
749 }
750
751 // Could not optimize.
752 return SDValue();
753}
754
755static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
756 TargetLowering::DAGCombinerInfo &DCI,
757 const MipsSubtarget &Subtarget) {
758 if (DCI.isBeforeLegalizeOps())
759 return SDValue();
760
761 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
762
763 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
764 if (!FalseC || FalseC->getZExtValue())
765 return SDValue();
766
767 // Since RHS (False) is 0, we swap the order of the True/False operands
768 // (obviously also inverting the condition) so that we can
769 // take advantage of conditional moves using the $0 register.
770 // Example:
771 // return (a != 0) ? x : 0;
772 // load $reg, x
773 // movz $reg, $0, a
774 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
775 MipsISD::CMovFP_T;
776
777 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
778 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
779 ValueIfFalse, FCC, ValueIfTrue, Glue);
780}
781
782static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
783 TargetLowering::DAGCombinerInfo &DCI,
784 const MipsSubtarget &Subtarget) {
785 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
786 return SDValue();
787
788 SDValue FirstOperand = N->getOperand(0);
789 unsigned FirstOperandOpc = FirstOperand.getOpcode();
790 SDValue Mask = N->getOperand(1);
791 EVT ValTy = N->getValueType(0);
792 SDLoc DL(N);
793
794 uint64_t Pos = 0, SMPos, SMSize;
795 ConstantSDNode *CN;
796 SDValue NewOperand;
797 unsigned Opc;
798
799 // Op's second operand must be a shifted mask.
800 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
801 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
802 return SDValue();
803
804 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
805 // Pattern match EXT.
806 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
807 // => ext $dst, $src, pos, size
808
809 // The second operand of the shift must be an immediate.
810 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
811 return SDValue();
812
813 Pos = CN->getZExtValue();
814
815 // Return if the shifted mask does not start at bit 0 or the sum of its size
816 // and Pos exceeds the word's size.
817 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
818 return SDValue();
819
820 Opc = MipsISD::Ext;
821 NewOperand = FirstOperand.getOperand(0);
822 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
823 // Pattern match CINS.
824 // $dst = and (shl $src , pos), mask
825 // => cins $dst, $src, pos, size
826 // mask is a shifted mask with consecutive 1's, pos = shift amount,
827 // size = population count.
828
829 // The second operand of the shift must be an immediate.
830 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
831 return SDValue();
832
833 Pos = CN->getZExtValue();
834
835 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
836 Pos + SMSize > ValTy.getSizeInBits())
837 return SDValue();
838
839 NewOperand = FirstOperand.getOperand(0);
840 // SMSize is 'location' (position) in this case, not size.
841 SMSize--;
842 Opc = MipsISD::CIns;
843 } else {
844 // Pattern match EXT.
845 // $dst = and $src, (2**size - 1) , if size > 16
846 // => ext $dst, $src, pos, size , pos = 0
847
848 // If the mask is <= 0xffff, andi can be used instead.
849 if (CN->getZExtValue() <= 0xffff)
850 return SDValue();
851
852 // Return if the mask doesn't start at position 0.
853 if (SMPos)
854 return SDValue();
855
856 Opc = MipsISD::Ext;
857 NewOperand = FirstOperand;
858 }
859 return DAG.getNode(Opc, DL, ValTy, NewOperand,
860 DAG.getConstant(Pos, DL, MVT::i32),
861 DAG.getConstant(SMSize, DL, MVT::i32));
862}
863
864static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
865 TargetLowering::DAGCombinerInfo &DCI,
866 const MipsSubtarget &Subtarget) {
867 // Pattern match INS.
868 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
869 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
870 // => ins $dst, $src, size, pos, $src1
871 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
872 return SDValue();
873
874 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
875 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
876 ConstantSDNode *CN, *CN1;
877
878 // See if Op's first operand matches (and $src1 , mask0).
879 if (And0.getOpcode() != ISD::AND)
880 return SDValue();
881
882 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
883 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
884 return SDValue();
885
886 // See if Op's second operand matches (and (shl $src, pos), mask1).
887 if (And1.getOpcode() == ISD::AND &&
888 And1.getOperand(0).getOpcode() == ISD::SHL) {
889
890 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
891 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
892 return SDValue();
893
894 // The shift masks must have the same position and size.
895 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
896 return SDValue();
897
898 SDValue Shl = And1.getOperand(0);
899
900 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
901 return SDValue();
902
903 unsigned Shamt = CN->getZExtValue();
904
905 // Return if the shift amount and the first bit position of mask are not the
906 // same.
907 EVT ValTy = N->getValueType(0);
908 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
909 return SDValue();
910
911 SDLoc DL(N);
912 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
913 DAG.getConstant(SMPos0, DL, MVT::i32),
914 DAG.getConstant(SMSize0, DL, MVT::i32),
915 And0.getOperand(0));
916 } else {
917 // Pattern match DINS.
918 // $dst = or (and $src, mask0), mask1
919 // where mask0 = ((1 << SMSize0) -1) << SMPos0
920 // => dins $dst, $src, pos, size
921 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
922 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
923 (SMSize0 + SMPos0 <= 32))) {
924 // Check if AND instruction has constant as argument
925 bool isConstCase = And1.getOpcode() != ISD::AND;
926 if (And1.getOpcode() == ISD::AND) {
927 if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
928 return SDValue();
929 } else {
930 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
931 return SDValue();
932 }
933 // Don't generate INS if constant OR operand doesn't fit into bits
934 // cleared by constant AND operand.
935 if (CN->getSExtValue() & CN1->getSExtValue())
936 return SDValue();
937
938 SDLoc DL(N);
939 EVT ValTy = N->getOperand(0)->getValueType(0);
940 SDValue Const1;
941 SDValue SrlX;
942 if (!isConstCase) {
943 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
944 SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
945 }
946 return DAG.getNode(
947 MipsISD::Ins, DL, N->getValueType(0),
948 isConstCase
949 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
950 : SrlX,
951 DAG.getConstant(SMPos0, DL, MVT::i32),
952 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
953 : SMSize0,
954 DL, MVT::i32),
955 And0->getOperand(0));
956
957 }
958 return SDValue();
959 }
960}
961
962static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG,
963 const MipsSubtarget &Subtarget) {
964 // ROOTNode must have a multiplication as an operand for the match to be
965 // successful.
966 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
967 ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
968 return SDValue();
969
970 // We don't handle vector types here.
971 if (ROOTNode->getValueType(0).isVector())
972 return SDValue();
973
974 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
975 // arithmetic. E.g.
976 // (add (mul a b) c) =>
977 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
978 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
979 // or
980 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
981 //
982 // The overhead of setting up the Hi/Lo registers and reassembling the
983 // result makes this a dubious optimzation for MIPS64. The core of the
984 // problem is that Hi/Lo contain the upper and lower 32 bits of the
985 // operand and result.
986 //
987 // It requires a chain of 4 add/mul for MIPS64R2 to get better code
988 // density than doing it naively, 5 for MIPS64. Additionally, using
989 // madd/msub on MIPS64 requires the operands actually be 32 bit sign
990 // extended operands, not true 64 bit values.
991 //
992 // FIXME: For the moment, disable this completely for MIPS64.
993 if (Subtarget.hasMips64())
994 return SDValue();
995
996 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
997 ? ROOTNode->getOperand(0)
998 : ROOTNode->getOperand(1);
999
1000 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
1001 ? ROOTNode->getOperand(1)
1002 : ROOTNode->getOperand(0);
1003
1004 // Transform this to a MADD only if the user of this node is the add.
1005 // If there are other users of the mul, this function returns here.
1006 if (!Mult.hasOneUse())
1007 return SDValue();
1008
1009 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
1010 // must be in canonical form, i.e. sign extended. For MIPS32, the operands
1011 // of the multiply must have 32 or more sign bits, otherwise we cannot
1012 // perform this optimization. We have to check this here as we're performing
1013 // this optimization pre-legalization.
1014 SDValue MultLHS = Mult->getOperand(0);
1015 SDValue MultRHS = Mult->getOperand(1);
1016
1017 bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND &&
1018 MultRHS->getOpcode() == ISD::SIGN_EXTEND;
1019 bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND &&
1020 MultRHS->getOpcode() == ISD::ZERO_EXTEND;
1021
1022 if (!IsSigned && !IsUnsigned)
1023 return SDValue();
1024
1025 // Initialize accumulator.
1026 SDLoc DL(ROOTNode);
1027 SDValue TopHalf;
1028 SDValue BottomHalf;
1029 BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1030 CurDAG.getIntPtrConstant(0, DL));
1031
1032 TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1033 CurDAG.getIntPtrConstant(1, DL));
1034 SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
1035 BottomHalf,
1036 TopHalf);
1037
1038 // Create MipsMAdd(u) / MipsMSub(u) node.
1039 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1040 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1041 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1042 SDValue MAddOps[3] = {
1043 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1044 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1045 EVT VTs[2] = {MVT::i32, MVT::i32};
1046 SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1047
1048 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1049 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1050 SDValue Combined =
1051 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1052 return Combined;
1053}
1054
1055static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG,
1056 TargetLowering::DAGCombinerInfo &DCI,
1057 const MipsSubtarget &Subtarget) {
1058 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1059 if (DCI.isBeforeLegalizeOps()) {
1060 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1061 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1062 return performMADD_MSUBCombine(N, DAG, Subtarget);
1063
1064 return SDValue();
1065 }
1066
1067 return SDValue();
1068}
1069
1070static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
1071 TargetLowering::DAGCombinerInfo &DCI,
1072 const MipsSubtarget &Subtarget) {
1073 // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1074 if (DCI.isBeforeLegalizeOps()) {
1075 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1076 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1077 return performMADD_MSUBCombine(N, DAG, Subtarget);
1078
1079 return SDValue();
1080 }
1081
1082 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1083 SDValue Add = N->getOperand(1);
1084
1085 if (Add.getOpcode() != ISD::ADD)
1086 return SDValue();
1087
1088 SDValue Lo = Add.getOperand(1);
1089
1090 if ((Lo.getOpcode() != MipsISD::Lo) ||
1091 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1092 return SDValue();
1093
1094 EVT ValTy = N->getValueType(0);
1095 SDLoc DL(N);
1096
1097 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1098 Add.getOperand(0));
1099 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1100}
1101
1102static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
1103 TargetLowering::DAGCombinerInfo &DCI,
1104 const MipsSubtarget &Subtarget) {
1105 // Pattern match CINS.
1106 // $dst = shl (and $src , imm), pos
1107 // => cins $dst, $src, pos, size
1108
1109 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1110 return SDValue();
1111
1112 SDValue FirstOperand = N->getOperand(0);
1113 unsigned FirstOperandOpc = FirstOperand.getOpcode();
1114 SDValue SecondOperand = N->getOperand(1);
1115 EVT ValTy = N->getValueType(0);
1116 SDLoc DL(N);
1117
1118 uint64_t Pos = 0, SMPos, SMSize;
1119 ConstantSDNode *CN;
1120 SDValue NewOperand;
1121
1122 // The second operand of the shift must be an immediate.
1123 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1124 return SDValue();
1125
1126 Pos = CN->getZExtValue();
1127
1128 if (Pos >= ValTy.getSizeInBits())
1129 return SDValue();
1130
1131 if (FirstOperandOpc != ISD::AND)
1132 return SDValue();
1133
1134 // AND's second operand must be a shifted mask.
1135 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1136 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
1137 return SDValue();
1138
1139 // Return if the shifted mask does not start at bit 0 or the sum of its size
1140 // and Pos exceeds the word's size.
1141 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1142 return SDValue();
1143
1144 NewOperand = FirstOperand.getOperand(0);
1145 // SMSize is 'location' (position) in this case, not size.
1146 SMSize--;
1147
1148 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1149 DAG.getConstant(Pos, DL, MVT::i32),
1150 DAG.getConstant(SMSize, DL, MVT::i32));
1151}
1152
1153SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
1154 const {
1155 SelectionDAG &DAG = DCI.DAG;
1156 unsigned Opc = N->getOpcode();
1157
1158 switch (Opc) {
1159 default: break;
1160 case ISD::SDIVREM:
1161 case ISD::UDIVREM:
1162 return performDivRemCombine(N, DAG, DCI, Subtarget);
1163 case ISD::SELECT:
1164 return performSELECTCombine(N, DAG, DCI, Subtarget);
1165 case MipsISD::CMovFP_F:
1166 case MipsISD::CMovFP_T:
1167 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1168 case ISD::AND:
1169 return performANDCombine(N, DAG, DCI, Subtarget);
1170 case ISD::OR:
1171 return performORCombine(N, DAG, DCI, Subtarget);
1172 case ISD::ADD:
1173 return performADDCombine(N, DAG, DCI, Subtarget);
1174 case ISD::SHL:
1175 return performSHLCombine(N, DAG, DCI, Subtarget);
1176 case ISD::SUB:
1177 return performSUBCombine(N, DAG, DCI, Subtarget);
1178 }
1179
1180 return SDValue();
1181}
1182
1183bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1184 return Subtarget.hasMips32();
1185}
1186
1187bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1188 return Subtarget.hasMips32();
1189}
1190
1191bool MipsTargetLowering::shouldFoldConstantShiftPairToMask(
1192 const SDNode *N, CombineLevel Level) const {
1193 if (N->getOperand(0).getValueType().isVector())
1194 return false;
1195 return true;
1196}
1197
1198void
1199MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1200 SmallVectorImpl<SDValue> &Results,
1201 SelectionDAG &DAG) const {
1202 return LowerOperationWrapper(N, Results, DAG);
1203}
1204
1205SDValue MipsTargetLowering::
1206LowerOperation(SDValue Op, SelectionDAG &DAG) const
1207{
1208 switch (Op.getOpcode())
1209 {
1210 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1211 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1212 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1213 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1214 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1215 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1216 case ISD::SELECT: return lowerSELECT(Op, DAG);
1217 case ISD::SETCC: return lowerSETCC(Op, DAG);
1218 case ISD::VASTART: return lowerVASTART(Op, DAG);
1219 case ISD::VAARG: return lowerVAARG(Op, DAG);
1220 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1221 case ISD::FABS: return lowerFABS(Op, DAG);
1222 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1223 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1224 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1225 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1226 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1227 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1228 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1229 case ISD::LOAD: return lowerLOAD(Op, DAG);
1230 case ISD::STORE: return lowerSTORE(Op, DAG);
1231 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1232 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1233 }
1234 return SDValue();
1235}
1236
1237//===----------------------------------------------------------------------===//
1238// Lower helper functions
1239//===----------------------------------------------------------------------===//
1240
1241// addLiveIn - This helper function adds the specified physical register to the
1242// MachineFunction as a live in value. It also creates a corresponding
1243// virtual register for it.
1244static unsigned
1245addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1246{
1247 Register VReg = MF.getRegInfo().createVirtualRegister(RC);
1248 MF.getRegInfo().addLiveIn(PReg, VReg);
1249 return VReg;
1250}
1251
1252static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1253 MachineBasicBlock &MBB,
1254 const TargetInstrInfo &TII,
1255 bool Is64Bit, bool IsMicroMips) {
1256 if (NoZeroDivCheck)
1257 return &MBB;
1258
1259 // Insert instruction "teq $divisor_reg, $zero, 7".
1260 MachineBasicBlock::iterator I(MI);
1261 MachineInstrBuilder MIB;
1262 MachineOperand &Divisor = MI.getOperand(2);
1263 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1264 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1265 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1266 .addReg(Mips::ZERO)
1267 .addImm(7);
1268
1269 // Use the 32-bit sub-register if this is a 64-bit division.
1270 if (Is64Bit)
1271 MIB->getOperand(0).setSubReg(Mips::sub_32);
1272
1273 // Clear Divisor's kill flag.
1274 Divisor.setIsKill(false);
1275
1276 // We would normally delete the original instruction here but in this case
1277 // we only needed to inject an additional instruction rather than replace it.
1278
1279 return &MBB;
1280}
1281
1282MachineBasicBlock *
1283MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1284 MachineBasicBlock *BB) const {
1285 switch (MI.getOpcode()) {
1286 default:
1287 llvm_unreachable("Unexpected instr type to insert")::llvm::llvm_unreachable_internal("Unexpected instr type to insert"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1287)
;
1288 case Mips::ATOMIC_LOAD_ADD_I8:
1289 return emitAtomicBinaryPartword(MI, BB, 1);
1290 case Mips::ATOMIC_LOAD_ADD_I16:
1291 return emitAtomicBinaryPartword(MI, BB, 2);
1292 case Mips::ATOMIC_LOAD_ADD_I32:
1293 return emitAtomicBinary(MI, BB);
1294 case Mips::ATOMIC_LOAD_ADD_I64:
1295 return emitAtomicBinary(MI, BB);
1296
1297 case Mips::ATOMIC_LOAD_AND_I8:
1298 return emitAtomicBinaryPartword(MI, BB, 1);
1299 case Mips::ATOMIC_LOAD_AND_I16:
1300 return emitAtomicBinaryPartword(MI, BB, 2);
1301 case Mips::ATOMIC_LOAD_AND_I32:
1302 return emitAtomicBinary(MI, BB);
1303 case Mips::ATOMIC_LOAD_AND_I64:
1304 return emitAtomicBinary(MI, BB);
1305
1306 case Mips::ATOMIC_LOAD_OR_I8:
1307 return emitAtomicBinaryPartword(MI, BB, 1);
1308 case Mips::ATOMIC_LOAD_OR_I16:
1309 return emitAtomicBinaryPartword(MI, BB, 2);
1310 case Mips::ATOMIC_LOAD_OR_I32:
1311 return emitAtomicBinary(MI, BB);
1312 case Mips::ATOMIC_LOAD_OR_I64:
1313 return emitAtomicBinary(MI, BB);
1314
1315 case Mips::ATOMIC_LOAD_XOR_I8:
1316 return emitAtomicBinaryPartword(MI, BB, 1);
1317 case Mips::ATOMIC_LOAD_XOR_I16:
1318 return emitAtomicBinaryPartword(MI, BB, 2);
1319 case Mips::ATOMIC_LOAD_XOR_I32:
1320 return emitAtomicBinary(MI, BB);
1321 case Mips::ATOMIC_LOAD_XOR_I64:
1322 return emitAtomicBinary(MI, BB);
1323
1324 case Mips::ATOMIC_LOAD_NAND_I8:
1325 return emitAtomicBinaryPartword(MI, BB, 1);
1326 case Mips::ATOMIC_LOAD_NAND_I16:
1327 return emitAtomicBinaryPartword(MI, BB, 2);
1328 case Mips::ATOMIC_LOAD_NAND_I32:
1329 return emitAtomicBinary(MI, BB);
1330 case Mips::ATOMIC_LOAD_NAND_I64:
1331 return emitAtomicBinary(MI, BB);
1332
1333 case Mips::ATOMIC_LOAD_SUB_I8:
1334 return emitAtomicBinaryPartword(MI, BB, 1);
1335 case Mips::ATOMIC_LOAD_SUB_I16:
1336 return emitAtomicBinaryPartword(MI, BB, 2);
1337 case Mips::ATOMIC_LOAD_SUB_I32:
1338 return emitAtomicBinary(MI, BB);
1339 case Mips::ATOMIC_LOAD_SUB_I64:
1340 return emitAtomicBinary(MI, BB);
1341
1342 case Mips::ATOMIC_SWAP_I8:
1343 return emitAtomicBinaryPartword(MI, BB, 1);
1344 case Mips::ATOMIC_SWAP_I16:
1345 return emitAtomicBinaryPartword(MI, BB, 2);
1346 case Mips::ATOMIC_SWAP_I32:
1347 return emitAtomicBinary(MI, BB);
1348 case Mips::ATOMIC_SWAP_I64:
1349 return emitAtomicBinary(MI, BB);
1350
1351 case Mips::ATOMIC_CMP_SWAP_I8:
1352 return emitAtomicCmpSwapPartword(MI, BB, 1);
1353 case Mips::ATOMIC_CMP_SWAP_I16:
1354 return emitAtomicCmpSwapPartword(MI, BB, 2);
1355 case Mips::ATOMIC_CMP_SWAP_I32:
1356 return emitAtomicCmpSwap(MI, BB);
1357 case Mips::ATOMIC_CMP_SWAP_I64:
1358 return emitAtomicCmpSwap(MI, BB);
1359
1360 case Mips::ATOMIC_LOAD_MIN_I8:
1361 return emitAtomicBinaryPartword(MI, BB, 1);
1362 case Mips::ATOMIC_LOAD_MIN_I16:
1363 return emitAtomicBinaryPartword(MI, BB, 2);
1364 case Mips::ATOMIC_LOAD_MIN_I32:
1365 return emitAtomicBinary(MI, BB);
1366 case Mips::ATOMIC_LOAD_MIN_I64:
1367 return emitAtomicBinary(MI, BB);
1368
1369 case Mips::ATOMIC_LOAD_MAX_I8:
1370 return emitAtomicBinaryPartword(MI, BB, 1);
1371 case Mips::ATOMIC_LOAD_MAX_I16:
1372 return emitAtomicBinaryPartword(MI, BB, 2);
1373 case Mips::ATOMIC_LOAD_MAX_I32:
1374 return emitAtomicBinary(MI, BB);
1375 case Mips::ATOMIC_LOAD_MAX_I64:
1376 return emitAtomicBinary(MI, BB);
1377
1378 case Mips::ATOMIC_LOAD_UMIN_I8:
1379 return emitAtomicBinaryPartword(MI, BB, 1);
1380 case Mips::ATOMIC_LOAD_UMIN_I16:
1381 return emitAtomicBinaryPartword(MI, BB, 2);
1382 case Mips::ATOMIC_LOAD_UMIN_I32:
1383 return emitAtomicBinary(MI, BB);
1384 case Mips::ATOMIC_LOAD_UMIN_I64:
1385 return emitAtomicBinary(MI, BB);
1386
1387 case Mips::ATOMIC_LOAD_UMAX_I8:
1388 return emitAtomicBinaryPartword(MI, BB, 1);
1389 case Mips::ATOMIC_LOAD_UMAX_I16:
1390 return emitAtomicBinaryPartword(MI, BB, 2);
1391 case Mips::ATOMIC_LOAD_UMAX_I32:
1392 return emitAtomicBinary(MI, BB);
1393 case Mips::ATOMIC_LOAD_UMAX_I64:
1394 return emitAtomicBinary(MI, BB);
1395
1396 case Mips::PseudoSDIV:
1397 case Mips::PseudoUDIV:
1398 case Mips::DIV:
1399 case Mips::DIVU:
1400 case Mips::MOD:
1401 case Mips::MODU:
1402 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1403 false);
1404 case Mips::SDIV_MM_Pseudo:
1405 case Mips::UDIV_MM_Pseudo:
1406 case Mips::SDIV_MM:
1407 case Mips::UDIV_MM:
1408 case Mips::DIV_MMR6:
1409 case Mips::DIVU_MMR6:
1410 case Mips::MOD_MMR6:
1411 case Mips::MODU_MMR6:
1412 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1413 case Mips::PseudoDSDIV:
1414 case Mips::PseudoDUDIV:
1415 case Mips::DDIV:
1416 case Mips::DDIVU:
1417 case Mips::DMOD:
1418 case Mips::DMODU:
1419 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1420
1421 case Mips::PseudoSELECT_I:
1422 case Mips::PseudoSELECT_I64:
1423 case Mips::PseudoSELECT_S:
1424 case Mips::PseudoSELECT_D32:
1425 case Mips::PseudoSELECT_D64:
1426 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1427 case Mips::PseudoSELECTFP_F_I:
1428 case Mips::PseudoSELECTFP_F_I64:
1429 case Mips::PseudoSELECTFP_F_S:
1430 case Mips::PseudoSELECTFP_F_D32:
1431 case Mips::PseudoSELECTFP_F_D64:
1432 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1433 case Mips::PseudoSELECTFP_T_I:
1434 case Mips::PseudoSELECTFP_T_I64:
1435 case Mips::PseudoSELECTFP_T_S:
1436 case Mips::PseudoSELECTFP_T_D32:
1437 case Mips::PseudoSELECTFP_T_D64:
1438 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1439 case Mips::PseudoD_SELECT_I:
1440 case Mips::PseudoD_SELECT_I64:
1441 return emitPseudoD_SELECT(MI, BB);
1442 case Mips::LDR_W:
1443 return emitLDR_W(MI, BB);
1444 case Mips::LDR_D:
1445 return emitLDR_D(MI, BB);
1446 case Mips::STR_W:
1447 return emitSTR_W(MI, BB);
1448 case Mips::STR_D:
1449 return emitSTR_D(MI, BB);
1450 }
1451}
1452
1453// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1454// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1455MachineBasicBlock *
1456MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1457 MachineBasicBlock *BB) const {
1458
1459 MachineFunction *MF = BB->getParent();
1460 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1461 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1462 DebugLoc DL = MI.getDebugLoc();
1463
1464 unsigned AtomicOp;
1465 bool NeedsAdditionalReg = false;
1466 switch (MI.getOpcode()) {
1467 case Mips::ATOMIC_LOAD_ADD_I32:
1468 AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1469 break;
1470 case Mips::ATOMIC_LOAD_SUB_I32:
1471 AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1472 break;
1473 case Mips::ATOMIC_LOAD_AND_I32:
1474 AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1475 break;
1476 case Mips::ATOMIC_LOAD_OR_I32:
1477 AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1478 break;
1479 case Mips::ATOMIC_LOAD_XOR_I32:
1480 AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1481 break;
1482 case Mips::ATOMIC_LOAD_NAND_I32:
1483 AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1484 break;
1485 case Mips::ATOMIC_SWAP_I32:
1486 AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1487 break;
1488 case Mips::ATOMIC_LOAD_ADD_I64:
1489 AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1490 break;
1491 case Mips::ATOMIC_LOAD_SUB_I64:
1492 AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1493 break;
1494 case Mips::ATOMIC_LOAD_AND_I64:
1495 AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1496 break;
1497 case Mips::ATOMIC_LOAD_OR_I64:
1498 AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1499 break;
1500 case Mips::ATOMIC_LOAD_XOR_I64:
1501 AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1502 break;
1503 case Mips::ATOMIC_LOAD_NAND_I64:
1504 AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1505 break;
1506 case Mips::ATOMIC_SWAP_I64:
1507 AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1508 break;
1509 case Mips::ATOMIC_LOAD_MIN_I32:
1510 AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA;
1511 NeedsAdditionalReg = true;
1512 break;
1513 case Mips::ATOMIC_LOAD_MAX_I32:
1514 AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA;
1515 NeedsAdditionalReg = true;
1516 break;
1517 case Mips::ATOMIC_LOAD_UMIN_I32:
1518 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA;
1519 NeedsAdditionalReg = true;
1520 break;
1521 case Mips::ATOMIC_LOAD_UMAX_I32:
1522 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA;
1523 NeedsAdditionalReg = true;
1524 break;
1525 case Mips::ATOMIC_LOAD_MIN_I64:
1526 AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA;
1527 NeedsAdditionalReg = true;
1528 break;
1529 case Mips::ATOMIC_LOAD_MAX_I64:
1530 AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA;
1531 NeedsAdditionalReg = true;
1532 break;
1533 case Mips::ATOMIC_LOAD_UMIN_I64:
1534 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA;
1535 NeedsAdditionalReg = true;
1536 break;
1537 case Mips::ATOMIC_LOAD_UMAX_I64:
1538 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA;
1539 NeedsAdditionalReg = true;
1540 break;
1541 default:
1542 llvm_unreachable("Unknown pseudo atomic for replacement!")::llvm::llvm_unreachable_internal("Unknown pseudo atomic for replacement!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1542)
;
1543 }
1544
1545 Register OldVal = MI.getOperand(0).getReg();
1546 Register Ptr = MI.getOperand(1).getReg();
1547 Register Incr = MI.getOperand(2).getReg();
1548 Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1549
1550 MachineBasicBlock::iterator II(MI);
1551
1552 // The scratch registers here with the EarlyClobber | Define | Implicit
1553 // flags is used to persuade the register allocator and the machine
1554 // verifier to accept the usage of this register. This has to be a real
1555 // register which has an UNDEF value but is dead after the instruction which
1556 // is unique among the registers chosen for the instruction.
1557
1558 // The EarlyClobber flag has the semantic properties that the operand it is
1559 // attached to is clobbered before the rest of the inputs are read. Hence it
1560 // must be unique among the operands to the instruction.
1561 // The Define flag is needed to coerce the machine verifier that an Undef
1562 // value isn't a problem.
1563 // The Dead flag is needed as the value in scratch isn't used by any other
1564 // instruction. Kill isn't used as Dead is more precise.
1565 // The implicit flag is here due to the interaction between the other flags
1566 // and the machine verifier.
1567
1568 // For correctness purpose, a new pseudo is introduced here. We need this
1569 // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1570 // that is spread over >1 basic blocks. A register allocator which
1571 // introduces (or any codegen infact) a store, can violate the expectations
1572 // of the hardware.
1573 //
1574 // An atomic read-modify-write sequence starts with a linked load
1575 // instruction and ends with a store conditional instruction. The atomic
1576 // read-modify-write sequence fails if any of the following conditions
1577 // occur between the execution of ll and sc:
1578 // * A coherent store is completed by another process or coherent I/O
1579 // module into the block of synchronizable physical memory containing
1580 // the word. The size and alignment of the block is
1581 // implementation-dependent.
1582 // * A coherent store is executed between an LL and SC sequence on the
1583 // same processor to the block of synchornizable physical memory
1584 // containing the word.
1585 //
1586
1587 Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1588 Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1589
1590 BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1591 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1592
1593 MachineInstrBuilder MIB =
1594 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1595 .addReg(OldVal, RegState::Define | RegState::EarlyClobber)
1596 .addReg(PtrCopy)
1597 .addReg(IncrCopy)
1598 .addReg(Scratch, RegState::Define | RegState::EarlyClobber |
1599 RegState::Implicit | RegState::Dead);
1600 if (NeedsAdditionalReg) {
1601 Register Scratch2 =
1602 RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1603 MIB.addReg(Scratch2, RegState::Define | RegState::EarlyClobber |
1604 RegState::Implicit | RegState::Dead);
1605 }
1606
1607 MI.eraseFromParent();
1608
1609 return BB;
1610}
1611
1612MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1613 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1614 unsigned SrcReg) const {
1615 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1616 const DebugLoc &DL = MI.getDebugLoc();
1617
1618 if (Subtarget.hasMips32r2() && Size == 1) {
1619 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1620 return BB;
1621 }
1622
1623 if (Subtarget.hasMips32r2() && Size == 2) {
1624 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1625 return BB;
1626 }
1627
1628 MachineFunction *MF = BB->getParent();
1629 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1630 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1631 Register ScrReg = RegInfo.createVirtualRegister(RC);
1632
1633 assert(Size < 32)(static_cast <bool> (Size < 32) ? void (0) : __assert_fail
("Size < 32", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1633, __extension__ __PRETTY_FUNCTION__))
;
1634 int64_t ShiftImm = 32 - (Size * 8);
1635
1636 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1637 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1638
1639 return BB;
1640}
1641
1642MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1643 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1644 assert((Size == 1 || Size == 2) &&(static_cast <bool> ((Size == 1 || Size == 2) &&
"Unsupported size for EmitAtomicBinaryPartial.") ? void (0) :
__assert_fail ("(Size == 1 || Size == 2) && \"Unsupported size for EmitAtomicBinaryPartial.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1645, __extension__ __PRETTY_FUNCTION__))
1645 "Unsupported size for EmitAtomicBinaryPartial.")(static_cast <bool> ((Size == 1 || Size == 2) &&
"Unsupported size for EmitAtomicBinaryPartial.") ? void (0) :
__assert_fail ("(Size == 1 || Size == 2) && \"Unsupported size for EmitAtomicBinaryPartial.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1645, __extension__ __PRETTY_FUNCTION__))
;
1646
1647 MachineFunction *MF = BB->getParent();
1648 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1649 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1650 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1651 const TargetRegisterClass *RCp =
1652 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1653 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1654 DebugLoc DL = MI.getDebugLoc();
1655
1656 Register Dest = MI.getOperand(0).getReg();
1657 Register Ptr = MI.getOperand(1).getReg();
1658 Register Incr = MI.getOperand(2).getReg();
1659
1660 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1661 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1662 Register Mask = RegInfo.createVirtualRegister(RC);
1663 Register Mask2 = RegInfo.createVirtualRegister(RC);
1664 Register Incr2 = RegInfo.createVirtualRegister(RC);
1665 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1666 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1667 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1668 Register Scratch = RegInfo.createVirtualRegister(RC);
1669 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1670 Register Scratch3 = RegInfo.createVirtualRegister(RC);
1671
1672 unsigned AtomicOp = 0;
1673 bool NeedsAdditionalReg = false;
1674 switch (MI.getOpcode()) {
1675 case Mips::ATOMIC_LOAD_NAND_I8:
1676 AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1677 break;
1678 case Mips::ATOMIC_LOAD_NAND_I16:
1679 AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1680 break;
1681 case Mips::ATOMIC_SWAP_I8:
1682 AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1683 break;
1684 case Mips::ATOMIC_SWAP_I16:
1685 AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1686 break;
1687 case Mips::ATOMIC_LOAD_ADD_I8:
1688 AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1689 break;
1690 case Mips::ATOMIC_LOAD_ADD_I16:
1691 AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1692 break;
1693 case Mips::ATOMIC_LOAD_SUB_I8:
1694 AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1695 break;
1696 case Mips::ATOMIC_LOAD_SUB_I16:
1697 AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1698 break;
1699 case Mips::ATOMIC_LOAD_AND_I8:
1700 AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1701 break;
1702 case Mips::ATOMIC_LOAD_AND_I16:
1703 AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1704 break;
1705 case Mips::ATOMIC_LOAD_OR_I8:
1706 AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1707 break;
1708 case Mips::ATOMIC_LOAD_OR_I16:
1709 AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1710 break;
1711 case Mips::ATOMIC_LOAD_XOR_I8:
1712 AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1713 break;
1714 case Mips::ATOMIC_LOAD_XOR_I16:
1715 AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1716 break;
1717 case Mips::ATOMIC_LOAD_MIN_I8:
1718 AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA;
1719 NeedsAdditionalReg = true;
1720 break;
1721 case Mips::ATOMIC_LOAD_MIN_I16:
1722 AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA;
1723 NeedsAdditionalReg = true;
1724 break;
1725 case Mips::ATOMIC_LOAD_MAX_I8:
1726 AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA;
1727 NeedsAdditionalReg = true;
1728 break;
1729 case Mips::ATOMIC_LOAD_MAX_I16:
1730 AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA;
1731 NeedsAdditionalReg = true;
1732 break;
1733 case Mips::ATOMIC_LOAD_UMIN_I8:
1734 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA;
1735 NeedsAdditionalReg = true;
1736 break;
1737 case Mips::ATOMIC_LOAD_UMIN_I16:
1738 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA;
1739 NeedsAdditionalReg = true;
1740 break;
1741 case Mips::ATOMIC_LOAD_UMAX_I8:
1742 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA;
1743 NeedsAdditionalReg = true;
1744 break;
1745 case Mips::ATOMIC_LOAD_UMAX_I16:
1746 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA;
1747 NeedsAdditionalReg = true;
1748 break;
1749 default:
1750 llvm_unreachable("Unknown subword atomic pseudo for expansion!")::llvm::llvm_unreachable_internal("Unknown subword atomic pseudo for expansion!"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1750)
;
1751 }
1752
1753 // insert new blocks after the current block
1754 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1755 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1756 MachineFunction::iterator It = ++BB->getIterator();
1757 MF->insert(It, exitMBB);
1758
1759 // Transfer the remainder of BB and its successor edges to exitMBB.
1760 exitMBB->splice(exitMBB->begin(), BB,
1761 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1762 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1763
1764 BB->addSuccessor(exitMBB, BranchProbability::getOne());
1765
1766 // thisMBB:
1767 // addiu masklsb2,$0,-4 # 0xfffffffc
1768 // and alignedaddr,ptr,masklsb2
1769 // andi ptrlsb2,ptr,3
1770 // sll shiftamt,ptrlsb2,3
1771 // ori maskupper,$0,255 # 0xff
1772 // sll mask,maskupper,shiftamt
1773 // nor mask2,$0,mask
1774 // sll incr2,incr,shiftamt
1775
1776 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1777 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1778 .addReg(ABI.GetNullPtr()).addImm(-4);
1779 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1780 .addReg(Ptr).addReg(MaskLSB2);
1781 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1782 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1783 if (Subtarget.isLittle()) {
1784 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1785 } else {
1786 Register Off = RegInfo.createVirtualRegister(RC);
1787 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1788 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1789 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1790 }
1791 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1792 .addReg(Mips::ZERO).addImm(MaskImm);
1793 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1794 .addReg(MaskUpper).addReg(ShiftAmt);
1795 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1796 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1797
1798
1799 // The purposes of the flags on the scratch registers is explained in
1800 // emitAtomicBinary. In summary, we need a scratch register which is going to
1801 // be undef, that is unique among registers chosen for the instruction.
1802
1803 MachineInstrBuilder MIB =
1804 BuildMI(BB, DL, TII->get(AtomicOp))
1805 .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1806 .addReg(AlignedAddr)
1807 .addReg(Incr2)
1808 .addReg(Mask)
1809 .addReg(Mask2)
1810 .addReg(ShiftAmt)
1811 .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1812 RegState::Dead | RegState::Implicit)
1813 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
1814 RegState::Dead | RegState::Implicit)
1815 .addReg(Scratch3, RegState::EarlyClobber | RegState::Define |
1816 RegState::Dead | RegState::Implicit);
1817 if (NeedsAdditionalReg) {
1818 Register Scratch4 = RegInfo.createVirtualRegister(RC);
1819 MIB.addReg(Scratch4, RegState::EarlyClobber | RegState::Define |
1820 RegState::Dead | RegState::Implicit);
1821 }
1822
1823 MI.eraseFromParent(); // The instruction is gone now.
1824
1825 return exitMBB;
1826}
1827
1828// Lower atomic compare and swap to a pseudo instruction, taking care to
1829// define a scratch register for the pseudo instruction's expansion. The
1830// instruction is expanded after the register allocator as to prevent
1831// the insertion of stores between the linked load and the store conditional.
1832
1833MachineBasicBlock *
1834MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1835 MachineBasicBlock *BB) const {
1836
1837 assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||(static_cast <bool> ((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
|| MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && "Unsupported atomic pseudo for EmitAtomicCmpSwap."
) ? void (0) : __assert_fail ("(MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 || MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && \"Unsupported atomic pseudo for EmitAtomicCmpSwap.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1839, __extension__ __PRETTY_FUNCTION__))
1838 MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&(static_cast <bool> ((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
|| MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && "Unsupported atomic pseudo for EmitAtomicCmpSwap."
) ? void (0) : __assert_fail ("(MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 || MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && \"Unsupported atomic pseudo for EmitAtomicCmpSwap.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1839, __extension__ __PRETTY_FUNCTION__))
1839 "Unsupported atomic pseudo for EmitAtomicCmpSwap.")(static_cast <bool> ((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
|| MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && "Unsupported atomic pseudo for EmitAtomicCmpSwap."
) ? void (0) : __assert_fail ("(MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 || MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) && \"Unsupported atomic pseudo for EmitAtomicCmpSwap.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1839, __extension__ __PRETTY_FUNCTION__))
;
1840
1841 const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1842
1843 MachineFunction *MF = BB->getParent();
1844 MachineRegisterInfo &MRI = MF->getRegInfo();
1845 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1846 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1847 DebugLoc DL = MI.getDebugLoc();
1848
1849 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1850 ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1851 : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1852 Register Dest = MI.getOperand(0).getReg();
1853 Register Ptr = MI.getOperand(1).getReg();
1854 Register OldVal = MI.getOperand(2).getReg();
1855 Register NewVal = MI.getOperand(3).getReg();
1856
1857 Register Scratch = MRI.createVirtualRegister(RC);
1858 MachineBasicBlock::iterator II(MI);
1859
1860 // We need to create copies of the various registers and kill them at the
1861 // atomic pseudo. If the copies are not made, when the atomic is expanded
1862 // after fast register allocation, the spills will end up outside of the
1863 // blocks that their values are defined in, causing livein errors.
1864
1865 Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1866 Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1867 Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1868
1869 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1870 BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1871 BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1872
1873 // The purposes of the flags on the scratch registers is explained in
1874 // emitAtomicBinary. In summary, we need a scratch register which is going to
1875 // be undef, that is unique among registers chosen for the instruction.
1876
1877 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1878 .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1879 .addReg(PtrCopy, RegState::Kill)
1880 .addReg(OldValCopy, RegState::Kill)
1881 .addReg(NewValCopy, RegState::Kill)
1882 .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1883 RegState::Dead | RegState::Implicit);
1884
1885 MI.eraseFromParent(); // The instruction is gone now.
1886
1887 return BB;
1888}
1889
1890MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1891 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1892 assert((Size == 1 || Size == 2) &&(static_cast <bool> ((Size == 1 || Size == 2) &&
"Unsupported size for EmitAtomicCmpSwapPartial.") ? void (0)
: __assert_fail ("(Size == 1 || Size == 2) && \"Unsupported size for EmitAtomicCmpSwapPartial.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1893, __extension__ __PRETTY_FUNCTION__))
1893 "Unsupported size for EmitAtomicCmpSwapPartial.")(static_cast <bool> ((Size == 1 || Size == 2) &&
"Unsupported size for EmitAtomicCmpSwapPartial.") ? void (0)
: __assert_fail ("(Size == 1 || Size == 2) && \"Unsupported size for EmitAtomicCmpSwapPartial.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1893, __extension__ __PRETTY_FUNCTION__))
;
1894
1895 MachineFunction *MF = BB->getParent();
1896 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1897 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1898 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1899 const TargetRegisterClass *RCp =
1900 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1901 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1902 DebugLoc DL = MI.getDebugLoc();
1903
1904 Register Dest = MI.getOperand(0).getReg();
1905 Register Ptr = MI.getOperand(1).getReg();
1906 Register CmpVal = MI.getOperand(2).getReg();
1907 Register NewVal = MI.getOperand(3).getReg();
1908
1909 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1910 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1911 Register Mask = RegInfo.createVirtualRegister(RC);
1912 Register Mask2 = RegInfo.createVirtualRegister(RC);
1913 Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1914 Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1915 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1916 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1917 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1918 Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1919 Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
1920 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
1921 ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
1922 : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
1923
1924 // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
1925 // flags are used to coerce the register allocator and the machine verifier to
1926 // accept the usage of these registers.
1927 // The EarlyClobber flag has the semantic properties that the operand it is
1928 // attached to is clobbered before the rest of the inputs are read. Hence it
1929 // must be unique among the operands to the instruction.
1930 // The Define flag is needed to coerce the machine verifier that an Undef
1931 // value isn't a problem.
1932 // The Dead flag is needed as the value in scratch isn't used by any other
1933 // instruction. Kill isn't used as Dead is more precise.
1934 Register Scratch = RegInfo.createVirtualRegister(RC);
1935 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1936
1937 // insert new blocks after the current block
1938 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1939 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1940 MachineFunction::iterator It = ++BB->getIterator();
1941 MF->insert(It, exitMBB);
1942
1943 // Transfer the remainder of BB and its successor edges to exitMBB.
1944 exitMBB->splice(exitMBB->begin(), BB,
1945 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1946 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1947
1948 BB->addSuccessor(exitMBB, BranchProbability::getOne());
1949
1950 // thisMBB:
1951 // addiu masklsb2,$0,-4 # 0xfffffffc
1952 // and alignedaddr,ptr,masklsb2
1953 // andi ptrlsb2,ptr,3
1954 // xori ptrlsb2,ptrlsb2,3 # Only for BE
1955 // sll shiftamt,ptrlsb2,3
1956 // ori maskupper,$0,255 # 0xff
1957 // sll mask,maskupper,shiftamt
1958 // nor mask2,$0,mask
1959 // andi maskedcmpval,cmpval,255
1960 // sll shiftedcmpval,maskedcmpval,shiftamt
1961 // andi maskednewval,newval,255
1962 // sll shiftednewval,maskednewval,shiftamt
1963 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1964 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1965 .addReg(ABI.GetNullPtr()).addImm(-4);
1966 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1967 .addReg(Ptr).addReg(MaskLSB2);
1968 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1969 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1970 if (Subtarget.isLittle()) {
1971 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1972 } else {
1973 Register Off = RegInfo.createVirtualRegister(RC);
1974 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1975 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1976 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1977 }
1978 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1979 .addReg(Mips::ZERO).addImm(MaskImm);
1980 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1981 .addReg(MaskUpper).addReg(ShiftAmt);
1982 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1983 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1984 .addReg(CmpVal).addImm(MaskImm);
1985 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1986 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1987 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1988 .addReg(NewVal).addImm(MaskImm);
1989 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1990 .addReg(MaskedNewVal).addReg(ShiftAmt);
1991
1992 // The purposes of the flags on the scratch registers are explained in
1993 // emitAtomicBinary. In summary, we need a scratch register which is going to
1994 // be undef, that is unique among the register chosen for the instruction.
1995
1996 BuildMI(BB, DL, TII->get(AtomicOp))
1997 .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1998 .addReg(AlignedAddr)
1999 .addReg(Mask)
2000 .addReg(ShiftedCmpVal)
2001 .addReg(Mask2)
2002 .addReg(ShiftedNewVal)
2003 .addReg(ShiftAmt)
2004 .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
2005 RegState::Dead | RegState::Implicit)
2006 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
2007 RegState::Dead | RegState::Implicit);
2008
2009 MI.eraseFromParent(); // The instruction is gone now.
2010
2011 return exitMBB;
2012}
2013
2014SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2015 // The first operand is the chain, the second is the condition, the third is
2016 // the block to branch to if the condition is true.
2017 SDValue Chain = Op.getOperand(0);
2018 SDValue Dest = Op.getOperand(2);
2019 SDLoc DL(Op);
2020
2021 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6())(static_cast <bool> (!Subtarget.hasMips32r6() &&
!Subtarget.hasMips64r6()) ? void (0) : __assert_fail ("!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2021, __extension__ __PRETTY_FUNCTION__))
;
2022 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2023
2024 // Return if flag is not set by a floating point comparison.
2025 if (CondRes.getOpcode() != MipsISD::FPCmp)
2026 return Op;
2027
2028 SDValue CCNode = CondRes.getOperand(2);
2029 Mips::CondCode CC =
2030 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2031 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
2032 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2033 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2034 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2035 FCC0, Dest, CondRes);
2036}
2037
2038SDValue MipsTargetLowering::
2039lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2040{
2041 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6())(static_cast <bool> (!Subtarget.hasMips32r6() &&
!Subtarget.hasMips64r6()) ? void (0) : __assert_fail ("!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2041, __extension__ __PRETTY_FUNCTION__))
;
2042 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2043
2044 // Return if flag is not set by a floating point comparison.
2045 if (Cond.getOpcode() != MipsISD::FPCmp)
2046 return Op;
2047
2048 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2049 SDLoc(Op));
2050}
2051
2052SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2053 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6())(static_cast <bool> (!Subtarget.hasMips32r6() &&
!Subtarget.hasMips64r6()) ? void (0) : __assert_fail ("!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2053, __extension__ __PRETTY_FUNCTION__))
;
2054 SDValue Cond = createFPCmp(DAG, Op);
2055
2056 assert(Cond.getOpcode() == MipsISD::FPCmp &&(static_cast <bool> (Cond.getOpcode() == MipsISD::FPCmp
&& "Floating point operand expected.") ? void (0) : __assert_fail
("Cond.getOpcode() == MipsISD::FPCmp && \"Floating point operand expected.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2057, __extension__ __PRETTY_FUNCTION__))
2057 "Floating point operand expected.")(static_cast <bool> (Cond.getOpcode() == MipsISD::FPCmp
&& "Floating point operand expected.") ? void (0) : __assert_fail
("Cond.getOpcode() == MipsISD::FPCmp && \"Floating point operand expected.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2057, __extension__ __PRETTY_FUNCTION__))
;
2058
2059 SDLoc DL(Op);
2060 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2061 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2062
2063 return createCMovFP(DAG, Cond, True, False, DL);
2064}
2065
2066SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2067 SelectionDAG &DAG) const {
2068 EVT Ty = Op.getValueType();
2069 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2070 const GlobalValue *GV = N->getGlobal();
2071
2072 if (!isPositionIndependent()) {
2073 const MipsTargetObjectFile *TLOF =
2074 static_cast<const MipsTargetObjectFile *>(
2075 getTargetMachine().getObjFileLowering());
2076 const GlobalObject *GO = GV->getBaseObject();
2077 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2078 // %gp_rel relocation
2079 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2080
2081 // %hi/%lo relocation
2082 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2083 // %highest/%higher/%hi/%lo relocation
2084 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2085 }
2086
2087 // Every other architecture would use shouldAssumeDSOLocal in here, but
2088 // mips is special.
2089 // * In PIC code mips requires got loads even for local statics!
2090 // * To save on got entries, for local statics the got entry contains the
2091 // page and an additional add instruction takes care of the low bits.
2092 // * It is legal to access a hidden symbol with a non hidden undefined,
2093 // so one cannot guarantee that all access to a hidden symbol will know
2094 // it is hidden.
2095 // * Mips linkers don't support creating a page and a full got entry for
2096 // the same symbol.
2097 // * Given all that, we have to use a full got entry for hidden symbols :-(
2098 if (GV->hasLocalLinkage())
2099 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2100
2101 if (Subtarget.useXGOT())
2102 return getAddrGlobalLargeGOT(
2103 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2104 DAG.getEntryNode(),
2105 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2106
2107 return getAddrGlobal(
2108 N, SDLoc(N), Ty, DAG,
2109 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2110 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2111}
2112
2113SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2114 SelectionDAG &DAG) const {
2115 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2116 EVT Ty = Op.getValueType();
2117
2118 if (!isPositionIndependent())
2119 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2120 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2121
2122 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2123}
2124
2125SDValue MipsTargetLowering::
2126lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2127{
2128 // If the relocation model is PIC, use the General Dynamic TLS Model or
2129 // Local Dynamic TLS model, otherwise use the Initial Exec or
2130 // Local Exec TLS Model.
2131
2132 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2133 if (DAG.getTarget().useEmulatedTLS())
2134 return LowerToTLSEmulatedModel(GA, DAG);
2135
2136 SDLoc DL(GA);
2137 const GlobalValue *GV = GA->getGlobal();
2138 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2139
2140 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2141
2142 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2143 // General Dynamic and Local Dynamic TLS Model.
2144 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2145 : MipsII::MO_TLSGD;
2146
2147 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2148 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2149 getGlobalReg(DAG, PtrVT), TGA);
2150 unsigned PtrSize = PtrVT.getSizeInBits();
2151 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2152
2153 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2154
2155 ArgListTy Args;
2156 ArgListEntry Entry;
2157 Entry.Node = Argument;
2158 Entry.Ty = PtrTy;
2159 Args.push_back(Entry);
2160
2161 TargetLowering::CallLoweringInfo CLI(DAG);
2162 CLI.setDebugLoc(DL)
2163 .setChain(DAG.getEntryNode())
2164 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2165 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2166
2167 SDValue Ret = CallResult.first;
2168
2169 if (model != TLSModel::LocalDynamic)
2170 return Ret;
2171
2172 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2173 MipsII::MO_DTPREL_HI);
2174 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2175 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2176 MipsII::MO_DTPREL_LO);
2177 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2178 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2179 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2180 }
2181
2182 SDValue Offset;
2183 if (model == TLSModel::InitialExec) {
2184 // Initial Exec TLS Model
2185 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2186 MipsII::MO_GOTTPREL);
2187 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2188 TGA);
2189 Offset =
2190 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2191 } else {
2192 // Local Exec TLS Model
2193 assert(model == TLSModel::LocalExec)(static_cast <bool> (model == TLSModel::LocalExec) ? void
(0) : __assert_fail ("model == TLSModel::LocalExec", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2193, __extension__ __PRETTY_FUNCTION__))
;
2194 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2195 MipsII::MO_TPREL_HI);
2196 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2197 MipsII::MO_TPREL_LO);
2198 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2199 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2200 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2201 }
2202
2203 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2204 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2205}
2206
2207SDValue MipsTargetLowering::
2208lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2209{
2210 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2211 EVT Ty = Op.getValueType();
2212
2213 if (!isPositionIndependent())
2214 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2215 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2216
2217 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2218}
2219
2220SDValue MipsTargetLowering::
2221lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2222{
2223 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2224 EVT Ty = Op.getValueType();
2225
2226 if (!isPositionIndependent()) {
2227 const MipsTargetObjectFile *TLOF =
2228 static_cast<const MipsTargetObjectFile *>(
2229 getTargetMachine().getObjFileLowering());
2230
2231 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2232 getTargetMachine()))
2233 // %gp_rel relocation
2234 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2235
2236 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2237 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2238 }
2239
2240 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2241}
2242
2243SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2244 MachineFunction &MF = DAG.getMachineFunction();
2245 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2246
2247 SDLoc DL(Op);
2248 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2249 getPointerTy(MF.getDataLayout()));
2250
2251 // vastart just stores the address of the VarArgsFrameIndex slot into the
2252 // memory location argument.
2253 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2254 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2255 MachinePointerInfo(SV));
2256}
2257
2258SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2259 SDNode *Node = Op.getNode();
2260 EVT VT = Node->getValueType(0);
2261 SDValue Chain = Node->getOperand(0);
2262 SDValue VAListPtr = Node->getOperand(1);
2263 const Align Align =
2264 llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2265 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2266 SDLoc DL(Node);
2267 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2268
2269 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2270 VAListPtr, MachinePointerInfo(SV));
2271 SDValue VAList = VAListLoad;
2272
2273 // Re-align the pointer if necessary.
2274 // It should only ever be necessary for 64-bit types on O32 since the minimum
2275 // argument alignment is the same as the maximum type alignment for N32/N64.
2276 //
2277 // FIXME: We currently align too often. The code generator doesn't notice
2278 // when the pointer is still aligned from the last va_arg (or pair of
2279 // va_args for the i64 on O32 case).
2280 if (Align > getMinStackArgumentAlignment()) {
2281 VAList = DAG.getNode(
2282 ISD::ADD, DL, VAList.getValueType(), VAList,
2283 DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2284
2285 VAList = DAG.getNode(
2286 ISD::AND, DL, VAList.getValueType(), VAList,
2287 DAG.getConstant(-(int64_t)Align.value(), DL, VAList.getValueType()));
2288 }
2289
2290 // Increment the pointer, VAList, to the next vaarg.
2291 auto &TD = DAG.getDataLayout();
2292 unsigned ArgSizeInBytes =
2293 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2294 SDValue Tmp3 =
2295 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2296 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2297 DL, VAList.getValueType()));
2298 // Store the incremented VAList to the legalized pointer
2299 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2300 MachinePointerInfo(SV));
2301
2302 // In big-endian mode we must adjust the pointer when the load size is smaller
2303 // than the argument slot size. We must also reduce the known alignment to
2304 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2305 // the correct half of the slot, and reduce the alignment from 8 (slot
2306 // alignment) down to 4 (type alignment).
2307 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2308 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2309 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2310 DAG.getIntPtrConstant(Adjustment, DL));
2311 }
2312 // Load the actual argument out of the pointer VAList
2313 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2314}
2315
2316static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2317 bool HasExtractInsert) {
2318 EVT TyX = Op.getOperand(0).getValueType();
2319 EVT TyY = Op.getOperand(1).getValueType();
2320 SDLoc DL(Op);
2321 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2322 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2323 SDValue Res;
2324
2325 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2326 // to i32.
2327 SDValue X = (TyX == MVT::f32) ?
2328 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2329 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2330 Const1);
2331 SDValue Y = (TyY == MVT::f32) ?
2332 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2333 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2334 Const1);
2335
2336 if (HasExtractInsert) {
2337 // ext E, Y, 31, 1 ; extract bit31 of Y
2338 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2339 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2340 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2341 } else {
2342 // sll SllX, X, 1
2343 // srl SrlX, SllX, 1
2344 // srl SrlY, Y, 31
2345 // sll SllY, SrlX, 31
2346 // or Or, SrlX, SllY
2347 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2348 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2349 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2350 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2351 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2352 }
2353
2354 if (TyX == MVT::f32)
2355 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2356
2357 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2358 Op.getOperand(0),
2359 DAG.getConstant(0, DL, MVT::i32));
2360 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2361}
2362
2363static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2364 bool HasExtractInsert) {
2365 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2366 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2367 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2368 SDLoc DL(Op);
2369 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2370
2371 // Bitcast to integer nodes.
2372 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2373 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2374
2375 if (HasExtractInsert) {
2376 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2377 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2378 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2379 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2380
2381 if (WidthX > WidthY)
2382 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2383 else if (WidthY > WidthX)
2384 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2385
2386 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2387 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2388 X);
2389 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2390 }
2391
2392 // (d)sll SllX, X, 1
2393 // (d)srl SrlX, SllX, 1
2394 // (d)srl SrlY, Y, width(Y)-1
2395 // (d)sll SllY, SrlX, width(Y)-1
2396 // or Or, SrlX, SllY
2397 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2398 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2399 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2400 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2401
2402 if (WidthX > WidthY)
2403 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2404 else if (WidthY > WidthX)
2405 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2406
2407 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2408 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2409 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2410 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2411}
2412
2413SDValue
2414MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2415 if (Subtarget.isGP64bit())
2416 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2417
2418 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2419}
2420
2421static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
2422 bool HasExtractInsert) {
2423 SDLoc DL(Op);
2424 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2425
2426 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2427 // to i32.
2428 SDValue X = (Op.getValueType() == MVT::f32)
2429 ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2430 : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2431 Op.getOperand(0), Const1);
2432
2433 // Clear MSB.
2434 if (HasExtractInsert)
2435 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2436 DAG.getRegister(Mips::ZERO, MVT::i32),
2437 DAG.getConstant(31, DL, MVT::i32), Const1, X);
2438 else {
2439 // TODO: Provide DAG patterns which transform (and x, cst)
2440 // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2441 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2442 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2443 }
2444
2445 if (Op.getValueType() == MVT::f32)
2446 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2447
2448 // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2449 // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2450 // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2451 // place.
2452 SDValue LowX =
2453 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2454 DAG.getConstant(0, DL, MVT::i32));
2455 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2456}
2457
2458static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
2459 bool HasExtractInsert) {
2460 SDLoc DL(Op);
2461 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2462
2463 // Bitcast to integer node.
2464 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2465
2466 // Clear MSB.
2467 if (HasExtractInsert)
2468 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2469 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2470 DAG.getConstant(63, DL, MVT::i32), Const1, X);
2471 else {
2472 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2473 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2474 }
2475
2476 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2477}
2478
2479SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2480 if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2481 return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2482
2483 return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2484}
2485
2486SDValue MipsTargetLowering::
2487lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2488 // check the depth
2489 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2490 DAG.getContext()->emitError(
2491 "return address can be determined only for current frame");
2492 return SDValue();
2493 }
2494
2495 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2496 MFI.setFrameAddressIsTaken(true);
2497 EVT VT = Op.getValueType();
2498 SDLoc DL(Op);
2499 SDValue FrameAddr = DAG.getCopyFromReg(
2500 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2501 return FrameAddr;
2502}
2503
2504SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2505 SelectionDAG &DAG) const {
2506 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2507 return SDValue();
2508
2509 // check the depth
2510 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2511 DAG.getContext()->emitError(
2512 "return address can be determined only for current frame");
2513 return SDValue();
2514 }
2515
2516 MachineFunction &MF = DAG.getMachineFunction();
2517 MachineFrameInfo &MFI = MF.getFrameInfo();
2518 MVT VT = Op.getSimpleValueType();
2519 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2520 MFI.setReturnAddressIsTaken(true);
2521
2522 // Return RA, which contains the return address. Mark it an implicit live-in.
2523 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2524 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2525}
2526
2527// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2528// generated from __builtin_eh_return (offset, handler)
2529// The effect of this is to adjust the stack pointer by "offset"
2530// and then branch to "handler".
2531SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2532 const {
2533 MachineFunction &MF = DAG.getMachineFunction();
2534 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2535
2536 MipsFI->setCallsEhReturn();
2537 SDValue Chain = Op.getOperand(0);
2538 SDValue Offset = Op.getOperand(1);
2539 SDValue Handler = Op.getOperand(2);
2540 SDLoc DL(Op);
2541 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2542
2543 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2544 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2545 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2546 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2547 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2548 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2549 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2550 DAG.getRegister(OffsetReg, Ty),
2551 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2552 Chain.getValue(1));
2553}
2554
2555SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2556 SelectionDAG &DAG) const {
2557 // FIXME: Need pseudo-fence for 'singlethread' fences
2558 // FIXME: Set SType for weaker fences where supported/appropriate.
2559 unsigned SType = 0;
2560 SDLoc DL(Op);
2561 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2562 DAG.getConstant(SType, DL, MVT::i32));
2563}
2564
2565SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2566 SelectionDAG &DAG) const {
2567 SDLoc DL(Op);
2568 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2569
2570 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2571 SDValue Shamt = Op.getOperand(2);
2572 // if shamt < (VT.bits):
2573 // lo = (shl lo, shamt)
2574 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2575 // else:
2576 // lo = 0
2577 // hi = (shl lo, shamt[4:0])
2578 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2579 DAG.getConstant(-1, DL, MVT::i32));
2580 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2581 DAG.getConstant(1, DL, VT));
2582 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2583 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2584 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2585 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2586 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2587 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2588 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2589 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2590 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2591
2592 SDValue Ops[2] = {Lo, Hi};
2593 return DAG.getMergeValues(Ops, DL);
2594}
2595
2596SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2597 bool IsSRA) const {
2598 SDLoc DL(Op);
2599 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2600 SDValue Shamt = Op.getOperand(2);
2601 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2602
2603 // if shamt < (VT.bits):
2604 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2605 // if isSRA:
2606 // hi = (sra hi, shamt)
2607 // else:
2608 // hi = (srl hi, shamt)
2609 // else:
2610 // if isSRA:
2611 // lo = (sra hi, shamt[4:0])
2612 // hi = (sra hi, 31)
2613 // else:
2614 // lo = (srl hi, shamt[4:0])
2615 // hi = 0
2616 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2617 DAG.getConstant(-1, DL, MVT::i32));
2618 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2619 DAG.getConstant(1, DL, VT));
2620 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2621 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2622 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2623 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2624 DL, VT, Hi, Shamt);
2625 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2626 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2627 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2628 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2629
2630 if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2631 SDVTList VTList = DAG.getVTList(VT, VT);
2632 return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64
2633 : Mips::PseudoD_SELECT_I,
2634 DL, VTList, Cond, ShiftRightHi,
2635 IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2636 ShiftRightHi);
2637 }
2638
2639 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2640 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2641 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2642
2643 SDValue Ops[2] = {Lo, Hi};
2644 return DAG.getMergeValues(Ops, DL);
2645}
2646
2647static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2648 SDValue Chain, SDValue Src, unsigned Offset) {
2649 SDValue Ptr = LD->getBasePtr();
2650 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2651 EVT BasePtrVT = Ptr.getValueType();
2652 SDLoc DL(LD);
2653 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2654
2655 if (Offset)
2656 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2657 DAG.getConstant(Offset, DL, BasePtrVT));
2658
2659 SDValue Ops[] = { Chain, Ptr, Src };
2660 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2661 LD->getMemOperand());
2662}
2663
2664// Expand an unaligned 32 or 64-bit integer load node.
2665SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2666 LoadSDNode *LD = cast<LoadSDNode>(Op);
2667 EVT MemVT = LD->getMemoryVT();
2668
2669 if (Subtarget.systemSupportsUnalignedAccess())
2670 return Op;
2671
2672 // Return if load is aligned or if MemVT is neither i32 nor i64.
2673 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2674 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2675 return SDValue();
2676
2677 bool IsLittle = Subtarget.isLittle();
2678 EVT VT = Op.getValueType();
2679 ISD::LoadExtType ExtType = LD->getExtensionType();
2680 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2681
2682 assert((VT == MVT::i32) || (VT == MVT::i64))(static_cast <bool> ((VT == MVT::i32) || (VT == MVT::i64
)) ? void (0) : __assert_fail ("(VT == MVT::i32) || (VT == MVT::i64)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2682, __extension__ __PRETTY_FUNCTION__))
;
2683
2684 // Expand
2685 // (set dst, (i64 (load baseptr)))
2686 // to
2687 // (set tmp, (ldl (add baseptr, 7), undef))
2688 // (set dst, (ldr baseptr, tmp))
2689 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2690 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2691 IsLittle ? 7 : 0);
2692 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2693 IsLittle ? 0 : 7);
2694 }
2695
2696 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2697 IsLittle ? 3 : 0);
2698 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2699 IsLittle ? 0 : 3);
2700
2701 // Expand
2702 // (set dst, (i32 (load baseptr))) or
2703 // (set dst, (i64 (sextload baseptr))) or
2704 // (set dst, (i64 (extload baseptr)))
2705 // to
2706 // (set tmp, (lwl (add baseptr, 3), undef))
2707 // (set dst, (lwr baseptr, tmp))
2708 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2709 (ExtType == ISD::EXTLOAD))
2710 return LWR;
2711
2712 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD))(static_cast <bool> ((VT == MVT::i64) && (ExtType
== ISD::ZEXTLOAD)) ? void (0) : __assert_fail ("(VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD)"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2712, __extension__ __PRETTY_FUNCTION__))
;
2713
2714 // Expand
2715 // (set dst, (i64 (zextload baseptr)))
2716 // to
2717 // (set tmp0, (lwl (add baseptr, 3), undef))
2718 // (set tmp1, (lwr baseptr, tmp0))
2719 // (set tmp2, (shl tmp1, 32))
2720 // (set dst, (srl tmp2, 32))
2721 SDLoc DL(LD);
2722 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2723 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2724 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2725 SDValue Ops[] = { SRL, LWR.getValue(1) };
2726 return DAG.getMergeValues(Ops, DL);
2727}
2728
2729static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2730 SDValue Chain, unsigned Offset) {
2731 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2732 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2733 SDLoc DL(SD);
2734 SDVTList VTList = DAG.getVTList(MVT::Other);
2735
2736 if (Offset)
2737 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2738 DAG.getConstant(Offset, DL, BasePtrVT));
2739
2740 SDValue Ops[] = { Chain, Value, Ptr };
2741 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2742 SD->getMemOperand());
2743}
2744
2745// Expand an unaligned 32 or 64-bit integer store node.
2746static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2747 bool IsLittle) {
2748 SDValue Value = SD->getValue(), Chain = SD->getChain();
2749 EVT VT = Value.getValueType();
2750
2751 // Expand
2752 // (store val, baseptr) or
2753 // (truncstore val, baseptr)
2754 // to
2755 // (swl val, (add baseptr, 3))
2756 // (swr val, baseptr)
2757 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2758 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2759 IsLittle ? 3 : 0);
2760 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2761 }
2762
2763 assert(VT == MVT::i64)(static_cast <bool> (VT == MVT::i64) ? void (0) : __assert_fail
("VT == MVT::i64", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2763, __extension__ __PRETTY_FUNCTION__))
;
2764
2765 // Expand
2766 // (store val, baseptr)
2767 // to
2768 // (sdl val, (add baseptr, 7))
2769 // (sdr val, baseptr)
2770 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2771 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2772}
2773
2774// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2775static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG,
2776 bool SingleFloat) {
2777 SDValue Val = SD->getValue();
2778
2779 if (Val.getOpcode() != ISD::FP_TO_SINT ||
2780 (Val.getValueSizeInBits() > 32 && SingleFloat))
2781 return SDValue();
2782
2783 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2784 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2785 Val.getOperand(0));
2786 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2787 SD->getPointerInfo(), SD->getAlignment(),
2788 SD->getMemOperand()->getFlags());
2789}
2790
2791SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2792 StoreSDNode *SD = cast<StoreSDNode>(Op);
2793 EVT MemVT = SD->getMemoryVT();
2794
2795 // Lower unaligned integer stores.
2796 if (!Subtarget.systemSupportsUnalignedAccess() &&
2797 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2798 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2799 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2800
2801 return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
2802}
2803
2804SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2805 SelectionDAG &DAG) const {
2806
2807 // Return a fixed StackObject with offset 0 which points to the old stack
2808 // pointer.
2809 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2810 EVT ValTy = Op->getValueType(0);
2811 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2812 return DAG.getFrameIndex(FI, ValTy);
2813}
2814
2815SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2816 SelectionDAG &DAG) const {
2817 if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2818 return SDValue();
2819
2820 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2821 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2822 Op.getOperand(0));
2823 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2824}
2825
2826//===----------------------------------------------------------------------===//
2827// Calling Convention Implementation
2828//===----------------------------------------------------------------------===//
2829
2830//===----------------------------------------------------------------------===//
2831// TODO: Implement a generic logic using tblgen that can support this.
2832// Mips O32 ABI rules:
2833// ---
2834// i32 - Passed in A0, A1, A2, A3 and stack
2835// f32 - Only passed in f32 registers if no int reg has been used yet to hold
2836// an argument. Otherwise, passed in A1, A2, A3 and stack.
2837// f64 - Only passed in two aliased f32 registers if no int reg has been used
2838// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2839// not used, it must be shadowed. If only A3 is available, shadow it and
2840// go to stack.
2841// vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2842// vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2843// with the remainder spilled to the stack.
2844// vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2845// spilling the remainder to the stack.
2846//
2847// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2848//===----------------------------------------------------------------------===//
2849
2850static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2851 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2852 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2853 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2854 State.getMachineFunction().getSubtarget());
2855
2856 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2857
2858 const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2859
2860 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2861
2862 static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2863
2864 // Do not process byval args here.
2865 if (ArgFlags.isByVal())
2866 return true;
2867
2868 // Promote i8 and i16
2869 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2870 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2871 LocVT = MVT::i32;
2872 if (ArgFlags.isSExt())
2873 LocInfo = CCValAssign::SExtUpper;
2874 else if (ArgFlags.isZExt())
2875 LocInfo = CCValAssign::ZExtUpper;
2876 else
2877 LocInfo = CCValAssign::AExtUpper;
2878 }
2879 }
2880
2881 // Promote i8 and i16
2882 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2883 LocVT = MVT::i32;
2884 if (ArgFlags.isSExt())
2885 LocInfo = CCValAssign::SExt;
2886 else if (ArgFlags.isZExt())
2887 LocInfo = CCValAssign::ZExt;
2888 else
2889 LocInfo = CCValAssign::AExt;
2890 }
2891
2892 unsigned Reg;
2893
2894 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2895 // is true: function is vararg, argument is 3rd or higher, there is previous
2896 // argument which is not f32 or f64.
2897 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2898 State.getFirstUnallocated(F32Regs) != ValNo;
2899 Align OrigAlign = ArgFlags.getNonZeroOrigAlign();
2900 bool isI64 = (ValVT == MVT::i32 && OrigAlign == Align(8));
2901 bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2902
2903 // The MIPS vector ABI for floats passes them in a pair of registers
2904 if (ValVT == MVT::i32 && isVectorFloat) {
2905 // This is the start of an vector that was scalarized into an unknown number
2906 // of components. It doesn't matter how many there are. Allocate one of the
2907 // notional 8 byte aligned registers which map onto the argument stack, and
2908 // shadow the register lost to alignment requirements.
2909 if (ArgFlags.isSplit()) {
2910 Reg = State.AllocateReg(FloatVectorIntRegs);
2911 if (Reg == Mips::A2)
2912 State.AllocateReg(Mips::A1);
2913 else if (Reg == 0)
2914 State.AllocateReg(Mips::A3);
2915 } else {
2916 // If we're an intermediate component of the split, we can just attempt to
2917 // allocate a register directly.
2918 Reg = State.AllocateReg(IntRegs);
2919 }
2920 } else if (ValVT == MVT::i32 ||
2921 (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2922 Reg = State.AllocateReg(IntRegs);
2923 // If this is the first part of an i64 arg,
2924 // the allocated register must be either A0 or A2.
2925 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2926 Reg = State.AllocateReg(IntRegs);
2927 LocVT = MVT::i32;
2928 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2929 LocVT = MVT::i32;
2930
2931 // Allocate int register and shadow next int register. If first
2932 // available register is Mips::A1 or Mips::A3, shadow it too.
2933 Reg = State.AllocateReg(IntRegs);
2934 if (Reg == Mips::A1 || Reg == Mips::A3)
2935 Reg = State.AllocateReg(IntRegs);
2936
2937 if (Reg) {
2938 State.addLoc(
2939 CCValAssign::getCustomReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2940 MCRegister HiReg = State.AllocateReg(IntRegs);
2941 assert(HiReg)(static_cast <bool> (HiReg) ? void (0) : __assert_fail (
"HiReg", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2941, __extension__ __PRETTY_FUNCTION__))
;
2942 State.addLoc(
2943 CCValAssign::getCustomReg(ValNo, ValVT, HiReg, LocVT, LocInfo));
2944 return false;
2945 }
2946 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2947 // we are guaranteed to find an available float register
2948 if (ValVT == MVT::f32) {
2949 Reg = State.AllocateReg(F32Regs);
2950 // Shadow int register
2951 State.AllocateReg(IntRegs);
2952 } else {
2953 Reg = State.AllocateReg(F64Regs);
2954 // Shadow int registers
2955 unsigned Reg2 = State.AllocateReg(IntRegs);
2956 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2957 State.AllocateReg(IntRegs);
2958 State.AllocateReg(IntRegs);
2959 }
2960 } else
2961 llvm_unreachable("Cannot handle this ValVT.")::llvm::llvm_unreachable_internal("Cannot handle this ValVT."
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2961)
;
2962
2963 if (!Reg) {
2964 unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
2965 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2966 } else
2967 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2968
2969 return false;
2970}
2971
2972static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2973 MVT LocVT, CCValAssign::LocInfo LocInfo,
2974 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2975 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2976
2977 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2978}
2979
2980static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2981 MVT LocVT, CCValAssign::LocInfo LocInfo,
2982 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2983 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2984
2985 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2986}
2987
2988static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2989 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2990 CCState &State) LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__));
2991
2992#include "MipsGenCallingConv.inc"
2993
2994 CCAssignFn *MipsTargetLowering::CCAssignFnForCall() const{
2995 return CC_Mips_FixedArg;
2996 }
2997
2998 CCAssignFn *MipsTargetLowering::CCAssignFnForReturn() const{
2999 return RetCC_Mips;
3000 }
3001//===----------------------------------------------------------------------===//
3002// Call Calling Convention Implementation
3003//===----------------------------------------------------------------------===//
3004
3005SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3006 SDValue Chain, SDValue Arg,
3007 const SDLoc &DL, bool IsTailCall,
3008 SelectionDAG &DAG) const {
3009 if (!IsTailCall) {
3010 SDValue PtrOff =
3011 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
3012 DAG.getIntPtrConstant(Offset, DL));
3013 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
3014 }
3015
3016 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3017 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3018 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3019 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(), MaybeAlign(),
3020 MachineMemOperand::MOVolatile);
3021}
3022
3023void MipsTargetLowering::
3024getOpndList(SmallVectorImpl<SDValue> &Ops,
3025 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3026 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
3027 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
3028 SDValue Chain) const {
3029 // Insert node "GP copy globalreg" before call to function.
3030 //
3031 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3032 // in PIC mode) allow symbols to be resolved via lazy binding.
3033 // The lazy binding stub requires GP to point to the GOT.
3034 // Note that we don't need GP to point to the GOT for indirect calls
3035 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3036 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3037 // used for the function (that is, Mips linker doesn't generate lazy binding
3038 // stub for a function whose address is taken in the program).
3039 if (IsPICCall && !InternalLinkage && IsCallReloc) {
3040 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3041 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3042 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3043 }
3044
3045 // Build a sequence of copy-to-reg nodes chained together with token
3046 // chain and flag operands which copy the outgoing args into registers.
3047 // The InFlag in necessary since all emitted instructions must be
3048 // stuck together.
3049 SDValue InFlag;
3050
3051 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3052 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
3053 RegsToPass[i].second, InFlag);
3054 InFlag = Chain.getValue(1);
3055 }
3056
3057 // Add argument registers to the end of the list so that they are
3058 // known live into the call.
3059 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3060 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
3061 RegsToPass[i].second.getValueType()));
3062
3063 // Add a register mask operand representing the call-preserved registers.
3064 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3065 const uint32_t *Mask =
3066 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3067 assert(Mask && "Missing call preserved mask for calling convention")(static_cast <bool> (Mask && "Missing call preserved mask for calling convention"
) ? void (0) : __assert_fail ("Mask && \"Missing call preserved mask for calling convention\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3067, __extension__ __PRETTY_FUNCTION__))
;
3068 if (Subtarget.inMips16HardFloat()) {
3069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
3070 StringRef Sym = G->getGlobal()->getName();
3071 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3072 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3073 Mask = MipsRegisterInfo::getMips16RetHelperMask();
3074 }
3075 }
3076 }
3077 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3078
3079 if (InFlag.getNode())
3080 Ops.push_back(InFlag);
3081}
3082
3083void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
3084 SDNode *Node) const {
3085 switch (MI.getOpcode()) {
3086 default:
3087 return;
3088 case Mips::JALR:
3089 case Mips::JALRPseudo:
3090 case Mips::JALR64:
3091 case Mips::JALR64Pseudo:
3092 case Mips::JALR16_MM:
3093 case Mips::JALRC16_MMR6:
3094 case Mips::TAILCALLREG:
3095 case Mips::TAILCALLREG64:
3096 case Mips::TAILCALLR6REG:
3097 case Mips::TAILCALL64R6REG:
3098 case Mips::TAILCALLREG_MM:
3099 case Mips::TAILCALLREG_MMR6: {
3100 if (!EmitJalrReloc ||
3101 Subtarget.inMips16Mode() ||
3102 !isPositionIndependent() ||
3103 Node->getNumOperands() < 1 ||
3104 Node->getOperand(0).getNumOperands() < 2) {
3105 return;
3106 }
3107 // We are after the callee address, set by LowerCall().
3108 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3109 // symbol.
3110 const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3111 StringRef Sym;
3112 if (const GlobalAddressSDNode *G =
3113 dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
3114 // We must not emit the R_MIPS_JALR relocation against data symbols
3115 // since this will cause run-time crashes if the linker replaces the
3116 // call instruction with a relative branch to the data symbol.
3117 if (!isa<Function>(G->getGlobal())) {
3118 LLVM_DEBUG(dbgs() << "Not adding R_MIPS_JALR against data symbol "do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mips-lower")) { dbgs() << "Not adding R_MIPS_JALR against data symbol "
<< G->getGlobal()->getName() << "\n"; } } while
(false)
3119 << G->getGlobal()->getName() << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mips-lower")) { dbgs() << "Not adding R_MIPS_JALR against data symbol "
<< G->getGlobal()->getName() << "\n"; } } while
(false)
;
3120 return;
3121 }
3122 Sym = G->getGlobal()->getName();
3123 }
3124 else if (const ExternalSymbolSDNode *ES =
3125 dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
3126 Sym = ES->getSymbol();
3127 }
3128
3129 if (Sym.empty())
3130 return;
3131
3132 MachineFunction *MF = MI.getParent()->getParent();
3133 MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3134 LLVM_DEBUG(dbgs() << "Adding R_MIPS_JALR against " << Sym << "\n")do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType
("mips-lower")) { dbgs() << "Adding R_MIPS_JALR against "
<< Sym << "\n"; } } while (false)
;
3135 MI.addOperand(MachineOperand::CreateMCSymbol(S, MipsII::MO_JALR));
3136 }
3137 }
3138}
3139
3140/// LowerCall - functions arguments are copied from virtual regs to
3141/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3142SDValue
3143MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3144 SmallVectorImpl<SDValue> &InVals) const {
3145 SelectionDAG &DAG = CLI.DAG;
3146 SDLoc DL = CLI.DL;
3147 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3148 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3149 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3150 SDValue Chain = CLI.Chain;
3151 SDValue Callee = CLI.Callee;
1
Value assigned to 'Callee.Node'
3152 bool &IsTailCall = CLI.IsTailCall;
3153 CallingConv::ID CallConv = CLI.CallConv;
3154 bool IsVarArg = CLI.IsVarArg;
3155
3156 MachineFunction &MF = DAG.getMachineFunction();
3157 MachineFrameInfo &MFI = MF.getFrameInfo();
3158 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3159 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3160 bool IsPIC = isPositionIndependent();
3161
3162 // Analyze operands of the call, assigning locations to each operand.
3163 SmallVector<CCValAssign, 16> ArgLocs;
3164 MipsCCState CCInfo(
3165 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3166 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
3167
3168 const ExternalSymbolSDNode *ES =
3169 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
2
Assuming null pointer is passed into cast
3
Assuming pointer value is null
3170
3171 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3172 // is during the lowering of a call with a byval argument which produces
3173 // a call to memcpy. For the O32 case, this causes the caller to allocate
3174 // stack space for the reserved argument area for the callee, then recursively
3175 // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3176 // ABIs mandate that the callee allocates the reserved argument area. We do
3177 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3178 //
3179 // If the callee has a byval argument and memcpy is used, we are mandated
3180 // to already have produced a reserved argument area for the callee for O32.
3181 // Therefore, the reserved argument area can be reused for both calls.
3182 //
3183 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3184 // present, as we have yet to hook that node onto the chain.
3185 //
3186 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3187 // case. GCC does a similar trick, in that wherever possible, it calculates
3188 // the maximum out going argument area (including the reserved area), and
3189 // preallocates the stack space on entrance to the caller.
3190 //
3191 // FIXME: We should do the same for efficiency and space.
3192
3193 // Note: The check on the calling convention below must match
3194 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3195 bool MemcpyInByVal = ES
3.1
'ES' is null
3.1
'ES' is null
&&
3196 StringRef(ES->getSymbol()) == StringRef("memcpy") &&
3197 CallConv != CallingConv::Fast &&
3198 Chain.getOpcode() == ISD::CALLSEQ_START;
3199
3200 // Allocate the reserved argument area. It seems strange to do this from the
3201 // caller side but removing it breaks the frame size calculation.
3202 unsigned ReservedArgArea =
3203 MemcpyInByVal
3.2
'MemcpyInByVal' is false
3.2
'MemcpyInByVal' is false
? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
4
'?' condition is false
3204 CCInfo.AllocateStack(ReservedArgArea, Align(1));
3205
3206 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
3207 ES
4.1
'ES' is null
4.1
'ES' is null
? ES->getSymbol() : nullptr);
5
'?' condition is false
3208
3209 // Get a count of how many bytes are to be pushed on the stack.
3210 unsigned NextStackOffset = CCInfo.getNextStackOffset();
3211
3212 // Call site info for function parameters tracking.
3213 MachineFunction::CallSiteInfo CSInfo;
3214
3215 // Check if it's really possible to do a tail call. Restrict it to functions
3216 // that are part of this compilation unit.
3217 bool InternalLinkage = false;
3218 if (IsTailCall) {
6
Assuming 'IsTailCall' is false
7
Taking false branch
3219 IsTailCall = isEligibleForTailCallOptimization(
3220 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3221 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3222 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3223 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3224 G->getGlobal()->hasPrivateLinkage() ||
3225 G->getGlobal()->hasHiddenVisibility() ||
3226 G->getGlobal()->hasProtectedVisibility());
3227 }
3228 }
3229 if (!IsTailCall
7.1
'IsTailCall' is false
7.1
'IsTailCall' is false
&& CLI.CB && CLI.CB->isMustTailCall())
8
Assuming field 'CB' is null
3230 report_fatal_error("failed to perform tail call elimination on a call "
3231 "site marked musttail");
3232
3233 if (IsTailCall
8.1
'IsTailCall' is false
8.1
'IsTailCall' is false
)
9
Taking false branch
3234 ++NumTailCalls;
3235
3236 // Chain is the output chain of the last Load/Store or CopyToReg node.
3237 // ByValChain is the output chain of the last Memcpy node created for copying
3238 // byval arguments to the stack.
3239 unsigned StackAlignment = TFL->getStackAlignment();
3240 NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3241 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3242
3243 if (!(IsTailCall
9.1
'IsTailCall' is false
9.1
'IsTailCall' is false
|| MemcpyInByVal))
10
Taking true branch
3244 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3245
3246 SDValue StackPtr =
3247 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
11
'?' condition is false
3248 getPointerTy(DAG.getDataLayout()));
3249
3250 std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3251 SmallVector<SDValue, 8> MemOpChains;
3252
3253 CCInfo.rewindByValRegsInfo();
3254
3255 // Walk the register/memloc assignments, inserting copies/loads.
3256 for (unsigned i = 0, e = ArgLocs.size(), OutIdx = 0; i != e; ++i, ++OutIdx) {
12
Assuming 'i' is equal to 'e'
13
Loop condition is false. Execution continues on line 3369
3257 SDValue Arg = OutVals[OutIdx];
3258 CCValAssign &VA = ArgLocs[i];
3259 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3260 ISD::ArgFlagsTy Flags = Outs[OutIdx].Flags;
3261 bool UseUpperBits = false;
3262
3263 // ByVal Arg.
3264 if (Flags.isByVal()) {
3265 unsigned FirstByValReg, LastByValReg;
3266 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3267 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3268
3269 assert(Flags.getByValSize() &&(static_cast <bool> (Flags.getByValSize() && "ByVal args of size 0 should have been ignored by front-end."
) ? void (0) : __assert_fail ("Flags.getByValSize() && \"ByVal args of size 0 should have been ignored by front-end.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3270, __extension__ __PRETTY_FUNCTION__))
3270 "ByVal args of size 0 should have been ignored by front-end.")(static_cast <bool> (Flags.getByValSize() && "ByVal args of size 0 should have been ignored by front-end."
) ? void (0) : __assert_fail ("Flags.getByValSize() && \"ByVal args of size 0 should have been ignored by front-end.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3270, __extension__ __PRETTY_FUNCTION__))
;
3271 assert(ByValIdx < CCInfo.getInRegsParamsCount())(static_cast <bool> (ByValIdx < CCInfo.getInRegsParamsCount
()) ? void (0) : __assert_fail ("ByValIdx < CCInfo.getInRegsParamsCount()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3271, __extension__ __PRETTY_FUNCTION__))
;
3272 assert(!IsTailCall &&(static_cast <bool> (!IsTailCall && "Do not tail-call optimize if there is a byval argument."
) ? void (0) : __assert_fail ("!IsTailCall && \"Do not tail-call optimize if there is a byval argument.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3273, __extension__ __PRETTY_FUNCTION__))
3273 "Do not tail-call optimize if there is a byval argument.")(static_cast <bool> (!IsTailCall && "Do not tail-call optimize if there is a byval argument."
) ? void (0) : __assert_fail ("!IsTailCall && \"Do not tail-call optimize if there is a byval argument.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3273, __extension__ __PRETTY_FUNCTION__))
;
3274 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3275 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3276 VA);
3277 CCInfo.nextInRegsParam();
3278 continue;
3279 }
3280
3281 // Promote the value if needed.
3282 switch (VA.getLocInfo()) {
3283 default:
3284 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3284)
;
3285 case CCValAssign::Full:
3286 if (VA.isRegLoc()) {
3287 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3288 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3289 (ValVT == MVT::i64 && LocVT == MVT::f64))
3290 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3291 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3292 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3293 Arg, DAG.getConstant(0, DL, MVT::i32));
3294 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3295 Arg, DAG.getConstant(1, DL, MVT::i32));
3296 if (!Subtarget.isLittle())
3297 std::swap(Lo, Hi);
3298
3299 assert(VA.needsCustom())(static_cast <bool> (VA.needsCustom()) ? void (0) : __assert_fail
("VA.needsCustom()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3299, __extension__ __PRETTY_FUNCTION__))
;
3300
3301 Register LocRegLo = VA.getLocReg();
3302 Register LocRegHigh = ArgLocs[++i].getLocReg();
3303 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3304 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3305 continue;
3306 }
3307 }
3308 break;
3309 case CCValAssign::BCvt:
3310 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3311 break;
3312 case CCValAssign::SExtUpper:
3313 UseUpperBits = true;
3314 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3315 case CCValAssign::SExt:
3316 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3317 break;
3318 case CCValAssign::ZExtUpper:
3319 UseUpperBits = true;
3320 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3321 case CCValAssign::ZExt:
3322 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3323 break;
3324 case CCValAssign::AExtUpper:
3325 UseUpperBits = true;
3326 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3327 case CCValAssign::AExt:
3328 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3329 break;
3330 }
3331
3332 if (UseUpperBits) {
3333 unsigned ValSizeInBits = Outs[OutIdx].ArgVT.getSizeInBits();
3334 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3335 Arg = DAG.getNode(
3336 ISD::SHL, DL, VA.getLocVT(), Arg,
3337 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3338 }
3339
3340 // Arguments that can be passed on register must be kept at
3341 // RegsToPass vector
3342 if (VA.isRegLoc()) {
3343 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3344
3345 // If the parameter is passed through reg $D, which splits into
3346 // two physical registers, avoid creating call site info.
3347 if (Mips::AFGR64RegClass.contains(VA.getLocReg()))
3348 continue;
3349
3350 // Collect CSInfo about which register passes which parameter.
3351 const TargetOptions &Options = DAG.getTarget().Options;
3352 if (Options.SupportsDebugEntryValues)
3353 CSInfo.emplace_back(VA.getLocReg(), i);
3354
3355 continue;
3356 }
3357
3358 // Register can't get to this point...
3359 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3359, __extension__ __PRETTY_FUNCTION__))
;
3360
3361 // emit ISD::STORE whichs stores the
3362 // parameter value to a stack Location
3363 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3364 Chain, Arg, DL, IsTailCall, DAG));
3365 }
3366
3367 // Transform all store nodes into one single node because all store
3368 // nodes are independent of each other.
3369 if (!MemOpChains.empty())
14
Taking false branch
3370 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3371
3372 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3373 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3374 // node so that legalize doesn't hack it.
3375
3376 EVT Ty = Callee.getValueType();
15
Calling 'SDValue::getValueType'
3377 bool GlobalOrExternal = false, IsCallReloc = false;
3378
3379 // The long-calls feature is ignored in case of PIC.
3380 // While we do not support -mshared / -mno-shared properly,
3381 // ignore long-calls in case of -mabicalls too.
3382 if (!Subtarget.isABICalls() && !IsPIC) {
3383 // If the function should be called using "long call",
3384 // get its address into a register to prevent using
3385 // of the `jal` instruction for the direct call.
3386 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3387 if (Subtarget.useLongCalls())
3388 Callee = Subtarget.hasSym32()
3389 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3390 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3391 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3392 bool UseLongCalls = Subtarget.useLongCalls();
3393 // If the function has long-call/far/near attribute
3394 // it overrides command line switch pased to the backend.
3395 if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3396 if (F->hasFnAttribute("long-call"))
3397 UseLongCalls = true;
3398 else if (F->hasFnAttribute("short-call"))
3399 UseLongCalls = false;
3400 }
3401 if (UseLongCalls)
3402 Callee = Subtarget.hasSym32()
3403 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3404 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3405 }
3406 }
3407
3408 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3409 if (IsPIC) {
3410 const GlobalValue *Val = G->getGlobal();
3411 InternalLinkage = Val->hasInternalLinkage();
3412
3413 if (InternalLinkage)
3414 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3415 else if (Subtarget.useXGOT()) {
3416 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3417 MipsII::MO_CALL_LO16, Chain,
3418 FuncInfo->callPtrInfo(MF, Val));
3419 IsCallReloc = true;
3420 } else {
3421 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3422 FuncInfo->callPtrInfo(MF, Val));
3423 IsCallReloc = true;
3424 }
3425 } else
3426 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3427 getPointerTy(DAG.getDataLayout()), 0,
3428 MipsII::MO_NO_FLAG);
3429 GlobalOrExternal = true;
3430 }
3431 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3432 const char *Sym = S->getSymbol();
3433
3434 if (!IsPIC) // static
3435 Callee = DAG.getTargetExternalSymbol(
3436 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
3437 else if (Subtarget.useXGOT()) {
3438 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3439 MipsII::MO_CALL_LO16, Chain,
3440 FuncInfo->callPtrInfo(MF, Sym));
3441 IsCallReloc = true;
3442 } else { // PIC
3443 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3444 FuncInfo->callPtrInfo(MF, Sym));
3445 IsCallReloc = true;
3446 }
3447
3448 GlobalOrExternal = true;
3449 }
3450
3451 SmallVector<SDValue, 8> Ops(1, Chain);
3452 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3453
3454 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3455 IsCallReloc, CLI, Callee, Chain);
3456
3457 if (IsTailCall) {
3458 MF.getFrameInfo().setHasTailCall();
3459 SDValue Ret = DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3460 DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
3461 return Ret;
3462 }
3463
3464 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3465 SDValue InFlag = Chain.getValue(1);
3466
3467 DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
3468
3469 // Create the CALLSEQ_END node in the case of where it is not a call to
3470 // memcpy.
3471 if (!(MemcpyInByVal)) {
3472 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3473 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3474 InFlag = Chain.getValue(1);
3475 }
3476
3477 // Handle result values, copying them out of physregs into vregs that we
3478 // return.
3479 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3480 InVals, CLI);
3481}
3482
3483/// LowerCallResult - Lower the result values of a call into the
3484/// appropriate copies out of appropriate physical registers.
3485SDValue MipsTargetLowering::LowerCallResult(
3486 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3487 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3488 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3489 TargetLowering::CallLoweringInfo &CLI) const {
3490 // Assign locations to each value returned by this call.
3491 SmallVector<CCValAssign, 16> RVLocs;
3492 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3493 *DAG.getContext());
3494
3495 const ExternalSymbolSDNode *ES =
3496 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3497 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3498 ES ? ES->getSymbol() : nullptr);
3499
3500 // Copy all of the result registers out of their specified physreg.
3501 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3502 CCValAssign &VA = RVLocs[i];
3503 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3503, __extension__ __PRETTY_FUNCTION__))
;
3504
3505 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3506 RVLocs[i].getLocVT(), InFlag);
3507 Chain = Val.getValue(1);
3508 InFlag = Val.getValue(2);
3509
3510 if (VA.isUpperBitsInLoc()) {
3511 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3512 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3513 unsigned Shift =
3514 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3515 Val = DAG.getNode(
3516 Shift, DL, VA.getLocVT(), Val,
3517 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3518 }
3519
3520 switch (VA.getLocInfo()) {
3521 default:
3522 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3522)
;
3523 case CCValAssign::Full:
3524 break;
3525 case CCValAssign::BCvt:
3526 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3527 break;
3528 case CCValAssign::AExt:
3529 case CCValAssign::AExtUpper:
3530 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3531 break;
3532 case CCValAssign::ZExt:
3533 case CCValAssign::ZExtUpper:
3534 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3535 DAG.getValueType(VA.getValVT()));
3536 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3537 break;
3538 case CCValAssign::SExt:
3539 case CCValAssign::SExtUpper:
3540 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3541 DAG.getValueType(VA.getValVT()));
3542 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3543 break;
3544 }
3545
3546 InVals.push_back(Val);
3547 }
3548
3549 return Chain;
3550}
3551
3552static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3553 EVT ArgVT, const SDLoc &DL,
3554 SelectionDAG &DAG) {
3555 MVT LocVT = VA.getLocVT();
3556 EVT ValVT = VA.getValVT();
3557
3558 // Shift into the upper bits if necessary.
3559 switch (VA.getLocInfo()) {
3560 default:
3561 break;
3562 case CCValAssign::AExtUpper:
3563 case CCValAssign::SExtUpper:
3564 case CCValAssign::ZExtUpper: {
3565 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3566 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3567 unsigned Opcode =
3568 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3569 Val = DAG.getNode(
3570 Opcode, DL, VA.getLocVT(), Val,
3571 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3572 break;
3573 }
3574 }
3575
3576 // If this is an value smaller than the argument slot size (32-bit for O32,
3577 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3578 // size. Extract the value and insert any appropriate assertions regarding
3579 // sign/zero extension.
3580 switch (VA.getLocInfo()) {
3581 default:
3582 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3582)
;
3583 case CCValAssign::Full:
3584 break;
3585 case CCValAssign::AExtUpper:
3586 case CCValAssign::AExt:
3587 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3588 break;
3589 case CCValAssign::SExtUpper:
3590 case CCValAssign::SExt:
3591 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3592 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3593 break;
3594 case CCValAssign::ZExtUpper:
3595 case CCValAssign::ZExt:
3596 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3597 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3598 break;
3599 case CCValAssign::BCvt:
3600 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3601 break;
3602 }
3603
3604 return Val;
3605}
3606
3607//===----------------------------------------------------------------------===//
3608// Formal Arguments Calling Convention Implementation
3609//===----------------------------------------------------------------------===//
3610/// LowerFormalArguments - transform physical registers into virtual registers
3611/// and generate load operations for arguments places on the stack.
3612SDValue MipsTargetLowering::LowerFormalArguments(
3613 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3614 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3615 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3616 MachineFunction &MF = DAG.getMachineFunction();
3617 MachineFrameInfo &MFI = MF.getFrameInfo();
3618 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3619
3620 MipsFI->setVarArgsFrameIndex(0);
3621
3622 // Used with vargs to acumulate store chains.
3623 std::vector<SDValue> OutChains;
3624
3625 // Assign locations to all of the incoming arguments.
3626 SmallVector<CCValAssign, 16> ArgLocs;
3627 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3628 *DAG.getContext());
3629 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), Align(1));
3630 const Function &Func = DAG.getMachineFunction().getFunction();
3631 Function::const_arg_iterator FuncArg = Func.arg_begin();
3632
3633 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3634 report_fatal_error(
3635 "Functions with the interrupt attribute cannot have arguments!");
3636
3637 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3638 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3639 CCInfo.getInRegsParamsCount() > 0);
3640
3641 unsigned CurArgIdx = 0;
3642 CCInfo.rewindByValRegsInfo();
3643
3644 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3645 CCValAssign &VA = ArgLocs[i];
3646 if (Ins[InsIdx].isOrigArg()) {
3647 std::advance(FuncArg, Ins[InsIdx].getOrigArgIndex() - CurArgIdx);
3648 CurArgIdx = Ins[InsIdx].getOrigArgIndex();
3649 }
3650 EVT ValVT = VA.getValVT();
3651 ISD::ArgFlagsTy Flags = Ins[InsIdx].Flags;
3652 bool IsRegLoc = VA.isRegLoc();
3653
3654 if (Flags.isByVal()) {
3655 assert(Ins[InsIdx].isOrigArg() && "Byval arguments cannot be implicit")(static_cast <bool> (Ins[InsIdx].isOrigArg() &&
"Byval arguments cannot be implicit") ? void (0) : __assert_fail
("Ins[InsIdx].isOrigArg() && \"Byval arguments cannot be implicit\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3655, __extension__ __PRETTY_FUNCTION__))
;
3656 unsigned FirstByValReg, LastByValReg;
3657 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3658 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3659
3660 assert(Flags.getByValSize() &&(static_cast <bool> (Flags.getByValSize() && "ByVal args of size 0 should have been ignored by front-end."
) ? void (0) : __assert_fail ("Flags.getByValSize() && \"ByVal args of size 0 should have been ignored by front-end.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3661, __extension__ __PRETTY_FUNCTION__))
3661 "ByVal args of size 0 should have been ignored by front-end.")(static_cast <bool> (Flags.getByValSize() && "ByVal args of size 0 should have been ignored by front-end."
) ? void (0) : __assert_fail ("Flags.getByValSize() && \"ByVal args of size 0 should have been ignored by front-end.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3661, __extension__ __PRETTY_FUNCTION__))
;
3662 assert(ByValIdx < CCInfo.getInRegsParamsCount())(static_cast <bool> (ByValIdx < CCInfo.getInRegsParamsCount
()) ? void (0) : __assert_fail ("ByValIdx < CCInfo.getInRegsParamsCount()"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3662, __extension__ __PRETTY_FUNCTION__))
;
3663 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3664 FirstByValReg, LastByValReg, VA, CCInfo);
3665 CCInfo.nextInRegsParam();
3666 continue;
3667 }
3668
3669 // Arguments stored on registers
3670 if (IsRegLoc) {
3671 MVT RegVT = VA.getLocVT();
3672 Register ArgReg = VA.getLocReg();
3673 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3674
3675 // Transform the arguments stored on
3676 // physical registers into virtual ones
3677 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3678 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3679
3680 ArgValue =
3681 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3682
3683 // Handle floating point arguments passed in integer registers and
3684 // long double arguments passed in floating point registers.
3685 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3686 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3687 (RegVT == MVT::f64 && ValVT == MVT::i64))
3688 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3689 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3690 ValVT == MVT::f64) {
3691 assert(VA.needsCustom() && "Expected custom argument for f64 split")(static_cast <bool> (VA.needsCustom() && "Expected custom argument for f64 split"
) ? void (0) : __assert_fail ("VA.needsCustom() && \"Expected custom argument for f64 split\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3691, __extension__ __PRETTY_FUNCTION__))
;
3692 CCValAssign &NextVA = ArgLocs[++i];
3693 unsigned Reg2 =
3694 addLiveIn(DAG.getMachineFunction(), NextVA.getLocReg(), RC);
3695 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3696 if (!Subtarget.isLittle())
3697 std::swap(ArgValue, ArgValue2);
3698 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3699 ArgValue, ArgValue2);
3700 }
3701
3702 InVals.push_back(ArgValue);
3703 } else { // VA.isRegLoc()
3704 MVT LocVT = VA.getLocVT();
3705
3706 assert(!VA.needsCustom() && "unexpected custom memory argument")(static_cast <bool> (!VA.needsCustom() && "unexpected custom memory argument"
) ? void (0) : __assert_fail ("!VA.needsCustom() && \"unexpected custom memory argument\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3706, __extension__ __PRETTY_FUNCTION__))
;
3707
3708 if (ABI.IsO32()) {
3709 // We ought to be able to use LocVT directly but O32 sets it to i32
3710 // when allocating floating point values to integer registers.
3711 // This shouldn't influence how we load the value into registers unless
3712 // we are targeting softfloat.
3713 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3714 LocVT = VA.getValVT();
3715 }
3716
3717 // sanity check
3718 assert(VA.isMemLoc())(static_cast <bool> (VA.isMemLoc()) ? void (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3718, __extension__ __PRETTY_FUNCTION__))
;
3719
3720 // The stack pointer offset is relative to the caller stack frame.
3721 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3722 VA.getLocMemOffset(), true);
3723
3724 // Create load nodes to retrieve arguments from the stack
3725 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3726 SDValue ArgValue = DAG.getLoad(
3727 LocVT, DL, Chain, FIN,
3728 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3729 OutChains.push_back(ArgValue.getValue(1));
3730
3731 ArgValue =
3732 UnpackFromArgumentSlot(ArgValue, VA, Ins[InsIdx].ArgVT, DL, DAG);
3733
3734 InVals.push_back(ArgValue);
3735 }
3736 }
3737
3738 for (unsigned i = 0, e = ArgLocs.size(), InsIdx = 0; i != e; ++i, ++InsIdx) {
3739
3740 if (ArgLocs[i].needsCustom()) {
3741 ++i;
3742 continue;
3743 }
3744
3745 // The mips ABIs for returning structs by value requires that we copy
3746 // the sret argument into $v0 for the return. Save the argument into
3747 // a virtual register so that we can access it from the return points.
3748 if (Ins[InsIdx].Flags.isSRet()) {
3749 unsigned Reg = MipsFI->getSRetReturnReg();
3750 if (!Reg) {
3751 Reg = MF.getRegInfo().createVirtualRegister(
3752 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3753 MipsFI->setSRetReturnReg(Reg);
3754 }
3755 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3756 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3757 break;
3758 }
3759 }
3760
3761 if (IsVarArg)
3762 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3763
3764 // All stores are grouped in one node to allow the matching between
3765 // the size of Ins and InVals. This only happens when on varg functions
3766 if (!OutChains.empty()) {
3767 OutChains.push_back(Chain);
3768 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3769 }
3770
3771 return Chain;
3772}
3773
3774//===----------------------------------------------------------------------===//
3775// Return Value Calling Convention Implementation
3776//===----------------------------------------------------------------------===//
3777
3778bool
3779MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3780 MachineFunction &MF, bool IsVarArg,
3781 const SmallVectorImpl<ISD::OutputArg> &Outs,
3782 LLVMContext &Context) const {
3783 SmallVector<CCValAssign, 16> RVLocs;
3784 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3785 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3786}
3787
3788bool MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type,
3789 bool IsSigned) const {
3790 if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32)
3791 return true;
3792
3793 return IsSigned;
3794}
3795
3796SDValue
3797MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3798 const SDLoc &DL,
3799 SelectionDAG &DAG) const {
3800 MachineFunction &MF = DAG.getMachineFunction();
3801 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3802
3803 MipsFI->setISR();
3804
3805 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3806}
3807
3808SDValue
3809MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3810 bool IsVarArg,
3811 const SmallVectorImpl<ISD::OutputArg> &Outs,
3812 const SmallVectorImpl<SDValue> &OutVals,
3813 const SDLoc &DL, SelectionDAG &DAG) const {
3814 // CCValAssign - represent the assignment of
3815 // the return value to a location
3816 SmallVector<CCValAssign, 16> RVLocs;
3817 MachineFunction &MF = DAG.getMachineFunction();
3818
3819 // CCState - Info about the registers and stack slot.
3820 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3821
3822 // Analyze return values.
3823 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3824
3825 SDValue Flag;
3826 SmallVector<SDValue, 4> RetOps(1, Chain);
3827
3828 // Copy the result values into the output registers.
3829 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3830 SDValue Val = OutVals[i];
3831 CCValAssign &VA = RVLocs[i];
3832 assert(VA.isRegLoc() && "Can only return in registers!")(static_cast <bool> (VA.isRegLoc() && "Can only return in registers!"
) ? void (0) : __assert_fail ("VA.isRegLoc() && \"Can only return in registers!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3832, __extension__ __PRETTY_FUNCTION__))
;
3833 bool UseUpperBits = false;
3834
3835 switch (VA.getLocInfo()) {
3836 default:
3837 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3837)
;
3838 case CCValAssign::Full:
3839 break;
3840 case CCValAssign::BCvt:
3841 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3842 break;
3843 case CCValAssign::AExtUpper:
3844 UseUpperBits = true;
3845 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3846 case CCValAssign::AExt:
3847 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3848 break;
3849 case CCValAssign::ZExtUpper:
3850 UseUpperBits = true;
3851 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3852 case CCValAssign::ZExt:
3853 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3854 break;
3855 case CCValAssign::SExtUpper:
3856 UseUpperBits = true;
3857 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3858 case CCValAssign::SExt:
3859 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3860 break;
3861 }
3862
3863 if (UseUpperBits) {
3864 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3865 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3866 Val = DAG.getNode(
3867 ISD::SHL, DL, VA.getLocVT(), Val,
3868 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3869 }
3870
3871 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3872
3873 // Guarantee that all emitted copies are stuck together with flags.
3874 Flag = Chain.getValue(1);
3875 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3876 }
3877
3878 // The mips ABIs for returning structs by value requires that we copy
3879 // the sret argument into $v0 for the return. We saved the argument into
3880 // a virtual register in the entry block, so now we copy the value out
3881 // and into $v0.
3882 if (MF.getFunction().hasStructRetAttr()) {
3883 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3884 unsigned Reg = MipsFI->getSRetReturnReg();
3885
3886 if (!Reg)
3887 llvm_unreachable("sret virtual register not created in the entry block")::llvm::llvm_unreachable_internal("sret virtual register not created in the entry block"
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3887)
;
3888 SDValue Val =
3889 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3890 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3891
3892 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3893 Flag = Chain.getValue(1);
3894 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3895 }
3896
3897 RetOps[0] = Chain; // Update chain.
3898
3899 // Add the flag if we have it.
3900 if (Flag.getNode())
3901 RetOps.push_back(Flag);
3902
3903 // ISRs must use "eret".
3904 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
3905 return LowerInterruptReturn(RetOps, DL, DAG);
3906
3907 // Standard return on Mips is a "jr $ra"
3908 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3909}
3910
3911//===----------------------------------------------------------------------===//
3912// Mips Inline Assembly Support
3913//===----------------------------------------------------------------------===//
3914
3915/// getConstraintType - Given a constraint letter, return the type of
3916/// constraint it is for this target.
3917MipsTargetLowering::ConstraintType
3918MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3919 // Mips specific constraints
3920 // GCC config/mips/constraints.md
3921 //
3922 // 'd' : An address register. Equivalent to r
3923 // unless generating MIPS16 code.
3924 // 'y' : Equivalent to r; retained for
3925 // backwards compatibility.
3926 // 'c' : A register suitable for use in an indirect
3927 // jump. This will always be $25 for -mabicalls.
3928 // 'l' : The lo register. 1 word storage.
3929 // 'x' : The hilo register pair. Double word storage.
3930 if (Constraint.size() == 1) {
3931 switch (Constraint[0]) {
3932 default : break;
3933 case 'd':
3934 case 'y':
3935 case 'f':
3936 case 'c':
3937 case 'l':
3938 case 'x':
3939 return C_RegisterClass;
3940 case 'R':
3941 return C_Memory;
3942 }
3943 }
3944
3945 if (Constraint == "ZC")
3946 return C_Memory;
3947
3948 return TargetLowering::getConstraintType(Constraint);
3949}
3950
3951/// Examine constraint type and operand type and determine a weight value.
3952/// This object must already have been set up with the operand type
3953/// and the current alternative constraint selected.
3954TargetLowering::ConstraintWeight
3955MipsTargetLowering::getSingleConstraintMatchWeight(
3956 AsmOperandInfo &info, const char *constraint) const {
3957 ConstraintWeight weight = CW_Invalid;
3958 Value *CallOperandVal = info.CallOperandVal;
3959 // If we don't have a value, we can't do a match,
3960 // but allow it at the lowest weight.
3961 if (!CallOperandVal)
3962 return CW_Default;
3963 Type *type = CallOperandVal->getType();
3964 // Look at the constraint type.
3965 switch (*constraint) {
3966 default:
3967 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3968 break;
3969 case 'd':
3970 case 'y':
3971 if (type->isIntegerTy())
3972 weight = CW_Register;
3973 break;
3974 case 'f': // FPU or MSA register
3975 if (Subtarget.hasMSA() && type->isVectorTy() &&
3976 type->getPrimitiveSizeInBits().getFixedSize() == 128)
3977 weight = CW_Register;
3978 else if (type->isFloatTy())
3979 weight = CW_Register;
3980 break;
3981 case 'c': // $25 for indirect jumps
3982 case 'l': // lo register
3983 case 'x': // hilo register pair
3984 if (type->isIntegerTy())
3985 weight = CW_SpecificReg;
3986 break;
3987 case 'I': // signed 16 bit immediate
3988 case 'J': // integer zero
3989 case 'K': // unsigned 16 bit immediate
3990 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3991 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3992 case 'O': // signed 15 bit immediate (+- 16383)
3993 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3994 if (isa<ConstantInt>(CallOperandVal))
3995 weight = CW_Constant;
3996 break;
3997 case 'R':
3998 weight = CW_Memory;
3999 break;
4000 }
4001 return weight;
4002}
4003
4004/// This is a helper function to parse a physical register string and split it
4005/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
4006/// that is returned indicates whether parsing was successful. The second flag
4007/// is true if the numeric part exists.
4008static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
4009 unsigned long long &Reg) {
4010 if (C.front() != '{' || C.back() != '}')
4011 return std::make_pair(false, false);
4012
4013 // Search for the first numeric character.
4014 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
4015 I = std::find_if(B, E, isdigit);
4016
4017 Prefix = StringRef(B, I - B);
4018
4019 // The second flag is set to false if no numeric characters were found.
4020 if (I == E)
4021 return std::make_pair(true, false);
4022
4023 // Parse the numeric characters.
4024 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
4025 true);
4026}
4027
4028EVT MipsTargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
4029 ISD::NodeType) const {
4030 bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
4031 EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
4032 return VT.bitsLT(MinVT) ? MinVT : VT;
4033}
4034
4035std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
4036parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
4037 const TargetRegisterInfo *TRI =
4038 Subtarget.getRegisterInfo();
4039 const TargetRegisterClass *RC;
4040 StringRef Prefix;
4041 unsigned long long Reg;
4042
4043 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
4044
4045 if (!R.first)
4046 return std::make_pair(0U, nullptr);
4047
4048 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
4049 // No numeric characters follow "hi" or "lo".
4050 if (R.second)
4051 return std::make_pair(0U, nullptr);
4052
4053 RC = TRI->getRegClass(Prefix == "hi" ?
4054 Mips::HI32RegClassID : Mips::LO32RegClassID);
4055 return std::make_pair(*(RC->begin()), RC);
4056 } else if (Prefix.startswith("$msa")) {
4057 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
4058
4059 // No numeric characters follow the name.
4060 if (R.second)
4061 return std::make_pair(0U, nullptr);
4062
4063 Reg = StringSwitch<unsigned long long>(Prefix)
4064 .Case("$msair", Mips::MSAIR)
4065 .Case("$msacsr", Mips::MSACSR)
4066 .Case("$msaaccess", Mips::MSAAccess)
4067 .Case("$msasave", Mips::MSASave)
4068 .Case("$msamodify", Mips::MSAModify)
4069 .Case("$msarequest", Mips::MSARequest)
4070 .Case("$msamap", Mips::MSAMap)
4071 .Case("$msaunmap", Mips::MSAUnmap)
4072 .Default(0);
4073
4074 if (!Reg)
4075 return std::make_pair(0U, nullptr);
4076
4077 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
4078 return std::make_pair(Reg, RC);
4079 }
4080
4081 if (!R.second)
4082 return std::make_pair(0U, nullptr);
4083
4084 if (Prefix == "$f") { // Parse $f0-$f31.
4085 // If the size of FP registers is 64-bit or Reg is an even number, select
4086 // the 64-bit register class. Otherwise, select the 32-bit register class.
4087 if (VT == MVT::Other)
4088 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
4089
4090 RC = getRegClassFor(VT);
4091
4092 if (RC == &Mips::AFGR64RegClass) {
4093 assert(Reg % 2 == 0)(static_cast <bool> (Reg % 2 == 0) ? void (0) : __assert_fail
("Reg % 2 == 0", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4093, __extension__ __PRETTY_FUNCTION__))
;
4094 Reg >>= 1;
4095 }
4096 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
4097 RC = TRI->getRegClass(Mips::FCCRegClassID);
4098 else if (Prefix == "$w") { // Parse $w0-$w31.
4099 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
4100 } else { // Parse $0-$31.
4101 assert(Prefix == "$")(static_cast <bool> (Prefix == "$") ? void (0) : __assert_fail
("Prefix == \"$\"", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4101, __extension__ __PRETTY_FUNCTION__))
;
4102 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
4103 }
4104
4105 assert(Reg < RC->getNumRegs())(static_cast <bool> (Reg < RC->getNumRegs()) ? void
(0) : __assert_fail ("Reg < RC->getNumRegs()", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4105, __extension__ __PRETTY_FUNCTION__))
;
4106 return std::make_pair(*(RC->begin() + Reg), RC);
4107}
4108
4109/// Given a register class constraint, like 'r', if this corresponds directly
4110/// to an LLVM register class, return a register of 0 and the register class
4111/// pointer.
4112std::pair<unsigned, const TargetRegisterClass *>
4113MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4114 StringRef Constraint,
4115 MVT VT) const {
4116 if (Constraint.size() == 1) {
4117 switch (Constraint[0]) {
4118 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
4119 case 'y': // Same as 'r'. Exists for compatibility.
4120 case 'r':
4121 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
4122 if (Subtarget.inMips16Mode())
4123 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
4124 return std::make_pair(0U, &Mips::GPR32RegClass);
4125 }
4126 if (VT == MVT::i64 && !Subtarget.isGP64bit())
4127 return std::make_pair(0U, &Mips::GPR32RegClass);
4128 if (VT == MVT::i64 && Subtarget.isGP64bit())
4129 return std::make_pair(0U, &Mips::GPR64RegClass);
4130 // This will generate an error message
4131 return std::make_pair(0U, nullptr);
4132 case 'f': // FPU or MSA register
4133 if (VT == MVT::v16i8)
4134 return std::make_pair(0U, &Mips::MSA128BRegClass);
4135 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
4136 return std::make_pair(0U, &Mips::MSA128HRegClass);
4137 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
4138 return std::make_pair(0U, &Mips::MSA128WRegClass);
4139 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
4140 return std::make_pair(0U, &Mips::MSA128DRegClass);
4141 else if (VT == MVT::f32)
4142 return std::make_pair(0U, &Mips::FGR32RegClass);
4143 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
4144 if (Subtarget.isFP64bit())
4145 return std::make_pair(0U, &Mips::FGR64RegClass);
4146 return std::make_pair(0U, &Mips::AFGR64RegClass);
4147 }
4148 break;
4149 case 'c': // register suitable for indirect jump
4150 if (VT == MVT::i32)
4151 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
4152 if (VT == MVT::i64)
4153 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
4154 // This will generate an error message
4155 return std::make_pair(0U, nullptr);
4156 case 'l': // use the `lo` register to store values
4157 // that are no bigger than a word
4158 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4159 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4160 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4161 case 'x': // use the concatenated `hi` and `lo` registers
4162 // to store doubleword values
4163 // Fixme: Not triggering the use of both hi and low
4164 // This will generate an error message
4165 return std::make_pair(0U, nullptr);
4166 }
4167 }
4168
4169 if (!Constraint.empty()) {
4170 std::pair<unsigned, const TargetRegisterClass *> R;
4171 R = parseRegForInlineAsmConstraint(Constraint, VT);
4172
4173 if (R.second)
4174 return R;
4175 }
4176
4177 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4178}
4179
4180/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4181/// vector. If it is invalid, don't add anything to Ops.
4182void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4183 std::string &Constraint,
4184 std::vector<SDValue>&Ops,
4185 SelectionDAG &DAG) const {
4186 SDLoc DL(Op);
4187 SDValue Result;
4188
4189 // Only support length 1 constraints for now.
4190 if (Constraint.length() > 1) return;
4191
4192 char ConstraintLetter = Constraint[0];
4193 switch (ConstraintLetter) {
4194 default: break; // This will fall through to the generic implementation
4195 case 'I': // Signed 16 bit constant
4196 // If this fails, the parent routine will give an error
4197 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4198 EVT Type = Op.getValueType();
4199 int64_t Val = C->getSExtValue();
4200 if (isInt<16>(Val)) {
4201 Result = DAG.getTargetConstant(Val, DL, Type);
4202 break;
4203 }
4204 }
4205 return;
4206 case 'J': // integer zero
4207 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4208 EVT Type = Op.getValueType();
4209 int64_t Val = C->getZExtValue();
4210 if (Val == 0) {
4211 Result = DAG.getTargetConstant(0, DL, Type);
4212 break;
4213 }
4214 }
4215 return;
4216 case 'K': // unsigned 16 bit immediate
4217 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4218 EVT Type = Op.getValueType();
4219 uint64_t Val = (uint64_t)C->getZExtValue();
4220 if (isUInt<16>(Val)) {
4221 Result = DAG.getTargetConstant(Val, DL, Type);
4222 break;
4223 }
4224 }
4225 return;
4226 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4227 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4228 EVT Type = Op.getValueType();
4229 int64_t Val = C->getSExtValue();
4230 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4231 Result = DAG.getTargetConstant(Val, DL, Type);
4232 break;
4233 }
4234 }
4235 return;
4236 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4237 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4238 EVT Type = Op.getValueType();
4239 int64_t Val = C->getSExtValue();
4240 if ((Val >= -65535) && (Val <= -1)) {
4241 Result = DAG.getTargetConstant(Val, DL, Type);
4242 break;
4243 }
4244 }
4245 return;
4246 case 'O': // signed 15 bit immediate
4247 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4248 EVT Type = Op.getValueType();
4249 int64_t Val = C->getSExtValue();
4250 if ((isInt<15>(Val))) {
4251 Result = DAG.getTargetConstant(Val, DL, Type);
4252 break;
4253 }
4254 }
4255 return;
4256 case 'P': // immediate in the range of 1 to 65535 (inclusive)
4257 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4258 EVT Type = Op.getValueType();
4259 int64_t Val = C->getSExtValue();
4260 if ((Val <= 65535) && (Val >= 1)) {
4261 Result = DAG.getTargetConstant(Val, DL, Type);
4262 break;
4263 }
4264 }
4265 return;
4266 }
4267
4268 if (Result.getNode()) {
4269 Ops.push_back(Result);
4270 return;
4271 }
4272
4273 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4274}
4275
4276bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4277 const AddrMode &AM, Type *Ty,
4278 unsigned AS,
4279 Instruction *I) const {
4280 // No global is ever allowed as a base.
4281 if (AM.BaseGV)
4282 return false;
4283
4284 switch (AM.Scale) {
4285 case 0: // "r+i" or just "i", depending on HasBaseReg.
4286 break;
4287 case 1:
4288 if (!AM.HasBaseReg) // allow "r+i".
4289 break;
4290 return false; // disallow "r+r" or "r+r+i".
4291 default:
4292 return false;
4293 }
4294
4295 return true;
4296}
4297
4298bool
4299MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4300 // The Mips target isn't yet aware of offsets.
4301 return false;
4302}
4303
4304EVT MipsTargetLowering::getOptimalMemOpType(
4305 const MemOp &Op, const AttributeList &FuncAttributes) const {
4306 if (Subtarget.hasMips64())
4307 return MVT::i64;
4308
4309 return MVT::i32;
4310}
4311
4312bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4313 bool ForCodeSize) const {
4314 if (VT != MVT::f32 && VT != MVT::f64)
4315 return false;
4316 if (Imm.isNegZero())
4317 return false;
4318 return Imm.isZero();
4319}
4320
4321unsigned MipsTargetLowering::getJumpTableEncoding() const {
4322
4323 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4324 if (ABI.IsN64() && isPositionIndependent())
4325 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4326
4327 return TargetLowering::getJumpTableEncoding();
4328}
4329
4330bool MipsTargetLowering::useSoftFloat() const {
4331 return Subtarget.useSoftFloat();
4332}
4333
4334void MipsTargetLowering::copyByValRegs(
4335 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4336 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4337 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4338 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4339 MipsCCState &State) const {
4340 MachineFunction &MF = DAG.getMachineFunction();
4341 MachineFrameInfo &MFI = MF.getFrameInfo();
4342 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4343 unsigned NumRegs = LastReg - FirstReg;
4344 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4345 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4346 int FrameObjOffset;
4347 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4348
4349 if (RegAreaSize)
4350 FrameObjOffset =
4351 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4352 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4353 else
4354 FrameObjOffset = VA.getLocMemOffset();
4355
4356 // Create frame object.
4357 EVT PtrTy = getPointerTy(DAG.getDataLayout());
4358 // Make the fixed object stored to mutable so that the load instructions
4359 // referencing it have their memory dependencies added.
4360 // Set the frame object as isAliased which clears the underlying objects
4361 // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4362 // stores as dependencies for loads referencing this fixed object.
4363 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4364 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4365 InVals.push_back(FIN);
4366
4367 if (!NumRegs)
4368 return;
4369
4370 // Copy arg registers.
4371 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4372 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4373
4374 for (unsigned I = 0; I < NumRegs; ++I) {
4375 unsigned ArgReg = ByValArgRegs[FirstReg + I];
4376 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4377 unsigned Offset = I * GPRSizeInBytes;
4378 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4379 DAG.getConstant(Offset, DL, PtrTy));
4380 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4381 StorePtr, MachinePointerInfo(FuncArg, Offset));
4382 OutChains.push_back(Store);
4383 }
4384}
4385
4386// Copy byVal arg to registers and stack.
4387void MipsTargetLowering::passByValArg(
4388 SDValue Chain, const SDLoc &DL,
4389 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4390 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4391 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4392 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4393 const CCValAssign &VA) const {
4394 unsigned ByValSizeInBytes = Flags.getByValSize();
4395 unsigned OffsetInBytes = 0; // From beginning of struct
4396 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4397 Align Alignment =
4398 std::min(Flags.getNonZeroByValAlign(), Align(RegSizeInBytes));
4399 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4400 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4401 unsigned NumRegs = LastReg - FirstReg;
4402
4403 if (NumRegs) {
4404 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4405 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4406 unsigned I = 0;
4407
4408 // Copy words to registers.
4409 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4410 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4411 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4412 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4413 MachinePointerInfo(), Alignment);
4414 MemOpChains.push_back(LoadVal.getValue(1));
4415 unsigned ArgReg = ArgRegs[FirstReg + I];
4416 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4417 }
4418
4419 // Return if the struct has been fully copied.
4420 if (ByValSizeInBytes == OffsetInBytes)
4421 return;
4422
4423 // Copy the remainder of the byval argument with sub-word loads and shifts.
4424 if (LeftoverBytes) {
4425 SDValue Val;
4426
4427 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4428 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4429 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4430
4431 if (RemainingSizeInBytes < LoadSizeInBytes)
4432 continue;
4433
4434 // Load subword.
4435 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4436 DAG.getConstant(OffsetInBytes, DL,
4437 PtrTy));
4438 SDValue LoadVal = DAG.getExtLoad(
4439 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4440 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4441 MemOpChains.push_back(LoadVal.getValue(1));
4442
4443 // Shift the loaded value.
4444 unsigned Shamt;
4445
4446 if (isLittle)
4447 Shamt = TotalBytesLoaded * 8;
4448 else
4449 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4450
4451 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4452 DAG.getConstant(Shamt, DL, MVT::i32));
4453
4454 if (Val.getNode())
4455 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4456 else
4457 Val = Shift;
4458
4459 OffsetInBytes += LoadSizeInBytes;
4460 TotalBytesLoaded += LoadSizeInBytes;
4461 Alignment = std::min(Alignment, Align(LoadSizeInBytes));
4462 }
4463
4464 unsigned ArgReg = ArgRegs[FirstReg + I];
4465 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4466 return;
4467 }
4468 }
4469
4470 // Copy remainder of byval arg to it with memcpy.
4471 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4472 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4473 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4474 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4475 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4476 Chain = DAG.getMemcpy(
4477 Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, DL, PtrTy),
4478 Align(Alignment), /*isVolatile=*/false, /*AlwaysInline=*/false,
4479 /*isTailCall=*/false, MachinePointerInfo(), MachinePointerInfo());
4480 MemOpChains.push_back(Chain);
4481}
4482
4483void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4484 SDValue Chain, const SDLoc &DL,
4485 SelectionDAG &DAG,
4486 CCState &State) const {
4487 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
4488 unsigned Idx = State.getFirstUnallocated(ArgRegs);
4489 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4490 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4491 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4492 MachineFunction &MF = DAG.getMachineFunction();
4493 MachineFrameInfo &MFI = MF.getFrameInfo();
4494 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4495
4496 // Offset of the first variable argument from stack pointer.
4497 int VaArgOffset;
4498
4499 if (ArgRegs.size() == Idx)
4500 VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4501 else {
4502 VaArgOffset =
4503 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4504 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4505 }
4506
4507 // Record the frame index of the first variable argument
4508 // which is a value necessary to VASTART.
4509 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4510 MipsFI->setVarArgsFrameIndex(FI);
4511
4512 // Copy the integer registers that have not been used for argument passing
4513 // to the argument register save area. For O32, the save area is allocated
4514 // in the caller's stack frame, while for N32/64, it is allocated in the
4515 // callee's stack frame.
4516 for (unsigned I = Idx; I < ArgRegs.size();
4517 ++I, VaArgOffset += RegSizeInBytes) {
4518 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4519 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4520 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4521 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4522 SDValue Store =
4523 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4524 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4525 (Value *)nullptr);
4526 OutChains.push_back(Store);
4527 }
4528}
4529
4530void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4531 Align Alignment) const {
4532 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4533
4534 assert(Size && "Byval argument's size shouldn't be 0.")(static_cast <bool> (Size && "Byval argument's size shouldn't be 0."
) ? void (0) : __assert_fail ("Size && \"Byval argument's size shouldn't be 0.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4534, __extension__ __PRETTY_FUNCTION__))
;
4535
4536 Alignment = std::min(Alignment, TFL->getStackAlign());
4537
4538 unsigned FirstReg = 0;
4539 unsigned NumRegs = 0;
4540
4541 if (State->getCallingConv() != CallingConv::Fast) {
4542 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4543 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4544 // FIXME: The O32 case actually describes no shadow registers.
4545 const MCPhysReg *ShadowRegs =
4546 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4547
4548 // We used to check the size as well but we can't do that anymore since
4549 // CCState::HandleByVal() rounds up the size after calling this function.
4550 assert((static_cast <bool> (Alignment >= Align(RegSizeInBytes
) && "Byval argument's alignment should be a multiple of RegSizeInBytes."
) ? void (0) : __assert_fail ("Alignment >= Align(RegSizeInBytes) && \"Byval argument's alignment should be a multiple of RegSizeInBytes.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4552, __extension__ __PRETTY_FUNCTION__))
4551 Alignment >= Align(RegSizeInBytes) &&(static_cast <bool> (Alignment >= Align(RegSizeInBytes
) && "Byval argument's alignment should be a multiple of RegSizeInBytes."
) ? void (0) : __assert_fail ("Alignment >= Align(RegSizeInBytes) && \"Byval argument's alignment should be a multiple of RegSizeInBytes.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4552, __extension__ __PRETTY_FUNCTION__))
4552 "Byval argument's alignment should be a multiple of RegSizeInBytes.")(static_cast <bool> (Alignment >= Align(RegSizeInBytes
) && "Byval argument's alignment should be a multiple of RegSizeInBytes."
) ? void (0) : __assert_fail ("Alignment >= Align(RegSizeInBytes) && \"Byval argument's alignment should be a multiple of RegSizeInBytes.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4552, __extension__ __PRETTY_FUNCTION__))
;
4553
4554 FirstReg = State->getFirstUnallocated(IntArgRegs);
4555
4556 // If Alignment > RegSizeInBytes, the first arg register must be even.
4557 // FIXME: This condition happens to do the right thing but it's not the
4558 // right way to test it. We want to check that the stack frame offset
4559 // of the register is aligned.
4560 if ((Alignment > RegSizeInBytes) && (FirstReg % 2)) {
4561 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4562 ++FirstReg;
4563 }
4564
4565 // Mark the registers allocated.
4566 Size = alignTo(Size, RegSizeInBytes);
4567 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4568 Size -= RegSizeInBytes, ++I, ++NumRegs)
4569 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4570 }
4571
4572 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4573}
4574
4575MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4576 MachineBasicBlock *BB,
4577 bool isFPCmp,
4578 unsigned Opc) const {
4579 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&(static_cast <bool> (!(Subtarget.hasMips4() || Subtarget
.hasMips32()) && "Subtarget already supports SELECT nodes with the use of"
"conditional-move instructions.") ? void (0) : __assert_fail
("!(Subtarget.hasMips4() || Subtarget.hasMips32()) && \"Subtarget already supports SELECT nodes with the use of\" \"conditional-move instructions.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4581, __extension__ __PRETTY_FUNCTION__))
4580 "Subtarget already supports SELECT nodes with the use of"(static_cast <bool> (!(Subtarget.hasMips4() || Subtarget
.hasMips32()) && "Subtarget already supports SELECT nodes with the use of"
"conditional-move instructions.") ? void (0) : __assert_fail
("!(Subtarget.hasMips4() || Subtarget.hasMips32()) && \"Subtarget already supports SELECT nodes with the use of\" \"conditional-move instructions.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4581, __extension__ __PRETTY_FUNCTION__))
4581 "conditional-move instructions.")(static_cast <bool> (!(Subtarget.hasMips4() || Subtarget
.hasMips32()) && "Subtarget already supports SELECT nodes with the use of"
"conditional-move instructions.") ? void (0) : __assert_fail
("!(Subtarget.hasMips4() || Subtarget.hasMips32()) && \"Subtarget already supports SELECT nodes with the use of\" \"conditional-move instructions.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4581, __extension__ __PRETTY_FUNCTION__))
;
4582
4583 const TargetInstrInfo *TII =
4584 Subtarget.getInstrInfo();
4585 DebugLoc DL = MI.getDebugLoc();
4586
4587 // To "insert" a SELECT instruction, we actually have to insert the
4588 // diamond control-flow pattern. The incoming instruction knows the
4589 // destination vreg to set, the condition code register to branch on, the
4590 // true/false values to select between, and a branch opcode to use.
4591 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4592 MachineFunction::iterator It = ++BB->getIterator();
4593
4594 // thisMBB:
4595 // ...
4596 // TrueVal = ...
4597 // setcc r1, r2, r3
4598 // bNE r1, r0, copy1MBB
4599 // fallthrough --> copy0MBB
4600 MachineBasicBlock *thisMBB = BB;
4601 MachineFunction *F = BB->getParent();
4602 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4603 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4604 F->insert(It, copy0MBB);
4605 F->insert(It, sinkMBB);
4606
4607 // Transfer the remainder of BB and its successor edges to sinkMBB.
4608 sinkMBB->splice(sinkMBB->begin(), BB,
4609 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4610 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4611
4612 // Next, add the true and fallthrough blocks as its successors.
4613 BB->addSuccessor(copy0MBB);
4614 BB->addSuccessor(sinkMBB);
4615
4616 if (isFPCmp) {
4617 // bc1[tf] cc, sinkMBB
4618 BuildMI(BB, DL, TII->get(Opc))
4619 .addReg(MI.getOperand(1).getReg())
4620 .addMBB(sinkMBB);
4621 } else {
4622 // bne rs, $0, sinkMBB
4623 BuildMI(BB, DL, TII->get(Opc))
4624 .addReg(MI.getOperand(1).getReg())
4625 .addReg(Mips::ZERO)
4626 .addMBB(sinkMBB);
4627 }
4628
4629 // copy0MBB:
4630 // %FalseValue = ...
4631 // # fallthrough to sinkMBB
4632 BB = copy0MBB;
4633
4634 // Update machine-CFG edges
4635 BB->addSuccessor(sinkMBB);
4636
4637 // sinkMBB:
4638 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4639 // ...
4640 BB = sinkMBB;
4641
4642 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4643 .addReg(MI.getOperand(2).getReg())
4644 .addMBB(thisMBB)
4645 .addReg(MI.getOperand(3).getReg())
4646 .addMBB(copy0MBB);
4647
4648 MI.eraseFromParent(); // The pseudo instruction is gone now.
4649
4650 return BB;
4651}
4652
4653MachineBasicBlock *
4654MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI,
4655 MachineBasicBlock *BB) const {
4656 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&(static_cast <bool> (!(Subtarget.hasMips4() || Subtarget
.hasMips32()) && "Subtarget already supports SELECT nodes with the use of"
"conditional-move instructions.") ? void (0) : __assert_fail
("!(Subtarget.hasMips4() || Subtarget.hasMips32()) && \"Subtarget already supports SELECT nodes with the use of\" \"conditional-move instructions.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4658, __extension__ __PRETTY_FUNCTION__))
4657 "Subtarget already supports SELECT nodes with the use of"(static_cast <bool> (!(Subtarget.hasMips4() || Subtarget
.hasMips32()) && "Subtarget already supports SELECT nodes with the use of"
"conditional-move instructions.") ? void (0) : __assert_fail
("!(Subtarget.hasMips4() || Subtarget.hasMips32()) && \"Subtarget already supports SELECT nodes with the use of\" \"conditional-move instructions.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4658, __extension__ __PRETTY_FUNCTION__))
4658 "conditional-move instructions.")(static_cast <bool> (!(Subtarget.hasMips4() || Subtarget
.hasMips32()) && "Subtarget already supports SELECT nodes with the use of"
"conditional-move instructions.") ? void (0) : __assert_fail
("!(Subtarget.hasMips4() || Subtarget.hasMips32()) && \"Subtarget already supports SELECT nodes with the use of\" \"conditional-move instructions.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4658, __extension__ __PRETTY_FUNCTION__))
;
4659
4660 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4661 DebugLoc DL = MI.getDebugLoc();
4662
4663 // D_SELECT substitutes two SELECT nodes that goes one after another and
4664 // have the same condition operand. On machines which don't have
4665 // conditional-move instruction, it reduces unnecessary branch instructions
4666 // which are result of using two diamond patterns that are result of two
4667 // SELECT pseudo instructions.
4668 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4669 MachineFunction::iterator It = ++BB->getIterator();
4670
4671 // thisMBB:
4672 // ...
4673 // TrueVal = ...
4674 // setcc r1, r2, r3
4675 // bNE r1, r0, copy1MBB
4676 // fallthrough --> copy0MBB
4677 MachineBasicBlock *thisMBB = BB;
4678 MachineFunction *F = BB->getParent();
4679 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4680 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4681 F->insert(It, copy0MBB);
4682 F->insert(It, sinkMBB);
4683
4684 // Transfer the remainder of BB and its successor edges to sinkMBB.
4685 sinkMBB->splice(sinkMBB->begin(), BB,
4686 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4687 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4688
4689 // Next, add the true and fallthrough blocks as its successors.
4690 BB->addSuccessor(copy0MBB);
4691 BB->addSuccessor(sinkMBB);
4692
4693 // bne rs, $0, sinkMBB
4694 BuildMI(BB, DL, TII->get(Mips::BNE))
4695 .addReg(MI.getOperand(2).getReg())
4696 .addReg(Mips::ZERO)
4697 .addMBB(sinkMBB);
4698
4699 // copy0MBB:
4700 // %FalseValue = ...
4701 // # fallthrough to sinkMBB
4702 BB = copy0MBB;
4703
4704 // Update machine-CFG edges
4705 BB->addSuccessor(sinkMBB);
4706
4707 // sinkMBB:
4708 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4709 // ...
4710 BB = sinkMBB;
4711
4712 // Use two PHI nodes to select two reults
4713 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4714 .addReg(MI.getOperand(3).getReg())
4715 .addMBB(thisMBB)
4716 .addReg(MI.getOperand(5).getReg())
4717 .addMBB(copy0MBB);
4718 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg())
4719 .addReg(MI.getOperand(4).getReg())
4720 .addMBB(thisMBB)
4721 .addReg(MI.getOperand(6).getReg())
4722 .addMBB(copy0MBB);
4723
4724 MI.eraseFromParent(); // The pseudo instruction is gone now.
4725
4726 return BB;
4727}
4728
4729// FIXME? Maybe this could be a TableGen attribute on some registers and
4730// this table could be generated automatically from RegInfo.
4731Register
4732MipsTargetLowering::getRegisterByName(const char *RegName, LLT VT,
4733 const MachineFunction &MF) const {
4734 // Named registers is expected to be fairly rare. For now, just support $28
4735 // since the linux kernel uses it.
4736 if (Subtarget.isGP64bit()) {
4737 Register Reg = StringSwitch<Register>(RegName)
4738 .Case("$28", Mips::GP_64)
4739 .Default(Register());
4740 if (Reg)
4741 return Reg;
4742 } else {
4743 Register Reg = StringSwitch<Register>(RegName)
4744 .Case("$28", Mips::GP)
4745 .Default(Register());
4746 if (Reg)
4747 return Reg;
4748 }
4749 report_fatal_error("Invalid register name global variable");
4750}
4751
4752MachineBasicBlock *MipsTargetLowering::emitLDR_W(MachineInstr &MI,
4753 MachineBasicBlock *BB) const {
4754 MachineFunction *MF = BB->getParent();
4755 MachineRegisterInfo &MRI = MF->getRegInfo();
4756 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4757 const bool IsLittle = Subtarget.isLittle();
4758 DebugLoc DL = MI.getDebugLoc();
4759
4760 Register Dest = MI.getOperand(0).getReg();
4761 Register Address = MI.getOperand(1).getReg();
4762 unsigned Imm = MI.getOperand(2).getImm();
4763
4764 MachineBasicBlock::iterator I(MI);
4765
4766 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4767 // Mips release 6 can load from adress that is not naturally-aligned.
4768 Register Temp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4769 BuildMI(*BB, I, DL, TII->get(Mips::LW))
4770 .addDef(Temp)
4771 .addUse(Address)
4772 .addImm(Imm);
4773 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(Temp);
4774 } else {
4775 // Mips release 5 needs to use instructions that can load from an unaligned
4776 // memory address.
4777 Register LoadHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4778 Register LoadFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4779 Register Undef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4780 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(Undef);
4781 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
4782 .addDef(LoadHalf)
4783 .addUse(Address)
4784 .addImm(Imm + (IsLittle ? 0 : 3))
4785 .addUse(Undef);
4786 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
4787 .addDef(LoadFull)
4788 .addUse(Address)
4789 .addImm(Imm + (IsLittle ? 3 : 0))
4790 .addUse(LoadHalf);
4791 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Dest).addUse(LoadFull);
4792 }
4793
4794 MI.eraseFromParent();
4795 return BB;
4796}
4797
4798MachineBasicBlock *MipsTargetLowering::emitLDR_D(MachineInstr &MI,
4799 MachineBasicBlock *BB) const {
4800 MachineFunction *MF = BB->getParent();
4801 MachineRegisterInfo &MRI = MF->getRegInfo();
4802 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4803 const bool IsLittle = Subtarget.isLittle();
4804 DebugLoc DL = MI.getDebugLoc();
4805
4806 Register Dest = MI.getOperand(0).getReg();
4807 Register Address = MI.getOperand(1).getReg();
4808 unsigned Imm = MI.getOperand(2).getImm();
4809
4810 MachineBasicBlock::iterator I(MI);
4811
4812 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4813 // Mips release 6 can load from adress that is not naturally-aligned.
4814 if (Subtarget.isGP64bit()) {
4815 Register Temp = MRI.createVirtualRegister(&Mips::GPR64RegClass);
4816 BuildMI(*BB, I, DL, TII->get(Mips::LD))
4817 .addDef(Temp)
4818 .addUse(Address)
4819 .addImm(Imm);
4820 BuildMI(*BB, I, DL, TII->get(Mips::FILL_D)).addDef(Dest).addUse(Temp);
4821 } else {
4822 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4823 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4824 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4825 BuildMI(*BB, I, DL, TII->get(Mips::LW))
4826 .addDef(Lo)
4827 .addUse(Address)
4828 .addImm(Imm + (IsLittle ? 0 : 4));
4829 BuildMI(*BB, I, DL, TII->get(Mips::LW))
4830 .addDef(Hi)
4831 .addUse(Address)
4832 .addImm(Imm + (IsLittle ? 4 : 0));
4833 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(Lo);
4834 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
4835 .addUse(Wtemp)
4836 .addUse(Hi)
4837 .addImm(1);
4838 }
4839 } else {
4840 // Mips release 5 needs to use instructions that can load from an unaligned
4841 // memory address.
4842 Register LoHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4843 Register LoFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4844 Register LoUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4845 Register HiHalf = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4846 Register HiFull = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4847 Register HiUndef = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4848 Register Wtemp = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4849 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(LoUndef);
4850 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
4851 .addDef(LoHalf)
4852 .addUse(Address)
4853 .addImm(Imm + (IsLittle ? 0 : 7))
4854 .addUse(LoUndef);
4855 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
4856 .addDef(LoFull)
4857 .addUse(Address)
4858 .addImm(Imm + (IsLittle ? 3 : 4))
4859 .addUse(LoHalf);
4860 BuildMI(*BB, I, DL, TII->get(Mips::IMPLICIT_DEF)).addDef(HiUndef);
4861 BuildMI(*BB, I, DL, TII->get(Mips::LWR))
4862 .addDef(HiHalf)
4863 .addUse(Address)
4864 .addImm(Imm + (IsLittle ? 4 : 3))
4865 .addUse(HiUndef);
4866 BuildMI(*BB, I, DL, TII->get(Mips::LWL))
4867 .addDef(HiFull)
4868 .addUse(Address)
4869 .addImm(Imm + (IsLittle ? 7 : 0))
4870 .addUse(HiHalf);
4871 BuildMI(*BB, I, DL, TII->get(Mips::FILL_W)).addDef(Wtemp).addUse(LoFull);
4872 BuildMI(*BB, I, DL, TII->get(Mips::INSERT_W), Dest)
4873 .addUse(Wtemp)
4874 .addUse(HiFull)
4875 .addImm(1);
4876 }
4877
4878 MI.eraseFromParent();
4879 return BB;
4880}
4881
4882MachineBasicBlock *MipsTargetLowering::emitSTR_W(MachineInstr &MI,
4883 MachineBasicBlock *BB) const {
4884 MachineFunction *MF = BB->getParent();
4885 MachineRegisterInfo &MRI = MF->getRegInfo();
4886 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4887 const bool IsLittle = Subtarget.isLittle();
4888 DebugLoc DL = MI.getDebugLoc();
4889
4890 Register StoreVal = MI.getOperand(0).getReg();
4891 Register Address = MI.getOperand(1).getReg();
4892 unsigned Imm = MI.getOperand(2).getImm();
4893
4894 MachineBasicBlock::iterator I(MI);
4895
4896 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4897 // Mips release 6 can store to adress that is not naturally-aligned.
4898 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4899 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4900 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(BitcastW).addUse(StoreVal);
4901 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4902 .addDef(Tmp)
4903 .addUse(BitcastW)
4904 .addImm(0);
4905 BuildMI(*BB, I, DL, TII->get(Mips::SW))
4906 .addUse(Tmp)
4907 .addUse(Address)
4908 .addImm(Imm);
4909 } else {
4910 // Mips release 5 needs to use instructions that can store to an unaligned
4911 // memory address.
4912 Register Tmp = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4913 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4914 .addDef(Tmp)
4915 .addUse(StoreVal)
4916 .addImm(0);
4917 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
4918 .addUse(Tmp)
4919 .addUse(Address)
4920 .addImm(Imm + (IsLittle ? 0 : 3));
4921 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
4922 .addUse(Tmp)
4923 .addUse(Address)
4924 .addImm(Imm + (IsLittle ? 3 : 0));
4925 }
4926
4927 MI.eraseFromParent();
4928
4929 return BB;
4930}
4931
4932MachineBasicBlock *MipsTargetLowering::emitSTR_D(MachineInstr &MI,
4933 MachineBasicBlock *BB) const {
4934 MachineFunction *MF = BB->getParent();
4935 MachineRegisterInfo &MRI = MF->getRegInfo();
4936 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4937 const bool IsLittle = Subtarget.isLittle();
4938 DebugLoc DL = MI.getDebugLoc();
4939
4940 Register StoreVal = MI.getOperand(0).getReg();
4941 Register Address = MI.getOperand(1).getReg();
4942 unsigned Imm = MI.getOperand(2).getImm();
4943
4944 MachineBasicBlock::iterator I(MI);
4945
4946 if (Subtarget.hasMips32r6() || Subtarget.hasMips64r6()) {
4947 // Mips release 6 can store to adress that is not naturally-aligned.
4948 if (Subtarget.isGP64bit()) {
4949 Register BitcastD = MRI.createVirtualRegister(&Mips::MSA128DRegClass);
4950 Register Lo = MRI.createVirtualRegister(&Mips::GPR64RegClass);
4951 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
4952 .addDef(BitcastD)
4953 .addUse(StoreVal);
4954 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_D))
4955 .addDef(Lo)
4956 .addUse(BitcastD)
4957 .addImm(0);
4958 BuildMI(*BB, I, DL, TII->get(Mips::SD))
4959 .addUse(Lo)
4960 .addUse(Address)
4961 .addImm(Imm);
4962 } else {
4963 Register BitcastW = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4964 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4965 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4966 BuildMI(*BB, I, DL, TII->get(Mips::COPY))
4967 .addDef(BitcastW)
4968 .addUse(StoreVal);
4969 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4970 .addDef(Lo)
4971 .addUse(BitcastW)
4972 .addImm(0);
4973 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4974 .addDef(Hi)
4975 .addUse(BitcastW)
4976 .addImm(1);
4977 BuildMI(*BB, I, DL, TII->get(Mips::SW))
4978 .addUse(Lo)
4979 .addUse(Address)
4980 .addImm(Imm + (IsLittle ? 0 : 4));
4981 BuildMI(*BB, I, DL, TII->get(Mips::SW))
4982 .addUse(Hi)
4983 .addUse(Address)
4984 .addImm(Imm + (IsLittle ? 4 : 0));
4985 }
4986 } else {
4987 // Mips release 5 needs to use instructions that can store to an unaligned
4988 // memory address.
4989 Register Bitcast = MRI.createVirtualRegister(&Mips::MSA128WRegClass);
4990 Register Lo = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4991 Register Hi = MRI.createVirtualRegister(&Mips::GPR32RegClass);
4992 BuildMI(*BB, I, DL, TII->get(Mips::COPY)).addDef(Bitcast).addUse(StoreVal);
4993 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4994 .addDef(Lo)
4995 .addUse(Bitcast)
4996 .addImm(0);
4997 BuildMI(*BB, I, DL, TII->get(Mips::COPY_S_W))
4998 .addDef(Hi)
4999 .addUse(Bitcast)
5000 .addImm(1);
5001 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5002 .addUse(Lo)
5003 .addUse(Address)
5004 .addImm(Imm + (IsLittle ? 0 : 3));
5005 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5006 .addUse(Lo)
5007 .addUse(Address)
5008 .addImm(Imm + (IsLittle ? 3 : 0));
5009 BuildMI(*BB, I, DL, TII->get(Mips::SWR))
5010 .addUse(Hi)
5011 .addUse(Address)
5012 .addImm(Imm + (IsLittle ? 4 : 7));
5013 BuildMI(*BB, I, DL, TII->get(Mips::SWL))
5014 .addUse(Hi)
5015 .addUse(Address)
5016 .addImm(Imm + (IsLittle ? 7 : 4));
5017 }
5018
5019 MI.eraseFromParent();
5020 return BB;
5021}

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h

1//===- llvm/CodeGen/SelectionDAGNodes.h - SelectionDAG Nodes ----*- C++ -*-===//
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 declares the SDNode class and derived classes, which are used to
10// represent the nodes and operations present in a SelectionDAG. These nodes
11// and operations are machine code level operations, with some similarities to
12// the GCC RTL representation.
13//
14// Clients should include the SelectionDAG.h file instead of this file directly.
15//
16//===----------------------------------------------------------------------===//
17
18#ifndef LLVM_CODEGEN_SELECTIONDAGNODES_H
19#define LLVM_CODEGEN_SELECTIONDAGNODES_H
20
21#include "llvm/ADT/APFloat.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/BitVector.h"
24#include "llvm/ADT/FoldingSet.h"
25#include "llvm/ADT/GraphTraits.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/SmallVector.h"
28#include "llvm/ADT/ilist_node.h"
29#include "llvm/ADT/iterator.h"
30#include "llvm/ADT/iterator_range.h"
31#include "llvm/CodeGen/ISDOpcodes.h"
32#include "llvm/CodeGen/MachineMemOperand.h"
33#include "llvm/CodeGen/Register.h"
34#include "llvm/CodeGen/ValueTypes.h"
35#include "llvm/IR/Constants.h"
36#include "llvm/IR/DebugLoc.h"
37#include "llvm/IR/Instruction.h"
38#include "llvm/IR/Instructions.h"
39#include "llvm/IR/Metadata.h"
40#include "llvm/IR/Operator.h"
41#include "llvm/Support/AlignOf.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/Casting.h"
44#include "llvm/Support/ErrorHandling.h"
45#include "llvm/Support/MachineValueType.h"
46#include "llvm/Support/TypeSize.h"
47#include <algorithm>
48#include <cassert>
49#include <climits>
50#include <cstddef>
51#include <cstdint>
52#include <cstring>
53#include <iterator>
54#include <string>
55#include <tuple>
56
57namespace llvm {
58
59class APInt;
60class Constant;
61template <typename T> struct DenseMapInfo;
62class GlobalValue;
63class MachineBasicBlock;
64class MachineConstantPoolValue;
65class MCSymbol;
66class raw_ostream;
67class SDNode;
68class SelectionDAG;
69class Type;
70class Value;
71
72void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
73 bool force = false);
74
75/// This represents a list of ValueType's that has been intern'd by
76/// a SelectionDAG. Instances of this simple value class are returned by
77/// SelectionDAG::getVTList(...).
78///
79struct SDVTList {
80 const EVT *VTs;
81 unsigned int NumVTs;
82};
83
84namespace ISD {
85
86 /// Node predicates
87
88/// If N is a BUILD_VECTOR or SPLAT_VECTOR node whose elements are all the
89/// same constant or undefined, return true and return the constant value in
90/// \p SplatValue.
91bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
92
93/// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
94/// all of the elements are ~0 or undef. If \p BuildVectorOnly is set to
95/// true, it only checks BUILD_VECTOR.
96bool isConstantSplatVectorAllOnes(const SDNode *N,
97 bool BuildVectorOnly = false);
98
99/// Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where
100/// all of the elements are 0 or undef. If \p BuildVectorOnly is set to true, it
101/// only checks BUILD_VECTOR.
102bool isConstantSplatVectorAllZeros(const SDNode *N,
103 bool BuildVectorOnly = false);
104
105/// Return true if the specified node is a BUILD_VECTOR where all of the
106/// elements are ~0 or undef.
107bool isBuildVectorAllOnes(const SDNode *N);
108
109/// Return true if the specified node is a BUILD_VECTOR where all of the
110/// elements are 0 or undef.
111bool isBuildVectorAllZeros(const SDNode *N);
112
113/// Return true if the specified node is a BUILD_VECTOR node of all
114/// ConstantSDNode or undef.
115bool isBuildVectorOfConstantSDNodes(const SDNode *N);
116
117/// Return true if the specified node is a BUILD_VECTOR node of all
118/// ConstantFPSDNode or undef.
119bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
120
121/// Return true if the node has at least one operand and all operands of the
122/// specified node are ISD::UNDEF.
123bool allOperandsUndef(const SDNode *N);
124
125} // end namespace ISD
126
127//===----------------------------------------------------------------------===//
128/// Unlike LLVM values, Selection DAG nodes may return multiple
129/// values as the result of a computation. Many nodes return multiple values,
130/// from loads (which define a token and a return value) to ADDC (which returns
131/// a result and a carry value), to calls (which may return an arbitrary number
132/// of values).
133///
134/// As such, each use of a SelectionDAG computation must indicate the node that
135/// computes it as well as which return value to use from that node. This pair
136/// of information is represented with the SDValue value type.
137///
138class SDValue {
139 friend struct DenseMapInfo<SDValue>;
140
141 SDNode *Node = nullptr; // The node defining the value we are using.
142 unsigned ResNo = 0; // Which return value of the node we are using.
143
144public:
145 SDValue() = default;
146 SDValue(SDNode *node, unsigned resno);
147
148 /// get the index which selects a specific result in the SDNode
149 unsigned getResNo() const { return ResNo; }
150
151 /// get the SDNode which holds the desired result
152 SDNode *getNode() const { return Node; }
153
154 /// set the SDNode
155 void setNode(SDNode *N) { Node = N; }
156
157 inline SDNode *operator->() const { return Node; }
158
159 bool operator==(const SDValue &O) const {
160 return Node == O.Node && ResNo == O.ResNo;
161 }
162 bool operator!=(const SDValue &O) const {
163 return !operator==(O);
164 }
165 bool operator<(const SDValue &O) const {
166 return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
167 }
168 explicit operator bool() const {
169 return Node != nullptr;
170 }
171
172 SDValue getValue(unsigned R) const {
173 return SDValue(Node, R);
174 }
175
176 /// Return true if this node is an operand of N.
177 bool isOperandOf(const SDNode *N) const;
178
179 /// Return the ValueType of the referenced return value.
180 inline EVT getValueType() const;
181
182 /// Return the simple ValueType of the referenced return value.
183 MVT getSimpleValueType() const {
184 return getValueType().getSimpleVT();
185 }
186
187 /// Returns the size of the value in bits.
188 ///
189 /// If the value type is a scalable vector type, the scalable property will
190 /// be set and the runtime size will be a positive integer multiple of the
191 /// base size.
192 TypeSize getValueSizeInBits() const {
193 return getValueType().getSizeInBits();
194 }
195
196 uint64_t getScalarValueSizeInBits() const {
197 return getValueType().getScalarType().getFixedSizeInBits();
198 }
199
200 // Forwarding methods - These forward to the corresponding methods in SDNode.
201 inline unsigned getOpcode() const;
202 inline unsigned getNumOperands() const;
203 inline const SDValue &getOperand(unsigned i) const;
204 inline uint64_t getConstantOperandVal(unsigned i) const;
205 inline const APInt &getConstantOperandAPInt(unsigned i) const;
206 inline bool isTargetMemoryOpcode() const;
207 inline bool isTargetOpcode() const;
208 inline bool isMachineOpcode() const;
209 inline bool isUndef() const;
210 inline unsigned getMachineOpcode() const;
211 inline const DebugLoc &getDebugLoc() const;
212 inline void dump() const;
213 inline void dump(const SelectionDAG *G) const;
214 inline void dumpr() const;
215 inline void dumpr(const SelectionDAG *G) const;
216
217 /// Return true if this operand (which must be a chain) reaches the
218 /// specified operand without crossing any side-effecting instructions.
219 /// In practice, this looks through token factors and non-volatile loads.
220 /// In order to remain efficient, this only
221 /// looks a couple of nodes in, it does not do an exhaustive search.
222 bool reachesChainWithoutSideEffects(SDValue Dest,
223 unsigned Depth = 2) const;
224
225 /// Return true if there are no nodes using value ResNo of Node.
226 inline bool use_empty() const;
227
228 /// Return true if there is exactly one node using value ResNo of Node.
229 inline bool hasOneUse() const;
230};
231
232template<> struct DenseMapInfo<SDValue> {
233 static inline SDValue getEmptyKey() {
234 SDValue V;
235 V.ResNo = -1U;
236 return V;
237 }
238
239 static inline SDValue getTombstoneKey() {
240 SDValue V;
241 V.ResNo = -2U;
242 return V;
243 }
244
245 static unsigned getHashValue(const SDValue &Val) {
246 return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
247 (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
248 }
249
250 static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
251 return LHS == RHS;
252 }
253};
254
255/// Allow casting operators to work directly on
256/// SDValues as if they were SDNode*'s.
257template<> struct simplify_type<SDValue> {
258 using SimpleType = SDNode *;
259
260 static SimpleType getSimplifiedValue(SDValue &Val) {
261 return Val.getNode();
262 }
263};
264template<> struct simplify_type<const SDValue> {
265 using SimpleType = /*const*/ SDNode *;
266
267 static SimpleType getSimplifiedValue(const SDValue &Val) {
268 return Val.getNode();
269 }
270};
271
272/// Represents a use of a SDNode. This class holds an SDValue,
273/// which records the SDNode being used and the result number, a
274/// pointer to the SDNode using the value, and Next and Prev pointers,
275/// which link together all the uses of an SDNode.
276///
277class SDUse {
278 /// Val - The value being used.
279 SDValue Val;
280 /// User - The user of this value.
281 SDNode *User = nullptr;
282 /// Prev, Next - Pointers to the uses list of the SDNode referred by
283 /// this operand.
284 SDUse **Prev = nullptr;
285 SDUse *Next = nullptr;
286
287public:
288 SDUse() = default;
289 SDUse(const SDUse &U) = delete;
290 SDUse &operator=(const SDUse &) = delete;
291
292 /// Normally SDUse will just implicitly convert to an SDValue that it holds.
293 operator const SDValue&() const { return Val; }
294
295 /// If implicit conversion to SDValue doesn't work, the get() method returns
296 /// the SDValue.
297 const SDValue &get() const { return Val; }
298
299 /// This returns the SDNode that contains this Use.
300 SDNode *getUser() { return User; }
301
302 /// Get the next SDUse in the use list.
303 SDUse *getNext() const { return Next; }
304
305 /// Convenience function for get().getNode().
306 SDNode *getNode() const { return Val.getNode(); }
307 /// Convenience function for get().getResNo().
308 unsigned getResNo() const { return Val.getResNo(); }
309 /// Convenience function for get().getValueType().
310 EVT getValueType() const { return Val.getValueType(); }
311
312 /// Convenience function for get().operator==
313 bool operator==(const SDValue &V) const {
314 return Val == V;
315 }
316
317 /// Convenience function for get().operator!=
318 bool operator!=(const SDValue &V) const {
319 return Val != V;
320 }
321
322 /// Convenience function for get().operator<
323 bool operator<(const SDValue &V) const {
324 return Val < V;
325 }
326
327private:
328 friend class SelectionDAG;
329 friend class SDNode;
330 // TODO: unfriend HandleSDNode once we fix its operand handling.
331 friend class HandleSDNode;
332
333 void setUser(SDNode *p) { User = p; }
334
335 /// Remove this use from its existing use list, assign it the
336 /// given value, and add it to the new value's node's use list.
337 inline void set(const SDValue &V);
338 /// Like set, but only supports initializing a newly-allocated
339 /// SDUse with a non-null value.
340 inline void setInitial(const SDValue &V);
341 /// Like set, but only sets the Node portion of the value,
342 /// leaving the ResNo portion unmodified.
343 inline void setNode(SDNode *N);
344
345 void addToList(SDUse **List) {
346 Next = *List;
347 if (Next) Next->Prev = &Next;
348 Prev = List;
349 *List = this;
350 }
351
352 void removeFromList() {
353 *Prev = Next;
354 if (Next) Next->Prev = Prev;
355 }
356};
357
358/// simplify_type specializations - Allow casting operators to work directly on
359/// SDValues as if they were SDNode*'s.
360template<> struct simplify_type<SDUse> {
361 using SimpleType = SDNode *;
362
363 static SimpleType getSimplifiedValue(SDUse &Val) {
364 return Val.getNode();
365 }
366};
367
368/// These are IR-level optimization flags that may be propagated to SDNodes.
369/// TODO: This data structure should be shared by the IR optimizer and the
370/// the backend.
371struct SDNodeFlags {
372private:
373 bool NoUnsignedWrap : 1;
374 bool NoSignedWrap : 1;
375 bool Exact : 1;
376 bool NoNaNs : 1;
377 bool NoInfs : 1;
378 bool NoSignedZeros : 1;
379 bool AllowReciprocal : 1;
380 bool AllowContract : 1;
381 bool ApproximateFuncs : 1;
382 bool AllowReassociation : 1;
383
384 // We assume instructions do not raise floating-point exceptions by default,
385 // and only those marked explicitly may do so. We could choose to represent
386 // this via a positive "FPExcept" flags like on the MI level, but having a
387 // negative "NoFPExcept" flag here (that defaults to true) makes the flag
388 // intersection logic more straightforward.
389 bool NoFPExcept : 1;
390
391public:
392 /// Default constructor turns off all optimization flags.
393 SDNodeFlags()
394 : NoUnsignedWrap(false), NoSignedWrap(false), Exact(false), NoNaNs(false),
395 NoInfs(false), NoSignedZeros(false), AllowReciprocal(false),
396 AllowContract(false), ApproximateFuncs(false),
397 AllowReassociation(false), NoFPExcept(false) {}
398
399 /// Propagate the fast-math-flags from an IR FPMathOperator.
400 void copyFMF(const FPMathOperator &FPMO) {
401 setNoNaNs(FPMO.hasNoNaNs());
402 setNoInfs(FPMO.hasNoInfs());
403 setNoSignedZeros(FPMO.hasNoSignedZeros());
404 setAllowReciprocal(FPMO.hasAllowReciprocal());
405 setAllowContract(FPMO.hasAllowContract());
406 setApproximateFuncs(FPMO.hasApproxFunc());
407 setAllowReassociation(FPMO.hasAllowReassoc());
408 }
409
410 // These are mutators for each flag.
411 void setNoUnsignedWrap(bool b) { NoUnsignedWrap = b; }
412 void setNoSignedWrap(bool b) { NoSignedWrap = b; }
413 void setExact(bool b) { Exact = b; }
414 void setNoNaNs(bool b) { NoNaNs = b; }
415 void setNoInfs(bool b) { NoInfs = b; }
416 void setNoSignedZeros(bool b) { NoSignedZeros = b; }
417 void setAllowReciprocal(bool b) { AllowReciprocal = b; }
418 void setAllowContract(bool b) { AllowContract = b; }
419 void setApproximateFuncs(bool b) { ApproximateFuncs = b; }
420 void setAllowReassociation(bool b) { AllowReassociation = b; }
421 void setNoFPExcept(bool b) { NoFPExcept = b; }
422
423 // These are accessors for each flag.
424 bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
425 bool hasNoSignedWrap() const { return NoSignedWrap; }
426 bool hasExact() const { return Exact; }
427 bool hasNoNaNs() const { return NoNaNs; }
428 bool hasNoInfs() const { return NoInfs; }
429 bool hasNoSignedZeros() const { return NoSignedZeros; }
430 bool hasAllowReciprocal() const { return AllowReciprocal; }
431 bool hasAllowContract() const { return AllowContract; }
432 bool hasApproximateFuncs() const { return ApproximateFuncs; }
433 bool hasAllowReassociation() const { return AllowReassociation; }
434 bool hasNoFPExcept() const { return NoFPExcept; }
435
436 /// Clear any flags in this flag set that aren't also set in Flags. All
437 /// flags will be cleared if Flags are undefined.
438 void intersectWith(const SDNodeFlags Flags) {
439 NoUnsignedWrap &= Flags.NoUnsignedWrap;
440 NoSignedWrap &= Flags.NoSignedWrap;
441 Exact &= Flags.Exact;
442 NoNaNs &= Flags.NoNaNs;
443 NoInfs &= Flags.NoInfs;
444 NoSignedZeros &= Flags.NoSignedZeros;
445 AllowReciprocal &= Flags.AllowReciprocal;
446 AllowContract &= Flags.AllowContract;
447 ApproximateFuncs &= Flags.ApproximateFuncs;
448 AllowReassociation &= Flags.AllowReassociation;
449 NoFPExcept &= Flags.NoFPExcept;
450 }
451};
452
453/// Represents one node in the SelectionDAG.
454///
455class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
456private:
457 /// The operation that this node performs.
458 int16_t NodeType;
459
460protected:
461 // We define a set of mini-helper classes to help us interpret the bits in our
462 // SubclassData. These are designed to fit within a uint16_t so they pack
463 // with NodeType.
464
465#if defined(_AIX) && (!defined(__GNUC__4) || defined(__clang__1))
466// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
467// and give the `pack` pragma push semantics.
468#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")pack(2)
469#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")pack(pop)
470#else
471#define BEGIN_TWO_BYTE_PACK()
472#define END_TWO_BYTE_PACK()
473#endif
474
475BEGIN_TWO_BYTE_PACK()
476 class SDNodeBitfields {
477 friend class SDNode;
478 friend class MemIntrinsicSDNode;
479 friend class MemSDNode;
480 friend class SelectionDAG;
481
482 uint16_t HasDebugValue : 1;
483 uint16_t IsMemIntrinsic : 1;
484 uint16_t IsDivergent : 1;
485 };
486 enum { NumSDNodeBits = 3 };
487
488 class ConstantSDNodeBitfields {
489 friend class ConstantSDNode;
490
491 uint16_t : NumSDNodeBits;
492
493 uint16_t IsOpaque : 1;
494 };
495
496 class MemSDNodeBitfields {
497 friend class MemSDNode;
498 friend class MemIntrinsicSDNode;
499 friend class AtomicSDNode;
500
501 uint16_t : NumSDNodeBits;
502
503 uint16_t IsVolatile : 1;
504 uint16_t IsNonTemporal : 1;
505 uint16_t IsDereferenceable : 1;
506 uint16_t IsInvariant : 1;
507 };
508 enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
509
510 class LSBaseSDNodeBitfields {
511 friend class LSBaseSDNode;
512 friend class MaskedLoadStoreSDNode;
513 friend class MaskedGatherScatterSDNode;
514
515 uint16_t : NumMemSDNodeBits;
516
517 // This storage is shared between disparate class hierarchies to hold an
518 // enumeration specific to the class hierarchy in use.
519 // LSBaseSDNode => enum ISD::MemIndexedMode
520 // MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
521 // MaskedGatherScatterSDNode => enum ISD::MemIndexType
522 uint16_t AddressingMode : 3;
523 };
524 enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
525
526 class LoadSDNodeBitfields {
527 friend class LoadSDNode;
528 friend class MaskedLoadSDNode;
529 friend class MaskedGatherSDNode;
530
531 uint16_t : NumLSBaseSDNodeBits;
532
533 uint16_t ExtTy : 2; // enum ISD::LoadExtType
534 uint16_t IsExpanding : 1;
535 };
536
537 class StoreSDNodeBitfields {
538 friend class StoreSDNode;
539 friend class MaskedStoreSDNode;
540 friend class MaskedScatterSDNode;
541
542 uint16_t : NumLSBaseSDNodeBits;
543
544 uint16_t IsTruncating : 1;
545 uint16_t IsCompressing : 1;
546 };
547
548 union {
549 char RawSDNodeBits[sizeof(uint16_t)];
550 SDNodeBitfields SDNodeBits;
551 ConstantSDNodeBitfields ConstantSDNodeBits;
552 MemSDNodeBitfields MemSDNodeBits;
553 LSBaseSDNodeBitfields LSBaseSDNodeBits;
554 LoadSDNodeBitfields LoadSDNodeBits;
555 StoreSDNodeBitfields StoreSDNodeBits;
556 };
557END_TWO_BYTE_PACK()
558#undef BEGIN_TWO_BYTE_PACK
559#undef END_TWO_BYTE_PACK
560
561 // RawSDNodeBits must cover the entirety of the union. This means that all of
562 // the union's members must have size <= RawSDNodeBits. We write the RHS as
563 // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
564 static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
565 static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
566 static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
567 static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
568 static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
569 static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
570
571private:
572 friend class SelectionDAG;
573 // TODO: unfriend HandleSDNode once we fix its operand handling.
574 friend class HandleSDNode;
575
576 /// Unique id per SDNode in the DAG.
577 int NodeId = -1;
578
579 /// The values that are used by this operation.
580 SDUse *OperandList = nullptr;
581
582 /// The types of the values this node defines. SDNode's may
583 /// define multiple values simultaneously.
584 const EVT *ValueList;
585
586 /// List of uses for this SDNode.
587 SDUse *UseList = nullptr;
588
589 /// The number of entries in the Operand/Value list.
590 unsigned short NumOperands = 0;
591 unsigned short NumValues;
592
593 // The ordering of the SDNodes. It roughly corresponds to the ordering of the
594 // original LLVM instructions.
595 // This is used for turning off scheduling, because we'll forgo
596 // the normal scheduling algorithms and output the instructions according to
597 // this ordering.
598 unsigned IROrder;
599
600 /// Source line information.
601 DebugLoc debugLoc;
602
603 /// Return a pointer to the specified value type.
604 static const EVT *getValueTypeList(EVT VT);
605
606 SDNodeFlags Flags;
607
608public:
609 /// Unique and persistent id per SDNode in the DAG.
610 /// Used for debug printing.
611 uint16_t PersistentId;
612
613 //===--------------------------------------------------------------------===//
614 // Accessors
615 //
616
617 /// Return the SelectionDAG opcode value for this node. For
618 /// pre-isel nodes (those for which isMachineOpcode returns false), these
619 /// are the opcode values in the ISD and <target>ISD namespaces. For
620 /// post-isel opcodes, see getMachineOpcode.
621 unsigned getOpcode() const { return (unsigned short)NodeType; }
622
623 /// Test if this node has a target-specific opcode (in the
624 /// \<target\>ISD namespace).
625 bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
626
627 /// Test if this node has a target-specific opcode that may raise
628 /// FP exceptions (in the \<target\>ISD namespace and greater than
629 /// FIRST_TARGET_STRICTFP_OPCODE). Note that all target memory
630 /// opcode are currently automatically considered to possibly raise
631 /// FP exceptions as well.
632 bool isTargetStrictFPOpcode() const {
633 return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
634 }
635
636 /// Test if this node has a target-specific
637 /// memory-referencing opcode (in the \<target\>ISD namespace and
638 /// greater than FIRST_TARGET_MEMORY_OPCODE).
639 bool isTargetMemoryOpcode() const {
640 return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
641 }
642
643 /// Return true if the type of the node type undefined.
644 bool isUndef() const { return NodeType == ISD::UNDEF; }
645
646 /// Test if this node is a memory intrinsic (with valid pointer information).
647 /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
648 /// non-memory intrinsics (with chains) that are not really instances of
649 /// MemSDNode. For such nodes, we need some extra state to determine the
650 /// proper classof relationship.
651 bool isMemIntrinsic() const {
652 return (NodeType == ISD::INTRINSIC_W_CHAIN ||
653 NodeType == ISD::INTRINSIC_VOID) &&
654 SDNodeBits.IsMemIntrinsic;
655 }
656
657 /// Test if this node is a strict floating point pseudo-op.
658 bool isStrictFPOpcode() {
659 switch (NodeType) {
660 default:
661 return false;
662 case ISD::STRICT_FP16_TO_FP:
663 case ISD::STRICT_FP_TO_FP16:
664#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
665 case ISD::STRICT_##DAGN:
666#include "llvm/IR/ConstrainedOps.def"
667 return true;
668 }
669 }
670
671 /// Test if this node has a post-isel opcode, directly
672 /// corresponding to a MachineInstr opcode.
673 bool isMachineOpcode() const { return NodeType < 0; }
674
675 /// This may only be called if isMachineOpcode returns
676 /// true. It returns the MachineInstr opcode value that the node's opcode
677 /// corresponds to.
678 unsigned getMachineOpcode() const {
679 assert(isMachineOpcode() && "Not a MachineInstr opcode!")(static_cast <bool> (isMachineOpcode() && "Not a MachineInstr opcode!"
) ? void (0) : __assert_fail ("isMachineOpcode() && \"Not a MachineInstr opcode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 679, __extension__ __PRETTY_FUNCTION__))
;
680 return ~NodeType;
681 }
682
683 bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
684 void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
685
686 bool isDivergent() const { return SDNodeBits.IsDivergent; }
687
688 /// Return true if there are no uses of this node.
689 bool use_empty() const { return UseList == nullptr; }
690
691 /// Return true if there is exactly one use of this node.
692 bool hasOneUse() const { return hasSingleElement(uses()); }
693
694 /// Return the number of uses of this node. This method takes
695 /// time proportional to the number of uses.
696 size_t use_size() const { return std::distance(use_begin(), use_end()); }
697
698 /// Return the unique node id.
699 int getNodeId() const { return NodeId; }
700
701 /// Set unique node id.
702 void setNodeId(int Id) { NodeId = Id; }
703
704 /// Return the node ordering.
705 unsigned getIROrder() const { return IROrder; }
706
707 /// Set the node ordering.
708 void setIROrder(unsigned Order) { IROrder = Order; }
709
710 /// Return the source location info.
711 const DebugLoc &getDebugLoc() const { return debugLoc; }
712
713 /// Set source location info. Try to avoid this, putting
714 /// it in the constructor is preferable.
715 void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
716
717 /// This class provides iterator support for SDUse
718 /// operands that use a specific SDNode.
719 class use_iterator {
720 friend class SDNode;
721
722 SDUse *Op = nullptr;
723
724 explicit use_iterator(SDUse *op) : Op(op) {}
725
726 public:
727 using iterator_category = std::forward_iterator_tag;
728 using value_type = SDUse;
729 using difference_type = std::ptrdiff_t;
730 using pointer = value_type *;
731 using reference = value_type &;
732
733 use_iterator() = default;
734 use_iterator(const use_iterator &I) : Op(I.Op) {}
735
736 bool operator==(const use_iterator &x) const {
737 return Op == x.Op;
738 }
739 bool operator!=(const use_iterator &x) const {
740 return !operator==(x);
741 }
742
743 /// Return true if this iterator is at the end of uses list.
744 bool atEnd() const { return Op == nullptr; }
745
746 // Iterator traversal: forward iteration only.
747 use_iterator &operator++() { // Preincrement
748 assert(Op && "Cannot increment end iterator!")(static_cast <bool> (Op && "Cannot increment end iterator!"
) ? void (0) : __assert_fail ("Op && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 748, __extension__ __PRETTY_FUNCTION__))
;
749 Op = Op->getNext();
750 return *this;
751 }
752
753 use_iterator operator++(int) { // Postincrement
754 use_iterator tmp = *this; ++*this; return tmp;
755 }
756
757 /// Retrieve a pointer to the current user node.
758 SDNode *operator*() const {
759 assert(Op && "Cannot dereference end iterator!")(static_cast <bool> (Op && "Cannot dereference end iterator!"
) ? void (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 759, __extension__ __PRETTY_FUNCTION__))
;
760 return Op->getUser();
761 }
762
763 SDNode *operator->() const { return operator*(); }
764
765 SDUse &getUse() const { return *Op; }
766
767 /// Retrieve the operand # of this use in its user.
768 unsigned getOperandNo() const {
769 assert(Op && "Cannot dereference end iterator!")(static_cast <bool> (Op && "Cannot dereference end iterator!"
) ? void (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 769, __extension__ __PRETTY_FUNCTION__))
;
770 return (unsigned)(Op - Op->getUser()->OperandList);
771 }
772 };
773
774 /// Provide iteration support to walk over all uses of an SDNode.
775 use_iterator use_begin() const {
776 return use_iterator(UseList);
777 }
778
779 static use_iterator use_end() { return use_iterator(nullptr); }
780
781 inline iterator_range<use_iterator> uses() {
782 return make_range(use_begin(), use_end());
783 }
784 inline iterator_range<use_iterator> uses() const {
785 return make_range(use_begin(), use_end());
786 }
787
788 /// Return true if there are exactly NUSES uses of the indicated value.
789 /// This method ignores uses of other values defined by this operation.
790 bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
791
792 /// Return true if there are any use of the indicated value.
793 /// This method ignores uses of other values defined by this operation.
794 bool hasAnyUseOfValue(unsigned Value) const;
795
796 /// Return true if this node is the only use of N.
797 bool isOnlyUserOf(const SDNode *N) const;
798
799 /// Return true if this node is an operand of N.
800 bool isOperandOf(const SDNode *N) const;
801
802 /// Return true if this node is a predecessor of N.
803 /// NOTE: Implemented on top of hasPredecessor and every bit as
804 /// expensive. Use carefully.
805 bool isPredecessorOf(const SDNode *N) const {
806 return N->hasPredecessor(this);
807 }
808
809 /// Return true if N is a predecessor of this node.
810 /// N is either an operand of this node, or can be reached by recursively
811 /// traversing up the operands.
812 /// NOTE: This is an expensive method. Use it carefully.
813 bool hasPredecessor(const SDNode *N) const;
814
815 /// Returns true if N is a predecessor of any node in Worklist. This
816 /// helper keeps Visited and Worklist sets externally to allow unions
817 /// searches to be performed in parallel, caching of results across
818 /// queries and incremental addition to Worklist. Stops early if N is
819 /// found but will resume. Remember to clear Visited and Worklists
820 /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
821 /// giving up. The TopologicalPrune flag signals that positive NodeIds are
822 /// topologically ordered (Operands have strictly smaller node id) and search
823 /// can be pruned leveraging this.
824 static bool hasPredecessorHelper(const SDNode *N,
825 SmallPtrSetImpl<const SDNode *> &Visited,
826 SmallVectorImpl<const SDNode *> &Worklist,
827 unsigned int MaxSteps = 0,
828 bool TopologicalPrune = false) {
829 SmallVector<const SDNode *, 8> DeferredNodes;
830 if (Visited.count(N))
831 return true;
832
833 // Node Id's are assigned in three places: As a topological
834 // ordering (> 0), during legalization (results in values set to
835 // 0), new nodes (set to -1). If N has a topolgical id then we
836 // know that all nodes with ids smaller than it cannot be
837 // successors and we need not check them. Filter out all node
838 // that can't be matches. We add them to the worklist before exit
839 // in case of multiple calls. Note that during selection the topological id
840 // may be violated if a node's predecessor is selected before it. We mark
841 // this at selection negating the id of unselected successors and
842 // restricting topological pruning to positive ids.
843
844 int NId = N->getNodeId();
845 // If we Invalidated the Id, reconstruct original NId.
846 if (NId < -1)
847 NId = -(NId + 1);
848
849 bool Found = false;
850 while (!Worklist.empty()) {
851 const SDNode *M = Worklist.pop_back_val();
852 int MId = M->getNodeId();
853 if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
854 (MId > 0) && (MId < NId)) {
855 DeferredNodes.push_back(M);
856 continue;
857 }
858 for (const SDValue &OpV : M->op_values()) {
859 SDNode *Op = OpV.getNode();
860 if (Visited.insert(Op).second)
861 Worklist.push_back(Op);
862 if (Op == N)
863 Found = true;
864 }
865 if (Found)
866 break;
867 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
868 break;
869 }
870 // Push deferred nodes back on worklist.
871 Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
872 // If we bailed early, conservatively return found.
873 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
874 return true;
875 return Found;
876 }
877
878 /// Return true if all the users of N are contained in Nodes.
879 /// NOTE: Requires at least one match, but doesn't require them all.
880 static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
881
882 /// Return the number of values used by this operation.
883 unsigned getNumOperands() const { return NumOperands; }
884
885 /// Return the maximum number of operands that a SDNode can hold.
886 static constexpr size_t getMaxNumOperands() {
887 return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
888 }
889
890 /// Helper method returns the integer value of a ConstantSDNode operand.
891 inline uint64_t getConstantOperandVal(unsigned Num) const;
892
893 /// Helper method returns the APInt of a ConstantSDNode operand.
894 inline const APInt &getConstantOperandAPInt(unsigned Num) const;
895
896 const SDValue &getOperand(unsigned Num) const {
897 assert(Num < NumOperands && "Invalid child # of SDNode!")(static_cast <bool> (Num < NumOperands && "Invalid child # of SDNode!"
) ? void (0) : __assert_fail ("Num < NumOperands && \"Invalid child # of SDNode!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 897, __extension__ __PRETTY_FUNCTION__))
;
898 return OperandList[Num];
899 }
900
901 using op_iterator = SDUse *;
902
903 op_iterator op_begin() const { return OperandList; }
904 op_iterator op_end() const { return OperandList+NumOperands; }
905 ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
906
907 /// Iterator for directly iterating over the operand SDValue's.
908 struct value_op_iterator
909 : iterator_adaptor_base<value_op_iterator, op_iterator,
910 std::random_access_iterator_tag, SDValue,
911 ptrdiff_t, value_op_iterator *,
912 value_op_iterator *> {
913 explicit value_op_iterator(SDUse *U = nullptr)
914 : iterator_adaptor_base(U) {}
915
916 const SDValue &operator*() const { return I->get(); }
917 };
918
919 iterator_range<value_op_iterator> op_values() const {
920 return make_range(value_op_iterator(op_begin()),
921 value_op_iterator(op_end()));
922 }
923
924 SDVTList getVTList() const {
925 SDVTList X = { ValueList, NumValues };
926 return X;
927 }
928
929 /// If this node has a glue operand, return the node
930 /// to which the glue operand points. Otherwise return NULL.
931 SDNode *getGluedNode() const {
932 if (getNumOperands() != 0 &&
933 getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
934 return getOperand(getNumOperands()-1).getNode();
935 return nullptr;
936 }
937
938 /// If this node has a glue value with a user, return
939 /// the user (there is at most one). Otherwise return NULL.
940 SDNode *getGluedUser() const {
941 for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
942 if (UI.getUse().get().getValueType() == MVT::Glue)
943 return *UI;
944 return nullptr;
945 }
946
947 SDNodeFlags getFlags() const { return Flags; }
948 void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
949
950 /// Clear any flags in this node that aren't also set in Flags.
951 /// If Flags is not in a defined state then this has no effect.
952 void intersectFlagsWith(const SDNodeFlags Flags);
953
954 /// Return the number of values defined/returned by this operator.
955 unsigned getNumValues() const { return NumValues; }
956
957 /// Return the type of a specified result.
958 EVT getValueType(unsigned ResNo) const {
959 assert(ResNo < NumValues && "Illegal result number!")(static_cast <bool> (ResNo < NumValues && "Illegal result number!"
) ? void (0) : __assert_fail ("ResNo < NumValues && \"Illegal result number!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 959, __extension__ __PRETTY_FUNCTION__))
;
960 return ValueList[ResNo];
961 }
962
963 /// Return the type of a specified result as a simple type.
964 MVT getSimpleValueType(unsigned ResNo) const {
965 return getValueType(ResNo).getSimpleVT();
966 }
967
968 /// Returns MVT::getSizeInBits(getValueType(ResNo)).
969 ///
970 /// If the value type is a scalable vector type, the scalable property will
971 /// be set and the runtime size will be a positive integer multiple of the
972 /// base size.
973 TypeSize getValueSizeInBits(unsigned ResNo) const {
974 return getValueType(ResNo).getSizeInBits();
975 }
976
977 using value_iterator = const EVT *;
978
979 value_iterator value_begin() const { return ValueList; }
980 value_iterator value_end() const { return ValueList+NumValues; }
981 iterator_range<value_iterator> values() const {
982 return llvm::make_range(value_begin(), value_end());
983 }
984
985 /// Return the opcode of this operation for printing.
986 std::string getOperationName(const SelectionDAG *G = nullptr) const;
987 static const char* getIndexedModeName(ISD::MemIndexedMode AM);
988 void print_types(raw_ostream &OS, const SelectionDAG *G) const;
989 void print_details(raw_ostream &OS, const SelectionDAG *G) const;
990 void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
991 void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
992
993 /// Print a SelectionDAG node and all children down to
994 /// the leaves. The given SelectionDAG allows target-specific nodes
995 /// to be printed in human-readable form. Unlike printr, this will
996 /// print the whole DAG, including children that appear multiple
997 /// times.
998 ///
999 void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
1000
1001 /// Print a SelectionDAG node and children up to
1002 /// depth "depth." The given SelectionDAG allows target-specific
1003 /// nodes to be printed in human-readable form. Unlike printr, this
1004 /// will print children that appear multiple times wherever they are
1005 /// used.
1006 ///
1007 void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
1008 unsigned depth = 100) const;
1009
1010 /// Dump this node, for debugging.
1011 void dump() const;
1012
1013 /// Dump (recursively) this node and its use-def subgraph.
1014 void dumpr() const;
1015
1016 /// Dump this node, for debugging.
1017 /// The given SelectionDAG allows target-specific nodes to be printed
1018 /// in human-readable form.
1019 void dump(const SelectionDAG *G) const;
1020
1021 /// Dump (recursively) this node and its use-def subgraph.
1022 /// The given SelectionDAG allows target-specific nodes to be printed
1023 /// in human-readable form.
1024 void dumpr(const SelectionDAG *G) const;
1025
1026 /// printrFull to dbgs(). The given SelectionDAG allows
1027 /// target-specific nodes to be printed in human-readable form.
1028 /// Unlike dumpr, this will print the whole DAG, including children
1029 /// that appear multiple times.
1030 void dumprFull(const SelectionDAG *G = nullptr) const;
1031
1032 /// printrWithDepth to dbgs(). The given
1033 /// SelectionDAG allows target-specific nodes to be printed in
1034 /// human-readable form. Unlike dumpr, this will print children
1035 /// that appear multiple times wherever they are used.
1036 ///
1037 void dumprWithDepth(const SelectionDAG *G = nullptr,
1038 unsigned depth = 100) const;
1039
1040 /// Gather unique data for the node.
1041 void Profile(FoldingSetNodeID &ID) const;
1042
1043 /// This method should only be used by the SDUse class.
1044 void addUse(SDUse &U) { U.addToList(&UseList); }
1045
1046protected:
1047 static SDVTList getSDVTList(EVT VT) {
1048 SDVTList Ret = { getValueTypeList(VT), 1 };
1049 return Ret;
1050 }
1051
1052 /// Create an SDNode.
1053 ///
1054 /// SDNodes are created without any operands, and never own the operand
1055 /// storage. To add operands, see SelectionDAG::createOperands.
1056 SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
1057 : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs),
1058 IROrder(Order), debugLoc(std::move(dl)) {
1059 memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits));
1060 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")(static_cast <bool> (debugLoc.hasTrivialDestructor() &&
"Expected trivial destructor") ? void (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1060, __extension__ __PRETTY_FUNCTION__))
;
1061 assert(NumValues == VTs.NumVTs &&(static_cast <bool> (NumValues == VTs.NumVTs &&
"NumValues wasn't wide enough for its operands!") ? void (0)
: __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1062, __extension__ __PRETTY_FUNCTION__))
1062 "NumValues wasn't wide enough for its operands!")(static_cast <bool> (NumValues == VTs.NumVTs &&
"NumValues wasn't wide enough for its operands!") ? void (0)
: __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1062, __extension__ __PRETTY_FUNCTION__))
;
1063 }
1064
1065 /// Release the operands and set this node to have zero operands.
1066 void DropOperands();
1067};
1068
1069/// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
1070/// into SDNode creation functions.
1071/// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
1072/// from the original Instruction, and IROrder is the ordinal position of
1073/// the instruction.
1074/// When an SDNode is created after the DAG is being built, both DebugLoc and
1075/// the IROrder are propagated from the original SDNode.
1076/// So SDLoc class provides two constructors besides the default one, one to
1077/// be used by the DAGBuilder, the other to be used by others.
1078class SDLoc {
1079private:
1080 DebugLoc DL;
1081 int IROrder = 0;
1082
1083public:
1084 SDLoc() = default;
1085 SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
1086 SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
1087 SDLoc(const Instruction *I, int Order) : IROrder(Order) {
1088 assert(Order >= 0 && "bad IROrder")(static_cast <bool> (Order >= 0 && "bad IROrder"
) ? void (0) : __assert_fail ("Order >= 0 && \"bad IROrder\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1088, __extension__ __PRETTY_FUNCTION__))
;
1089 if (I)
1090 DL = I->getDebugLoc();
1091 }
1092
1093 unsigned getIROrder() const { return IROrder; }
1094 const DebugLoc &getDebugLoc() const { return DL; }
1095};
1096
1097// Define inline functions from the SDValue class.
1098
1099inline SDValue::SDValue(SDNode *node, unsigned resno)
1100 : Node(node), ResNo(resno) {
1101 // Explicitly check for !ResNo to avoid use-after-free, because there are
1102 // callers that use SDValue(N, 0) with a deleted N to indicate successful
1103 // combines.
1104 assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&(static_cast <bool> ((!Node || !ResNo || ResNo < Node
->getNumValues()) && "Invalid result number for the given node!"
) ? void (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1105, __extension__ __PRETTY_FUNCTION__))
1105 "Invalid result number for the given node!")(static_cast <bool> ((!Node || !ResNo || ResNo < Node
->getNumValues()) && "Invalid result number for the given node!"
) ? void (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1105, __extension__ __PRETTY_FUNCTION__))
;
1106 assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.")(static_cast <bool> (ResNo < -2U && "Cannot use result numbers reserved for DenseMaps."
) ? void (0) : __assert_fail ("ResNo < -2U && \"Cannot use result numbers reserved for DenseMaps.\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1106, __extension__ __PRETTY_FUNCTION__))
;
1107}
1108
1109inline unsigned SDValue::getOpcode() const {
1110 return Node->getOpcode();
1111}
1112
1113inline EVT SDValue::getValueType() const {
1114 return Node->getValueType(ResNo);
16
Called C++ object pointer is null
1115}
1116
1117inline unsigned SDValue::getNumOperands() const {
1118 return Node->getNumOperands();
1119}
1120
1121inline const SDValue &SDValue::getOperand(unsigned i) const {
1122 return Node->getOperand(i);
1123}
1124
1125inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
1126 return Node->getConstantOperandVal(i);
1127}
1128
1129inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const {
1130 return Node->getConstantOperandAPInt(i);
1131}
1132
1133inline bool SDValue::isTargetOpcode() const {
1134 return Node->isTargetOpcode();
1135}
1136
1137inline bool SDValue::isTargetMemoryOpcode() const {
1138 return Node->isTargetMemoryOpcode();
1139}
1140
1141inline bool SDValue::isMachineOpcode() const {
1142 return Node->isMachineOpcode();
1143}
1144
1145inline unsigned SDValue::getMachineOpcode() const {
1146 return Node->getMachineOpcode();
1147}
1148
1149inline bool SDValue::isUndef() const {
1150 return Node->isUndef();
1151}
1152
1153inline bool SDValue::use_empty() const {
1154 return !Node->hasAnyUseOfValue(ResNo);
1155}
1156
1157inline bool SDValue::hasOneUse() const {
1158 return Node->hasNUsesOfValue(1, ResNo);
1159}
1160
1161inline const DebugLoc &SDValue::getDebugLoc() const {
1162 return Node->getDebugLoc();
1163}
1164
1165inline void SDValue::dump() const {
1166 return Node->dump();
1167}
1168
1169inline void SDValue::dump(const SelectionDAG *G) const {
1170 return Node->dump(G);
1171}
1172
1173inline void SDValue::dumpr() const {
1174 return Node->dumpr();
1175}
1176
1177inline void SDValue::dumpr(const SelectionDAG *G) const {
1178 return Node->dumpr(G);
1179}
1180
1181// Define inline functions from the SDUse class.
1182
1183inline void SDUse::set(const SDValue &V) {
1184 if (Val.getNode()) removeFromList();
1185 Val = V;
1186 if (V.getNode()) V.getNode()->addUse(*this);
1187}
1188
1189inline void SDUse::setInitial(const SDValue &V) {
1190 Val = V;
1191 V.getNode()->addUse(*this);
1192}
1193
1194inline void SDUse::setNode(SDNode *N) {
1195 if (Val.getNode()) removeFromList();
1196 Val.setNode(N);
1197 if (N) N->addUse(*this);
1198}
1199
1200/// This class is used to form a handle around another node that
1201/// is persistent and is updated across invocations of replaceAllUsesWith on its
1202/// operand. This node should be directly created by end-users and not added to
1203/// the AllNodes list.
1204class HandleSDNode : public SDNode {
1205 SDUse Op;
1206
1207public:
1208 explicit HandleSDNode(SDValue X)
1209 : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1210 // HandleSDNodes are never inserted into the DAG, so they won't be
1211 // auto-numbered. Use ID 65535 as a sentinel.
1212 PersistentId = 0xffff;
1213
1214 // Manually set up the operand list. This node type is special in that it's
1215 // always stack allocated and SelectionDAG does not manage its operands.
1216 // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
1217 // be so special.
1218 Op.setUser(this);
1219 Op.setInitial(X);
1220 NumOperands = 1;
1221 OperandList = &Op;
1222 }
1223 ~HandleSDNode();
1224
1225 const SDValue &getValue() const { return Op; }
1226};
1227
1228class AddrSpaceCastSDNode : public SDNode {
1229private:
1230 unsigned SrcAddrSpace;
1231 unsigned DestAddrSpace;
1232
1233public:
1234 AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1235 unsigned SrcAS, unsigned DestAS);
1236
1237 unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1238 unsigned getDestAddressSpace() const { return DestAddrSpace; }
1239
1240 static bool classof(const SDNode *N) {
1241 return N->getOpcode() == ISD::ADDRSPACECAST;
1242 }
1243};
1244
1245/// This is an abstract virtual class for memory operations.
1246class MemSDNode : public SDNode {
1247private:
1248 // VT of in-memory value.
1249 EVT MemoryVT;
1250
1251protected:
1252 /// Memory reference information.
1253 MachineMemOperand *MMO;
1254
1255public:
1256 MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTs,
1257 EVT memvt, MachineMemOperand *MMO);
1258
1259 bool readMem() const { return MMO->isLoad(); }
1260 bool writeMem() const { return MMO->isStore(); }
1261
1262 /// Returns alignment and volatility of the memory access
1263 Align getOriginalAlign() const { return MMO->getBaseAlign(); }
1264 Align getAlign() const { return MMO->getAlign(); }
1265 // FIXME: Remove once transition to getAlign is over.
1266 unsigned getAlignment() const { return MMO->getAlign().value(); }
1267
1268 /// Return the SubclassData value, without HasDebugValue. This contains an
1269 /// encoding of the volatile flag, as well as bits used by subclasses. This
1270 /// function should only be used to compute a FoldingSetNodeID value.
1271 /// The HasDebugValue bit is masked out because CSE map needs to match
1272 /// nodes with debug info with nodes without debug info. Same is about
1273 /// isDivergent bit.
1274 unsigned getRawSubclassData() const {
1275 uint16_t Data;
1276 union {
1277 char RawSDNodeBits[sizeof(uint16_t)];
1278 SDNodeBitfields SDNodeBits;
1279 };
1280 memcpy(&RawSDNodeBits, &this->RawSDNodeBits, sizeof(this->RawSDNodeBits));
1281 SDNodeBits.HasDebugValue = 0;
1282 SDNodeBits.IsDivergent = false;
1283 memcpy(&Data, &RawSDNodeBits, sizeof(RawSDNodeBits));
1284 return Data;
1285 }
1286
1287 bool isVolatile() const { return MemSDNodeBits.IsVolatile; }
1288 bool isNonTemporal() const { return MemSDNodeBits.IsNonTemporal; }
1289 bool isDereferenceable() const { return MemSDNodeBits.IsDereferenceable; }
1290 bool isInvariant() const { return MemSDNodeBits.IsInvariant; }
1291
1292 // Returns the offset from the location of the access.
1293 int64_t getSrcValueOffset() const { return MMO->getOffset(); }
1294
1295 /// Returns the AA info that describes the dereference.
1296 AAMDNodes getAAInfo() const { return MMO->getAAInfo(); }
1297
1298 /// Returns the Ranges that describes the dereference.
1299 const MDNode *getRanges() const { return MMO->getRanges(); }
1300
1301 /// Returns the synchronization scope ID for this memory operation.
1302 SyncScope::ID getSyncScopeID() const { return MMO->getSyncScopeID(); }
1303
1304 /// Return the atomic ordering requirements for this memory operation. For
1305 /// cmpxchg atomic operations, return the atomic ordering requirements when
1306 /// store occurs.
1307 AtomicOrdering getSuccessOrdering() const {
1308 return MMO->getSuccessOrdering();
1309 }
1310
1311 /// Return a single atomic ordering that is at least as strong as both the
1312 /// success and failure orderings for an atomic operation. (For operations
1313 /// other than cmpxchg, this is equivalent to getSuccessOrdering().)
1314 AtomicOrdering getMergedOrdering() const { return MMO->getMergedOrdering(); }
1315
1316 /// Return true if the memory operation ordering is Unordered or higher.
1317 bool isAtomic() const { return MMO->isAtomic(); }
1318
1319 /// Returns true if the memory operation doesn't imply any ordering
1320 /// constraints on surrounding memory operations beyond the normal memory
1321 /// aliasing rules.
1322 bool isUnordered() const { return MMO->isUnordered(); }
1323
1324 /// Returns true if the memory operation is neither atomic or volatile.
1325 bool isSimple() const { return !isAtomic() && !isVolatile(); }
1326
1327 /// Return the type of the in-memory value.
1328 EVT getMemoryVT() const { return MemoryVT; }
1329
1330 /// Return a MachineMemOperand object describing the memory
1331 /// reference performed by operation.
1332 MachineMemOperand *getMemOperand() const { return MMO; }
1333
1334 const MachinePointerInfo &getPointerInfo() const {
1335 return MMO->getPointerInfo();
1336 }
1337
1338 /// Return the address space for the associated pointer
1339 unsigned getAddressSpace() const {
1340 return getPointerInfo().getAddrSpace();
1341 }
1342
1343 /// Update this MemSDNode's MachineMemOperand information
1344 /// to reflect the alignment of NewMMO, if it has a greater alignment.
1345 /// This must only be used when the new alignment applies to all users of
1346 /// this MachineMemOperand.
1347 void refineAlignment(const MachineMemOperand *NewMMO) {
1348 MMO->refineAlignment(NewMMO);
1349 }
1350
1351 const SDValue &getChain() const { return getOperand(0); }
1352
1353 const SDValue &getBasePtr() const {
1354 switch (getOpcode()) {
1355 case ISD::STORE:
1356 case ISD::MSTORE:
1357 return getOperand(2);
1358 case ISD::MGATHER:
1359 case ISD::MSCATTER:
1360 return getOperand(3);
1361 default:
1362 return getOperand(1);
1363 }
1364 }
1365
1366 // Methods to support isa and dyn_cast
1367 static bool classof(const SDNode *N) {
1368 // For some targets, we lower some target intrinsics to a MemIntrinsicNode
1369 // with either an intrinsic or a target opcode.
1370 switch (N->getOpcode()) {
1371 case ISD::LOAD:
1372 case ISD::STORE:
1373 case ISD::PREFETCH:
1374 case ISD::ATOMIC_CMP_SWAP:
1375 case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
1376 case ISD::ATOMIC_SWAP:
1377 case ISD::ATOMIC_LOAD_ADD:
1378 case ISD::ATOMIC_LOAD_SUB:
1379 case ISD::ATOMIC_LOAD_AND:
1380 case ISD::ATOMIC_LOAD_CLR:
1381 case ISD::ATOMIC_LOAD_OR:
1382 case ISD::ATOMIC_LOAD_XOR:
1383 case ISD::ATOMIC_LOAD_NAND:
1384 case ISD::ATOMIC_LOAD_MIN:
1385 case ISD::ATOMIC_LOAD_MAX:
1386 case ISD::ATOMIC_LOAD_UMIN:
1387 case ISD::ATOMIC_LOAD_UMAX:
1388 case ISD::ATOMIC_LOAD_FADD:
1389 case ISD::ATOMIC_LOAD_FSUB:
1390 case ISD::ATOMIC_LOAD:
1391 case ISD::ATOMIC_STORE:
1392 case ISD::MLOAD:
1393 case ISD::MSTORE:
1394 case ISD::MGATHER:
1395 case ISD::MSCATTER:
1396 return true;
1397 default:
1398 return N->isMemIntrinsic() || N->isTargetMemoryOpcode();
1399 }
1400 }
1401};
1402
1403/// This is an SDNode representing atomic operations.
1404class AtomicSDNode : public MemSDNode {
1405public:
1406 AtomicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl, SDVTList VTL,
1407 EVT MemVT, MachineMemOperand *MMO)
1408 : MemSDNode(Opc, Order, dl, VTL, MemVT, MMO) {
1409 assert(((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) ||(static_cast <bool> (((Opc != ISD::ATOMIC_LOAD &&
Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? void (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1410, __extension__ __PRETTY_FUNCTION__))
1410 MMO->isAtomic()) && "then why are we using an AtomicSDNode?")(static_cast <bool> (((Opc != ISD::ATOMIC_LOAD &&
Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && "then why are we using an AtomicSDNode?"
) ? void (0) : __assert_fail ("((Opc != ISD::ATOMIC_LOAD && Opc != ISD::ATOMIC_STORE) || MMO->isAtomic()) && \"then why are we using an AtomicSDNode?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1410, __extension__ __PRETTY_FUNCTION__))
;
1411 }
1412
1413 const SDValue &getBasePtr() const { return getOperand(1); }
1414 const SDValue &getVal() const { return getOperand(2); }
1415
1416 /// Returns true if this SDNode represents cmpxchg atomic operation, false
1417 /// otherwise.
1418 bool isCompareAndSwap() const {
1419 unsigned Op = getOpcode();
1420 return Op == ISD::ATOMIC_CMP_SWAP ||
1421 Op == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS;
1422 }
1423
1424 /// For cmpxchg atomic operations, return the atomic ordering requirements
1425 /// when store does not occur.
1426 AtomicOrdering getFailureOrdering() const {
1427 assert(isCompareAndSwap() && "Must be cmpxchg operation")(static_cast <bool> (isCompareAndSwap() && "Must be cmpxchg operation"
) ? void (0) : __assert_fail ("isCompareAndSwap() && \"Must be cmpxchg operation\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1427, __extension__ __PRETTY_FUNCTION__))
;
1428 return MMO->getFailureOrdering();
1429 }
1430
1431 // Methods to support isa and dyn_cast
1432 static bool classof(const SDNode *N) {
1433 return N->getOpcode() == ISD::ATOMIC_CMP_SWAP ||
1434 N->getOpcode() == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS ||
1435 N->getOpcode() == ISD::ATOMIC_SWAP ||
1436 N->getOpcode() == ISD::ATOMIC_LOAD_ADD ||
1437 N->getOpcode() == ISD::ATOMIC_LOAD_SUB ||
1438 N->getOpcode() == ISD::ATOMIC_LOAD_AND ||
1439 N->getOpcode() == ISD::ATOMIC_LOAD_CLR ||
1440 N->getOpcode() == ISD::ATOMIC_LOAD_OR ||
1441 N->getOpcode() == ISD::ATOMIC_LOAD_XOR ||
1442 N->getOpcode() == ISD::ATOMIC_LOAD_NAND ||
1443 N->getOpcode() == ISD::ATOMIC_LOAD_MIN ||
1444 N->getOpcode() == ISD::ATOMIC_LOAD_MAX ||
1445 N->getOpcode() == ISD::ATOMIC_LOAD_UMIN ||
1446 N->getOpcode() == ISD::ATOMIC_LOAD_UMAX ||
1447 N->getOpcode() == ISD::ATOMIC_LOAD_FADD ||
1448 N->getOpcode() == ISD::ATOMIC_LOAD_FSUB ||
1449 N->getOpcode() == ISD::ATOMIC_LOAD ||
1450 N->getOpcode() == ISD::ATOMIC_STORE;
1451 }
1452};
1453
1454/// This SDNode is used for target intrinsics that touch
1455/// memory and need an associated MachineMemOperand. Its opcode may be
1456/// INTRINSIC_VOID, INTRINSIC_W_CHAIN, PREFETCH, or a target-specific opcode
1457/// with a value not less than FIRST_TARGET_MEMORY_OPCODE.
1458class MemIntrinsicSDNode : public MemSDNode {
1459public:
1460 MemIntrinsicSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
1461 SDVTList VTs, EVT MemoryVT, MachineMemOperand *MMO)
1462 : MemSDNode(Opc, Order, dl, VTs, MemoryVT, MMO) {
1463 SDNodeBits.IsMemIntrinsic = true;
1464 }
1465
1466 // Methods to support isa and dyn_cast
1467 static bool classof(const SDNode *N) {
1468 // We lower some target intrinsics to their target opcode
1469 // early a node with a target opcode can be of this class
1470 return N->isMemIntrinsic() ||
1471 N->getOpcode() == ISD::PREFETCH ||
1472 N->isTargetMemoryOpcode();
1473 }
1474};
1475
1476/// This SDNode is used to implement the code generator
1477/// support for the llvm IR shufflevector instruction. It combines elements
1478/// from two input vectors into a new input vector, with the selection and
1479/// ordering of elements determined by an array of integers, referred to as
1480/// the shuffle mask. For input vectors of width N, mask indices of 0..N-1
1481/// refer to elements from the LHS input, and indices from N to 2N-1 the RHS.
1482/// An index of -1 is treated as undef, such that the code generator may put
1483/// any value in the corresponding element of the result.
1484class ShuffleVectorSDNode : public SDNode {
1485 // The memory for Mask is owned by the SelectionDAG's OperandAllocator, and
1486 // is freed when the SelectionDAG object is destroyed.
1487 const int *Mask;
1488
1489protected:
1490 friend class SelectionDAG;
1491
1492 ShuffleVectorSDNode(EVT VT, unsigned Order, const DebugLoc &dl, const int *M)
1493 : SDNode(ISD::VECTOR_SHUFFLE, Order, dl, getSDVTList(VT)), Mask(M) {}
1494
1495public:
1496 ArrayRef<int> getMask() const {
1497 EVT VT = getValueType(0);
1498 return makeArrayRef(Mask, VT.getVectorNumElements());
1499 }
1500
1501 int getMaskElt(unsigned Idx) const {
1502 assert(Idx < getValueType(0).getVectorNumElements() && "Idx out of range!")(static_cast <bool> (Idx < getValueType(0).getVectorNumElements
() && "Idx out of range!") ? void (0) : __assert_fail
("Idx < getValueType(0).getVectorNumElements() && \"Idx out of range!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1502, __extension__ __PRETTY_FUNCTION__))
;
1503 return Mask[Idx];
1504 }
1505
1506 bool isSplat() const { return isSplatMask(Mask, getValueType(0)); }
1507
1508 int getSplatIndex() const {
1509 assert(isSplat() && "Cannot get splat index for non-splat!")(static_cast <bool> (isSplat() && "Cannot get splat index for non-splat!"
) ? void (0) : __assert_fail ("isSplat() && \"Cannot get splat index for non-splat!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1509, __extension__ __PRETTY_FUNCTION__))
;
1510 EVT VT = getValueType(0);
1511 for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
1512 if (Mask[i] >= 0)
1513 return Mask[i];
1514
1515 // We can choose any index value here and be correct because all elements
1516 // are undefined. Return 0 for better potential for callers to simplify.
1517 return 0;
1518 }
1519
1520 static bool isSplatMask(const int *Mask, EVT VT);
1521
1522 /// Change values in a shuffle permute mask assuming
1523 /// the two vector operands have swapped position.
1524 static void commuteMask(MutableArrayRef<int> Mask) {
1525 unsigned NumElems = Mask.size();
1526 for (unsigned i = 0; i != NumElems; ++i) {
1527 int idx = Mask[i];
1528 if (idx < 0)
1529 continue;
1530 else if (idx < (int)NumElems)
1531 Mask[i] = idx + NumElems;
1532 else
1533 Mask[i] = idx - NumElems;
1534 }
1535 }
1536
1537 static bool classof(const SDNode *N) {
1538 return N->getOpcode() == ISD::VECTOR_SHUFFLE;
1539 }
1540};
1541
1542class ConstantSDNode : public SDNode {
1543 friend class SelectionDAG;
1544
1545 const ConstantInt *Value;
1546
1547 ConstantSDNode(bool isTarget, bool isOpaque, const ConstantInt *val, EVT VT)
1548 : SDNode(isTarget ? ISD::TargetConstant : ISD::Constant, 0, DebugLoc(),
1549 getSDVTList(VT)),
1550 Value(val) {
1551 ConstantSDNodeBits.IsOpaque = isOpaque;
1552 }
1553
1554public:
1555 const ConstantInt *getConstantIntValue() const { return Value; }
1556 const APInt &getAPIntValue() const { return Value->getValue(); }
1557 uint64_t getZExtValue() const { return Value->getZExtValue(); }
1558 int64_t getSExtValue() const { return Value->getSExtValue(); }
1559 uint64_t getLimitedValue(uint64_t Limit = UINT64_MAX(18446744073709551615UL)) {
1560 return Value->getLimitedValue(Limit);
1561 }
1562 MaybeAlign getMaybeAlignValue() const { return Value->getMaybeAlignValue(); }
1563 Align getAlignValue() const { return Value->getAlignValue(); }
1564
1565 bool isOne() const { return Value->isOne(); }
1566 bool isNullValue() const { return Value->isZero(); }
1567 bool isAllOnesValue() const { return Value->isMinusOne(); }
1568
1569 bool isOpaque() const { return ConstantSDNodeBits.IsOpaque; }
1570
1571 static bool classof(const SDNode *N) {
1572 return N->getOpcode() == ISD::Constant ||
1573 N->getOpcode() == ISD::TargetConstant;
1574 }
1575};
1576
1577uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
1578 return cast<ConstantSDNode>(getOperand(Num))->getZExtValue();
1579}
1580
1581const APInt &SDNode::getConstantOperandAPInt(unsigned Num) const {
1582 return cast<ConstantSDNode>(getOperand(Num))->getAPIntValue();
1583}
1584
1585class ConstantFPSDNode : public SDNode {
1586 friend class SelectionDAG;
1587
1588 const ConstantFP *Value;
1589
1590 ConstantFPSDNode(bool isTarget, const ConstantFP *val, EVT VT)
1591 : SDNode(isTarget ? ISD::TargetConstantFP : ISD::ConstantFP, 0,
1592 DebugLoc(), getSDVTList(VT)),
1593 Value(val) {}
1594
1595public:
1596 const APFloat& getValueAPF() const { return Value->getValueAPF(); }
1597 const ConstantFP *getConstantFPValue() const { return Value; }
1598
1599 /// Return true if the value is positive or negative zero.
1600 bool isZero() const { return Value->isZero(); }
1601
1602 /// Return true if the value is a NaN.
1603 bool isNaN() const { return Value->isNaN(); }
1604
1605 /// Return true if the value is an infinity
1606 bool isInfinity() const { return Value->isInfinity(); }
1607
1608 /// Return true if the value is negative.
1609 bool isNegative() const { return Value->isNegative(); }
1610
1611 /// We don't rely on operator== working on double values, as
1612 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
1613 /// As such, this method can be used to do an exact bit-for-bit comparison of
1614 /// two floating point values.
1615
1616 /// We leave the version with the double argument here because it's just so
1617 /// convenient to write "2.0" and the like. Without this function we'd
1618 /// have to duplicate its logic everywhere it's called.
1619 bool isExactlyValue(double V) const {
1620 return Value->getValueAPF().isExactlyValue(V);
1621 }
1622 bool isExactlyValue(const APFloat& V) const;
1623
1624 static bool isValueValidForType(EVT VT, const APFloat& Val);
1625
1626 static bool classof(const SDNode *N) {
1627 return N->getOpcode() == ISD::ConstantFP ||
1628 N->getOpcode() == ISD::TargetConstantFP;
1629 }
1630};
1631
1632/// Returns true if \p V is a constant integer zero.
1633bool isNullConstant(SDValue V);
1634
1635/// Returns true if \p V is an FP constant with a value of positive zero.
1636bool isNullFPConstant(SDValue V);
1637
1638/// Returns true if \p V is an integer constant with all bits set.
1639bool isAllOnesConstant(SDValue V);
1640
1641/// Returns true if \p V is a constant integer one.
1642bool isOneConstant(SDValue V);
1643
1644/// Return the non-bitcasted source operand of \p V if it exists.
1645/// If \p V is not a bitcasted value, it is returned as-is.
1646SDValue peekThroughBitcasts(SDValue V);
1647
1648/// Return the non-bitcasted and one-use source operand of \p V if it exists.
1649/// If \p V is not a bitcasted one-use value, it is returned as-is.
1650SDValue peekThroughOneUseBitcasts(SDValue V);
1651
1652/// Return the non-extracted vector source operand of \p V if it exists.
1653/// If \p V is not an extracted subvector, it is returned as-is.
1654SDValue peekThroughExtractSubvectors(SDValue V);
1655
1656/// Returns true if \p V is a bitwise not operation. Assumes that an all ones
1657/// constant is canonicalized to be operand 1.
1658bool isBitwiseNot(SDValue V, bool AllowUndefs = false);
1659
1660/// Returns the SDNode if it is a constant splat BuildVector or constant int.
1661ConstantSDNode *isConstOrConstSplat(SDValue N, bool AllowUndefs = false,
1662 bool AllowTruncation = false);
1663
1664/// Returns the SDNode if it is a demanded constant splat BuildVector or
1665/// constant int.
1666ConstantSDNode *isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
1667 bool AllowUndefs = false,
1668 bool AllowTruncation = false);
1669
1670/// Returns the SDNode if it is a constant splat BuildVector or constant float.
1671ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, bool AllowUndefs = false);
1672
1673/// Returns the SDNode if it is a demanded constant splat BuildVector or
1674/// constant float.
1675ConstantFPSDNode *isConstOrConstSplatFP(SDValue N, const APInt &DemandedElts,
1676 bool AllowUndefs = false);
1677
1678/// Return true if the value is a constant 0 integer or a splatted vector of
1679/// a constant 0 integer (with no undefs by default).
1680/// Build vector implicit truncation is not an issue for null values.
1681bool isNullOrNullSplat(SDValue V, bool AllowUndefs = false);
1682
1683/// Return true if the value is a constant 1 integer or a splatted vector of a
1684/// constant 1 integer (with no undefs).
1685/// Does not permit build vector implicit truncation.
1686bool isOneOrOneSplat(SDValue V, bool AllowUndefs = false);
1687
1688/// Return true if the value is a constant -1 integer or a splatted vector of a
1689/// constant -1 integer (with no undefs).
1690/// Does not permit build vector implicit truncation.
1691bool isAllOnesOrAllOnesSplat(SDValue V, bool AllowUndefs = false);
1692
1693/// Return true if \p V is either a integer or FP constant.
1694inline bool isIntOrFPConstant(SDValue V) {
1695 return isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V);
1696}
1697
1698class GlobalAddressSDNode : public SDNode {
1699 friend class SelectionDAG;
1700
1701 const GlobalValue *TheGlobal;
1702 int64_t Offset;
1703 unsigned TargetFlags;
1704
1705 GlobalAddressSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL,
1706 const GlobalValue *GA, EVT VT, int64_t o,
1707 unsigned TF);
1708
1709public:
1710 const GlobalValue *getGlobal() const { return TheGlobal; }
1711 int64_t getOffset() const { return Offset; }
1712 unsigned getTargetFlags() const { return TargetFlags; }
1713 // Return the address space this GlobalAddress belongs to.
1714 unsigned getAddressSpace() const;
1715
1716 static bool classof(const SDNode *N) {
1717 return N->getOpcode() == ISD::GlobalAddress ||
1718 N->getOpcode() == ISD::TargetGlobalAddress ||
1719 N->getOpcode() == ISD::GlobalTLSAddress ||
1720 N->getOpcode() == ISD::TargetGlobalTLSAddress;
1721 }
1722};
1723
1724class FrameIndexSDNode : public SDNode {
1725 friend class SelectionDAG;
1726
1727 int FI;
1728
1729 FrameIndexSDNode(int fi, EVT VT, bool isTarg)
1730 : SDNode(isTarg ? ISD::TargetFrameIndex : ISD::FrameIndex,
1731 0, DebugLoc(), getSDVTList(VT)), FI(fi) {
1732 }
1733
1734public:
1735 int getIndex() const { return FI; }
1736
1737 static bool classof(const SDNode *N) {
1738 return N->getOpcode() == ISD::FrameIndex ||
1739 N->getOpcode() == ISD::TargetFrameIndex;
1740 }
1741};
1742
1743/// This SDNode is used for LIFETIME_START/LIFETIME_END values, which indicate
1744/// the offet and size that are started/ended in the underlying FrameIndex.
1745class LifetimeSDNode : public SDNode {
1746 friend class SelectionDAG;
1747 int64_t Size;
1748 int64_t Offset; // -1 if offset is unknown.
1749
1750 LifetimeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl,
1751 SDVTList VTs, int64_t Size, int64_t Offset)
1752 : SDNode(Opcode, Order, dl, VTs), Size(Size), Offset(Offset) {}
1753public:
1754 int64_t getFrameIndex() const {
1755 return cast<FrameIndexSDNode>(getOperand(1))->getIndex();
1756 }
1757
1758 bool hasOffset() const { return Offset >= 0; }
1759 int64_t getOffset() const {
1760 assert(hasOffset() && "offset is unknown")(static_cast <bool> (hasOffset() && "offset is unknown"
) ? void (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1760, __extension__ __PRETTY_FUNCTION__))
;
1761 return Offset;
1762 }
1763 int64_t getSize() const {
1764 assert(hasOffset() && "offset is unknown")(static_cast <bool> (hasOffset() && "offset is unknown"
) ? void (0) : __assert_fail ("hasOffset() && \"offset is unknown\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1764, __extension__ __PRETTY_FUNCTION__))
;
1765 return Size;
1766 }
1767
1768 // Methods to support isa and dyn_cast
1769 static bool classof(const SDNode *N) {
1770 return N->getOpcode() == ISD::LIFETIME_START ||
1771 N->getOpcode() == ISD::LIFETIME_END;
1772 }
1773};
1774
1775/// This SDNode is used for PSEUDO_PROBE values, which are the function guid and
1776/// the index of the basic block being probed. A pseudo probe serves as a place
1777/// holder and will be removed at the end of compilation. It does not have any
1778/// operand because we do not want the instruction selection to deal with any.
1779class PseudoProbeSDNode : public SDNode {
1780 friend class SelectionDAG;
1781 uint64_t Guid;
1782 uint64_t Index;
1783 uint32_t Attributes;
1784
1785 PseudoProbeSDNode(unsigned Opcode, unsigned Order, const DebugLoc &Dl,
1786 SDVTList VTs, uint64_t Guid, uint64_t Index, uint32_t Attr)
1787 : SDNode(Opcode, Order, Dl, VTs), Guid(Guid), Index(Index),
1788 Attributes(Attr) {}
1789
1790public:
1791 uint64_t getGuid() const { return Guid; }
1792 uint64_t getIndex() const { return Index; }
1793 uint32_t getAttributes() const { return Attributes; }
1794
1795 // Methods to support isa and dyn_cast
1796 static bool classof(const SDNode *N) {
1797 return N->getOpcode() == ISD::PSEUDO_PROBE;
1798 }
1799};
1800
1801class JumpTableSDNode : public SDNode {
1802 friend class SelectionDAG;
1803
1804 int JTI;
1805 unsigned TargetFlags;
1806
1807 JumpTableSDNode(int jti, EVT VT, bool isTarg, unsigned TF)
1808 : SDNode(isTarg ? ISD::TargetJumpTable : ISD::JumpTable,
1809 0, DebugLoc(), getSDVTList(VT)), JTI(jti), TargetFlags(TF) {
1810 }
1811
1812public:
1813 int getIndex() const { return JTI; }
1814 unsigned getTargetFlags() const { return TargetFlags; }
1815
1816 static bool classof(const SDNode *N) {
1817 return N->getOpcode() == ISD::JumpTable ||
1818 N->getOpcode() == ISD::TargetJumpTable;
1819 }
1820};
1821
1822class ConstantPoolSDNode : public SDNode {
1823 friend class SelectionDAG;
1824
1825 union {
1826 const Constant *ConstVal;
1827 MachineConstantPoolValue *MachineCPVal;
1828 } Val;
1829 int Offset; // It's a MachineConstantPoolValue if top bit is set.
1830 Align Alignment; // Minimum alignment requirement of CP.
1831 unsigned TargetFlags;
1832
1833 ConstantPoolSDNode(bool isTarget, const Constant *c, EVT VT, int o,
1834 Align Alignment, unsigned TF)
1835 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1836 DebugLoc(), getSDVTList(VT)),
1837 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1838 assert(Offset >= 0 && "Offset is too large")(static_cast <bool> (Offset >= 0 && "Offset is too large"
) ? void (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1838, __extension__ __PRETTY_FUNCTION__))
;
1839 Val.ConstVal = c;
1840 }
1841
1842 ConstantPoolSDNode(bool isTarget, MachineConstantPoolValue *v, EVT VT, int o,
1843 Align Alignment, unsigned TF)
1844 : SDNode(isTarget ? ISD::TargetConstantPool : ISD::ConstantPool, 0,
1845 DebugLoc(), getSDVTList(VT)),
1846 Offset(o), Alignment(Alignment), TargetFlags(TF) {
1847 assert(Offset >= 0 && "Offset is too large")(static_cast <bool> (Offset >= 0 && "Offset is too large"
) ? void (0) : __assert_fail ("Offset >= 0 && \"Offset is too large\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1847, __extension__ __PRETTY_FUNCTION__))
;
1848 Val.MachineCPVal = v;
1849 Offset |= 1 << (sizeof(unsigned)*CHAR_BIT8-1);
1850 }
1851
1852public:
1853 bool isMachineConstantPoolEntry() const {
1854 return Offset < 0;
1855 }
1856
1857 const Constant *getConstVal() const {
1858 assert(!isMachineConstantPoolEntry() && "Wrong constantpool type")(static_cast <bool> (!isMachineConstantPoolEntry() &&
"Wrong constantpool type") ? void (0) : __assert_fail ("!isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1858, __extension__ __PRETTY_FUNCTION__))
;
1859 return Val.ConstVal;
1860 }
1861
1862 MachineConstantPoolValue *getMachineCPVal() const {
1863 assert(isMachineConstantPoolEntry() && "Wrong constantpool type")(static_cast <bool> (isMachineConstantPoolEntry() &&
"Wrong constantpool type") ? void (0) : __assert_fail ("isMachineConstantPoolEntry() && \"Wrong constantpool type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1863, __extension__ __PRETTY_FUNCTION__))
;
1864 return Val.MachineCPVal;
1865 }
1866
1867 int getOffset() const {
1868 return Offset & ~(1 << (sizeof(unsigned)*CHAR_BIT8-1));
1869 }
1870
1871 // Return the alignment of this constant pool object, which is either 0 (for
1872 // default alignment) or the desired value.
1873 Align getAlign() const { return Alignment; }
1874 unsigned getTargetFlags() const { return TargetFlags; }
1875
1876 Type *getType() const;
1877
1878 static bool classof(const SDNode *N) {
1879 return N->getOpcode() == ISD::ConstantPool ||
1880 N->getOpcode() == ISD::TargetConstantPool;
1881 }
1882};
1883
1884/// Completely target-dependent object reference.
1885class TargetIndexSDNode : public SDNode {
1886 friend class SelectionDAG;
1887
1888 unsigned TargetFlags;
1889 int Index;
1890 int64_t Offset;
1891
1892public:
1893 TargetIndexSDNode(int Idx, EVT VT, int64_t Ofs, unsigned TF)
1894 : SDNode(ISD::TargetIndex, 0, DebugLoc(), getSDVTList(VT)),
1895 TargetFlags(TF), Index(Idx), Offset(Ofs) {}
1896
1897 unsigned getTargetFlags() const { return TargetFlags; }
1898 int getIndex() const { return Index; }
1899 int64_t getOffset() const { return Offset; }
1900
1901 static bool classof(const SDNode *N) {
1902 return N->getOpcode() == ISD::TargetIndex;
1903 }
1904};
1905
1906class BasicBlockSDNode : public SDNode {
1907 friend class SelectionDAG;
1908
1909 MachineBasicBlock *MBB;
1910
1911 /// Debug info is meaningful and potentially useful here, but we create
1912 /// blocks out of order when they're jumped to, which makes it a bit
1913 /// harder. Let's see if we need it first.
1914 explicit BasicBlockSDNode(MachineBasicBlock *mbb)
1915 : SDNode(ISD::BasicBlock, 0, DebugLoc(), getSDVTList(MVT::Other)), MBB(mbb)
1916 {}
1917
1918public:
1919 MachineBasicBlock *getBasicBlock() const { return MBB; }
1920
1921 static bool classof(const SDNode *N) {
1922 return N->getOpcode() == ISD::BasicBlock;
1923 }
1924};
1925
1926/// A "pseudo-class" with methods for operating on BUILD_VECTORs.
1927class BuildVectorSDNode : public SDNode {
1928public:
1929 // These are constructed as SDNodes and then cast to BuildVectorSDNodes.
1930 explicit BuildVectorSDNode() = delete;
1931
1932 /// Check if this is a constant splat, and if so, find the
1933 /// smallest element size that splats the vector. If MinSplatBits is
1934 /// nonzero, the element size must be at least that large. Note that the
1935 /// splat element may be the entire vector (i.e., a one element vector).
1936 /// Returns the splat element value in SplatValue. Any undefined bits in
1937 /// that value are zero, and the corresponding bits in the SplatUndef mask
1938 /// are set. The SplatBitSize value is set to the splat element size in
1939 /// bits. HasAnyUndefs is set to true if any bits in the vector are
1940 /// undefined. isBigEndian describes the endianness of the target.
1941 bool isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
1942 unsigned &SplatBitSize, bool &HasAnyUndefs,
1943 unsigned MinSplatBits = 0,
1944 bool isBigEndian = false) const;
1945
1946 /// Returns the demanded splatted value or a null value if this is not a
1947 /// splat.
1948 ///
1949 /// The DemandedElts mask indicates the elements that must be in the splat.
1950 /// If passed a non-null UndefElements bitvector, it will resize it to match
1951 /// the vector width and set the bits where elements are undef.
1952 SDValue getSplatValue(const APInt &DemandedElts,
1953 BitVector *UndefElements = nullptr) const;
1954
1955 /// Returns the splatted value or a null value if this is not a splat.
1956 ///
1957 /// If passed a non-null UndefElements bitvector, it will resize it to match
1958 /// the vector width and set the bits where elements are undef.
1959 SDValue getSplatValue(BitVector *UndefElements = nullptr) const;
1960
1961 /// Find the shortest repeating sequence of values in the build vector.
1962 ///
1963 /// e.g. { u, X, u, X, u, u, X, u } -> { X }
1964 /// { X, Y, u, Y, u, u, X, u } -> { X, Y }
1965 ///
1966 /// Currently this must be a power-of-2 build vector.
1967 /// The DemandedElts mask indicates the elements that must be present,
1968 /// undemanded elements in Sequence may be null (SDValue()). If passed a
1969 /// non-null UndefElements bitvector, it will resize it to match the original
1970 /// vector width and set the bits where elements are undef. If result is
1971 /// false, Sequence will be empty.
1972 bool getRepeatedSequence(const APInt &DemandedElts,
1973 SmallVectorImpl<SDValue> &Sequence,
1974 BitVector *UndefElements = nullptr) const;
1975
1976 /// Find the shortest repeating sequence of values in the build vector.
1977 ///
1978 /// e.g. { u, X, u, X, u, u, X, u } -> { X }
1979 /// { X, Y, u, Y, u, u, X, u } -> { X, Y }
1980 ///
1981 /// Currently this must be a power-of-2 build vector.
1982 /// If passed a non-null UndefElements bitvector, it will resize it to match
1983 /// the original vector width and set the bits where elements are undef.
1984 /// If result is false, Sequence will be empty.
1985 bool getRepeatedSequence(SmallVectorImpl<SDValue> &Sequence,
1986 BitVector *UndefElements = nullptr) const;
1987
1988 /// Returns the demanded splatted constant or null if this is not a constant
1989 /// splat.
1990 ///
1991 /// The DemandedElts mask indicates the elements that must be in the splat.
1992 /// If passed a non-null UndefElements bitvector, it will resize it to match
1993 /// the vector width and set the bits where elements are undef.
1994 ConstantSDNode *
1995 getConstantSplatNode(const APInt &DemandedElts,
1996 BitVector *UndefElements = nullptr) const;
1997
1998 /// Returns the splatted constant or null if this is not a constant
1999 /// splat.
2000 ///
2001 /// If passed a non-null UndefElements bitvector, it will resize it to match
2002 /// the vector width and set the bits where elements are undef.
2003 ConstantSDNode *
2004 getConstantSplatNode(BitVector *UndefElements = nullptr) const;
2005
2006 /// Returns the demanded splatted constant FP or null if this is not a
2007 /// constant FP splat.
2008 ///
2009 /// The DemandedElts mask indicates the elements that must be in the splat.
2010 /// If passed a non-null UndefElements bitvector, it will resize it to match
2011 /// the vector width and set the bits where elements are undef.
2012 ConstantFPSDNode *
2013 getConstantFPSplatNode(const APInt &DemandedElts,
2014 BitVector *UndefElements = nullptr) const;
2015
2016 /// Returns the splatted constant FP or null if this is not a constant
2017 /// FP splat.
2018 ///
2019 /// If passed a non-null UndefElements bitvector, it will resize it to match
2020 /// the vector width and set the bits where elements are undef.
2021 ConstantFPSDNode *
2022 getConstantFPSplatNode(BitVector *UndefElements = nullptr) const;
2023
2024 /// If this is a constant FP splat and the splatted constant FP is an
2025 /// exact power or 2, return the log base 2 integer value. Otherwise,
2026 /// return -1.
2027 ///
2028 /// The BitWidth specifies the necessary bit precision.
2029 int32_t getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
2030 uint32_t BitWidth) const;
2031
2032 bool isConstant() const;
2033
2034 static bool classof(const SDNode *N) {
2035 return N->getOpcode() == ISD::BUILD_VECTOR;
2036 }
2037};
2038
2039/// An SDNode that holds an arbitrary LLVM IR Value. This is
2040/// used when the SelectionDAG needs to make a simple reference to something
2041/// in the LLVM IR representation.
2042///
2043class SrcValueSDNode : public SDNode {
2044 friend class SelectionDAG;
2045
2046 const Value *V;
2047
2048 /// Create a SrcValue for a general value.
2049 explicit SrcValueSDNode(const Value *v)
2050 : SDNode(ISD::SRCVALUE, 0, DebugLoc(), getSDVTList(MVT::Other)), V(v) {}
2051
2052public:
2053 /// Return the contained Value.
2054 const Value *getValue() const { return V; }
2055
2056 static bool classof(const SDNode *N) {
2057 return N->getOpcode() == ISD::SRCVALUE;
2058 }
2059};
2060
2061class MDNodeSDNode : public SDNode {
2062 friend class SelectionDAG;
2063
2064 const MDNode *MD;
2065
2066 explicit MDNodeSDNode(const MDNode *md)
2067 : SDNode(ISD::MDNODE_SDNODE, 0, DebugLoc(), getSDVTList(MVT::Other)), MD(md)
2068 {}
2069
2070public:
2071 const MDNode *getMD() const { return MD; }
2072
2073 static bool classof(const SDNode *N) {
2074 return N->getOpcode() == ISD::MDNODE_SDNODE;
2075 }
2076};
2077
2078class RegisterSDNode : public SDNode {
2079 friend class SelectionDAG;
2080
2081 Register Reg;
2082
2083 RegisterSDNode(Register reg, EVT VT)
2084 : SDNode(ISD::Register, 0, DebugLoc(), getSDVTList(VT)), Reg(reg) {}
2085
2086public:
2087 Register getReg() const { return Reg; }
2088
2089 static bool classof(const SDNode *N) {
2090 return N->getOpcode() == ISD::Register;
2091 }
2092};
2093
2094class RegisterMaskSDNode : public SDNode {
2095 friend class SelectionDAG;
2096
2097 // The memory for RegMask is not owned by the node.
2098 const uint32_t *RegMask;
2099
2100 RegisterMaskSDNode(const uint32_t *mask)
2101 : SDNode(ISD::RegisterMask, 0, DebugLoc(), getSDVTList(MVT::Untyped)),
2102 RegMask(mask) {}
2103
2104public:
2105 const uint32_t *getRegMask() const { return RegMask; }
2106
2107 static bool classof(const SDNode *N) {
2108 return N->getOpcode() == ISD::RegisterMask;
2109 }
2110};
2111
2112class BlockAddressSDNode : public SDNode {
2113 friend class SelectionDAG;
2114
2115 const BlockAddress *BA;
2116 int64_t Offset;
2117 unsigned TargetFlags;
2118
2119 BlockAddressSDNode(unsigned NodeTy, EVT VT, const BlockAddress *ba,
2120 int64_t o, unsigned Flags)
2121 : SDNode(NodeTy, 0, DebugLoc(), getSDVTList(VT)),
2122 BA(ba), Offset(o), TargetFlags(Flags) {}
2123
2124public:
2125 const BlockAddress *getBlockAddress() const { return BA; }
2126 int64_t getOffset() const { return Offset; }
2127 unsigned getTargetFlags() const { return TargetFlags; }
2128
2129 static bool classof(const SDNode *N) {
2130 return N->getOpcode() == ISD::BlockAddress ||
2131 N->getOpcode() == ISD::TargetBlockAddress;
2132 }
2133};
2134
2135class LabelSDNode : public SDNode {
2136 friend class SelectionDAG;
2137
2138 MCSymbol *Label;
2139
2140 LabelSDNode(unsigned Opcode, unsigned Order, const DebugLoc &dl, MCSymbol *L)
2141 : SDNode(Opcode, Order, dl, getSDVTList(MVT::Other)), Label(L) {
2142 assert(LabelSDNode::classof(this) && "not a label opcode")(static_cast <bool> (LabelSDNode::classof(this) &&
"not a label opcode") ? void (0) : __assert_fail ("LabelSDNode::classof(this) && \"not a label opcode\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2142, __extension__ __PRETTY_FUNCTION__))
;
2143 }
2144
2145public:
2146 MCSymbol *getLabel() const { return Label; }
2147
2148 static bool classof(const SDNode *N) {
2149 return N->getOpcode() == ISD::EH_LABEL ||
2150 N->getOpcode() == ISD::ANNOTATION_LABEL;
2151 }
2152};
2153
2154class ExternalSymbolSDNode : public SDNode {
2155 friend class SelectionDAG;
2156
2157 const char *Symbol;
2158 unsigned TargetFlags;
2159
2160 ExternalSymbolSDNode(bool isTarget, const char *Sym, unsigned TF, EVT VT)
2161 : SDNode(isTarget ? ISD::TargetExternalSymbol : ISD::ExternalSymbol, 0,
2162 DebugLoc(), getSDVTList(VT)),
2163 Symbol(Sym), TargetFlags(TF) {}
2164
2165public:
2166 const char *getSymbol() const { return Symbol; }
2167 unsigned getTargetFlags() const { return TargetFlags; }
2168
2169 static bool classof(const SDNode *N) {
2170 return N->getOpcode() == ISD::ExternalSymbol ||
2171 N->getOpcode() == ISD::TargetExternalSymbol;
2172 }
2173};
2174
2175class MCSymbolSDNode : public SDNode {
2176 friend class SelectionDAG;
2177
2178 MCSymbol *Symbol;
2179
2180 MCSymbolSDNode(MCSymbol *Symbol, EVT VT)
2181 : SDNode(ISD::MCSymbol, 0, DebugLoc(), getSDVTList(VT)), Symbol(Symbol) {}
2182
2183public:
2184 MCSymbol *getMCSymbol() const { return Symbol; }
2185
2186 static bool classof(const SDNode *N) {
2187 return N->getOpcode() == ISD::MCSymbol;
2188 }
2189};
2190
2191class CondCodeSDNode : public SDNode {
2192 friend class SelectionDAG;
2193
2194 ISD::CondCode Condition;
2195
2196 explicit CondCodeSDNode(ISD::CondCode Cond)
2197 : SDNode(ISD::CONDCODE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2198 Condition(Cond) {}
2199
2200public:
2201 ISD::CondCode get() const { return Condition; }
2202
2203 static bool classof(const SDNode *N) {
2204 return N->getOpcode() == ISD::CONDCODE;
2205 }
2206};
2207
2208/// This class is used to represent EVT's, which are used
2209/// to parameterize some operations.
2210class VTSDNode : public SDNode {
2211 friend class SelectionDAG;
2212
2213 EVT ValueType;
2214
2215 explicit VTSDNode(EVT VT)
2216 : SDNode(ISD::VALUETYPE, 0, DebugLoc(), getSDVTList(MVT::Other)),
2217 ValueType(VT) {}
2218
2219public:
2220 EVT getVT() const { return ValueType; }
2221
2222 static bool classof(const SDNode *N) {
2223 return N->getOpcode() == ISD::VALUETYPE;
2224 }
2225};
2226
2227/// Base class for LoadSDNode and StoreSDNode
2228class LSBaseSDNode : public MemSDNode {
2229public:
2230 LSBaseSDNode(ISD::NodeType NodeTy, unsigned Order, const DebugLoc &dl,
2231 SDVTList VTs, ISD::MemIndexedMode AM, EVT MemVT,
2232 MachineMemOperand *MMO)
2233 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2234 LSBaseSDNodeBits.AddressingMode = AM;
2235 assert(getAddressingMode() == AM && "Value truncated")(static_cast <bool> (getAddressingMode() == AM &&
"Value truncated") ? void (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2235, __extension__ __PRETTY_FUNCTION__))
;
2236 }
2237
2238 const SDValue &getOffset() const {
2239 return getOperand(getOpcode() == ISD::LOAD ? 2 : 3);
2240 }
2241
2242 /// Return the addressing mode for this load or store:
2243 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2244 ISD::MemIndexedMode getAddressingMode() const {
2245 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2246 }
2247
2248 /// Return true if this is a pre/post inc/dec load/store.
2249 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2250
2251 /// Return true if this is NOT a pre/post inc/dec load/store.
2252 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2253
2254 static bool classof(const SDNode *N) {
2255 return N->getOpcode() == ISD::LOAD ||
2256 N->getOpcode() == ISD::STORE;
2257 }
2258};
2259
2260/// This class is used to represent ISD::LOAD nodes.
2261class LoadSDNode : public LSBaseSDNode {
2262 friend class SelectionDAG;
2263
2264 LoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2265 ISD::MemIndexedMode AM, ISD::LoadExtType ETy, EVT MemVT,
2266 MachineMemOperand *MMO)
2267 : LSBaseSDNode(ISD::LOAD, Order, dl, VTs, AM, MemVT, MMO) {
2268 LoadSDNodeBits.ExtTy = ETy;
2269 assert(readMem() && "Load MachineMemOperand is not a load!")(static_cast <bool> (readMem() && "Load MachineMemOperand is not a load!"
) ? void (0) : __assert_fail ("readMem() && \"Load MachineMemOperand is not a load!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2269, __extension__ __PRETTY_FUNCTION__))
;
2270 assert(!writeMem() && "Load MachineMemOperand is a store!")(static_cast <bool> (!writeMem() && "Load MachineMemOperand is a store!"
) ? void (0) : __assert_fail ("!writeMem() && \"Load MachineMemOperand is a store!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2270, __extension__ __PRETTY_FUNCTION__))
;
2271 }
2272
2273public:
2274 /// Return whether this is a plain node,
2275 /// or one of the varieties of value-extending loads.
2276 ISD::LoadExtType getExtensionType() const {
2277 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2278 }
2279
2280 const SDValue &getBasePtr() const { return getOperand(1); }
2281 const SDValue &getOffset() const { return getOperand(2); }
2282
2283 static bool classof(const SDNode *N) {
2284 return N->getOpcode() == ISD::LOAD;
2285 }
2286};
2287
2288/// This class is used to represent ISD::STORE nodes.
2289class StoreSDNode : public LSBaseSDNode {
2290 friend class SelectionDAG;
2291
2292 StoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2293 ISD::MemIndexedMode AM, bool isTrunc, EVT MemVT,
2294 MachineMemOperand *MMO)
2295 : LSBaseSDNode(ISD::STORE, Order, dl, VTs, AM, MemVT, MMO) {
2296 StoreSDNodeBits.IsTruncating = isTrunc;
2297 assert(!readMem() && "Store MachineMemOperand is a load!")(static_cast <bool> (!readMem() && "Store MachineMemOperand is a load!"
) ? void (0) : __assert_fail ("!readMem() && \"Store MachineMemOperand is a load!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2297, __extension__ __PRETTY_FUNCTION__))
;
2298 assert(writeMem() && "Store MachineMemOperand is not a store!")(static_cast <bool> (writeMem() && "Store MachineMemOperand is not a store!"
) ? void (0) : __assert_fail ("writeMem() && \"Store MachineMemOperand is not a store!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2298, __extension__ __PRETTY_FUNCTION__))
;
2299 }
2300
2301public:
2302 /// Return true if the op does a truncation before store.
2303 /// For integers this is the same as doing a TRUNCATE and storing the result.
2304 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2305 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2306 void setTruncatingStore(bool Truncating) {
2307 StoreSDNodeBits.IsTruncating = Truncating;
2308 }
2309
2310 const SDValue &getValue() const { return getOperand(1); }
2311 const SDValue &getBasePtr() const { return getOperand(2); }
2312 const SDValue &getOffset() const { return getOperand(3); }
2313
2314 static bool classof(const SDNode *N) {
2315 return N->getOpcode() == ISD::STORE;
2316 }
2317};
2318
2319/// This base class is used to represent MLOAD and MSTORE nodes
2320class MaskedLoadStoreSDNode : public MemSDNode {
2321public:
2322 friend class SelectionDAG;
2323
2324 MaskedLoadStoreSDNode(ISD::NodeType NodeTy, unsigned Order,
2325 const DebugLoc &dl, SDVTList VTs,
2326 ISD::MemIndexedMode AM, EVT MemVT,
2327 MachineMemOperand *MMO)
2328 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2329 LSBaseSDNodeBits.AddressingMode = AM;
2330 assert(getAddressingMode() == AM && "Value truncated")(static_cast <bool> (getAddressingMode() == AM &&
"Value truncated") ? void (0) : __assert_fail ("getAddressingMode() == AM && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2330, __extension__ __PRETTY_FUNCTION__))
;
2331 }
2332
2333 // MaskedLoadSDNode (Chain, ptr, offset, mask, passthru)
2334 // MaskedStoreSDNode (Chain, data, ptr, offset, mask)
2335 // Mask is a vector of i1 elements
2336 const SDValue &getOffset() const {
2337 return getOperand(getOpcode() == ISD::MLOAD ? 2 : 3);
2338 }
2339 const SDValue &getMask() const {
2340 return getOperand(getOpcode() == ISD::MLOAD ? 3 : 4);
2341 }
2342
2343 /// Return the addressing mode for this load or store:
2344 /// unindexed, pre-inc, pre-dec, post-inc, or post-dec.
2345 ISD::MemIndexedMode getAddressingMode() const {
2346 return static_cast<ISD::MemIndexedMode>(LSBaseSDNodeBits.AddressingMode);
2347 }
2348
2349 /// Return true if this is a pre/post inc/dec load/store.
2350 bool isIndexed() const { return getAddressingMode() != ISD::UNINDEXED; }
2351
2352 /// Return true if this is NOT a pre/post inc/dec load/store.
2353 bool isUnindexed() const { return getAddressingMode() == ISD::UNINDEXED; }
2354
2355 static bool classof(const SDNode *N) {
2356 return N->getOpcode() == ISD::MLOAD ||
2357 N->getOpcode() == ISD::MSTORE;
2358 }
2359};
2360
2361/// This class is used to represent an MLOAD node
2362class MaskedLoadSDNode : public MaskedLoadStoreSDNode {
2363public:
2364 friend class SelectionDAG;
2365
2366 MaskedLoadSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2367 ISD::MemIndexedMode AM, ISD::LoadExtType ETy,
2368 bool IsExpanding, EVT MemVT, MachineMemOperand *MMO)
2369 : MaskedLoadStoreSDNode(ISD::MLOAD, Order, dl, VTs, AM, MemVT, MMO) {
2370 LoadSDNodeBits.ExtTy = ETy;
2371 LoadSDNodeBits.IsExpanding = IsExpanding;
2372 }
2373
2374 ISD::LoadExtType getExtensionType() const {
2375 return static_cast<ISD::LoadExtType>(LoadSDNodeBits.ExtTy);
2376 }
2377
2378 const SDValue &getBasePtr() const { return getOperand(1); }
2379 const SDValue &getOffset() const { return getOperand(2); }
2380 const SDValue &getMask() const { return getOperand(3); }
2381 const SDValue &getPassThru() const { return getOperand(4); }
2382
2383 static bool classof(const SDNode *N) {
2384 return N->getOpcode() == ISD::MLOAD;
2385 }
2386
2387 bool isExpandingLoad() const { return LoadSDNodeBits.IsExpanding; }
2388};
2389
2390/// This class is used to represent an MSTORE node
2391class MaskedStoreSDNode : public MaskedLoadStoreSDNode {
2392public:
2393 friend class SelectionDAG;
2394
2395 MaskedStoreSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2396 ISD::MemIndexedMode AM, bool isTrunc, bool isCompressing,
2397 EVT MemVT, MachineMemOperand *MMO)
2398 : MaskedLoadStoreSDNode(ISD::MSTORE, Order, dl, VTs, AM, MemVT, MMO) {
2399 StoreSDNodeBits.IsTruncating = isTrunc;
2400 StoreSDNodeBits.IsCompressing = isCompressing;
2401 }
2402
2403 /// Return true if the op does a truncation before store.
2404 /// For integers this is the same as doing a TRUNCATE and storing the result.
2405 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2406 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2407
2408 /// Returns true if the op does a compression to the vector before storing.
2409 /// The node contiguously stores the active elements (integers or floats)
2410 /// in src (those with their respective bit set in writemask k) to unaligned
2411 /// memory at base_addr.
2412 bool isCompressingStore() const { return StoreSDNodeBits.IsCompressing; }
2413
2414 const SDValue &getValue() const { return getOperand(1); }
2415 const SDValue &getBasePtr() const { return getOperand(2); }
2416 const SDValue &getOffset() const { return getOperand(3); }
2417 const SDValue &getMask() const { return getOperand(4); }
2418
2419 static bool classof(const SDNode *N) {
2420 return N->getOpcode() == ISD::MSTORE;
2421 }
2422};
2423
2424/// This is a base class used to represent
2425/// MGATHER and MSCATTER nodes
2426///
2427class MaskedGatherScatterSDNode : public MemSDNode {
2428public:
2429 friend class SelectionDAG;
2430
2431 MaskedGatherScatterSDNode(ISD::NodeType NodeTy, unsigned Order,
2432 const DebugLoc &dl, SDVTList VTs, EVT MemVT,
2433 MachineMemOperand *MMO, ISD::MemIndexType IndexType)
2434 : MemSDNode(NodeTy, Order, dl, VTs, MemVT, MMO) {
2435 LSBaseSDNodeBits.AddressingMode = IndexType;
2436 assert(getIndexType() == IndexType && "Value truncated")(static_cast <bool> (getIndexType() == IndexType &&
"Value truncated") ? void (0) : __assert_fail ("getIndexType() == IndexType && \"Value truncated\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2436, __extension__ __PRETTY_FUNCTION__))
;
2437 }
2438
2439 /// How is Index applied to BasePtr when computing addresses.
2440 ISD::MemIndexType getIndexType() const {
2441 return static_cast<ISD::MemIndexType>(LSBaseSDNodeBits.AddressingMode);
2442 }
2443 void setIndexType(ISD::MemIndexType IndexType) {
2444 LSBaseSDNodeBits.AddressingMode = IndexType;
2445 }
2446 bool isIndexScaled() const {
2447 return (getIndexType() == ISD::SIGNED_SCALED) ||
2448 (getIndexType() == ISD::UNSIGNED_SCALED);
2449 }
2450 bool isIndexSigned() const {
2451 return (getIndexType() == ISD::SIGNED_SCALED) ||
2452 (getIndexType() == ISD::SIGNED_UNSCALED);
2453 }
2454
2455 // In the both nodes address is Op1, mask is Op2:
2456 // MaskedGatherSDNode (Chain, passthru, mask, base, index, scale)
2457 // MaskedScatterSDNode (Chain, value, mask, base, index, scale)
2458 // Mask is a vector of i1 elements
2459 const SDValue &getBasePtr() const { return getOperand(3); }
2460 const SDValue &getIndex() const { return getOperand(4); }
2461 const SDValue &getMask() const { return getOperand(2); }
2462 const SDValue &getScale() const { return getOperand(5); }
2463
2464 static bool classof(const SDNode *N) {
2465 return N->getOpcode() == ISD::MGATHER ||
2466 N->getOpcode() == ISD::MSCATTER;
2467 }
2468};
2469
2470/// This class is used to represent an MGATHER node
2471///
2472class MaskedGatherSDNode : public MaskedGatherScatterSDNode {
2473public:
2474 friend class SelectionDAG;
2475
2476 MaskedGatherSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2477 EVT MemVT, MachineMemOperand *MMO,
2478 ISD::MemIndexType IndexType, ISD::LoadExtType ETy)
2479 : MaskedGatherScatterSDNode(ISD::MGATHER, Order, dl, VTs, MemVT, MMO,
2480 IndexType) {
2481 LoadSDNodeBits.ExtTy = ETy;
2482 }
2483
2484 const SDValue &getPassThru() const { return getOperand(1); }
2485
2486 ISD::LoadExtType getExtensionType() const {
2487 return ISD::LoadExtType(LoadSDNodeBits.ExtTy);
2488 }
2489
2490 static bool classof(const SDNode *N) {
2491 return N->getOpcode() == ISD::MGATHER;
2492 }
2493};
2494
2495/// This class is used to represent an MSCATTER node
2496///
2497class MaskedScatterSDNode : public MaskedGatherScatterSDNode {
2498public:
2499 friend class SelectionDAG;
2500
2501 MaskedScatterSDNode(unsigned Order, const DebugLoc &dl, SDVTList VTs,
2502 EVT MemVT, MachineMemOperand *MMO,
2503 ISD::MemIndexType IndexType, bool IsTrunc)
2504 : MaskedGatherScatterSDNode(ISD::MSCATTER, Order, dl, VTs, MemVT, MMO,
2505 IndexType) {
2506 StoreSDNodeBits.IsTruncating = IsTrunc;
2507 }
2508
2509 /// Return true if the op does a truncation before store.
2510 /// For integers this is the same as doing a TRUNCATE and storing the result.
2511 /// For floats, it is the same as doing an FP_ROUND and storing the result.
2512 bool isTruncatingStore() const { return StoreSDNodeBits.IsTruncating; }
2513
2514 const SDValue &getValue() const { return getOperand(1); }
2515
2516 static bool classof(const SDNode *N) {
2517 return N->getOpcode() == ISD::MSCATTER;
2518 }
2519};
2520
2521/// An SDNode that represents everything that will be needed
2522/// to construct a MachineInstr. These nodes are created during the
2523/// instruction selection proper phase.
2524///
2525/// Note that the only supported way to set the `memoperands` is by calling the
2526/// `SelectionDAG::setNodeMemRefs` function as the memory management happens
2527/// inside the DAG rather than in the node.
2528class MachineSDNode : public SDNode {
2529private:
2530 friend class SelectionDAG;
2531
2532 MachineSDNode(unsigned Opc, unsigned Order, const DebugLoc &DL, SDVTList VTs)
2533 : SDNode(Opc, Order, DL, VTs) {}
2534
2535 // We use a pointer union between a single `MachineMemOperand` pointer and
2536 // a pointer to an array of `MachineMemOperand` pointers. This is null when
2537 // the number of these is zero, the single pointer variant used when the
2538 // number is one, and the array is used for larger numbers.
2539 //
2540 // The array is allocated via the `SelectionDAG`'s allocator and so will
2541 // always live until the DAG is cleaned up and doesn't require ownership here.
2542 //
2543 // We can't use something simpler like `TinyPtrVector` here because `SDNode`
2544 // subclasses aren't managed in a conforming C++ manner. See the comments on
2545 // `SelectionDAG::MorphNodeTo` which details what all goes on, but the
2546 // constraint here is that these don't manage memory with their constructor or
2547 // destructor and can be initialized to a good state even if they start off
2548 // uninitialized.
2549 PointerUnion<MachineMemOperand *, MachineMemOperand **> MemRefs = {};
2550
2551 // Note that this could be folded into the above `MemRefs` member if doing so
2552 // is advantageous at some point. We don't need to store this in most cases.
2553 // However, at the moment this doesn't appear to make the allocation any
2554 // smaller and makes the code somewhat simpler to read.
2555 int NumMemRefs = 0;
2556
2557public:
2558 using mmo_iterator = ArrayRef<MachineMemOperand *>::const_iterator;
2559
2560 ArrayRef<MachineMemOperand *> memoperands() const {
2561 // Special case the common cases.
2562 if (NumMemRefs == 0)
2563 return {};
2564 if (NumMemRefs == 1)
2565 return makeArrayRef(MemRefs.getAddrOfPtr1(), 1);
2566
2567 // Otherwise we have an actual array.
2568 return makeArrayRef(MemRefs.get<MachineMemOperand **>(), NumMemRefs);
2569 }
2570 mmo_iterator memoperands_begin() const { return memoperands().begin(); }
2571 mmo_iterator memoperands_end() const { return memoperands().end(); }
2572 bool memoperands_empty() const { return memoperands().empty(); }
2573
2574 /// Clear out the memory reference descriptor list.
2575 void clearMemRefs() {
2576 MemRefs = nullptr;
2577 NumMemRefs = 0;
2578 }
2579
2580 static bool classof(const SDNode *N) {
2581 return N->isMachineOpcode();
2582 }
2583};
2584
2585/// An SDNode that records if a register contains a value that is guaranteed to
2586/// be aligned accordingly.
2587class AssertAlignSDNode : public SDNode {
2588 Align Alignment;
2589
2590public:
2591 AssertAlignSDNode(unsigned Order, const DebugLoc &DL, EVT VT, Align A)
2592 : SDNode(ISD::AssertAlign, Order, DL, getSDVTList(VT)), Alignment(A) {}
2593
2594 Align getAlign() const { return Alignment; }
2595
2596 static bool classof(const SDNode *N) {
2597 return N->getOpcode() == ISD::AssertAlign;
2598 }
2599};
2600
2601class SDNodeIterator {
2602 const SDNode *Node;
2603 unsigned Operand;
2604
2605 SDNodeIterator(const SDNode *N, unsigned Op) : Node(N), Operand(Op) {}
2606
2607public:
2608 using iterator_category = std::forward_iterator_tag;
2609 using value_type = SDNode;
2610 using difference_type = std::ptrdiff_t;
2611 using pointer = value_type *;
2612 using reference = value_type &;
2613
2614 bool operator==(const SDNodeIterator& x) const {
2615 return Operand == x.Operand;
2616 }
2617 bool operator!=(const SDNodeIterator& x) const { return !operator==(x); }
2618
2619 pointer operator*() const {
2620 return Node->getOperand(Operand).getNode();
2621 }
2622 pointer operator->() const { return operator*(); }
2623
2624 SDNodeIterator& operator++() { // Preincrement
2625 ++Operand;
2626 return *this;
2627 }
2628 SDNodeIterator operator++(int) { // Postincrement
2629 SDNodeIterator tmp = *this; ++*this; return tmp;
2630 }
2631 size_t operator-(SDNodeIterator Other) const {
2632 assert(Node == Other.Node &&(static_cast <bool> (Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? void (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2633, __extension__ __PRETTY_FUNCTION__))
2633 "Cannot compare iterators of two different nodes!")(static_cast <bool> (Node == Other.Node && "Cannot compare iterators of two different nodes!"
) ? void (0) : __assert_fail ("Node == Other.Node && \"Cannot compare iterators of two different nodes!\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 2633, __extension__ __PRETTY_FUNCTION__))
;
2634 return Operand - Other.Operand;
2635 }
2636
2637 static SDNodeIterator begin(const SDNode *N) { return SDNodeIterator(N, 0); }
2638 static SDNodeIterator end (const SDNode *N) {
2639 return SDNodeIterator(N, N->getNumOperands());
2640 }
2641
2642 unsigned getOperand() const { return Operand; }
2643 const SDNode *getNode() const { return Node; }
2644};
2645
2646template <> struct GraphTraits<SDNode*> {
2647 using NodeRef = SDNode *;
2648 using ChildIteratorType = SDNodeIterator;
2649
2650 static NodeRef getEntryNode(SDNode *N) { return N; }
2651
2652 static ChildIteratorType child_begin(NodeRef N) {
2653 return SDNodeIterator::begin(N);
2654 }
2655
2656 static ChildIteratorType child_end(NodeRef N) {
2657 return SDNodeIterator::end(N);
2658 }
2659};
2660
2661/// A representation of the largest SDNode, for use in sizeof().
2662///
2663/// This needs to be a union because the largest node differs on 32 bit systems
2664/// with 4 and 8 byte pointer alignment, respectively.
2665using LargestSDNode = AlignedCharArrayUnion<AtomicSDNode, TargetIndexSDNode,
2666 BlockAddressSDNode,
2667 GlobalAddressSDNode,
2668 PseudoProbeSDNode>;
2669
2670/// The SDNode class with the greatest alignment requirement.
2671using MostAlignedSDNode = GlobalAddressSDNode;
2672
2673namespace ISD {
2674
2675 /// Returns true if the specified node is a non-extending and unindexed load.
2676 inline bool isNormalLoad(const SDNode *N) {
2677 const LoadSDNode *Ld = dyn_cast<LoadSDNode>(N);
2678 return Ld && Ld->getExtensionType() == ISD::NON_EXTLOAD &&
2679 Ld->getAddressingMode() == ISD::UNINDEXED;
2680 }
2681
2682 /// Returns true if the specified node is a non-extending load.
2683 inline bool isNON_EXTLoad(const SDNode *N) {
2684 return isa<LoadSDNode>(N) &&
2685 cast<LoadSDNode>(N)->getExtensionType() == ISD::NON_EXTLOAD;
2686 }
2687
2688 /// Returns true if the specified node is a EXTLOAD.
2689 inline bool isEXTLoad(const SDNode *N) {
2690 return isa<LoadSDNode>(N) &&
2691 cast<LoadSDNode>(N)->getExtensionType() == ISD::EXTLOAD;
2692 }
2693
2694 /// Returns true if the specified node is a SEXTLOAD.
2695 inline bool isSEXTLoad(const SDNode *N) {
2696 return isa<LoadSDNode>(N) &&
2697 cast<LoadSDNode>(N)->getExtensionType() == ISD::SEXTLOAD;
2698 }
2699
2700 /// Returns true if the specified node is a ZEXTLOAD.
2701 inline bool isZEXTLoad(const SDNode *N) {
2702 return isa<LoadSDNode>(N) &&
2703 cast<LoadSDNode>(N)->getExtensionType() == ISD::ZEXTLOAD;
2704 }
2705
2706 /// Returns true if the specified node is an unindexed load.
2707 inline bool isUNINDEXEDLoad(const SDNode *N) {
2708 return isa<LoadSDNode>(N) &&
2709 cast<LoadSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2710 }
2711
2712 /// Returns true if the specified node is a non-truncating
2713 /// and unindexed store.
2714 inline bool isNormalStore(const SDNode *N) {
2715 const StoreSDNode *St = dyn_cast<StoreSDNode>(N);
2716 return St && !St->isTruncatingStore() &&
2717 St->getAddressingMode() == ISD::UNINDEXED;
2718 }
2719
2720 /// Returns true if the specified node is an unindexed store.
2721 inline bool isUNINDEXEDStore(const SDNode *N) {
2722 return isa<StoreSDNode>(N) &&
2723 cast<StoreSDNode>(N)->getAddressingMode() == ISD::UNINDEXED;
2724 }
2725
2726 /// Attempt to match a unary predicate against a scalar/splat constant or
2727 /// every element of a constant BUILD_VECTOR.
2728 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2729 bool matchUnaryPredicate(SDValue Op,
2730 std::function<bool(ConstantSDNode *)> Match,
2731 bool AllowUndefs = false);
2732
2733 /// Attempt to match a binary predicate against a pair of scalar/splat
2734 /// constants or every element of a pair of constant BUILD_VECTORs.
2735 /// If AllowUndef is true, then UNDEF elements will pass nullptr to Match.
2736 /// If AllowTypeMismatch is true then RetType + ArgTypes don't need to match.
2737 bool matchBinaryPredicate(
2738 SDValue LHS, SDValue RHS,
2739 std::function<bool(ConstantSDNode *, ConstantSDNode *)> Match,
2740 bool AllowUndefs = false, bool AllowTypeMismatch = false);
2741
2742 /// Returns true if the specified value is the overflow result from one
2743 /// of the overflow intrinsic nodes.
2744 inline bool isOverflowIntrOpRes(SDValue Op) {
2745 unsigned Opc = Op.getOpcode();
2746 return (Op.getResNo() == 1 &&
2747 (Opc == ISD::SADDO || Opc == ISD::UADDO || Opc == ISD::SSUBO ||
2748 Opc == ISD::USUBO || Opc == ISD::SMULO || Opc == ISD::UMULO));
2749 }
2750
2751} // end namespace ISD
2752
2753} // end namespace llvm
2754
2755#endif // LLVM_CODEGEN_SELECTIONDAGNODES_H