Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/Mips -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Mips -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-11/lib/clang/11.0.0/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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/lib/Target/Mips -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility hidden -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/lib/Target/Mips/MipsISelLowering.cpp

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

/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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/ValueTypes.h"
34#include "llvm/IR/Constants.h"
35#include "llvm/IR/DebugLoc.h"
36#include "llvm/IR/Instruction.h"
37#include "llvm/IR/Instructions.h"
38#include "llvm/IR/Metadata.h"
39#include "llvm/IR/Operator.h"
40#include "llvm/Support/AlignOf.h"
41#include "llvm/Support/AtomicOrdering.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/MachineValueType.h"
45#include "llvm/Support/TypeSize.h"
46#include <algorithm>
47#include <cassert>
48#include <climits>
49#include <cstddef>
50#include <cstdint>
51#include <cstring>
52#include <iterator>
53#include <string>
54#include <tuple>
55
56namespace llvm {
57
58class APInt;
59class Constant;
60template <typename T> struct DenseMapInfo;
61class GlobalValue;
62class MachineBasicBlock;
63class MachineConstantPoolValue;
64class MCSymbol;
65class raw_ostream;
66class SDNode;
67class SelectionDAG;
68class Type;
69class Value;
70
71void checkForCycles(const SDNode *N, const SelectionDAG *DAG = nullptr,
72 bool force = false);
73
74/// This represents a list of ValueType's that has been intern'd by
75/// a SelectionDAG. Instances of this simple value class are returned by
76/// SelectionDAG::getVTList(...).
77///
78struct SDVTList {
79 const EVT *VTs;
80 unsigned int NumVTs;
81};
82
83namespace ISD {
84
85 /// Node predicates
86
87 /// If N is a BUILD_VECTOR node whose elements are all the same constant or
88 /// undefined, return true and return the constant value in \p SplatValue.
89 bool isConstantSplatVector(const SDNode *N, APInt &SplatValue);
90
91 /// Return true if the specified node is a BUILD_VECTOR where all of the
92 /// elements are ~0 or undef.
93 bool isBuildVectorAllOnes(const SDNode *N);
94
95 /// Return true if the specified node is a BUILD_VECTOR where all of the
96 /// elements are 0 or undef.
97 bool isBuildVectorAllZeros(const SDNode *N);
98
99 /// Return true if the specified node is a BUILD_VECTOR node of all
100 /// ConstantSDNode or undef.
101 bool isBuildVectorOfConstantSDNodes(const SDNode *N);
102
103 /// Return true if the specified node is a BUILD_VECTOR node of all
104 /// ConstantFPSDNode or undef.
105 bool isBuildVectorOfConstantFPSDNodes(const SDNode *N);
106
107 /// Return true if the node has at least one operand and all operands of the
108 /// specified node are ISD::UNDEF.
109 bool allOperandsUndef(const SDNode *N);
110
111} // end namespace ISD
112
113//===----------------------------------------------------------------------===//
114/// Unlike LLVM values, Selection DAG nodes may return multiple
115/// values as the result of a computation. Many nodes return multiple values,
116/// from loads (which define a token and a return value) to ADDC (which returns
117/// a result and a carry value), to calls (which may return an arbitrary number
118/// of values).
119///
120/// As such, each use of a SelectionDAG computation must indicate the node that
121/// computes it as well as which return value to use from that node. This pair
122/// of information is represented with the SDValue value type.
123///
124class SDValue {
125 friend struct DenseMapInfo<SDValue>;
126
127 SDNode *Node = nullptr; // The node defining the value we are using.
128 unsigned ResNo = 0; // Which return value of the node we are using.
129
130public:
131 SDValue() = default;
132 SDValue(SDNode *node, unsigned resno);
133
134 /// get the index which selects a specific result in the SDNode
135 unsigned getResNo() const { return ResNo; }
136
137 /// get the SDNode which holds the desired result
138 SDNode *getNode() const { return Node; }
139
140 /// set the SDNode
141 void setNode(SDNode *N) { Node = N; }
142
143 inline SDNode *operator->() const { return Node; }
144
145 bool operator==(const SDValue &O) const {
146 return Node == O.Node && ResNo == O.ResNo;
147 }
148 bool operator!=(const SDValue &O) const {
149 return !operator==(O);
150 }
151 bool operator<(const SDValue &O) const {
152 return std::tie(Node, ResNo) < std::tie(O.Node, O.ResNo);
153 }
154 explicit operator bool() const {
155 return Node != nullptr;
156 }
157
158 SDValue getValue(unsigned R) const {
159 return SDValue(Node, R);
160 }
161
162 /// Return true if this node is an operand of N.
163 bool isOperandOf(const SDNode *N) const;
164
165 /// Return the ValueType of the referenced return value.
166 inline EVT getValueType() const;
167
168 /// Return the simple ValueType of the referenced return value.
169 MVT getSimpleValueType() const {
170 return getValueType().getSimpleVT();
171 }
172
173 /// Returns the size of the value in bits.
174 ///
175 /// If the value type is a scalable vector type, the scalable property will
176 /// be set and the runtime size will be a positive integer multiple of the
177 /// base size.
178 TypeSize getValueSizeInBits() const {
179 return getValueType().getSizeInBits();
180 }
181
182 TypeSize getScalarValueSizeInBits() const {
183 return getValueType().getScalarType().getSizeInBits();
184 }
185
186 // Forwarding methods - These forward to the corresponding methods in SDNode.
187 inline unsigned getOpcode() const;
188 inline unsigned getNumOperands() const;
189 inline const SDValue &getOperand(unsigned i) const;
190 inline uint64_t getConstantOperandVal(unsigned i) const;
191 inline const APInt &getConstantOperandAPInt(unsigned i) const;
192 inline bool isTargetMemoryOpcode() const;
193 inline bool isTargetOpcode() const;
194 inline bool isMachineOpcode() const;
195 inline bool isUndef() const;
196 inline unsigned getMachineOpcode() const;
197 inline const DebugLoc &getDebugLoc() const;
198 inline void dump() const;
199 inline void dump(const SelectionDAG *G) const;
200 inline void dumpr() const;
201 inline void dumpr(const SelectionDAG *G) const;
202
203 /// Return true if this operand (which must be a chain) reaches the
204 /// specified operand without crossing any side-effecting instructions.
205 /// In practice, this looks through token factors and non-volatile loads.
206 /// In order to remain efficient, this only
207 /// looks a couple of nodes in, it does not do an exhaustive search.
208 bool reachesChainWithoutSideEffects(SDValue Dest,
209 unsigned Depth = 2) const;
210
211 /// Return true if there are no nodes using value ResNo of Node.
212 inline bool use_empty() const;
213
214 /// Return true if there is exactly one node using value ResNo of Node.
215 inline bool hasOneUse() const;
216};
217
218template<> struct DenseMapInfo<SDValue> {
219 static inline SDValue getEmptyKey() {
220 SDValue V;
221 V.ResNo = -1U;
222 return V;
223 }
224
225 static inline SDValue getTombstoneKey() {
226 SDValue V;
227 V.ResNo = -2U;
228 return V;
229 }
230
231 static unsigned getHashValue(const SDValue &Val) {
232 return ((unsigned)((uintptr_t)Val.getNode() >> 4) ^
233 (unsigned)((uintptr_t)Val.getNode() >> 9)) + Val.getResNo();
234 }
235
236 static bool isEqual(const SDValue &LHS, const SDValue &RHS) {
237 return LHS == RHS;
238 }
239};
240
241/// Allow casting operators to work directly on
242/// SDValues as if they were SDNode*'s.
243template<> struct simplify_type<SDValue> {
244 using SimpleType = SDNode *;
245
246 static SimpleType getSimplifiedValue(SDValue &Val) {
247 return Val.getNode();
248 }
249};
250template<> struct simplify_type<const SDValue> {
251 using SimpleType = /*const*/ SDNode *;
252
253 static SimpleType getSimplifiedValue(const SDValue &Val) {
254 return Val.getNode();
255 }
256};
257
258/// Represents a use of a SDNode. This class holds an SDValue,
259/// which records the SDNode being used and the result number, a
260/// pointer to the SDNode using the value, and Next and Prev pointers,
261/// which link together all the uses of an SDNode.
262///
263class SDUse {
264 /// Val - The value being used.
265 SDValue Val;
266 /// User - The user of this value.
267 SDNode *User = nullptr;
268 /// Prev, Next - Pointers to the uses list of the SDNode referred by
269 /// this operand.
270 SDUse **Prev = nullptr;
271 SDUse *Next = nullptr;
272
273public:
274 SDUse() = default;
275 SDUse(const SDUse &U) = delete;
276 SDUse &operator=(const SDUse &) = delete;
277
278 /// Normally SDUse will just implicitly convert to an SDValue that it holds.
279 operator const SDValue&() const { return Val; }
280
281 /// If implicit conversion to SDValue doesn't work, the get() method returns
282 /// the SDValue.
283 const SDValue &get() const { return Val; }
284
285 /// This returns the SDNode that contains this Use.
286 SDNode *getUser() { return User; }
287
288 /// Get the next SDUse in the use list.
289 SDUse *getNext() const { return Next; }
290
291 /// Convenience function for get().getNode().
292 SDNode *getNode() const { return Val.getNode(); }
293 /// Convenience function for get().getResNo().
294 unsigned getResNo() const { return Val.getResNo(); }
295 /// Convenience function for get().getValueType().
296 EVT getValueType() const { return Val.getValueType(); }
297
298 /// Convenience function for get().operator==
299 bool operator==(const SDValue &V) const {
300 return Val == V;
301 }
302
303 /// Convenience function for get().operator!=
304 bool operator!=(const SDValue &V) const {
305 return Val != V;
306 }
307
308 /// Convenience function for get().operator<
309 bool operator<(const SDValue &V) const {
310 return Val < V;
311 }
312
313private:
314 friend class SelectionDAG;
315 friend class SDNode;
316 // TODO: unfriend HandleSDNode once we fix its operand handling.
317 friend class HandleSDNode;
318
319 void setUser(SDNode *p) { User = p; }
320
321 /// Remove this use from its existing use list, assign it the
322 /// given value, and add it to the new value's node's use list.
323 inline void set(const SDValue &V);
324 /// Like set, but only supports initializing a newly-allocated
325 /// SDUse with a non-null value.
326 inline void setInitial(const SDValue &V);
327 /// Like set, but only sets the Node portion of the value,
328 /// leaving the ResNo portion unmodified.
329 inline void setNode(SDNode *N);
330
331 void addToList(SDUse **List) {
332 Next = *List;
333 if (Next) Next->Prev = &Next;
334 Prev = List;
335 *List = this;
336 }
337
338 void removeFromList() {
339 *Prev = Next;
340 if (Next) Next->Prev = Prev;
341 }
342};
343
344/// simplify_type specializations - Allow casting operators to work directly on
345/// SDValues as if they were SDNode*'s.
346template<> struct simplify_type<SDUse> {
347 using SimpleType = SDNode *;
348
349 static SimpleType getSimplifiedValue(SDUse &Val) {
350 return Val.getNode();
351 }
352};
353
354/// These are IR-level optimization flags that may be propagated to SDNodes.
355/// TODO: This data structure should be shared by the IR optimizer and the
356/// the backend.
357struct SDNodeFlags {
358private:
359 // This bit is used to determine if the flags are in a defined state.
360 // Flag bits can only be masked out during intersection if the masking flags
361 // are defined.
362 bool AnyDefined : 1;
363
364 bool NoUnsignedWrap : 1;
365 bool NoSignedWrap : 1;
366 bool Exact : 1;
367 bool NoNaNs : 1;
368 bool NoInfs : 1;
369 bool NoSignedZeros : 1;
370 bool AllowReciprocal : 1;
371 bool VectorReduction : 1;
372 bool AllowContract : 1;
373 bool ApproximateFuncs : 1;
374 bool AllowReassociation : 1;
375
376 // We assume instructions do not raise floating-point exceptions by default,
377 // and only those marked explicitly may do so. We could choose to represent
378 // this via a positive "FPExcept" flags like on the MI level, but having a
379 // negative "NoFPExcept" flag here (that defaults to true) makes the flag
380 // intersection logic more straightforward.
381 bool NoFPExcept : 1;
382
383public:
384 /// Default constructor turns off all optimization flags.
385 SDNodeFlags()
386 : AnyDefined(false), NoUnsignedWrap(false), NoSignedWrap(false),
387 Exact(false), NoNaNs(false), NoInfs(false),
388 NoSignedZeros(false), AllowReciprocal(false), VectorReduction(false),
389 AllowContract(false), ApproximateFuncs(false),
390 AllowReassociation(false), NoFPExcept(false) {}
391
392 /// Propagate the fast-math-flags from an IR FPMathOperator.
393 void copyFMF(const FPMathOperator &FPMO) {
394 setNoNaNs(FPMO.hasNoNaNs());
395 setNoInfs(FPMO.hasNoInfs());
396 setNoSignedZeros(FPMO.hasNoSignedZeros());
397 setAllowReciprocal(FPMO.hasAllowReciprocal());
398 setAllowContract(FPMO.hasAllowContract());
399 setApproximateFuncs(FPMO.hasApproxFunc());
400 setAllowReassociation(FPMO.hasAllowReassoc());
401 }
402
403 /// Sets the state of the flags to the defined state.
404 void setDefined() { AnyDefined = true; }
405 /// Returns true if the flags are in a defined state.
406 bool isDefined() const { return AnyDefined; }
407
408 // These are mutators for each flag.
409 void setNoUnsignedWrap(bool b) {
410 setDefined();
411 NoUnsignedWrap = b;
412 }
413 void setNoSignedWrap(bool b) {
414 setDefined();
415 NoSignedWrap = b;
416 }
417 void setExact(bool b) {
418 setDefined();
419 Exact = b;
420 }
421 void setNoNaNs(bool b) {
422 setDefined();
423 NoNaNs = b;
424 }
425 void setNoInfs(bool b) {
426 setDefined();
427 NoInfs = b;
428 }
429 void setNoSignedZeros(bool b) {
430 setDefined();
431 NoSignedZeros = b;
432 }
433 void setAllowReciprocal(bool b) {
434 setDefined();
435 AllowReciprocal = b;
436 }
437 void setVectorReduction(bool b) {
438 setDefined();
439 VectorReduction = b;
440 }
441 void setAllowContract(bool b) {
442 setDefined();
443 AllowContract = b;
444 }
445 void setApproximateFuncs(bool b) {
446 setDefined();
447 ApproximateFuncs = b;
448 }
449 void setAllowReassociation(bool b) {
450 setDefined();
451 AllowReassociation = b;
452 }
453 void setNoFPExcept(bool b) {
454 setDefined();
455 NoFPExcept = b;
456 }
457
458 // These are accessors for each flag.
459 bool hasNoUnsignedWrap() const { return NoUnsignedWrap; }
460 bool hasNoSignedWrap() const { return NoSignedWrap; }
461 bool hasExact() const { return Exact; }
462 bool hasNoNaNs() const { return NoNaNs; }
463 bool hasNoInfs() const { return NoInfs; }
464 bool hasNoSignedZeros() const { return NoSignedZeros; }
465 bool hasAllowReciprocal() const { return AllowReciprocal; }
466 bool hasVectorReduction() const { return VectorReduction; }
467 bool hasAllowContract() const { return AllowContract; }
468 bool hasApproximateFuncs() const { return ApproximateFuncs; }
469 bool hasAllowReassociation() const { return AllowReassociation; }
470 bool hasNoFPExcept() const { return NoFPExcept; }
471
472 /// Clear any flags in this flag set that aren't also set in Flags.
473 /// If the given Flags are undefined then don't do anything.
474 void intersectWith(const SDNodeFlags Flags) {
475 if (!Flags.isDefined())
476 return;
477 NoUnsignedWrap &= Flags.NoUnsignedWrap;
478 NoSignedWrap &= Flags.NoSignedWrap;
479 Exact &= Flags.Exact;
480 NoNaNs &= Flags.NoNaNs;
481 NoInfs &= Flags.NoInfs;
482 NoSignedZeros &= Flags.NoSignedZeros;
483 AllowReciprocal &= Flags.AllowReciprocal;
484 VectorReduction &= Flags.VectorReduction;
485 AllowContract &= Flags.AllowContract;
486 ApproximateFuncs &= Flags.ApproximateFuncs;
487 AllowReassociation &= Flags.AllowReassociation;
488 NoFPExcept &= Flags.NoFPExcept;
489 }
490};
491
492/// Represents one node in the SelectionDAG.
493///
494class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
495private:
496 /// The operation that this node performs.
497 int16_t NodeType;
498
499protected:
500 // We define a set of mini-helper classes to help us interpret the bits in our
501 // SubclassData. These are designed to fit within a uint16_t so they pack
502 // with NodeType.
503
504#if defined(_AIX) && (!defined(__GNUC__4) || defined(__ibmxl__))
505// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
506// and give the `pack` pragma push semantics.
507#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")pack(2)
508#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")pack(pop)
509#else
510#define BEGIN_TWO_BYTE_PACK()
511#define END_TWO_BYTE_PACK()
512#endif
513
514BEGIN_TWO_BYTE_PACK()
515 class SDNodeBitfields {
516 friend class SDNode;
517 friend class MemIntrinsicSDNode;
518 friend class MemSDNode;
519 friend class SelectionDAG;
520
521 uint16_t HasDebugValue : 1;
522 uint16_t IsMemIntrinsic : 1;
523 uint16_t IsDivergent : 1;
524 };
525 enum { NumSDNodeBits = 3 };
526
527 class ConstantSDNodeBitfields {
528 friend class ConstantSDNode;
529
530 uint16_t : NumSDNodeBits;
531
532 uint16_t IsOpaque : 1;
533 };
534
535 class MemSDNodeBitfields {
536 friend class MemSDNode;
537 friend class MemIntrinsicSDNode;
538 friend class AtomicSDNode;
539
540 uint16_t : NumSDNodeBits;
541
542 uint16_t IsVolatile : 1;
543 uint16_t IsNonTemporal : 1;
544 uint16_t IsDereferenceable : 1;
545 uint16_t IsInvariant : 1;
546 };
547 enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
548
549 class LSBaseSDNodeBitfields {
550 friend class LSBaseSDNode;
551 friend class MaskedLoadStoreSDNode;
552 friend class MaskedGatherScatterSDNode;
553
554 uint16_t : NumMemSDNodeBits;
555
556 // This storage is shared between disparate class hierarchies to hold an
557 // enumeration specific to the class hierarchy in use.
558 // LSBaseSDNode => enum ISD::MemIndexedMode
559 // MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
560 // MaskedGatherScatterSDNode => enum ISD::MemIndexType
561 uint16_t AddressingMode : 3;
562 };
563 enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
564
565 class LoadSDNodeBitfields {
566 friend class LoadSDNode;
567 friend class MaskedLoadSDNode;
568
569 uint16_t : NumLSBaseSDNodeBits;
570
571 uint16_t ExtTy : 2; // enum ISD::LoadExtType
572 uint16_t IsExpanding : 1;
573 };
574
575 class StoreSDNodeBitfields {
576 friend class StoreSDNode;
577 friend class MaskedStoreSDNode;
578
579 uint16_t : NumLSBaseSDNodeBits;
580
581 uint16_t IsTruncating : 1;
582 uint16_t IsCompressing : 1;
583 };
584
585 union {
586 char RawSDNodeBits[sizeof(uint16_t)];
587 SDNodeBitfields SDNodeBits;
588 ConstantSDNodeBitfields ConstantSDNodeBits;
589 MemSDNodeBitfields MemSDNodeBits;
590 LSBaseSDNodeBitfields LSBaseSDNodeBits;
591 LoadSDNodeBitfields LoadSDNodeBits;
592 StoreSDNodeBitfields StoreSDNodeBits;
593 };
594END_TWO_BYTE_PACK()
595#undef BEGIN_TWO_BYTE_PACK
596#undef END_TWO_BYTE_PACK
597
598 // RawSDNodeBits must cover the entirety of the union. This means that all of
599 // the union's members must have size <= RawSDNodeBits. We write the RHS as
600 // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
601 static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
602 static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
603 static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
604 static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
605 static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
606 static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
607
608private:
609 friend class SelectionDAG;
610 // TODO: unfriend HandleSDNode once we fix its operand handling.
611 friend class HandleSDNode;
612
613 /// Unique id per SDNode in the DAG.
614 int NodeId = -1;
615
616 /// The values that are used by this operation.
617 SDUse *OperandList = nullptr;
618
619 /// The types of the values this node defines. SDNode's may
620 /// define multiple values simultaneously.
621 const EVT *ValueList;
622
623 /// List of uses for this SDNode.
624 SDUse *UseList = nullptr;
625
626 /// The number of entries in the Operand/Value list.
627 unsigned short NumOperands = 0;
628 unsigned short NumValues;
629
630 // The ordering of the SDNodes. It roughly corresponds to the ordering of the
631 // original LLVM instructions.
632 // This is used for turning off scheduling, because we'll forgo
633 // the normal scheduling algorithms and output the instructions according to
634 // this ordering.
635 unsigned IROrder;
636
637 /// Source line information.
638 DebugLoc debugLoc;
639
640 /// Return a pointer to the specified value type.
641 static const EVT *getValueTypeList(EVT VT);
642
643 SDNodeFlags Flags;
644
645public:
646 /// Unique and persistent id per SDNode in the DAG.
647 /// Used for debug printing.
648 uint16_t PersistentId;
649
650 //===--------------------------------------------------------------------===//
651 // Accessors
652 //
653
654 /// Return the SelectionDAG opcode value for this node. For
655 /// pre-isel nodes (those for which isMachineOpcode returns false), these
656 /// are the opcode values in the ISD and <target>ISD namespaces. For
657 /// post-isel opcodes, see getMachineOpcode.
658 unsigned getOpcode() const { return (unsigned short)NodeType; }
659
660 /// Test if this node has a target-specific opcode (in the
661 /// \<target\>ISD namespace).
662 bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
663
664 /// Test if this node has a target-specific opcode that may raise
665 /// FP exceptions (in the \<target\>ISD namespace and greater than
666 /// FIRST_TARGET_STRICTFP_OPCODE). Note that all target memory
667 /// opcode are currently automatically considered to possibly raise
668 /// FP exceptions as well.
669 bool isTargetStrictFPOpcode() const {
670 return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
671 }
672
673 /// Test if this node has a target-specific
674 /// memory-referencing opcode (in the \<target\>ISD namespace and
675 /// greater than FIRST_TARGET_MEMORY_OPCODE).
676 bool isTargetMemoryOpcode() const {
677 return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
678 }
679
680 /// Return true if the type of the node type undefined.
681 bool isUndef() const { return NodeType == ISD::UNDEF; }
682
683 /// Test if this node is a memory intrinsic (with valid pointer information).
684 /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
685 /// non-memory intrinsics (with chains) that are not really instances of
686 /// MemSDNode. For such nodes, we need some extra state to determine the
687 /// proper classof relationship.
688 bool isMemIntrinsic() const {
689 return (NodeType == ISD::INTRINSIC_W_CHAIN ||
690 NodeType == ISD::INTRINSIC_VOID) &&
691 SDNodeBits.IsMemIntrinsic;
692 }
693
694 /// Test if this node is a strict floating point pseudo-op.
695 bool isStrictFPOpcode() {
696 switch (NodeType) {
697 default:
698 return false;
699 case ISD::STRICT_FP16_TO_FP:
700 case ISD::STRICT_FP_TO_FP16:
701#define DAG_INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
702 case ISD::STRICT_##DAGN:
703#include "llvm/IR/ConstrainedOps.def"
704 return true;
705 }
706 }
707
708 /// Test if this node has a post-isel opcode, directly
709 /// corresponding to a MachineInstr opcode.
710 bool isMachineOpcode() const { return NodeType < 0; }
711
712 /// This may only be called if isMachineOpcode returns
713 /// true. It returns the MachineInstr opcode value that the node's opcode
714 /// corresponds to.
715 unsigned getMachineOpcode() const {
716 assert(isMachineOpcode() && "Not a MachineInstr opcode!")((isMachineOpcode() && "Not a MachineInstr opcode!") ?
static_cast<void> (0) : __assert_fail ("isMachineOpcode() && \"Not a MachineInstr opcode!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 716, __PRETTY_FUNCTION__))
;
717 return ~NodeType;
718 }
719
720 bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
721 void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
722
723 bool isDivergent() const { return SDNodeBits.IsDivergent; }
724
725 /// Return true if there are no uses of this node.
726 bool use_empty() const { return UseList == nullptr; }
727
728 /// Return true if there is exactly one use of this node.
729 bool hasOneUse() const {
730 return !use_empty() && std::next(use_begin()) == use_end();
731 }
732
733 /// Return the number of uses of this node. This method takes
734 /// time proportional to the number of uses.
735 size_t use_size() const { return std::distance(use_begin(), use_end()); }
736
737 /// Return the unique node id.
738 int getNodeId() const { return NodeId; }
739
740 /// Set unique node id.
741 void setNodeId(int Id) { NodeId = Id; }
742
743 /// Return the node ordering.
744 unsigned getIROrder() const { return IROrder; }
745
746 /// Set the node ordering.
747 void setIROrder(unsigned Order) { IROrder = Order; }
748
749 /// Return the source location info.
750 const DebugLoc &getDebugLoc() const { return debugLoc; }
751
752 /// Set source location info. Try to avoid this, putting
753 /// it in the constructor is preferable.
754 void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
755
756 /// This class provides iterator support for SDUse
757 /// operands that use a specific SDNode.
758 class use_iterator
759 : public std::iterator<std::forward_iterator_tag, SDUse, ptrdiff_t> {
760 friend class SDNode;
761
762 SDUse *Op = nullptr;
763
764 explicit use_iterator(SDUse *op) : Op(op) {}
765
766 public:
767 using reference = std::iterator<std::forward_iterator_tag,
768 SDUse, ptrdiff_t>::reference;
769 using pointer = std::iterator<std::forward_iterator_tag,
770 SDUse, ptrdiff_t>::pointer;
771
772 use_iterator() = default;
773 use_iterator(const use_iterator &I) : Op(I.Op) {}
774
775 bool operator==(const use_iterator &x) const {
776 return Op == x.Op;
777 }
778 bool operator!=(const use_iterator &x) const {
779 return !operator==(x);
780 }
781
782 /// Return true if this iterator is at the end of uses list.
783 bool atEnd() const { return Op == nullptr; }
784
785 // Iterator traversal: forward iteration only.
786 use_iterator &operator++() { // Preincrement
787 assert(Op && "Cannot increment end iterator!")((Op && "Cannot increment end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot increment end iterator!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 787, __PRETTY_FUNCTION__))
;
788 Op = Op->getNext();
789 return *this;
790 }
791
792 use_iterator operator++(int) { // Postincrement
793 use_iterator tmp = *this; ++*this; return tmp;
794 }
795
796 /// Retrieve a pointer to the current user node.
797 SDNode *operator*() const {
798 assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 798, __PRETTY_FUNCTION__))
;
799 return Op->getUser();
800 }
801
802 SDNode *operator->() const { return operator*(); }
803
804 SDUse &getUse() const { return *Op; }
805
806 /// Retrieve the operand # of this use in its user.
807 unsigned getOperandNo() const {
808 assert(Op && "Cannot dereference end iterator!")((Op && "Cannot dereference end iterator!") ? static_cast
<void> (0) : __assert_fail ("Op && \"Cannot dereference end iterator!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 808, __PRETTY_FUNCTION__))
;
809 return (unsigned)(Op - Op->getUser()->OperandList);
810 }
811 };
812
813 /// Provide iteration support to walk over all uses of an SDNode.
814 use_iterator use_begin() const {
815 return use_iterator(UseList);
816 }
817
818 static use_iterator use_end() { return use_iterator(nullptr); }
819
820 inline iterator_range<use_iterator> uses() {
821 return make_range(use_begin(), use_end());
822 }
823 inline iterator_range<use_iterator> uses() const {
824 return make_range(use_begin(), use_end());
825 }
826
827 /// Return true if there are exactly NUSES uses of the indicated value.
828 /// This method ignores uses of other values defined by this operation.
829 bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
830
831 /// Return true if there are any use of the indicated value.
832 /// This method ignores uses of other values defined by this operation.
833 bool hasAnyUseOfValue(unsigned Value) const;
834
835 /// Return true if this node is the only use of N.
836 bool isOnlyUserOf(const SDNode *N) const;
837
838 /// Return true if this node is an operand of N.
839 bool isOperandOf(const SDNode *N) const;
840
841 /// Return true if this node is a predecessor of N.
842 /// NOTE: Implemented on top of hasPredecessor and every bit as
843 /// expensive. Use carefully.
844 bool isPredecessorOf(const SDNode *N) const {
845 return N->hasPredecessor(this);
846 }
847
848 /// Return true if N is a predecessor of this node.
849 /// N is either an operand of this node, or can be reached by recursively
850 /// traversing up the operands.
851 /// NOTE: This is an expensive method. Use it carefully.
852 bool hasPredecessor(const SDNode *N) const;
853
854 /// Returns true if N is a predecessor of any node in Worklist. This
855 /// helper keeps Visited and Worklist sets externally to allow unions
856 /// searches to be performed in parallel, caching of results across
857 /// queries and incremental addition to Worklist. Stops early if N is
858 /// found but will resume. Remember to clear Visited and Worklists
859 /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
860 /// giving up. The TopologicalPrune flag signals that positive NodeIds are
861 /// topologically ordered (Operands have strictly smaller node id) and search
862 /// can be pruned leveraging this.
863 static bool hasPredecessorHelper(const SDNode *N,
864 SmallPtrSetImpl<const SDNode *> &Visited,
865 SmallVectorImpl<const SDNode *> &Worklist,
866 unsigned int MaxSteps = 0,
867 bool TopologicalPrune = false) {
868 SmallVector<const SDNode *, 8> DeferredNodes;
869 if (Visited.count(N))
870 return true;
871
872 // Node Id's are assigned in three places: As a topological
873 // ordering (> 0), during legalization (results in values set to
874 // 0), new nodes (set to -1). If N has a topolgical id then we
875 // know that all nodes with ids smaller than it cannot be
876 // successors and we need not check them. Filter out all node
877 // that can't be matches. We add them to the worklist before exit
878 // in case of multiple calls. Note that during selection the topological id
879 // may be violated if a node's predecessor is selected before it. We mark
880 // this at selection negating the id of unselected successors and
881 // restricting topological pruning to positive ids.
882
883 int NId = N->getNodeId();
884 // If we Invalidated the Id, reconstruct original NId.
885 if (NId < -1)
886 NId = -(NId + 1);
887
888 bool Found = false;
889 while (!Worklist.empty()) {
890 const SDNode *M = Worklist.pop_back_val();
891 int MId = M->getNodeId();
892 if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
893 (MId > 0) && (MId < NId)) {
894 DeferredNodes.push_back(M);
895 continue;
896 }
897 for (const SDValue &OpV : M->op_values()) {
898 SDNode *Op = OpV.getNode();
899 if (Visited.insert(Op).second)
900 Worklist.push_back(Op);
901 if (Op == N)
902 Found = true;
903 }
904 if (Found)
905 break;
906 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
907 break;
908 }
909 // Push deferred nodes back on worklist.
910 Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
911 // If we bailed early, conservatively return found.
912 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
913 return true;
914 return Found;
915 }
916
917 /// Return true if all the users of N are contained in Nodes.
918 /// NOTE: Requires at least one match, but doesn't require them all.
919 static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
920
921 /// Return the number of values used by this operation.
922 unsigned getNumOperands() const { return NumOperands; }
923
924 /// Return the maximum number of operands that a SDNode can hold.
925 static constexpr size_t getMaxNumOperands() {
926 return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
927 }
928
929 /// Helper method returns the integer value of a ConstantSDNode operand.
930 inline uint64_t getConstantOperandVal(unsigned Num) const;
931
932 /// Helper method returns the APInt of a ConstantSDNode operand.
933 inline const APInt &getConstantOperandAPInt(unsigned Num) const;
934
935 const SDValue &getOperand(unsigned Num) const {
936 assert(Num < NumOperands && "Invalid child # of SDNode!")((Num < NumOperands && "Invalid child # of SDNode!"
) ? static_cast<void> (0) : __assert_fail ("Num < NumOperands && \"Invalid child # of SDNode!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 936, __PRETTY_FUNCTION__))
;
937 return OperandList[Num];
938 }
939
940 using op_iterator = SDUse *;
941
942 op_iterator op_begin() const { return OperandList; }
943 op_iterator op_end() const { return OperandList+NumOperands; }
944 ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
945
946 /// Iterator for directly iterating over the operand SDValue's.
947 struct value_op_iterator
948 : iterator_adaptor_base<value_op_iterator, op_iterator,
949 std::random_access_iterator_tag, SDValue,
950 ptrdiff_t, value_op_iterator *,
951 value_op_iterator *> {
952 explicit value_op_iterator(SDUse *U = nullptr)
953 : iterator_adaptor_base(U) {}
954
955 const SDValue &operator*() const { return I->get(); }
956 };
957
958 iterator_range<value_op_iterator> op_values() const {
959 return make_range(value_op_iterator(op_begin()),
960 value_op_iterator(op_end()));
961 }
962
963 SDVTList getVTList() const {
964 SDVTList X = { ValueList, NumValues };
965 return X;
966 }
967
968 /// If this node has a glue operand, return the node
969 /// to which the glue operand points. Otherwise return NULL.
970 SDNode *getGluedNode() const {
971 if (getNumOperands() != 0 &&
972 getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
973 return getOperand(getNumOperands()-1).getNode();
974 return nullptr;
975 }
976
977 /// If this node has a glue value with a user, return
978 /// the user (there is at most one). Otherwise return NULL.
979 SDNode *getGluedUser() const {
980 for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
981 if (UI.getUse().get().getValueType() == MVT::Glue)
982 return *UI;
983 return nullptr;
984 }
985
986 const SDNodeFlags getFlags() const { return Flags; }
987 void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
988
989 /// Clear any flags in this node that aren't also set in Flags.
990 /// If Flags is not in a defined state then this has no effect.
991 void intersectFlagsWith(const SDNodeFlags Flags);
992
993 /// Return the number of values defined/returned by this operator.
994 unsigned getNumValues() const { return NumValues; }
995
996 /// Return the type of a specified result.
997 EVT getValueType(unsigned ResNo) const {
998 assert(ResNo < NumValues && "Illegal result number!")((ResNo < NumValues && "Illegal result number!") ?
static_cast<void> (0) : __assert_fail ("ResNo < NumValues && \"Illegal result number!\""
, "/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 998, __PRETTY_FUNCTION__))
;
999 return ValueList[ResNo];
1000 }
1001
1002 /// Return the type of a specified result as a simple type.
1003 MVT getSimpleValueType(unsigned ResNo) const {
1004 return getValueType(ResNo).getSimpleVT();
1005 }
1006
1007 /// Returns MVT::getSizeInBits(getValueType(ResNo)).
1008 ///
1009 /// If the value type is a scalable vector type, the scalable property will
1010 /// be set and the runtime size will be a positive integer multiple of the
1011 /// base size.
1012 TypeSize getValueSizeInBits(unsigned ResNo) const {
1013 return getValueType(ResNo).getSizeInBits();
1014 }
1015
1016 using value_iterator = const EVT *;
1017
1018 value_iterator value_begin() const { return ValueList; }
1019 value_iterator value_end() const { return ValueList+NumValues; }
1020 iterator_range<value_iterator> values() const {
1021 return llvm::make_range(value_begin(), value_end());
1022 }
1023
1024 /// Return the opcode of this operation for printing.
1025 std::string getOperationName(const SelectionDAG *G = nullptr) const;
1026 static const char* getIndexedModeName(ISD::MemIndexedMode AM);
1027 void print_types(raw_ostream &OS, const SelectionDAG *G) const;
1028 void print_details(raw_ostream &OS, const SelectionDAG *G) const;
1029 void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1030 void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1031
1032 /// Print a SelectionDAG node and all children down to
1033 /// the leaves. The given SelectionDAG allows target-specific nodes
1034 /// to be printed in human-readable form. Unl