Bug Summary

File:llvm/include/llvm/CodeGen/SelectionDAGNodes.h
Warning:line 1154, 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-10/lib/clang/10.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Target/Mips -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10/lib/clang/10.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-10~++20200112100611+7fa5290d5bd/build-llvm/lib/Target/Mips -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -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-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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-10~++20200112100611+7fa5290d5bd/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 }
1455}
1456
1457// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1458// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1459MachineBasicBlock *
1460MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1461 MachineBasicBlock *BB) const {
1462
1463 MachineFunction *MF = BB->getParent();
1464 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1465 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1466 DebugLoc DL = MI.getDebugLoc();
1467
1468 unsigned AtomicOp;
1469 bool NeedsAdditionalReg = false;
1470 switch (MI.getOpcode()) {
1471 case Mips::ATOMIC_LOAD_ADD_I32:
1472 AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1473 break;
1474 case Mips::ATOMIC_LOAD_SUB_I32:
1475 AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1476 break;
1477 case Mips::ATOMIC_LOAD_AND_I32:
1478 AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1479 break;
1480 case Mips::ATOMIC_LOAD_OR_I32:
1481 AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1482 break;
1483 case Mips::ATOMIC_LOAD_XOR_I32:
1484 AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1485 break;
1486 case Mips::ATOMIC_LOAD_NAND_I32:
1487 AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1488 break;
1489 case Mips::ATOMIC_SWAP_I32:
1490 AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1491 break;
1492 case Mips::ATOMIC_LOAD_ADD_I64:
1493 AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1494 break;
1495 case Mips::ATOMIC_LOAD_SUB_I64:
1496 AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1497 break;
1498 case Mips::ATOMIC_LOAD_AND_I64:
1499 AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1500 break;
1501 case Mips::ATOMIC_LOAD_OR_I64:
1502 AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1503 break;
1504 case Mips::ATOMIC_LOAD_XOR_I64:
1505 AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1506 break;
1507 case Mips::ATOMIC_LOAD_NAND_I64:
1508 AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1509 break;
1510 case Mips::ATOMIC_SWAP_I64:
1511 AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1512 break;
1513 case Mips::ATOMIC_LOAD_MIN_I32:
1514 AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA;
1515 NeedsAdditionalReg = true;
1516 break;
1517 case Mips::ATOMIC_LOAD_MAX_I32:
1518 AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA;
1519 NeedsAdditionalReg = true;
1520 break;
1521 case Mips::ATOMIC_LOAD_UMIN_I32:
1522 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA;
1523 NeedsAdditionalReg = true;
1524 break;
1525 case Mips::ATOMIC_LOAD_UMAX_I32:
1526 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA;
1527 NeedsAdditionalReg = true;
1528 break;
1529 case Mips::ATOMIC_LOAD_MIN_I64:
1530 AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA;
1531 NeedsAdditionalReg = true;
1532 break;
1533 case Mips::ATOMIC_LOAD_MAX_I64:
1534 AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA;
1535 NeedsAdditionalReg = true;
1536 break;
1537 case Mips::ATOMIC_LOAD_UMIN_I64:
1538 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA;
1539 NeedsAdditionalReg = true;
1540 break;
1541 case Mips::ATOMIC_LOAD_UMAX_I64:
1542 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA;
1543 NeedsAdditionalReg = true;
1544 break;
1545 default:
1546 llvm_unreachable("Unknown pseudo atomic for replacement!")::llvm::llvm_unreachable_internal("Unknown pseudo atomic for replacement!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1546)
;
1547 }
1548
1549 Register OldVal = MI.getOperand(0).getReg();
1550 Register Ptr = MI.getOperand(1).getReg();
1551 Register Incr = MI.getOperand(2).getReg();
1552 Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1553
1554 MachineBasicBlock::iterator II(MI);
1555
1556 // The scratch registers here with the EarlyClobber | Define | Implicit
1557 // flags is used to persuade the register allocator and the machine
1558 // verifier to accept the usage of this register. This has to be a real
1559 // register which has an UNDEF value but is dead after the instruction which
1560 // is unique among the registers chosen for the instruction.
1561
1562 // The EarlyClobber flag has the semantic properties that the operand it is
1563 // attached to is clobbered before the rest of the inputs are read. Hence it
1564 // must be unique among the operands to the instruction.
1565 // The Define flag is needed to coerce the machine verifier that an Undef
1566 // value isn't a problem.
1567 // The Dead flag is needed as the value in scratch isn't used by any other
1568 // instruction. Kill isn't used as Dead is more precise.
1569 // The implicit flag is here due to the interaction between the other flags
1570 // and the machine verifier.
1571
1572 // For correctness purpose, a new pseudo is introduced here. We need this
1573 // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1574 // that is spread over >1 basic blocks. A register allocator which
1575 // introduces (or any codegen infact) a store, can violate the expectations
1576 // of the hardware.
1577 //
1578 // An atomic read-modify-write sequence starts with a linked load
1579 // instruction and ends with a store conditional instruction. The atomic
1580 // read-modify-write sequence fails if any of the following conditions
1581 // occur between the execution of ll and sc:
1582 // * A coherent store is completed by another process or coherent I/O
1583 // module into the block of synchronizable physical memory containing
1584 // the word. The size and alignment of the block is
1585 // implementation-dependent.
1586 // * A coherent store is executed between an LL and SC sequence on the
1587 // same processor to the block of synchornizable physical memory
1588 // containing the word.
1589 //
1590
1591 Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1592 Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1593
1594 BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1595 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1596
1597 MachineInstrBuilder MIB =
1598 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1599 .addReg(OldVal, RegState::Define | RegState::EarlyClobber)
1600 .addReg(PtrCopy)
1601 .addReg(IncrCopy)
1602 .addReg(Scratch, RegState::Define | RegState::EarlyClobber |
1603 RegState::Implicit | RegState::Dead);
1604 if (NeedsAdditionalReg) {
1605 Register Scratch2 =
1606 RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1607 MIB.addReg(Scratch2, RegState::Define | RegState::EarlyClobber |
1608 RegState::Implicit | RegState::Dead);
1609 }
1610
1611 MI.eraseFromParent();
1612
1613 return BB;
1614}
1615
1616MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1617 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1618 unsigned SrcReg) const {
1619 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1620 const DebugLoc &DL = MI.getDebugLoc();
1621
1622 if (Subtarget.hasMips32r2() && Size == 1) {
1623 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1624 return BB;
1625 }
1626
1627 if (Subtarget.hasMips32r2() && Size == 2) {
1628 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1629 return BB;
1630 }
1631
1632 MachineFunction *MF = BB->getParent();
1633 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1634 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1635 Register ScrReg = RegInfo.createVirtualRegister(RC);
1636
1637 assert(Size < 32)((Size < 32) ? static_cast<void> (0) : __assert_fail
("Size < 32", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1637, __PRETTY_FUNCTION__))
;
1638 int64_t ShiftImm = 32 - (Size * 8);
1639
1640 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1641 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1642
1643 return BB;
1644}
1645
1646MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1647 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1648 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1649, __PRETTY_FUNCTION__))
1649 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1649, __PRETTY_FUNCTION__))
;
1650
1651 MachineFunction *MF = BB->getParent();
1652 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1653 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1654 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1655 const TargetRegisterClass *RCp =
1656 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1657 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1658 DebugLoc DL = MI.getDebugLoc();
1659
1660 Register Dest = MI.getOperand(0).getReg();
1661 Register Ptr = MI.getOperand(1).getReg();
1662 Register Incr = MI.getOperand(2).getReg();
1663
1664 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1665 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1666 Register Mask = RegInfo.createVirtualRegister(RC);
1667 Register Mask2 = RegInfo.createVirtualRegister(RC);
1668 Register Incr2 = RegInfo.createVirtualRegister(RC);
1669 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1670 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1671 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1672 Register Scratch = RegInfo.createVirtualRegister(RC);
1673 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1674 Register Scratch3 = RegInfo.createVirtualRegister(RC);
1675
1676 unsigned AtomicOp = 0;
1677 bool NeedsAdditionalReg = false;
1678 switch (MI.getOpcode()) {
1679 case Mips::ATOMIC_LOAD_NAND_I8:
1680 AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1681 break;
1682 case Mips::ATOMIC_LOAD_NAND_I16:
1683 AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1684 break;
1685 case Mips::ATOMIC_SWAP_I8:
1686 AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1687 break;
1688 case Mips::ATOMIC_SWAP_I16:
1689 AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1690 break;
1691 case Mips::ATOMIC_LOAD_ADD_I8:
1692 AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1693 break;
1694 case Mips::ATOMIC_LOAD_ADD_I16:
1695 AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1696 break;
1697 case Mips::ATOMIC_LOAD_SUB_I8:
1698 AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1699 break;
1700 case Mips::ATOMIC_LOAD_SUB_I16:
1701 AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1702 break;
1703 case Mips::ATOMIC_LOAD_AND_I8:
1704 AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1705 break;
1706 case Mips::ATOMIC_LOAD_AND_I16:
1707 AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1708 break;
1709 case Mips::ATOMIC_LOAD_OR_I8:
1710 AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1711 break;
1712 case Mips::ATOMIC_LOAD_OR_I16:
1713 AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1714 break;
1715 case Mips::ATOMIC_LOAD_XOR_I8:
1716 AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1717 break;
1718 case Mips::ATOMIC_LOAD_XOR_I16:
1719 AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1720 break;
1721 case Mips::ATOMIC_LOAD_MIN_I8:
1722 AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA;
1723 NeedsAdditionalReg = true;
1724 break;
1725 case Mips::ATOMIC_LOAD_MIN_I16:
1726 AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA;
1727 NeedsAdditionalReg = true;
1728 break;
1729 case Mips::ATOMIC_LOAD_MAX_I8:
1730 AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA;
1731 NeedsAdditionalReg = true;
1732 break;
1733 case Mips::ATOMIC_LOAD_MAX_I16:
1734 AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA;
1735 NeedsAdditionalReg = true;
1736 break;
1737 case Mips::ATOMIC_LOAD_UMIN_I8:
1738 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA;
1739 NeedsAdditionalReg = true;
1740 break;
1741 case Mips::ATOMIC_LOAD_UMIN_I16:
1742 AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA;
1743 NeedsAdditionalReg = true;
1744 break;
1745 case Mips::ATOMIC_LOAD_UMAX_I8:
1746 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA;
1747 NeedsAdditionalReg = true;
1748 break;
1749 case Mips::ATOMIC_LOAD_UMAX_I16:
1750 AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA;
1751 NeedsAdditionalReg = true;
1752 break;
1753 default:
1754 llvm_unreachable("Unknown subword atomic pseudo for expansion!")::llvm::llvm_unreachable_internal("Unknown subword atomic pseudo for expansion!"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1754)
;
1755 }
1756
1757 // insert new blocks after the current block
1758 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1759 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1760 MachineFunction::iterator It = ++BB->getIterator();
1761 MF->insert(It, exitMBB);
1762
1763 // Transfer the remainder of BB and its successor edges to exitMBB.
1764 exitMBB->splice(exitMBB->begin(), BB,
1765 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1766 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1767
1768 BB->addSuccessor(exitMBB, BranchProbability::getOne());
1769
1770 // thisMBB:
1771 // addiu masklsb2,$0,-4 # 0xfffffffc
1772 // and alignedaddr,ptr,masklsb2
1773 // andi ptrlsb2,ptr,3
1774 // sll shiftamt,ptrlsb2,3
1775 // ori maskupper,$0,255 # 0xff
1776 // sll mask,maskupper,shiftamt
1777 // nor mask2,$0,mask
1778 // sll incr2,incr,shiftamt
1779
1780 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1781 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1782 .addReg(ABI.GetNullPtr()).addImm(-4);
1783 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1784 .addReg(Ptr).addReg(MaskLSB2);
1785 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1786 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1787 if (Subtarget.isLittle()) {
1788 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1789 } else {
1790 Register Off = RegInfo.createVirtualRegister(RC);
1791 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1792 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1793 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1794 }
1795 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1796 .addReg(Mips::ZERO).addImm(MaskImm);
1797 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1798 .addReg(MaskUpper).addReg(ShiftAmt);
1799 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1800 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1801
1802
1803 // The purposes of the flags on the scratch registers is explained in
1804 // emitAtomicBinary. In summary, we need a scratch register which is going to
1805 // be undef, that is unique among registers chosen for the instruction.
1806
1807 MachineInstrBuilder MIB =
1808 BuildMI(BB, DL, TII->get(AtomicOp))
1809 .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1810 .addReg(AlignedAddr)
1811 .addReg(Incr2)
1812 .addReg(Mask)
1813 .addReg(Mask2)
1814 .addReg(ShiftAmt)
1815 .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1816 RegState::Dead | RegState::Implicit)
1817 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
1818 RegState::Dead | RegState::Implicit)
1819 .addReg(Scratch3, RegState::EarlyClobber | RegState::Define |
1820 RegState::Dead | RegState::Implicit);
1821 if (NeedsAdditionalReg) {
1822 Register Scratch4 = RegInfo.createVirtualRegister(RC);
1823 MIB.addReg(Scratch4, RegState::EarlyClobber | RegState::Define |
1824 RegState::Dead | RegState::Implicit);
1825 }
1826
1827 MI.eraseFromParent(); // The instruction is gone now.
1828
1829 return exitMBB;
1830}
1831
1832// Lower atomic compare and swap to a pseudo instruction, taking care to
1833// define a scratch register for the pseudo instruction's expansion. The
1834// instruction is expanded after the register allocator as to prevent
1835// the insertion of stores between the linked load and the store conditional.
1836
1837MachineBasicBlock *
1838MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1839 MachineBasicBlock *BB) const {
1840
1841 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1843, __PRETTY_FUNCTION__))
1842 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1843, __PRETTY_FUNCTION__))
1843 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1843, __PRETTY_FUNCTION__))
;
1844
1845 const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1846
1847 MachineFunction *MF = BB->getParent();
1848 MachineRegisterInfo &MRI = MF->getRegInfo();
1849 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1850 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1851 DebugLoc DL = MI.getDebugLoc();
1852
1853 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1854 ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1855 : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1856 Register Dest = MI.getOperand(0).getReg();
1857 Register Ptr = MI.getOperand(1).getReg();
1858 Register OldVal = MI.getOperand(2).getReg();
1859 Register NewVal = MI.getOperand(3).getReg();
1860
1861 Register Scratch = MRI.createVirtualRegister(RC);
1862 MachineBasicBlock::iterator II(MI);
1863
1864 // We need to create copies of the various registers and kill them at the
1865 // atomic pseudo. If the copies are not made, when the atomic is expanded
1866 // after fast register allocation, the spills will end up outside of the
1867 // blocks that their values are defined in, causing livein errors.
1868
1869 Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1870 Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1871 Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1872
1873 BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1874 BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1875 BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1876
1877 // The purposes of the flags on the scratch registers is explained in
1878 // emitAtomicBinary. In summary, we need a scratch register which is going to
1879 // be undef, that is unique among registers chosen for the instruction.
1880
1881 BuildMI(*BB, II, DL, TII->get(AtomicOp))
1882 .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1883 .addReg(PtrCopy, RegState::Kill)
1884 .addReg(OldValCopy, RegState::Kill)
1885 .addReg(NewValCopy, RegState::Kill)
1886 .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1887 RegState::Dead | RegState::Implicit);
1888
1889 MI.eraseFromParent(); // The instruction is gone now.
1890
1891 return BB;
1892}
1893
1894MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1895 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1896 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1897, __PRETTY_FUNCTION__))
1897 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 1897, __PRETTY_FUNCTION__))
;
1898
1899 MachineFunction *MF = BB->getParent();
1900 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1901 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1902 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1903 const TargetRegisterClass *RCp =
1904 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1905 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1906 DebugLoc DL = MI.getDebugLoc();
1907
1908 Register Dest = MI.getOperand(0).getReg();
1909 Register Ptr = MI.getOperand(1).getReg();
1910 Register CmpVal = MI.getOperand(2).getReg();
1911 Register NewVal = MI.getOperand(3).getReg();
1912
1913 Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1914 Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1915 Register Mask = RegInfo.createVirtualRegister(RC);
1916 Register Mask2 = RegInfo.createVirtualRegister(RC);
1917 Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1918 Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1919 Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1920 Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1921 Register MaskUpper = RegInfo.createVirtualRegister(RC);
1922 Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1923 Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
1924 unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
1925 ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
1926 : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
1927
1928 // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
1929 // flags are used to coerce the register allocator and the machine verifier to
1930 // accept the usage of these registers.
1931 // The EarlyClobber flag has the semantic properties that the operand it is
1932 // attached to is clobbered before the rest of the inputs are read. Hence it
1933 // must be unique among the operands to the instruction.
1934 // The Define flag is needed to coerce the machine verifier that an Undef
1935 // value isn't a problem.
1936 // The Dead flag is needed as the value in scratch isn't used by any other
1937 // instruction. Kill isn't used as Dead is more precise.
1938 Register Scratch = RegInfo.createVirtualRegister(RC);
1939 Register Scratch2 = RegInfo.createVirtualRegister(RC);
1940
1941 // insert new blocks after the current block
1942 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1943 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1944 MachineFunction::iterator It = ++BB->getIterator();
1945 MF->insert(It, exitMBB);
1946
1947 // Transfer the remainder of BB and its successor edges to exitMBB.
1948 exitMBB->splice(exitMBB->begin(), BB,
1949 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1950 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1951
1952 BB->addSuccessor(exitMBB, BranchProbability::getOne());
1953
1954 // thisMBB:
1955 // addiu masklsb2,$0,-4 # 0xfffffffc
1956 // and alignedaddr,ptr,masklsb2
1957 // andi ptrlsb2,ptr,3
1958 // xori ptrlsb2,ptrlsb2,3 # Only for BE
1959 // sll shiftamt,ptrlsb2,3
1960 // ori maskupper,$0,255 # 0xff
1961 // sll mask,maskupper,shiftamt
1962 // nor mask2,$0,mask
1963 // andi maskedcmpval,cmpval,255
1964 // sll shiftedcmpval,maskedcmpval,shiftamt
1965 // andi maskednewval,newval,255
1966 // sll shiftednewval,maskednewval,shiftamt
1967 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1968 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1969 .addReg(ABI.GetNullPtr()).addImm(-4);
1970 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1971 .addReg(Ptr).addReg(MaskLSB2);
1972 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1973 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1974 if (Subtarget.isLittle()) {
1975 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1976 } else {
1977 Register Off = RegInfo.createVirtualRegister(RC);
1978 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1979 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1980 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1981 }
1982 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1983 .addReg(Mips::ZERO).addImm(MaskImm);
1984 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1985 .addReg(MaskUpper).addReg(ShiftAmt);
1986 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1987 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1988 .addReg(CmpVal).addImm(MaskImm);
1989 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1990 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1991 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1992 .addReg(NewVal).addImm(MaskImm);
1993 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1994 .addReg(MaskedNewVal).addReg(ShiftAmt);
1995
1996 // The purposes of the flags on the scratch registers are explained in
1997 // emitAtomicBinary. In summary, we need a scratch register which is going to
1998 // be undef, that is unique among the register chosen for the instruction.
1999
2000 BuildMI(BB, DL, TII->get(AtomicOp))
2001 .addReg(Dest, RegState::Define | RegState::EarlyClobber)
2002 .addReg(AlignedAddr)
2003 .addReg(Mask)
2004 .addReg(ShiftedCmpVal)
2005 .addReg(Mask2)
2006 .addReg(ShiftedNewVal)
2007 .addReg(ShiftAmt)
2008 .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
2009 RegState::Dead | RegState::Implicit)
2010 .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
2011 RegState::Dead | RegState::Implicit);
2012
2013 MI.eraseFromParent(); // The instruction is gone now.
2014
2015 return exitMBB;
2016}
2017
2018SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2019 // The first operand is the chain, the second is the condition, the third is
2020 // the block to branch to if the condition is true.
2021 SDValue Chain = Op.getOperand(0);
2022 SDValue Dest = Op.getOperand(2);
2023 SDLoc DL(Op);
2024
2025 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6())((!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6(
)) ? static_cast<void> (0) : __assert_fail ("!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2025, __PRETTY_FUNCTION__))
;
2026 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2027
2028 // Return if flag is not set by a floating point comparison.
2029 if (CondRes.getOpcode() != MipsISD::FPCmp)
2030 return Op;
2031
2032 SDValue CCNode = CondRes.getOperand(2);
2033 Mips::CondCode CC =
2034 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2035 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
2036 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2037 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2038 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2039 FCC0, Dest, CondRes);
2040}
2041
2042SDValue MipsTargetLowering::
2043lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2044{
2045 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6())((!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6(
)) ? static_cast<void> (0) : __assert_fail ("!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2045, __PRETTY_FUNCTION__))
;
2046 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2047
2048 // Return if flag is not set by a floating point comparison.
2049 if (Cond.getOpcode() != MipsISD::FPCmp)
2050 return Op;
2051
2052 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2053 SDLoc(Op));
2054}
2055
2056SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2057 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6())((!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6(
)) ? static_cast<void> (0) : __assert_fail ("!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2057, __PRETTY_FUNCTION__))
;
2058 SDValue Cond = createFPCmp(DAG, Op);
2059
2060 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2061, __PRETTY_FUNCTION__))
2061 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2061, __PRETTY_FUNCTION__))
;
2062
2063 SDLoc DL(Op);
2064 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2065 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2066
2067 return createCMovFP(DAG, Cond, True, False, DL);
2068}
2069
2070SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2071 SelectionDAG &DAG) const {
2072 EVT Ty = Op.getValueType();
2073 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2074 const GlobalValue *GV = N->getGlobal();
2075
2076 if (!isPositionIndependent()) {
2077 const MipsTargetObjectFile *TLOF =
2078 static_cast<const MipsTargetObjectFile *>(
2079 getTargetMachine().getObjFileLowering());
2080 const GlobalObject *GO = GV->getBaseObject();
2081 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2082 // %gp_rel relocation
2083 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2084
2085 // %hi/%lo relocation
2086 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2087 // %highest/%higher/%hi/%lo relocation
2088 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2089 }
2090
2091 // Every other architecture would use shouldAssumeDSOLocal in here, but
2092 // mips is special.
2093 // * In PIC code mips requires got loads even for local statics!
2094 // * To save on got entries, for local statics the got entry contains the
2095 // page and an additional add instruction takes care of the low bits.
2096 // * It is legal to access a hidden symbol with a non hidden undefined,
2097 // so one cannot guarantee that all access to a hidden symbol will know
2098 // it is hidden.
2099 // * Mips linkers don't support creating a page and a full got entry for
2100 // the same symbol.
2101 // * Given all that, we have to use a full got entry for hidden symbols :-(
2102 if (GV->hasLocalLinkage())
2103 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2104
2105 if (Subtarget.useXGOT())
2106 return getAddrGlobalLargeGOT(
2107 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2108 DAG.getEntryNode(),
2109 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2110
2111 return getAddrGlobal(
2112 N, SDLoc(N), Ty, DAG,
2113 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2114 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2115}
2116
2117SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2118 SelectionDAG &DAG) const {
2119 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2120 EVT Ty = Op.getValueType();
2121
2122 if (!isPositionIndependent())
2123 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2124 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2125
2126 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2127}
2128
2129SDValue MipsTargetLowering::
2130lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2131{
2132 // If the relocation model is PIC, use the General Dynamic TLS Model or
2133 // Local Dynamic TLS model, otherwise use the Initial Exec or
2134 // Local Exec TLS Model.
2135
2136 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2137 if (DAG.getTarget().useEmulatedTLS())
2138 return LowerToTLSEmulatedModel(GA, DAG);
2139
2140 SDLoc DL(GA);
2141 const GlobalValue *GV = GA->getGlobal();
2142 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2143
2144 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2145
2146 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2147 // General Dynamic and Local Dynamic TLS Model.
2148 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2149 : MipsII::MO_TLSGD;
2150
2151 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2152 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2153 getGlobalReg(DAG, PtrVT), TGA);
2154 unsigned PtrSize = PtrVT.getSizeInBits();
2155 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2156
2157 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2158
2159 ArgListTy Args;
2160 ArgListEntry Entry;
2161 Entry.Node = Argument;
2162 Entry.Ty = PtrTy;
2163 Args.push_back(Entry);
2164
2165 TargetLowering::CallLoweringInfo CLI(DAG);
2166 CLI.setDebugLoc(DL)
2167 .setChain(DAG.getEntryNode())
2168 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2169 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2170
2171 SDValue Ret = CallResult.first;
2172
2173 if (model != TLSModel::LocalDynamic)
2174 return Ret;
2175
2176 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2177 MipsII::MO_DTPREL_HI);
2178 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2179 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2180 MipsII::MO_DTPREL_LO);
2181 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2182 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2183 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2184 }
2185
2186 SDValue Offset;
2187 if (model == TLSModel::InitialExec) {
2188 // Initial Exec TLS Model
2189 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2190 MipsII::MO_GOTTPREL);
2191 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2192 TGA);
2193 Offset =
2194 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2195 } else {
2196 // Local Exec TLS Model
2197 assert(model == TLSModel::LocalExec)((model == TLSModel::LocalExec) ? static_cast<void> (0)
: __assert_fail ("model == TLSModel::LocalExec", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2197, __PRETTY_FUNCTION__))
;
2198 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2199 MipsII::MO_TPREL_HI);
2200 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2201 MipsII::MO_TPREL_LO);
2202 SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2203 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2204 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2205 }
2206
2207 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2208 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2209}
2210
2211SDValue MipsTargetLowering::
2212lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2213{
2214 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2215 EVT Ty = Op.getValueType();
2216
2217 if (!isPositionIndependent())
2218 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2219 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2220
2221 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2222}
2223
2224SDValue MipsTargetLowering::
2225lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2226{
2227 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2228 EVT Ty = Op.getValueType();
2229
2230 if (!isPositionIndependent()) {
2231 const MipsTargetObjectFile *TLOF =
2232 static_cast<const MipsTargetObjectFile *>(
2233 getTargetMachine().getObjFileLowering());
2234
2235 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2236 getTargetMachine()))
2237 // %gp_rel relocation
2238 return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2239
2240 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2241 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2242 }
2243
2244 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2245}
2246
2247SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2248 MachineFunction &MF = DAG.getMachineFunction();
2249 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2250
2251 SDLoc DL(Op);
2252 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2253 getPointerTy(MF.getDataLayout()));
2254
2255 // vastart just stores the address of the VarArgsFrameIndex slot into the
2256 // memory location argument.
2257 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2258 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2259 MachinePointerInfo(SV));
2260}
2261
2262SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2263 SDNode *Node = Op.getNode();
2264 EVT VT = Node->getValueType(0);
2265 SDValue Chain = Node->getOperand(0);
2266 SDValue VAListPtr = Node->getOperand(1);
2267 const Align Align =
2268 llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2269 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2270 SDLoc DL(Node);
2271 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2272
2273 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2274 VAListPtr, MachinePointerInfo(SV));
2275 SDValue VAList = VAListLoad;
2276
2277 // Re-align the pointer if necessary.
2278 // It should only ever be necessary for 64-bit types on O32 since the minimum
2279 // argument alignment is the same as the maximum type alignment for N32/N64.
2280 //
2281 // FIXME: We currently align too often. The code generator doesn't notice
2282 // when the pointer is still aligned from the last va_arg (or pair of
2283 // va_args for the i64 on O32 case).
2284 if (Align > getMinStackArgumentAlignment()) {
2285 VAList = DAG.getNode(
2286 ISD::ADD, DL, VAList.getValueType(), VAList,
2287 DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2288
2289 VAList = DAG.getNode(
2290 ISD::AND, DL, VAList.getValueType(), VAList,
2291 DAG.getConstant(-(int64_t)Align.value(), DL, VAList.getValueType()));
2292 }
2293
2294 // Increment the pointer, VAList, to the next vaarg.
2295 auto &TD = DAG.getDataLayout();
2296 unsigned ArgSizeInBytes =
2297 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2298 SDValue Tmp3 =
2299 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2300 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2301 DL, VAList.getValueType()));
2302 // Store the incremented VAList to the legalized pointer
2303 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2304 MachinePointerInfo(SV));
2305
2306 // In big-endian mode we must adjust the pointer when the load size is smaller
2307 // than the argument slot size. We must also reduce the known alignment to
2308 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2309 // the correct half of the slot, and reduce the alignment from 8 (slot
2310 // alignment) down to 4 (type alignment).
2311 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2312 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2313 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2314 DAG.getIntPtrConstant(Adjustment, DL));
2315 }
2316 // Load the actual argument out of the pointer VAList
2317 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2318}
2319
2320static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2321 bool HasExtractInsert) {
2322 EVT TyX = Op.getOperand(0).getValueType();
2323 EVT TyY = Op.getOperand(1).getValueType();
2324 SDLoc DL(Op);
2325 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2326 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2327 SDValue Res;
2328
2329 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2330 // to i32.
2331 SDValue X = (TyX == MVT::f32) ?
2332 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2333 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2334 Const1);
2335 SDValue Y = (TyY == MVT::f32) ?
2336 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2337 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2338 Const1);
2339
2340 if (HasExtractInsert) {
2341 // ext E, Y, 31, 1 ; extract bit31 of Y
2342 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2343 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2344 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2345 } else {
2346 // sll SllX, X, 1
2347 // srl SrlX, SllX, 1
2348 // srl SrlY, Y, 31
2349 // sll SllY, SrlX, 31
2350 // or Or, SrlX, SllY
2351 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2352 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2353 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2354 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2355 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2356 }
2357
2358 if (TyX == MVT::f32)
2359 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2360
2361 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2362 Op.getOperand(0),
2363 DAG.getConstant(0, DL, MVT::i32));
2364 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2365}
2366
2367static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2368 bool HasExtractInsert) {
2369 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2370 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2371 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2372 SDLoc DL(Op);
2373 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2374
2375 // Bitcast to integer nodes.
2376 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2377 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2378
2379 if (HasExtractInsert) {
2380 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2381 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2382 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2383 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2384
2385 if (WidthX > WidthY)
2386 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2387 else if (WidthY > WidthX)
2388 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2389
2390 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2391 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2392 X);
2393 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2394 }
2395
2396 // (d)sll SllX, X, 1
2397 // (d)srl SrlX, SllX, 1
2398 // (d)srl SrlY, Y, width(Y)-1
2399 // (d)sll SllY, SrlX, width(Y)-1
2400 // or Or, SrlX, SllY
2401 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2402 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2403 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2404 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2405
2406 if (WidthX > WidthY)
2407 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2408 else if (WidthY > WidthX)
2409 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2410
2411 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2412 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2413 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2414 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2415}
2416
2417SDValue
2418MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2419 if (Subtarget.isGP64bit())
2420 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2421
2422 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2423}
2424
2425static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
2426 bool HasExtractInsert) {
2427 SDLoc DL(Op);
2428 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2429
2430 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2431 // to i32.
2432 SDValue X = (Op.getValueType() == MVT::f32)
2433 ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2434 : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2435 Op.getOperand(0), Const1);
2436
2437 // Clear MSB.
2438 if (HasExtractInsert)
2439 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2440 DAG.getRegister(Mips::ZERO, MVT::i32),
2441 DAG.getConstant(31, DL, MVT::i32), Const1, X);
2442 else {
2443 // TODO: Provide DAG patterns which transform (and x, cst)
2444 // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2445 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2446 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2447 }
2448
2449 if (Op.getValueType() == MVT::f32)
2450 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2451
2452 // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2453 // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2454 // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2455 // place.
2456 SDValue LowX =
2457 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2458 DAG.getConstant(0, DL, MVT::i32));
2459 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2460}
2461
2462static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
2463 bool HasExtractInsert) {
2464 SDLoc DL(Op);
2465 SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2466
2467 // Bitcast to integer node.
2468 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2469
2470 // Clear MSB.
2471 if (HasExtractInsert)
2472 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2473 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2474 DAG.getConstant(63, DL, MVT::i32), Const1, X);
2475 else {
2476 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2477 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2478 }
2479
2480 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2481}
2482
2483SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2484 if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2485 return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2486
2487 return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2488}
2489
2490SDValue MipsTargetLowering::
2491lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2492 // check the depth
2493 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2494 DAG.getContext()->emitError(
2495 "return address can be determined only for current frame");
2496 return SDValue();
2497 }
2498
2499 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2500 MFI.setFrameAddressIsTaken(true);
2501 EVT VT = Op.getValueType();
2502 SDLoc DL(Op);
2503 SDValue FrameAddr = DAG.getCopyFromReg(
2504 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2505 return FrameAddr;
2506}
2507
2508SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2509 SelectionDAG &DAG) const {
2510 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2511 return SDValue();
2512
2513 // check the depth
2514 if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2515 DAG.getContext()->emitError(
2516 "return address can be determined only for current frame");
2517 return SDValue();
2518 }
2519
2520 MachineFunction &MF = DAG.getMachineFunction();
2521 MachineFrameInfo &MFI = MF.getFrameInfo();
2522 MVT VT = Op.getSimpleValueType();
2523 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2524 MFI.setReturnAddressIsTaken(true);
2525
2526 // Return RA, which contains the return address. Mark it an implicit live-in.
2527 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2528 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2529}
2530
2531// An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2532// generated from __builtin_eh_return (offset, handler)
2533// The effect of this is to adjust the stack pointer by "offset"
2534// and then branch to "handler".
2535SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2536 const {
2537 MachineFunction &MF = DAG.getMachineFunction();
2538 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2539
2540 MipsFI->setCallsEhReturn();
2541 SDValue Chain = Op.getOperand(0);
2542 SDValue Offset = Op.getOperand(1);
2543 SDValue Handler = Op.getOperand(2);
2544 SDLoc DL(Op);
2545 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2546
2547 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2548 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2549 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2550 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2551 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2552 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2553 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2554 DAG.getRegister(OffsetReg, Ty),
2555 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2556 Chain.getValue(1));
2557}
2558
2559SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2560 SelectionDAG &DAG) const {
2561 // FIXME: Need pseudo-fence for 'singlethread' fences
2562 // FIXME: Set SType for weaker fences where supported/appropriate.
2563 unsigned SType = 0;
2564 SDLoc DL(Op);
2565 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2566 DAG.getConstant(SType, DL, MVT::i32));
2567}
2568
2569SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2570 SelectionDAG &DAG) const {
2571 SDLoc DL(Op);
2572 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2573
2574 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2575 SDValue Shamt = Op.getOperand(2);
2576 // if shamt < (VT.bits):
2577 // lo = (shl lo, shamt)
2578 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2579 // else:
2580 // lo = 0
2581 // hi = (shl lo, shamt[4:0])
2582 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2583 DAG.getConstant(-1, DL, MVT::i32));
2584 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2585 DAG.getConstant(1, DL, VT));
2586 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2587 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2588 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2589 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2590 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2591 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2592 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2593 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2594 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2595
2596 SDValue Ops[2] = {Lo, Hi};
2597 return DAG.getMergeValues(Ops, DL);
2598}
2599
2600SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2601 bool IsSRA) const {
2602 SDLoc DL(Op);
2603 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2604 SDValue Shamt = Op.getOperand(2);
2605 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2606
2607 // if shamt < (VT.bits):
2608 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2609 // if isSRA:
2610 // hi = (sra hi, shamt)
2611 // else:
2612 // hi = (srl hi, shamt)
2613 // else:
2614 // if isSRA:
2615 // lo = (sra hi, shamt[4:0])
2616 // hi = (sra hi, 31)
2617 // else:
2618 // lo = (srl hi, shamt[4:0])
2619 // hi = 0
2620 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2621 DAG.getConstant(-1, DL, MVT::i32));
2622 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2623 DAG.getConstant(1, DL, VT));
2624 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2625 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2626 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2627 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2628 DL, VT, Hi, Shamt);
2629 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2630 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2631 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2632 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2633
2634 if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2635 SDVTList VTList = DAG.getVTList(VT, VT);
2636 return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64
2637 : Mips::PseudoD_SELECT_I,
2638 DL, VTList, Cond, ShiftRightHi,
2639 IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2640 ShiftRightHi);
2641 }
2642
2643 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2644 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2645 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2646
2647 SDValue Ops[2] = {Lo, Hi};
2648 return DAG.getMergeValues(Ops, DL);
2649}
2650
2651static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2652 SDValue Chain, SDValue Src, unsigned Offset) {
2653 SDValue Ptr = LD->getBasePtr();
2654 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2655 EVT BasePtrVT = Ptr.getValueType();
2656 SDLoc DL(LD);
2657 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2658
2659 if (Offset)
2660 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2661 DAG.getConstant(Offset, DL, BasePtrVT));
2662
2663 SDValue Ops[] = { Chain, Ptr, Src };
2664 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2665 LD->getMemOperand());
2666}
2667
2668// Expand an unaligned 32 or 64-bit integer load node.
2669SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2670 LoadSDNode *LD = cast<LoadSDNode>(Op);
2671 EVT MemVT = LD->getMemoryVT();
2672
2673 if (Subtarget.systemSupportsUnalignedAccess())
2674 return Op;
2675
2676 // Return if load is aligned or if MemVT is neither i32 nor i64.
2677 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2678 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2679 return SDValue();
2680
2681 bool IsLittle = Subtarget.isLittle();
2682 EVT VT = Op.getValueType();
2683 ISD::LoadExtType ExtType = LD->getExtensionType();
2684 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2685
2686 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2686, __PRETTY_FUNCTION__))
;
2687
2688 // Expand
2689 // (set dst, (i64 (load baseptr)))
2690 // to
2691 // (set tmp, (ldl (add baseptr, 7), undef))
2692 // (set dst, (ldr baseptr, tmp))
2693 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2694 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2695 IsLittle ? 7 : 0);
2696 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2697 IsLittle ? 0 : 7);
2698 }
2699
2700 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2701 IsLittle ? 3 : 0);
2702 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2703 IsLittle ? 0 : 3);
2704
2705 // Expand
2706 // (set dst, (i32 (load baseptr))) or
2707 // (set dst, (i64 (sextload baseptr))) or
2708 // (set dst, (i64 (extload baseptr)))
2709 // to
2710 // (set tmp, (lwl (add baseptr, 3), undef))
2711 // (set dst, (lwr baseptr, tmp))
2712 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2713 (ExtType == ISD::EXTLOAD))
2714 return LWR;
2715
2716 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2716, __PRETTY_FUNCTION__))
;
2717
2718 // Expand
2719 // (set dst, (i64 (zextload baseptr)))
2720 // to
2721 // (set tmp0, (lwl (add baseptr, 3), undef))
2722 // (set tmp1, (lwr baseptr, tmp0))
2723 // (set tmp2, (shl tmp1, 32))
2724 // (set dst, (srl tmp2, 32))
2725 SDLoc DL(LD);
2726 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2727 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2728 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2729 SDValue Ops[] = { SRL, LWR.getValue(1) };
2730 return DAG.getMergeValues(Ops, DL);
2731}
2732
2733static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2734 SDValue Chain, unsigned Offset) {
2735 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2736 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2737 SDLoc DL(SD);
2738 SDVTList VTList = DAG.getVTList(MVT::Other);
2739
2740 if (Offset)
2741 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2742 DAG.getConstant(Offset, DL, BasePtrVT));
2743
2744 SDValue Ops[] = { Chain, Value, Ptr };
2745 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2746 SD->getMemOperand());
2747}
2748
2749// Expand an unaligned 32 or 64-bit integer store node.
2750static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2751 bool IsLittle) {
2752 SDValue Value = SD->getValue(), Chain = SD->getChain();
2753 EVT VT = Value.getValueType();
2754
2755 // Expand
2756 // (store val, baseptr) or
2757 // (truncstore val, baseptr)
2758 // to
2759 // (swl val, (add baseptr, 3))
2760 // (swr val, baseptr)
2761 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2762 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2763 IsLittle ? 3 : 0);
2764 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2765 }
2766
2767 assert(VT == MVT::i64)((VT == MVT::i64) ? static_cast<void> (0) : __assert_fail
("VT == MVT::i64", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2767, __PRETTY_FUNCTION__))
;
2768
2769 // Expand
2770 // (store val, baseptr)
2771 // to
2772 // (sdl val, (add baseptr, 7))
2773 // (sdr val, baseptr)
2774 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2775 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2776}
2777
2778// Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2779static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG,
2780 bool SingleFloat) {
2781 SDValue Val = SD->getValue();
2782
2783 if (Val.getOpcode() != ISD::FP_TO_SINT ||
2784 (Val.getValueSizeInBits() > 32 && SingleFloat))
2785 return SDValue();
2786
2787 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2788 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2789 Val.getOperand(0));
2790 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2791 SD->getPointerInfo(), SD->getAlignment(),
2792 SD->getMemOperand()->getFlags());
2793}
2794
2795SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2796 StoreSDNode *SD = cast<StoreSDNode>(Op);
2797 EVT MemVT = SD->getMemoryVT();
2798
2799 // Lower unaligned integer stores.
2800 if (!Subtarget.systemSupportsUnalignedAccess() &&
2801 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2802 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2803 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2804
2805 return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
2806}
2807
2808SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2809 SelectionDAG &DAG) const {
2810
2811 // Return a fixed StackObject with offset 0 which points to the old stack
2812 // pointer.
2813 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2814 EVT ValTy = Op->getValueType(0);
2815 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2816 return DAG.getFrameIndex(FI, ValTy);
2817}
2818
2819SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2820 SelectionDAG &DAG) const {
2821 if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2822 return SDValue();
2823
2824 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2825 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2826 Op.getOperand(0));
2827 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2828}
2829
2830//===----------------------------------------------------------------------===//
2831// Calling Convention Implementation
2832//===----------------------------------------------------------------------===//
2833
2834//===----------------------------------------------------------------------===//
2835// TODO: Implement a generic logic using tblgen that can support this.
2836// Mips O32 ABI rules:
2837// ---
2838// i32 - Passed in A0, A1, A2, A3 and stack
2839// f32 - Only passed in f32 registers if no int reg has been used yet to hold
2840// an argument. Otherwise, passed in A1, A2, A3 and stack.
2841// f64 - Only passed in two aliased f32 registers if no int reg has been used
2842// yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2843// not used, it must be shadowed. If only A3 is available, shadow it and
2844// go to stack.
2845// vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2846// vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2847// with the remainder spilled to the stack.
2848// vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2849// spilling the remainder to the stack.
2850//
2851// For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2852//===----------------------------------------------------------------------===//
2853
2854static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2855 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2856 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2857 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2858 State.getMachineFunction().getSubtarget());
2859
2860 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2861
2862 const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2863
2864 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2865
2866 static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2867
2868 // Do not process byval args here.
2869 if (ArgFlags.isByVal())
2870 return true;
2871
2872 // Promote i8 and i16
2873 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2874 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2875 LocVT = MVT::i32;
2876 if (ArgFlags.isSExt())
2877 LocInfo = CCValAssign::SExtUpper;
2878 else if (ArgFlags.isZExt())
2879 LocInfo = CCValAssign::ZExtUpper;
2880 else
2881 LocInfo = CCValAssign::AExtUpper;
2882 }
2883 }
2884
2885 // Promote i8 and i16
2886 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2887 LocVT = MVT::i32;
2888 if (ArgFlags.isSExt())
2889 LocInfo = CCValAssign::SExt;
2890 else if (ArgFlags.isZExt())
2891 LocInfo = CCValAssign::ZExt;
2892 else
2893 LocInfo = CCValAssign::AExt;
2894 }
2895
2896 unsigned Reg;
2897
2898 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2899 // is true: function is vararg, argument is 3rd or higher, there is previous
2900 // argument which is not f32 or f64.
2901 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2902 State.getFirstUnallocated(F32Regs) != ValNo;
2903 unsigned OrigAlign = ArgFlags.getOrigAlign();
2904 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2905 bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2906
2907 // The MIPS vector ABI for floats passes them in a pair of registers
2908 if (ValVT == MVT::i32 && isVectorFloat) {
2909 // This is the start of an vector that was scalarized into an unknown number
2910 // of components. It doesn't matter how many there are. Allocate one of the
2911 // notional 8 byte aligned registers which map onto the argument stack, and
2912 // shadow the register lost to alignment requirements.
2913 if (ArgFlags.isSplit()) {
2914 Reg = State.AllocateReg(FloatVectorIntRegs);
2915 if (Reg == Mips::A2)
2916 State.AllocateReg(Mips::A1);
2917 else if (Reg == 0)
2918 State.AllocateReg(Mips::A3);
2919 } else {
2920 // If we're an intermediate component of the split, we can just attempt to
2921 // allocate a register directly.
2922 Reg = State.AllocateReg(IntRegs);
2923 }
2924 } else if (ValVT == MVT::i32 ||
2925 (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2926 Reg = State.AllocateReg(IntRegs);
2927 // If this is the first part of an i64 arg,
2928 // the allocated register must be either A0 or A2.
2929 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2930 Reg = State.AllocateReg(IntRegs);
2931 LocVT = MVT::i32;
2932 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2933 // Allocate int register and shadow next int register. If first
2934 // available register is Mips::A1 or Mips::A3, shadow it too.
2935 Reg = State.AllocateReg(IntRegs);
2936 if (Reg == Mips::A1 || Reg == Mips::A3)
2937 Reg = State.AllocateReg(IntRegs);
2938 State.AllocateReg(IntRegs);
2939 LocVT = MVT::i32;
2940 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2941 // we are guaranteed to find an available float register
2942 if (ValVT == MVT::f32) {
2943 Reg = State.AllocateReg(F32Regs);
2944 // Shadow int register
2945 State.AllocateReg(IntRegs);
2946 } else {
2947 Reg = State.AllocateReg(F64Regs);
2948 // Shadow int registers
2949 unsigned Reg2 = State.AllocateReg(IntRegs);
2950 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2951 State.AllocateReg(IntRegs);
2952 State.AllocateReg(IntRegs);
2953 }
2954 } else
2955 llvm_unreachable("Cannot handle this ValVT.")::llvm::llvm_unreachable_internal("Cannot handle this ValVT."
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 2955)
;
2956
2957 if (!Reg) {
2958 unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
2959 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2960 } else
2961 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2962
2963 return false;
2964}
2965
2966static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2967 MVT LocVT, CCValAssign::LocInfo LocInfo,
2968 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2969 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2970
2971 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2972}
2973
2974static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2975 MVT LocVT, CCValAssign::LocInfo LocInfo,
2976 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2977 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2978
2979 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2980}
2981
2982static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2983 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2984 CCState &State) LLVM_ATTRIBUTE_UNUSED__attribute__((__unused__));
2985
2986#include "MipsGenCallingConv.inc"
2987
2988 CCAssignFn *MipsTargetLowering::CCAssignFnForCall() const{
2989 return CC_Mips_FixedArg;
2990 }
2991
2992 CCAssignFn *MipsTargetLowering::CCAssignFnForReturn() const{
2993 return RetCC_Mips;
2994 }
2995//===----------------------------------------------------------------------===//
2996// Call Calling Convention Implementation
2997//===----------------------------------------------------------------------===//
2998
2999// Return next O32 integer argument register.
3000static unsigned getNextIntArgReg(unsigned Reg) {
3001 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3001, __PRETTY_FUNCTION__))
;
3002 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
3003}
3004
3005SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3006 SDValue Chain, SDValue Arg,
3007 const SDLoc &DL, bool IsTailCall,
3008 SelectionDAG &DAG) const {
3009 if (!IsTailCall) {
3010 SDValue PtrOff =
3011 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
3012 DAG.getIntPtrConstant(Offset, DL));
3013 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
3014 }
3015
3016 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3017 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3018 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3019 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
3020 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
3021}
3022
3023void MipsTargetLowering::
3024getOpndList(SmallVectorImpl<SDValue> &Ops,
3025 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3026 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
3027 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
3028 SDValue Chain) const {
3029 // Insert node "GP copy globalreg" before call to function.
3030 //
3031 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3032 // in PIC mode) allow symbols to be resolved via lazy binding.
3033 // The lazy binding stub requires GP to point to the GOT.
3034 // Note that we don't need GP to point to the GOT for indirect calls
3035 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3036 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3037 // used for the function (that is, Mips linker doesn't generate lazy binding
3038 // stub for a function whose address is taken in the program).
3039 if (IsPICCall && !InternalLinkage && IsCallReloc) {
3040 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3041 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3042 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3043 }
3044
3045 // Build a sequence of copy-to-reg nodes chained together with token
3046 // chain and flag operands which copy the outgoing args into registers.
3047 // The InFlag in necessary since all emitted instructions must be
3048 // stuck together.
3049 SDValue InFlag;
3050
3051 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3052 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
3053 RegsToPass[i].second, InFlag);
3054 InFlag = Chain.getValue(1);
3055 }
3056
3057 // Add argument registers to the end of the list so that they are
3058 // known live into the call.
3059 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3060 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
3061 RegsToPass[i].second.getValueType()));
3062
3063 // Add a register mask operand representing the call-preserved registers.
3064 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3065 const uint32_t *Mask =
3066 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3067 assert(Mask && "Missing call preserved mask for calling convention")((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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3067, __PRETTY_FUNCTION__))
;
3068 if (Subtarget.inMips16HardFloat()) {
3069 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
3070 StringRef Sym = G->getGlobal()->getName();
3071 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3072 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3073 Mask = MipsRegisterInfo::getMips16RetHelperMask();
3074 }
3075 }
3076 }
3077 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3078
3079 if (InFlag.getNode())
3080 Ops.push_back(InFlag);
3081}
3082
3083void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
3084 SDNode *Node) const {
3085 switch (MI.getOpcode()) {
3086 default:
3087 return;
3088 case Mips::JALR:
3089 case Mips::JALRPseudo:
3090 case Mips::JALR64:
3091 case Mips::JALR64Pseudo:
3092 case Mips::JALR16_MM:
3093 case Mips::JALRC16_MMR6:
3094 case Mips::TAILCALLREG:
3095 case Mips::TAILCALLREG64:
3096 case Mips::TAILCALLR6REG:
3097 case Mips::TAILCALL64R6REG:
3098 case Mips::TAILCALLREG_MM:
3099 case Mips::TAILCALLREG_MMR6: {
3100 if (!EmitJalrReloc ||
3101 Subtarget.inMips16Mode() ||
3102 !isPositionIndependent() ||
3103 Node->getNumOperands() < 1 ||
3104 Node->getOperand(0).getNumOperands() < 2) {
3105 return;
3106 }
3107 // We are after the callee address, set by LowerCall().
3108 // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3109 // symbol.
3110 const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3111 StringRef Sym;
3112 if (const GlobalAddressSDNode *G =
3113 dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
3114 Sym = G->getGlobal()->getName();
3115 }
3116 else if (const ExternalSymbolSDNode *ES =
3117 dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
3118 Sym = ES->getSymbol();
3119 }
3120
3121 if (Sym.empty())
3122 return;
3123
3124 MachineFunction *MF = MI.getParent()->getParent();
3125 MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3126 MI.addOperand(MachineOperand::CreateMCSymbol(S, MipsII::MO_JALR));
3127 }
3128 }
3129}
3130
3131/// LowerCall - functions arguments are copied from virtual regs to
3132/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3133SDValue
3134MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3135 SmallVectorImpl<SDValue> &InVals) const {
3136 SelectionDAG &DAG = CLI.DAG;
3137 SDLoc DL = CLI.DL;
3138 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3139 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
3140 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
3141 SDValue Chain = CLI.Chain;
3142 SDValue Callee = CLI.Callee;
1
Value assigned to 'Callee.Node'
3143 bool &IsTailCall = CLI.IsTailCall;
3144 CallingConv::ID CallConv = CLI.CallConv;
3145 bool IsVarArg = CLI.IsVarArg;
3146
3147 MachineFunction &MF = DAG.getMachineFunction();
3148 MachineFrameInfo &MFI = MF.getFrameInfo();
3149 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3150 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3151 bool IsPIC = isPositionIndependent();
3152
3153 // Analyze operands of the call, assigning locations to each operand.
3154 SmallVector<CCValAssign, 16> ArgLocs;
3155 MipsCCState CCInfo(
3156 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3157 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
3158
3159 const ExternalSymbolSDNode *ES =
3160 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
2
Assuming null pointer is passed into cast
3
Assuming pointer value is null
3161
3162 // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3163 // is during the lowering of a call with a byval argument which produces
3164 // a call to memcpy. For the O32 case, this causes the caller to allocate
3165 // stack space for the reserved argument area for the callee, then recursively
3166 // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3167 // ABIs mandate that the callee allocates the reserved argument area. We do
3168 // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3169 //
3170 // If the callee has a byval argument and memcpy is used, we are mandated
3171 // to already have produced a reserved argument area for the callee for O32.
3172 // Therefore, the reserved argument area can be reused for both calls.
3173 //
3174 // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3175 // present, as we have yet to hook that node onto the chain.
3176 //
3177 // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3178 // case. GCC does a similar trick, in that wherever possible, it calculates
3179 // the maximum out going argument area (including the reserved area), and
3180 // preallocates the stack space on entrance to the caller.
3181 //
3182 // FIXME: We should do the same for efficiency and space.
3183
3184 // Note: The check on the calling convention below must match
3185 // MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3186 bool MemcpyInByVal = ES
3.1
'ES' is null
3.1
'ES' is null
&&
3187 StringRef(ES->getSymbol()) == StringRef("memcpy") &&
3188 CallConv != CallingConv::Fast &&
3189 Chain.getOpcode() == ISD::CALLSEQ_START;
3190
3191 // Allocate the reserved argument area. It seems strange to do this from the
3192 // caller side but removing it breaks the frame size calculation.
3193 unsigned ReservedArgArea =
3194 MemcpyInByVal
3.2
'MemcpyInByVal' is false
3.2
'MemcpyInByVal' is false
? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
4
'?' condition is false
3195 CCInfo.AllocateStack(ReservedArgArea, 1);
3196
3197 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
3198 ES
4.1
'ES' is null
4.1
'ES' is null
? ES->getSymbol() : nullptr);
5
'?' condition is false
3199
3200 // Get a count of how many bytes are to be pushed on the stack.
3201 unsigned NextStackOffset = CCInfo.getNextStackOffset();
3202
3203 // Check if it's really possible to do a tail call. Restrict it to functions
3204 // that are part of this compilation unit.
3205 bool InternalLinkage = false;
3206 if (IsTailCall) {
6
Assuming 'IsTailCall' is false
7
Taking false branch
3207 IsTailCall = isEligibleForTailCallOptimization(
3208 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3209 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3210 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3211 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3212 G->getGlobal()->hasPrivateLinkage() ||
3213 G->getGlobal()->hasHiddenVisibility() ||
3214 G->getGlobal()->hasProtectedVisibility());
3215 }
3216 }
3217 if (!IsTailCall
7.1
'IsTailCall' is false
7.1
'IsTailCall' is false
&& CLI.CS && CLI.CS.isMustTailCall())
8
Assuming the condition is false
3218 report_fatal_error("failed to perform tail call elimination on a call "
3219 "site marked musttail");
3220
3221 if (IsTailCall
8.1
'IsTailCall' is false
8.1
'IsTailCall' is false
)
9
Taking false branch
3222 ++NumTailCalls;
3223
3224 // Chain is the output chain of the last Load/Store or CopyToReg node.
3225 // ByValChain is the output chain of the last Memcpy node created for copying
3226 // byval arguments to the stack.
3227 unsigned StackAlignment = TFL->getStackAlignment();
3228 NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3229 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3230
3231 if (!(IsTailCall
9.1
'IsTailCall' is false
9.1
'IsTailCall' is false
|| MemcpyInByVal))
10
Taking true branch
3232 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3233
3234 SDValue StackPtr =
3235 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
11
'?' condition is false
3236 getPointerTy(DAG.getDataLayout()));
3237
3238 std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3239 SmallVector<SDValue, 8> MemOpChains;
3240
3241 CCInfo.rewindByValRegsInfo();
3242
3243 // Walk the register/memloc assignments, inserting copies/loads.
3244 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 3343
3245 SDValue Arg = OutVals[i];
3246 CCValAssign &VA = ArgLocs[i];
3247 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3248 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3249 bool UseUpperBits = false;
3250
3251 // ByVal Arg.
3252 if (Flags.isByVal()) {
3253 unsigned FirstByValReg, LastByValReg;
3254 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3255 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3256
3257 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3258, __PRETTY_FUNCTION__))
3258 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3258, __PRETTY_FUNCTION__))
;
3259 assert(ByValIdx < CCInfo.getInRegsParamsCount())((ByValIdx < CCInfo.getInRegsParamsCount()) ? static_cast<
void> (0) : __assert_fail ("ByValIdx < CCInfo.getInRegsParamsCount()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3259, __PRETTY_FUNCTION__))
;
3260 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3261, __PRETTY_FUNCTION__))
3261 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3261, __PRETTY_FUNCTION__))
;
3262 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3263 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3264 VA);
3265 CCInfo.nextInRegsParam();
3266 continue;
3267 }
3268
3269 // Promote the value if needed.
3270 switch (VA.getLocInfo()) {
3271 default:
3272 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3272)
;
3273 case CCValAssign::Full:
3274 if (VA.isRegLoc()) {
3275 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3276 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3277 (ValVT == MVT::i64 && LocVT == MVT::f64))
3278 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3279 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3280 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3281 Arg, DAG.getConstant(0, DL, MVT::i32));
3282 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3283 Arg, DAG.getConstant(1, DL, MVT::i32));
3284 if (!Subtarget.isLittle())
3285 std::swap(Lo, Hi);
3286 Register LocRegLo = VA.getLocReg();
3287 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3288 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3289 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3290 continue;
3291 }
3292 }
3293 break;
3294 case CCValAssign::BCvt:
3295 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3296 break;
3297 case CCValAssign::SExtUpper:
3298 UseUpperBits = true;
3299 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3300 case CCValAssign::SExt:
3301 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3302 break;
3303 case CCValAssign::ZExtUpper:
3304 UseUpperBits = true;
3305 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3306 case CCValAssign::ZExt:
3307 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3308 break;
3309 case CCValAssign::AExtUpper:
3310 UseUpperBits = true;
3311 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3312 case CCValAssign::AExt:
3313 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3314 break;
3315 }
3316
3317 if (UseUpperBits) {
3318 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3319 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3320 Arg = DAG.getNode(
3321 ISD::SHL, DL, VA.getLocVT(), Arg,
3322 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3323 }
3324
3325 // Arguments that can be passed on register must be kept at
3326 // RegsToPass vector
3327 if (VA.isRegLoc()) {
3328 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3329 continue;
3330 }
3331
3332 // Register can't get to this point...
3333 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3333, __PRETTY_FUNCTION__))
;
3334
3335 // emit ISD::STORE whichs stores the
3336 // parameter value to a stack Location
3337 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3338 Chain, Arg, DL, IsTailCall, DAG));
3339 }
3340
3341 // Transform all store nodes into one single node because all store
3342 // nodes are independent of each other.
3343 if (!MemOpChains.empty())
14
Taking false branch
3344 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3345
3346 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3347 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3348 // node so that legalize doesn't hack it.
3349
3350 EVT Ty = Callee.getValueType();
15
Calling 'SDValue::getValueType'
3351 bool GlobalOrExternal = false, IsCallReloc = false;
3352
3353 // The long-calls feature is ignored in case of PIC.
3354 // While we do not support -mshared / -mno-shared properly,
3355 // ignore long-calls in case of -mabicalls too.
3356 if (!Subtarget.isABICalls() && !IsPIC) {
3357 // If the function should be called using "long call",
3358 // get its address into a register to prevent using
3359 // of the `jal` instruction for the direct call.
3360 if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3361 if (Subtarget.useLongCalls())
3362 Callee = Subtarget.hasSym32()
3363 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3364 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3365 } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3366 bool UseLongCalls = Subtarget.useLongCalls();
3367 // If the function has long-call/far/near attribute
3368 // it overrides command line switch pased to the backend.
3369 if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3370 if (F->hasFnAttribute("long-call"))
3371 UseLongCalls = true;
3372 else if (F->hasFnAttribute("short-call"))
3373 UseLongCalls = false;
3374 }
3375 if (UseLongCalls)
3376 Callee = Subtarget.hasSym32()
3377 ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3378 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3379 }
3380 }
3381
3382 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3383 if (IsPIC) {
3384 const GlobalValue *Val = G->getGlobal();
3385 InternalLinkage = Val->hasInternalLinkage();
3386
3387 if (InternalLinkage)
3388 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3389 else if (Subtarget.useXGOT()) {
3390 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3391 MipsII::MO_CALL_LO16, Chain,
3392 FuncInfo->callPtrInfo(Val));
3393 IsCallReloc = true;
3394 } else {
3395 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3396 FuncInfo->callPtrInfo(Val));
3397 IsCallReloc = true;
3398 }
3399 } else
3400 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3401 getPointerTy(DAG.getDataLayout()), 0,
3402 MipsII::MO_NO_FLAG);
3403 GlobalOrExternal = true;
3404 }
3405 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3406 const char *Sym = S->getSymbol();
3407
3408 if (!IsPIC) // static
3409 Callee = DAG.getTargetExternalSymbol(
3410 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
3411 else if (Subtarget.useXGOT()) {
3412 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3413 MipsII::MO_CALL_LO16, Chain,
3414 FuncInfo->callPtrInfo(Sym));
3415 IsCallReloc = true;
3416 } else { // PIC
3417 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3418 FuncInfo->callPtrInfo(Sym));
3419 IsCallReloc = true;
3420 }
3421
3422 GlobalOrExternal = true;
3423 }
3424
3425 SmallVector<SDValue, 8> Ops(1, Chain);
3426 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3427
3428 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3429 IsCallReloc, CLI, Callee, Chain);
3430
3431 if (IsTailCall) {
3432 MF.getFrameInfo().setHasTailCall();
3433 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3434 }
3435
3436 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3437 SDValue InFlag = Chain.getValue(1);
3438
3439 // Create the CALLSEQ_END node in the case of where it is not a call to
3440 // memcpy.
3441 if (!(MemcpyInByVal)) {
3442 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3443 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3444 InFlag = Chain.getValue(1);
3445 }
3446
3447 // Handle result values, copying them out of physregs into vregs that we
3448 // return.
3449 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3450 InVals, CLI);
3451}
3452
3453/// LowerCallResult - Lower the result values of a call into the
3454/// appropriate copies out of appropriate physical registers.
3455SDValue MipsTargetLowering::LowerCallResult(
3456 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3457 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3458 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3459 TargetLowering::CallLoweringInfo &CLI) const {
3460 // Assign locations to each value returned by this call.
3461 SmallVector<CCValAssign, 16> RVLocs;
3462 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3463 *DAG.getContext());
3464
3465 const ExternalSymbolSDNode *ES =
3466 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3467 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3468 ES ? ES->getSymbol() : nullptr);
3469
3470 // Copy all of the result registers out of their specified physreg.
3471 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3472 CCValAssign &VA = RVLocs[i];
3473 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3473, __PRETTY_FUNCTION__))
;
3474
3475 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3476 RVLocs[i].getLocVT(), InFlag);
3477 Chain = Val.getValue(1);
3478 InFlag = Val.getValue(2);
3479
3480 if (VA.isUpperBitsInLoc()) {
3481 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3482 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3483 unsigned Shift =
3484 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3485 Val = DAG.getNode(
3486 Shift, DL, VA.getLocVT(), Val,
3487 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3488 }
3489
3490 switch (VA.getLocInfo()) {
3491 default:
3492 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3492)
;
3493 case CCValAssign::Full:
3494 break;
3495 case CCValAssign::BCvt:
3496 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3497 break;
3498 case CCValAssign::AExt:
3499 case CCValAssign::AExtUpper:
3500 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3501 break;
3502 case CCValAssign::ZExt:
3503 case CCValAssign::ZExtUpper:
3504 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3505 DAG.getValueType(VA.getValVT()));
3506 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3507 break;
3508 case CCValAssign::SExt:
3509 case CCValAssign::SExtUpper:
3510 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3511 DAG.getValueType(VA.getValVT()));
3512 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3513 break;
3514 }
3515
3516 InVals.push_back(Val);
3517 }
3518
3519 return Chain;
3520}
3521
3522static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3523 EVT ArgVT, const SDLoc &DL,
3524 SelectionDAG &DAG) {
3525 MVT LocVT = VA.getLocVT();
3526 EVT ValVT = VA.getValVT();
3527
3528 // Shift into the upper bits if necessary.
3529 switch (VA.getLocInfo()) {
3530 default:
3531 break;
3532 case CCValAssign::AExtUpper:
3533 case CCValAssign::SExtUpper:
3534 case CCValAssign::ZExtUpper: {
3535 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3536 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3537 unsigned Opcode =
3538 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3539 Val = DAG.getNode(
3540 Opcode, DL, VA.getLocVT(), Val,
3541 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3542 break;
3543 }
3544 }
3545
3546 // If this is an value smaller than the argument slot size (32-bit for O32,
3547 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3548 // size. Extract the value and insert any appropriate assertions regarding
3549 // sign/zero extension.
3550 switch (VA.getLocInfo()) {
3551 default:
3552 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3552)
;
3553 case CCValAssign::Full:
3554 break;
3555 case CCValAssign::AExtUpper:
3556 case CCValAssign::AExt:
3557 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3558 break;
3559 case CCValAssign::SExtUpper:
3560 case CCValAssign::SExt:
3561 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3562 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3563 break;
3564 case CCValAssign::ZExtUpper:
3565 case CCValAssign::ZExt:
3566 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3567 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3568 break;
3569 case CCValAssign::BCvt:
3570 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3571 break;
3572 }
3573
3574 return Val;
3575}
3576
3577//===----------------------------------------------------------------------===//
3578// Formal Arguments Calling Convention Implementation
3579//===----------------------------------------------------------------------===//
3580/// LowerFormalArguments - transform physical registers into virtual registers
3581/// and generate load operations for arguments places on the stack.
3582SDValue MipsTargetLowering::LowerFormalArguments(
3583 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3584 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3585 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3586 MachineFunction &MF = DAG.getMachineFunction();
3587 MachineFrameInfo &MFI = MF.getFrameInfo();
3588 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3589
3590 MipsFI->setVarArgsFrameIndex(0);
3591
3592 // Used with vargs to acumulate store chains.
3593 std::vector<SDValue> OutChains;
3594
3595 // Assign locations to all of the incoming arguments.
3596 SmallVector<CCValAssign, 16> ArgLocs;
3597 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3598 *DAG.getContext());
3599 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3600 const Function &Func = DAG.getMachineFunction().getFunction();
3601 Function::const_arg_iterator FuncArg = Func.arg_begin();
3602
3603 if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3604 report_fatal_error(
3605 "Functions with the interrupt attribute cannot have arguments!");
3606
3607 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3608 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3609 CCInfo.getInRegsParamsCount() > 0);
3610
3611 unsigned CurArgIdx = 0;
3612 CCInfo.rewindByValRegsInfo();
3613
3614 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3615 CCValAssign &VA = ArgLocs[i];
3616 if (Ins[i].isOrigArg()) {
3617 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3618 CurArgIdx = Ins[i].getOrigArgIndex();
3619 }
3620 EVT ValVT = VA.getValVT();
3621 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3622 bool IsRegLoc = VA.isRegLoc();
3623
3624 if (Flags.isByVal()) {
3625 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3625, __PRETTY_FUNCTION__))
;
3626 unsigned FirstByValReg, LastByValReg;
3627 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3628 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3629
3630 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3631, __PRETTY_FUNCTION__))
3631 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3631, __PRETTY_FUNCTION__))
;
3632 assert(ByValIdx < CCInfo.getInRegsParamsCount())((ByValIdx < CCInfo.getInRegsParamsCount()) ? static_cast<
void> (0) : __assert_fail ("ByValIdx < CCInfo.getInRegsParamsCount()"
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3632, __PRETTY_FUNCTION__))
;
3633 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3634 FirstByValReg, LastByValReg, VA, CCInfo);
3635 CCInfo.nextInRegsParam();
3636 continue;
3637 }
3638
3639 // Arguments stored on registers
3640 if (IsRegLoc) {
3641 MVT RegVT = VA.getLocVT();
3642 Register ArgReg = VA.getLocReg();
3643 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3644
3645 // Transform the arguments stored on
3646 // physical registers into virtual ones
3647 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3648 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3649
3650 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3651
3652 // Handle floating point arguments passed in integer registers and
3653 // long double arguments passed in floating point registers.
3654 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3655 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3656 (RegVT == MVT::f64 && ValVT == MVT::i64))
3657 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3658 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3659 ValVT == MVT::f64) {
3660 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3661 getNextIntArgReg(ArgReg), RC);
3662 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3663 if (!Subtarget.isLittle())
3664 std::swap(ArgValue, ArgValue2);
3665 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3666 ArgValue, ArgValue2);
3667 }
3668
3669 InVals.push_back(ArgValue);
3670 } else { // VA.isRegLoc()
3671 MVT LocVT = VA.getLocVT();
3672
3673 if (ABI.IsO32()) {
3674 // We ought to be able to use LocVT directly but O32 sets it to i32
3675 // when allocating floating point values to integer registers.
3676 // This shouldn't influence how we load the value into registers unless
3677 // we are targeting softfloat.
3678 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3679 LocVT = VA.getValVT();
3680 }
3681
3682 // sanity check
3683 assert(VA.isMemLoc())((VA.isMemLoc()) ? static_cast<void> (0) : __assert_fail
("VA.isMemLoc()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3683, __PRETTY_FUNCTION__))
;
3684
3685 // The stack pointer offset is relative to the caller stack frame.
3686 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3687 VA.getLocMemOffset(), true);
3688
3689 // Create load nodes to retrieve arguments from the stack
3690 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3691 SDValue ArgValue = DAG.getLoad(
3692 LocVT, DL, Chain, FIN,
3693 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3694 OutChains.push_back(ArgValue.getValue(1));
3695
3696 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3697
3698 InVals.push_back(ArgValue);
3699 }
3700 }
3701
3702 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3703 // The mips ABIs for returning structs by value requires that we copy
3704 // the sret argument into $v0 for the return. Save the argument into
3705 // a virtual register so that we can access it from the return points.
3706 if (Ins[i].Flags.isSRet()) {
3707 unsigned Reg = MipsFI->getSRetReturnReg();
3708 if (!Reg) {
3709 Reg = MF.getRegInfo().createVirtualRegister(
3710 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3711 MipsFI->setSRetReturnReg(Reg);
3712 }
3713 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3714 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3715 break;
3716 }
3717 }
3718
3719 if (IsVarArg)
3720 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3721
3722 // All stores are grouped in one node to allow the matching between
3723 // the size of Ins and InVals. This only happens when on varg functions
3724 if (!OutChains.empty()) {
3725 OutChains.push_back(Chain);
3726 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3727 }
3728
3729 return Chain;
3730}
3731
3732//===----------------------------------------------------------------------===//
3733// Return Value Calling Convention Implementation
3734//===----------------------------------------------------------------------===//
3735
3736bool
3737MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3738 MachineFunction &MF, bool IsVarArg,
3739 const SmallVectorImpl<ISD::OutputArg> &Outs,
3740 LLVMContext &Context) const {
3741 SmallVector<CCValAssign, 16> RVLocs;
3742 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3743 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3744}
3745
3746bool MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type,
3747 bool IsSigned) const {
3748 if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32)
3749 return true;
3750
3751 return IsSigned;
3752}
3753
3754SDValue
3755MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3756 const SDLoc &DL,
3757 SelectionDAG &DAG) const {
3758 MachineFunction &MF = DAG.getMachineFunction();
3759 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3760
3761 MipsFI->setISR();
3762
3763 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3764}
3765
3766SDValue
3767MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3768 bool IsVarArg,
3769 const SmallVectorImpl<ISD::OutputArg> &Outs,
3770 const SmallVectorImpl<SDValue> &OutVals,
3771 const SDLoc &DL, SelectionDAG &DAG) const {
3772 // CCValAssign - represent the assignment of
3773 // the return value to a location
3774 SmallVector<CCValAssign, 16> RVLocs;
3775 MachineFunction &MF = DAG.getMachineFunction();
3776
3777 // CCState - Info about the registers and stack slot.
3778 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3779
3780 // Analyze return values.
3781 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3782
3783 SDValue Flag;
3784 SmallVector<SDValue, 4> RetOps(1, Chain);
3785
3786 // Copy the result values into the output registers.
3787 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3788 SDValue Val = OutVals[i];
3789 CCValAssign &VA = RVLocs[i];
3790 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3790, __PRETTY_FUNCTION__))
;
3791 bool UseUpperBits = false;
3792
3793 switch (VA.getLocInfo()) {
3794 default:
3795 llvm_unreachable("Unknown loc info!")::llvm::llvm_unreachable_internal("Unknown loc info!", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3795)
;
3796 case CCValAssign::Full:
3797 break;
3798 case CCValAssign::BCvt:
3799 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3800 break;
3801 case CCValAssign::AExtUpper:
3802 UseUpperBits = true;
3803 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3804 case CCValAssign::AExt:
3805 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3806 break;
3807 case CCValAssign::ZExtUpper:
3808 UseUpperBits = true;
3809 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3810 case CCValAssign::ZExt:
3811 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3812 break;
3813 case CCValAssign::SExtUpper:
3814 UseUpperBits = true;
3815 LLVM_FALLTHROUGH[[gnu::fallthrough]];
3816 case CCValAssign::SExt:
3817 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3818 break;
3819 }
3820
3821 if (UseUpperBits) {
3822 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3823 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3824 Val = DAG.getNode(
3825 ISD::SHL, DL, VA.getLocVT(), Val,
3826 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3827 }
3828
3829 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3830
3831 // Guarantee that all emitted copies are stuck together with flags.
3832 Flag = Chain.getValue(1);
3833 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3834 }
3835
3836 // The mips ABIs for returning structs by value requires that we copy
3837 // the sret argument into $v0 for the return. We saved the argument into
3838 // a virtual register in the entry block, so now we copy the value out
3839 // and into $v0.
3840 if (MF.getFunction().hasStructRetAttr()) {
3841 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3842 unsigned Reg = MipsFI->getSRetReturnReg();
3843
3844 if (!Reg)
3845 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 3845)
;
3846 SDValue Val =
3847 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3848 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3849
3850 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3851 Flag = Chain.getValue(1);
3852 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3853 }
3854
3855 RetOps[0] = Chain; // Update chain.
3856
3857 // Add the flag if we have it.
3858 if (Flag.getNode())
3859 RetOps.push_back(Flag);
3860
3861 // ISRs must use "eret".
3862 if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
3863 return LowerInterruptReturn(RetOps, DL, DAG);
3864
3865 // Standard return on Mips is a "jr $ra"
3866 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3867}
3868
3869//===----------------------------------------------------------------------===//
3870// Mips Inline Assembly Support
3871//===----------------------------------------------------------------------===//
3872
3873/// getConstraintType - Given a constraint letter, return the type of
3874/// constraint it is for this target.
3875MipsTargetLowering::ConstraintType
3876MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3877 // Mips specific constraints
3878 // GCC config/mips/constraints.md
3879 //
3880 // 'd' : An address register. Equivalent to r
3881 // unless generating MIPS16 code.
3882 // 'y' : Equivalent to r; retained for
3883 // backwards compatibility.
3884 // 'c' : A register suitable for use in an indirect
3885 // jump. This will always be $25 for -mabicalls.
3886 // 'l' : The lo register. 1 word storage.
3887 // 'x' : The hilo register pair. Double word storage.
3888 if (Constraint.size() == 1) {
3889 switch (Constraint[0]) {
3890 default : break;
3891 case 'd':
3892 case 'y':
3893 case 'f':
3894 case 'c':
3895 case 'l':
3896 case 'x':
3897 return C_RegisterClass;
3898 case 'R':
3899 return C_Memory;
3900 }
3901 }
3902
3903 if (Constraint == "ZC")
3904 return C_Memory;
3905
3906 return TargetLowering::getConstraintType(Constraint);
3907}
3908
3909/// Examine constraint type and operand type and determine a weight value.
3910/// This object must already have been set up with the operand type
3911/// and the current alternative constraint selected.
3912TargetLowering::ConstraintWeight
3913MipsTargetLowering::getSingleConstraintMatchWeight(
3914 AsmOperandInfo &info, const char *constraint) const {
3915 ConstraintWeight weight = CW_Invalid;
3916 Value *CallOperandVal = info.CallOperandVal;
3917 // If we don't have a value, we can't do a match,
3918 // but allow it at the lowest weight.
3919 if (!CallOperandVal)
3920 return CW_Default;
3921 Type *type = CallOperandVal->getType();
3922 // Look at the constraint type.
3923 switch (*constraint) {
3924 default:
3925 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3926 break;
3927 case 'd':
3928 case 'y':
3929 if (type->isIntegerTy())
3930 weight = CW_Register;
3931 break;
3932 case 'f': // FPU or MSA register
3933 if (Subtarget.hasMSA() && type->isVectorTy() &&
3934 cast<VectorType>(type)->getBitWidth() == 128)
3935 weight = CW_Register;
3936 else if (type->isFloatTy())
3937 weight = CW_Register;
3938 break;
3939 case 'c': // $25 for indirect jumps
3940 case 'l': // lo register
3941 case 'x': // hilo register pair
3942 if (type->isIntegerTy())
3943 weight = CW_SpecificReg;
3944 break;
3945 case 'I': // signed 16 bit immediate
3946 case 'J': // integer zero
3947 case 'K': // unsigned 16 bit immediate
3948 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3949 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3950 case 'O': // signed 15 bit immediate (+- 16383)
3951 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3952 if (isa<ConstantInt>(CallOperandVal))
3953 weight = CW_Constant;
3954 break;
3955 case 'R':
3956 weight = CW_Memory;
3957 break;
3958 }
3959 return weight;
3960}
3961
3962/// This is a helper function to parse a physical register string and split it
3963/// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3964/// that is returned indicates whether parsing was successful. The second flag
3965/// is true if the numeric part exists.
3966static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3967 unsigned long long &Reg) {
3968 if (C.front() != '{' || C.back() != '}')
3969 return std::make_pair(false, false);
3970
3971 // Search for the first numeric character.
3972 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3973 I = std::find_if(B, E, isdigit);
3974
3975 Prefix = StringRef(B, I - B);
3976
3977 // The second flag is set to false if no numeric characters were found.
3978 if (I == E)
3979 return std::make_pair(true, false);
3980
3981 // Parse the numeric characters.
3982 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3983 true);
3984}
3985
3986EVT MipsTargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
3987 ISD::NodeType) const {
3988 bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
3989 EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
3990 return VT.bitsLT(MinVT) ? MinVT : VT;
3991}
3992
3993std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3994parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3995 const TargetRegisterInfo *TRI =
3996 Subtarget.getRegisterInfo();
3997 const TargetRegisterClass *RC;
3998 StringRef Prefix;
3999 unsigned long long Reg;
4000
4001 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
4002
4003 if (!R.first)
4004 return std::make_pair(0U, nullptr);
4005
4006 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
4007 // No numeric characters follow "hi" or "lo".
4008 if (R.second)
4009 return std::make_pair(0U, nullptr);
4010
4011 RC = TRI->getRegClass(Prefix == "hi" ?
4012 Mips::HI32RegClassID : Mips::LO32RegClassID);
4013 return std::make_pair(*(RC->begin()), RC);
4014 } else if (Prefix.startswith("$msa")) {
4015 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
4016
4017 // No numeric characters follow the name.
4018 if (R.second)
4019 return std::make_pair(0U, nullptr);
4020
4021 Reg = StringSwitch<unsigned long long>(Prefix)
4022 .Case("$msair", Mips::MSAIR)
4023 .Case("$msacsr", Mips::MSACSR)
4024 .Case("$msaaccess", Mips::MSAAccess)
4025 .Case("$msasave", Mips::MSASave)
4026 .Case("$msamodify", Mips::MSAModify)
4027 .Case("$msarequest", Mips::MSARequest)
4028 .Case("$msamap", Mips::MSAMap)
4029 .Case("$msaunmap", Mips::MSAUnmap)
4030 .Default(0);
4031
4032 if (!Reg)
4033 return std::make_pair(0U, nullptr);
4034
4035 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
4036 return std::make_pair(Reg, RC);
4037 }
4038
4039 if (!R.second)
4040 return std::make_pair(0U, nullptr);
4041
4042 if (Prefix == "$f") { // Parse $f0-$f31.
4043 // If the size of FP registers is 64-bit or Reg is an even number, select
4044 // the 64-bit register class. Otherwise, select the 32-bit register class.
4045 if (VT == MVT::Other)
4046 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
4047
4048 RC = getRegClassFor(VT);
4049
4050 if (RC == &Mips::AFGR64RegClass) {
4051 assert(Reg % 2 == 0)((Reg % 2 == 0) ? static_cast<void> (0) : __assert_fail
("Reg % 2 == 0", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4051, __PRETTY_FUNCTION__))
;
4052 Reg >>= 1;
4053 }
4054 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
4055 RC = TRI->getRegClass(Mips::FCCRegClassID);
4056 else if (Prefix == "$w") { // Parse $w0-$w31.
4057 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
4058 } else { // Parse $0-$31.
4059 assert(Prefix == "$")((Prefix == "$") ? static_cast<void> (0) : __assert_fail
("Prefix == \"$\"", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4059, __PRETTY_FUNCTION__))
;
4060 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
4061 }
4062
4063 assert(Reg < RC->getNumRegs())((Reg < RC->getNumRegs()) ? static_cast<void> (0)
: __assert_fail ("Reg < RC->getNumRegs()", "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4063, __PRETTY_FUNCTION__))
;
4064 return std::make_pair(*(RC->begin() + Reg), RC);
4065}
4066
4067/// Given a register class constraint, like 'r', if this corresponds directly
4068/// to an LLVM register class, return a register of 0 and the register class
4069/// pointer.
4070std::pair<unsigned, const TargetRegisterClass *>
4071MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4072 StringRef Constraint,
4073 MVT VT) const {
4074 if (Constraint.size() == 1) {
4075 switch (Constraint[0]) {
4076 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
4077 case 'y': // Same as 'r'. Exists for compatibility.
4078 case 'r':
4079 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
4080 if (Subtarget.inMips16Mode())
4081 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
4082 return std::make_pair(0U, &Mips::GPR32RegClass);
4083 }
4084 if (VT == MVT::i64 && !Subtarget.isGP64bit())
4085 return std::make_pair(0U, &Mips::GPR32RegClass);
4086 if (VT == MVT::i64 && Subtarget.isGP64bit())
4087 return std::make_pair(0U, &Mips::GPR64RegClass);
4088 // This will generate an error message
4089 return std::make_pair(0U, nullptr);
4090 case 'f': // FPU or MSA register
4091 if (VT == MVT::v16i8)
4092 return std::make_pair(0U, &Mips::MSA128BRegClass);
4093 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
4094 return std::make_pair(0U, &Mips::MSA128HRegClass);
4095 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
4096 return std::make_pair(0U, &Mips::MSA128WRegClass);
4097 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
4098 return std::make_pair(0U, &Mips::MSA128DRegClass);
4099 else if (VT == MVT::f32)
4100 return std::make_pair(0U, &Mips::FGR32RegClass);
4101 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
4102 if (Subtarget.isFP64bit())
4103 return std::make_pair(0U, &Mips::FGR64RegClass);
4104 return std::make_pair(0U, &Mips::AFGR64RegClass);
4105 }
4106 break;
4107 case 'c': // register suitable for indirect jump
4108 if (VT == MVT::i32)
4109 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
4110 if (VT == MVT::i64)
4111 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
4112 // This will generate an error message
4113 return std::make_pair(0U, nullptr);
4114 case 'l': // use the `lo` register to store values
4115 // that are no bigger than a word
4116 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4117 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4118 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4119 case 'x': // use the concatenated `hi` and `lo` registers
4120 // to store doubleword values
4121 // Fixme: Not triggering the use of both hi and low
4122 // This will generate an error message
4123 return std::make_pair(0U, nullptr);
4124 }
4125 }
4126
4127 if (!Constraint.empty()) {
4128 std::pair<unsigned, const TargetRegisterClass *> R;
4129 R = parseRegForInlineAsmConstraint(Constraint, VT);
4130
4131 if (R.second)
4132 return R;
4133 }
4134
4135 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4136}
4137
4138/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4139/// vector. If it is invalid, don't add anything to Ops.
4140void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4141 std::string &Constraint,
4142 std::vector<SDValue>&Ops,
4143 SelectionDAG &DAG) const {
4144 SDLoc DL(Op);
4145 SDValue Result;
4146
4147 // Only support length 1 constraints for now.
4148 if (Constraint.length() > 1) return;
4149
4150 char ConstraintLetter = Constraint[0];
4151 switch (ConstraintLetter) {
4152 default: break; // This will fall through to the generic implementation
4153 case 'I': // Signed 16 bit constant
4154 // If this fails, the parent routine will give an error
4155 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4156 EVT Type = Op.getValueType();
4157 int64_t Val = C->getSExtValue();
4158 if (isInt<16>(Val)) {
4159 Result = DAG.getTargetConstant(Val, DL, Type);
4160 break;
4161 }
4162 }
4163 return;
4164 case 'J': // integer zero
4165 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4166 EVT Type = Op.getValueType();
4167 int64_t Val = C->getZExtValue();
4168 if (Val == 0) {
4169 Result = DAG.getTargetConstant(0, DL, Type);
4170 break;
4171 }
4172 }
4173 return;
4174 case 'K': // unsigned 16 bit immediate
4175 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4176 EVT Type = Op.getValueType();
4177 uint64_t Val = (uint64_t)C->getZExtValue();
4178 if (isUInt<16>(Val)) {
4179 Result = DAG.getTargetConstant(Val, DL, Type);
4180 break;
4181 }
4182 }
4183 return;
4184 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4185 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4186 EVT Type = Op.getValueType();
4187 int64_t Val = C->getSExtValue();
4188 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4189 Result = DAG.getTargetConstant(Val, DL, Type);
4190 break;
4191 }
4192 }
4193 return;
4194 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4195 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4196 EVT Type = Op.getValueType();
4197 int64_t Val = C->getSExtValue();
4198 if ((Val >= -65535) && (Val <= -1)) {
4199 Result = DAG.getTargetConstant(Val, DL, Type);
4200 break;
4201 }
4202 }
4203 return;
4204 case 'O': // signed 15 bit immediate
4205 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4206 EVT Type = Op.getValueType();
4207 int64_t Val = C->getSExtValue();
4208 if ((isInt<15>(Val))) {
4209 Result = DAG.getTargetConstant(Val, DL, Type);
4210 break;
4211 }
4212 }
4213 return;
4214 case 'P': // immediate in the range of 1 to 65535 (inclusive)
4215 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4216 EVT Type = Op.getValueType();
4217 int64_t Val = C->getSExtValue();
4218 if ((Val <= 65535) && (Val >= 1)) {
4219 Result = DAG.getTargetConstant(Val, DL, Type);
4220 break;
4221 }
4222 }
4223 return;
4224 }
4225
4226 if (Result.getNode()) {
4227 Ops.push_back(Result);
4228 return;
4229 }
4230
4231 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4232}
4233
4234bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4235 const AddrMode &AM, Type *Ty,
4236 unsigned AS,
4237 Instruction *I) const {
4238 // No global is ever allowed as a base.
4239 if (AM.BaseGV)
4240 return false;
4241
4242 switch (AM.Scale) {
4243 case 0: // "r+i" or just "i", depending on HasBaseReg.
4244 break;
4245 case 1:
4246 if (!AM.HasBaseReg) // allow "r+i".
4247 break;
4248 return false; // disallow "r+r" or "r+r+i".
4249 default:
4250 return false;
4251 }
4252
4253 return true;
4254}
4255
4256bool
4257MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4258 // The Mips target isn't yet aware of offsets.
4259 return false;
4260}
4261
4262EVT MipsTargetLowering::getOptimalMemOpType(
4263 uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
4264 bool ZeroMemset, bool MemcpyStrSrc,
4265 const AttributeList &FuncAttributes) const {
4266 if (Subtarget.hasMips64())
4267 return MVT::i64;
4268
4269 return MVT::i32;
4270}
4271
4272bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4273 bool ForCodeSize) const {
4274 if (VT != MVT::f32 && VT != MVT::f64)
4275 return false;
4276 if (Imm.isNegZero())
4277 return false;
4278 return Imm.isZero();
4279}
4280
4281unsigned MipsTargetLowering::getJumpTableEncoding() const {
4282
4283 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4284 if (ABI.IsN64() && isPositionIndependent())
4285 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4286
4287 return TargetLowering::getJumpTableEncoding();
4288}
4289
4290bool MipsTargetLowering::useSoftFloat() const {
4291 return Subtarget.useSoftFloat();
4292}
4293
4294void MipsTargetLowering::copyByValRegs(
4295 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4296 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4297 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4298 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4299 MipsCCState &State) const {
4300 MachineFunction &MF = DAG.getMachineFunction();
4301 MachineFrameInfo &MFI = MF.getFrameInfo();
4302 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4303 unsigned NumRegs = LastReg - FirstReg;
4304 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4305 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4306 int FrameObjOffset;
4307 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4308
4309 if (RegAreaSize)
4310 FrameObjOffset =
4311 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4312 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4313 else
4314 FrameObjOffset = VA.getLocMemOffset();
4315
4316 // Create frame object.
4317 EVT PtrTy = getPointerTy(DAG.getDataLayout());
4318 // Make the fixed object stored to mutable so that the load instructions
4319 // referencing it have their memory dependencies added.
4320 // Set the frame object as isAliased which clears the underlying objects
4321 // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4322 // stores as dependencies for loads referencing this fixed object.
4323 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4324 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4325 InVals.push_back(FIN);
4326
4327 if (!NumRegs)
4328 return;
4329
4330 // Copy arg registers.
4331 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4332 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4333
4334 for (unsigned I = 0; I < NumRegs; ++I) {
4335 unsigned ArgReg = ByValArgRegs[FirstReg + I];
4336 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4337 unsigned Offset = I * GPRSizeInBytes;
4338 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4339 DAG.getConstant(Offset, DL, PtrTy));
4340 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4341 StorePtr, MachinePointerInfo(FuncArg, Offset));
4342 OutChains.push_back(Store);
4343 }
4344}
4345
4346// Copy byVal arg to registers and stack.
4347void MipsTargetLowering::passByValArg(
4348 SDValue Chain, const SDLoc &DL,
4349 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4350 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4351 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4352 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4353 const CCValAssign &VA) const {
4354 unsigned ByValSizeInBytes = Flags.getByValSize();
4355 unsigned OffsetInBytes = 0; // From beginning of struct
4356 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4357 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
4358 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4359 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4360 unsigned NumRegs = LastReg - FirstReg;
4361
4362 if (NumRegs) {
4363 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4364 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4365 unsigned I = 0;
4366
4367 // Copy words to registers.
4368 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4369 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4370 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4371 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4372 MachinePointerInfo(), Alignment);
4373 MemOpChains.push_back(LoadVal.getValue(1));
4374 unsigned ArgReg = ArgRegs[FirstReg + I];
4375 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4376 }
4377
4378 // Return if the struct has been fully copied.
4379 if (ByValSizeInBytes == OffsetInBytes)
4380 return;
4381
4382 // Copy the remainder of the byval argument with sub-word loads and shifts.
4383 if (LeftoverBytes) {
4384 SDValue Val;
4385
4386 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4387 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4388 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4389
4390 if (RemainingSizeInBytes < LoadSizeInBytes)
4391 continue;
4392
4393 // Load subword.
4394 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4395 DAG.getConstant(OffsetInBytes, DL,
4396 PtrTy));
4397 SDValue LoadVal = DAG.getExtLoad(
4398 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4399 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4400 MemOpChains.push_back(LoadVal.getValue(1));
4401
4402 // Shift the loaded value.
4403 unsigned Shamt;
4404
4405 if (isLittle)
4406 Shamt = TotalBytesLoaded * 8;
4407 else
4408 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4409
4410 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4411 DAG.getConstant(Shamt, DL, MVT::i32));
4412
4413 if (Val.getNode())
4414 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4415 else
4416 Val = Shift;
4417
4418 OffsetInBytes += LoadSizeInBytes;
4419 TotalBytesLoaded += LoadSizeInBytes;
4420 Alignment = std::min(Alignment, LoadSizeInBytes);
4421 }
4422
4423 unsigned ArgReg = ArgRegs[FirstReg + I];
4424 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4425 return;
4426 }
4427 }
4428
4429 // Copy remainder of byval arg to it with memcpy.
4430 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4431 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4432 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4433 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4434 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4435 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4436 DAG.getConstant(MemCpySize, DL, PtrTy),
4437 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4438 /*isTailCall=*/false,
4439 MachinePointerInfo(), MachinePointerInfo());
4440 MemOpChains.push_back(Chain);
4441}
4442
4443void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4444 SDValue Chain, const SDLoc &DL,
4445 SelectionDAG &DAG,
4446 CCState &State) const {
4447 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
4448 unsigned Idx = State.getFirstUnallocated(ArgRegs);
4449 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4450 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4451 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4452 MachineFunction &MF = DAG.getMachineFunction();
4453 MachineFrameInfo &MFI = MF.getFrameInfo();
4454 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4455
4456 // Offset of the first variable argument from stack pointer.
4457 int VaArgOffset;
4458
4459 if (ArgRegs.size() == Idx)
4460 VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4461 else {
4462 VaArgOffset =
4463 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4464 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4465 }
4466
4467 // Record the frame index of the first variable argument
4468 // which is a value necessary to VASTART.
4469 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4470 MipsFI->setVarArgsFrameIndex(FI);
4471
4472 // Copy the integer registers that have not been used for argument passing
4473 // to the argument register save area. For O32, the save area is allocated
4474 // in the caller's stack frame, while for N32/64, it is allocated in the
4475 // callee's stack frame.
4476 for (unsigned I = Idx; I < ArgRegs.size();
4477 ++I, VaArgOffset += RegSizeInBytes) {
4478 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4479 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4480 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4481 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4482 SDValue Store =
4483 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4484 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4485 (Value *)nullptr);
4486 OutChains.push_back(Store);
4487 }
4488}
4489
4490void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4491 unsigned Align) const {
4492 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4493
4494 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4494, __PRETTY_FUNCTION__))
;
4495
4496 Align = std::min(Align, TFL->getStackAlignment());
4497
4498 unsigned FirstReg = 0;
4499 unsigned NumRegs = 0;
4500
4501 if (State->getCallingConv() != CallingConv::Fast) {
4502 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4503 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4504 // FIXME: The O32 case actually describes no shadow registers.
4505 const MCPhysReg *ShadowRegs =
4506 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4507
4508 // We used to check the size as well but we can't do that anymore since
4509 // CCState::HandleByVal() rounds up the size after calling this function.
4510 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4512, __PRETTY_FUNCTION__))
4511 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4512, __PRETTY_FUNCTION__))
4512 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4512, __PRETTY_FUNCTION__))
;
4513
4514 FirstReg = State->getFirstUnallocated(IntArgRegs);
4515
4516 // If Align > RegSizeInBytes, the first arg register must be even.
4517 // FIXME: This condition happens to do the right thing but it's not the
4518 // right way to test it. We want to check that the stack frame offset
4519 // of the register is aligned.
4520 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4521 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4522 ++FirstReg;
4523 }
4524
4525 // Mark the registers allocated.
4526 Size = alignTo(Size, RegSizeInBytes);
4527 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4528 Size -= RegSizeInBytes, ++I, ++NumRegs)
4529 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4530 }
4531
4532 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4533}
4534
4535MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4536 MachineBasicBlock *BB,
4537 bool isFPCmp,
4538 unsigned Opc) const {
4539 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4541, __PRETTY_FUNCTION__))
4540 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4541, __PRETTY_FUNCTION__))
4541 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4541, __PRETTY_FUNCTION__))
;
4542
4543 const TargetInstrInfo *TII =
4544 Subtarget.getInstrInfo();
4545 DebugLoc DL = MI.getDebugLoc();
4546
4547 // To "insert" a SELECT instruction, we actually have to insert the
4548 // diamond control-flow pattern. The incoming instruction knows the
4549 // destination vreg to set, the condition code register to branch on, the
4550 // true/false values to select between, and a branch opcode to use.
4551 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4552 MachineFunction::iterator It = ++BB->getIterator();
4553
4554 // thisMBB:
4555 // ...
4556 // TrueVal = ...
4557 // setcc r1, r2, r3
4558 // bNE r1, r0, copy1MBB
4559 // fallthrough --> copy0MBB
4560 MachineBasicBlock *thisMBB = BB;
4561 MachineFunction *F = BB->getParent();
4562 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4563 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4564 F->insert(It, copy0MBB);
4565 F->insert(It, sinkMBB);
4566
4567 // Transfer the remainder of BB and its successor edges to sinkMBB.
4568 sinkMBB->splice(sinkMBB->begin(), BB,
4569 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4570 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4571
4572 // Next, add the true and fallthrough blocks as its successors.
4573 BB->addSuccessor(copy0MBB);
4574 BB->addSuccessor(sinkMBB);
4575
4576 if (isFPCmp) {
4577 // bc1[tf] cc, sinkMBB
4578 BuildMI(BB, DL, TII->get(Opc))
4579 .addReg(MI.getOperand(1).getReg())
4580 .addMBB(sinkMBB);
4581 } else {
4582 // bne rs, $0, sinkMBB
4583 BuildMI(BB, DL, TII->get(Opc))
4584 .addReg(MI.getOperand(1).getReg())
4585 .addReg(Mips::ZERO)
4586 .addMBB(sinkMBB);
4587 }
4588
4589 // copy0MBB:
4590 // %FalseValue = ...
4591 // # fallthrough to sinkMBB
4592 BB = copy0MBB;
4593
4594 // Update machine-CFG edges
4595 BB->addSuccessor(sinkMBB);
4596
4597 // sinkMBB:
4598 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4599 // ...
4600 BB = sinkMBB;
4601
4602 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4603 .addReg(MI.getOperand(2).getReg())
4604 .addMBB(thisMBB)
4605 .addReg(MI.getOperand(3).getReg())
4606 .addMBB(copy0MBB);
4607
4608 MI.eraseFromParent(); // The pseudo instruction is gone now.
4609
4610 return BB;
4611}
4612
4613MachineBasicBlock *
4614MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI,
4615 MachineBasicBlock *BB) const {
4616 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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4618, __PRETTY_FUNCTION__))
4617 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4618, __PRETTY_FUNCTION__))
4618 "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-10~++20200112100611+7fa5290d5bd/llvm/lib/Target/Mips/MipsISelLowering.cpp"
, 4618, __PRETTY_FUNCTION__))
;
4619
4620 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4621 DebugLoc DL = MI.getDebugLoc();
4622
4623 // D_SELECT substitutes two SELECT nodes that goes one after another and
4624 // have the same condition operand. On machines which don't have
4625 // conditional-move instruction, it reduces unnecessary branch instructions
4626 // which are result of using two diamond patterns that are result of two
4627 // SELECT pseudo instructions.
4628 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4629 MachineFunction::iterator It = ++BB->getIterator();
4630
4631 // thisMBB:
4632 // ...
4633 // TrueVal = ...
4634 // setcc r1, r2, r3
4635 // bNE r1, r0, copy1MBB
4636 // fallthrough --> copy0MBB
4637 MachineBasicBlock *thisMBB = BB;
4638 MachineFunction *F = BB->getParent();
4639 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4640 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4641 F->insert(It, copy0MBB);
4642 F->insert(It, sinkMBB);
4643
4644 // Transfer the remainder of BB and its successor edges to sinkMBB.
4645 sinkMBB->splice(sinkMBB->begin(), BB,
4646 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4647 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4648
4649 // Next, add the true and fallthrough blocks as its successors.
4650 BB->addSuccessor(copy0MBB);
4651 BB->addSuccessor(sinkMBB);
4652
4653 // bne rs, $0, sinkMBB
4654 BuildMI(BB, DL, TII->get(Mips::BNE))
4655 .addReg(MI.getOperand(2).getReg())
4656 .addReg(Mips::ZERO)
4657 .addMBB(sinkMBB);
4658
4659 // copy0MBB:
4660 // %FalseValue = ...
4661 // # fallthrough to sinkMBB
4662 BB = copy0MBB;
4663
4664 // Update machine-CFG edges
4665 BB->addSuccessor(sinkMBB);
4666
4667 // sinkMBB:
4668 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4669 // ...
4670 BB = sinkMBB;
4671
4672 // Use two PHI nodes to select two reults
4673 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4674 .addReg(MI.getOperand(3).getReg())
4675 .addMBB(thisMBB)
4676 .addReg(MI.getOperand(5).getReg())
4677 .addMBB(copy0MBB);
4678 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg())
4679 .addReg(MI.getOperand(4).getReg())
4680 .addMBB(thisMBB)
4681 .addReg(MI.getOperand(6).getReg())
4682 .addMBB(copy0MBB);
4683
4684 MI.eraseFromParent(); // The pseudo instruction is gone now.
4685
4686 return BB;
4687}
4688
4689// FIXME? Maybe this could be a TableGen attribute on some registers and
4690// this table could be generated automatically from RegInfo.
4691Register
4692MipsTargetLowering::getRegisterByName(const char *RegName, LLT VT,
4693 const MachineFunction &MF) const {
4694 // Named registers is expected to be fairly rare. For now, just support $28
4695 // since the linux kernel uses it.
4696 if (Subtarget.isGP64bit()) {
4697 Register Reg = StringSwitch<Register>(RegName)
4698 .Case("$28", Mips::GP_64)
4699 .Default(Register());
4700 if (Reg)
4701 return Reg;
4702 } else {
4703 Register Reg = StringSwitch<Register>(RegName)
4704 .Case("$28", Mips::GP)
4705 .Default(Register());
4706 if (Reg)
4707 return Reg;
4708 }
4709 report_fatal_error("Invalid register name global variable");
4710}

/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/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 bool isFast() const {
473 return NoSignedZeros && AllowReciprocal && NoNaNs && NoInfs && NoFPExcept &&
474 AllowContract && ApproximateFuncs && AllowReassociation;
475 }
476
477 /// Clear any flags in this flag set that aren't also set in Flags.
478 /// If the given Flags are undefined then don't do anything.
479 void intersectWith(const SDNodeFlags Flags) {
480 if (!Flags.isDefined())
481 return;
482 NoUnsignedWrap &= Flags.NoUnsignedWrap;
483 NoSignedWrap &= Flags.NoSignedWrap;
484 Exact &= Flags.Exact;
485 NoNaNs &= Flags.NoNaNs;
486 NoInfs &= Flags.NoInfs;
487 NoSignedZeros &= Flags.NoSignedZeros;
488 AllowReciprocal &= Flags.AllowReciprocal;
489 VectorReduction &= Flags.VectorReduction;
490 AllowContract &= Flags.AllowContract;
491 ApproximateFuncs &= Flags.ApproximateFuncs;
492 AllowReassociation &= Flags.AllowReassociation;
493 NoFPExcept &= Flags.NoFPExcept;
494 }
495};
496
497/// Represents one node in the SelectionDAG.
498///
499class SDNode : public FoldingSetNode, public ilist_node<SDNode> {
500private:
501 /// The operation that this node performs.
502 int16_t NodeType;
503
504protected:
505 // We define a set of mini-helper classes to help us interpret the bits in our
506 // SubclassData. These are designed to fit within a uint16_t so they pack
507 // with NodeType.
508
509#if defined(_AIX) && (!defined(__GNUC__4) || defined(__ibmxl__))
510// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
511// and give the `pack` pragma push semantics.
512#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")pack(2)
513#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")pack(pop)
514#else
515#define BEGIN_TWO_BYTE_PACK()
516#define END_TWO_BYTE_PACK()
517#endif
518
519BEGIN_TWO_BYTE_PACK()
520 class SDNodeBitfields {
521 friend class SDNode;
522 friend class MemIntrinsicSDNode;
523 friend class MemSDNode;
524 friend class SelectionDAG;
525
526 uint16_t HasDebugValue : 1;
527 uint16_t IsMemIntrinsic : 1;
528 uint16_t IsDivergent : 1;
529 };
530 enum { NumSDNodeBits = 3 };
531
532 class ConstantSDNodeBitfields {
533 friend class ConstantSDNode;
534
535 uint16_t : NumSDNodeBits;
536
537 uint16_t IsOpaque : 1;
538 };
539
540 class MemSDNodeBitfields {
541 friend class MemSDNode;
542 friend class MemIntrinsicSDNode;
543 friend class AtomicSDNode;
544
545 uint16_t : NumSDNodeBits;
546
547 uint16_t IsVolatile : 1;
548 uint16_t IsNonTemporal : 1;
549 uint16_t IsDereferenceable : 1;
550 uint16_t IsInvariant : 1;
551 };
552 enum { NumMemSDNodeBits = NumSDNodeBits + 4 };
553
554 class LSBaseSDNodeBitfields {
555 friend class LSBaseSDNode;
556 friend class MaskedLoadStoreSDNode;
557 friend class MaskedGatherScatterSDNode;
558
559 uint16_t : NumMemSDNodeBits;
560
561 // This storage is shared between disparate class hierarchies to hold an
562 // enumeration specific to the class hierarchy in use.
563 // LSBaseSDNode => enum ISD::MemIndexedMode
564 // MaskedLoadStoreBaseSDNode => enum ISD::MemIndexedMode
565 // MaskedGatherScatterSDNode => enum ISD::MemIndexType
566 uint16_t AddressingMode : 3;
567 };
568 enum { NumLSBaseSDNodeBits = NumMemSDNodeBits + 3 };
569
570 class LoadSDNodeBitfields {
571 friend class LoadSDNode;
572 friend class MaskedLoadSDNode;
573
574 uint16_t : NumLSBaseSDNodeBits;
575
576 uint16_t ExtTy : 2; // enum ISD::LoadExtType
577 uint16_t IsExpanding : 1;
578 };
579
580 class StoreSDNodeBitfields {
581 friend class StoreSDNode;
582 friend class MaskedStoreSDNode;
583
584 uint16_t : NumLSBaseSDNodeBits;
585
586 uint16_t IsTruncating : 1;
587 uint16_t IsCompressing : 1;
588 };
589
590 union {
591 char RawSDNodeBits[sizeof(uint16_t)];
592 SDNodeBitfields SDNodeBits;
593 ConstantSDNodeBitfields ConstantSDNodeBits;
594 MemSDNodeBitfields MemSDNodeBits;
595 LSBaseSDNodeBitfields LSBaseSDNodeBits;
596 LoadSDNodeBitfields LoadSDNodeBits;
597 StoreSDNodeBitfields StoreSDNodeBits;
598 };
599END_TWO_BYTE_PACK()
600#undef BEGIN_TWO_BYTE_PACK
601#undef END_TWO_BYTE_PACK
602
603 // RawSDNodeBits must cover the entirety of the union. This means that all of
604 // the union's members must have size <= RawSDNodeBits. We write the RHS as
605 // "2" instead of sizeof(RawSDNodeBits) because MSVC can't handle the latter.
606 static_assert(sizeof(SDNodeBitfields) <= 2, "field too wide");
607 static_assert(sizeof(ConstantSDNodeBitfields) <= 2, "field too wide");
608 static_assert(sizeof(MemSDNodeBitfields) <= 2, "field too wide");
609 static_assert(sizeof(LSBaseSDNodeBitfields) <= 2, "field too wide");
610 static_assert(sizeof(LoadSDNodeBitfields) <= 2, "field too wide");
611 static_assert(sizeof(StoreSDNodeBitfields) <= 2, "field too wide");
612
613private:
614 friend class SelectionDAG;
615 // TODO: unfriend HandleSDNode once we fix its operand handling.
616 friend class HandleSDNode;
617
618 /// Unique id per SDNode in the DAG.
619 int NodeId = -1;
620
621 /// The values that are used by this operation.
622 SDUse *OperandList = nullptr;
623
624 /// The types of the values this node defines. SDNode's may
625 /// define multiple values simultaneously.
626 const EVT *ValueList;
627
628 /// List of uses for this SDNode.
629 SDUse *UseList = nullptr;
630
631 /// The number of entries in the Operand/Value list.
632 unsigned short NumOperands = 0;
633 unsigned short NumValues;
634
635 // The ordering of the SDNodes. It roughly corresponds to the ordering of the
636 // original LLVM instructions.
637 // This is used for turning off scheduling, because we'll forgo
638 // the normal scheduling algorithms and output the instructions according to
639 // this ordering.
640 unsigned IROrder;
641
642 /// Source line information.
643 DebugLoc debugLoc;
644
645 /// Return a pointer to the specified value type.
646 static const EVT *getValueTypeList(EVT VT);
647
648 SDNodeFlags Flags;
649
650public:
651 /// Unique and persistent id per SDNode in the DAG.
652 /// Used for debug printing.
653 uint16_t PersistentId;
654
655 //===--------------------------------------------------------------------===//
656 // Accessors
657 //
658
659 /// Return the SelectionDAG opcode value for this node. For
660 /// pre-isel nodes (those for which isMachineOpcode returns false), these
661 /// are the opcode values in the ISD and <target>ISD namespaces. For
662 /// post-isel opcodes, see getMachineOpcode.
663 unsigned getOpcode() const { return (unsigned short)NodeType; }
664
665 /// Test if this node has a target-specific opcode (in the
666 /// \<target\>ISD namespace).
667 bool isTargetOpcode() const { return NodeType >= ISD::BUILTIN_OP_END; }
668
669 /// Test if this node has a target-specific opcode that may raise
670 /// FP exceptions (in the \<target\>ISD namespace and greater than
671 /// FIRST_TARGET_STRICTFP_OPCODE). Note that all target memory
672 /// opcode are currently automatically considered to possibly raise
673 /// FP exceptions as well.
674 bool isTargetStrictFPOpcode() const {
675 return NodeType >= ISD::FIRST_TARGET_STRICTFP_OPCODE;
676 }
677
678 /// Test if this node has a target-specific
679 /// memory-referencing opcode (in the \<target\>ISD namespace and
680 /// greater than FIRST_TARGET_MEMORY_OPCODE).
681 bool isTargetMemoryOpcode() const {
682 return NodeType >= ISD::FIRST_TARGET_MEMORY_OPCODE;
683 }
684
685 /// Return true if the type of the node type undefined.
686 bool isUndef() const { return NodeType == ISD::UNDEF; }
687
688 /// Test if this node is a memory intrinsic (with valid pointer information).
689 /// INTRINSIC_W_CHAIN and INTRINSIC_VOID nodes are sometimes created for
690 /// non-memory intrinsics (with chains) that are not really instances of
691 /// MemSDNode. For such nodes, we need some extra state to determine the
692 /// proper classof relationship.
693 bool isMemIntrinsic() const {
694 return (NodeType == ISD::INTRINSIC_W_CHAIN ||
695 NodeType == ISD::INTRINSIC_VOID) &&
696 SDNodeBits.IsMemIntrinsic;
697 }
698
699 /// Test if this node is a strict floating point pseudo-op.
700 bool isStrictFPOpcode() {
701 switch (NodeType) {
702 default:
703 return false;
704#define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC, DAGN) \
705 case ISD::STRICT_##DAGN:
706#include "llvm/IR/ConstrainedOps.def"
707 return true;
708 }
709 }
710
711 /// Test if this node has a post-isel opcode, directly
712 /// corresponding to a MachineInstr opcode.
713 bool isMachineOpcode() const { return NodeType < 0; }
714
715 /// This may only be called if isMachineOpcode returns
716 /// true. It returns the MachineInstr opcode value that the node's opcode
717 /// corresponds to.
718 unsigned getMachineOpcode() const {
719 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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 719, __PRETTY_FUNCTION__))
;
720 return ~NodeType;
721 }
722
723 bool getHasDebugValue() const { return SDNodeBits.HasDebugValue; }
724 void setHasDebugValue(bool b) { SDNodeBits.HasDebugValue = b; }
725
726 bool isDivergent() const { return SDNodeBits.IsDivergent; }
727
728 /// Return true if there are no uses of this node.
729 bool use_empty() const { return UseList == nullptr; }
730
731 /// Return true if there is exactly one use of this node.
732 bool hasOneUse() const {
733 return !use_empty() && std::next(use_begin()) == use_end();
734 }
735
736 /// Return the number of uses of this node. This method takes
737 /// time proportional to the number of uses.
738 size_t use_size() const { return std::distance(use_begin(), use_end()); }
739
740 /// Return the unique node id.
741 int getNodeId() const { return NodeId; }
742
743 /// Set unique node id.
744 void setNodeId(int Id) { NodeId = Id; }
745
746 /// Return the node ordering.
747 unsigned getIROrder() const { return IROrder; }
748
749 /// Set the node ordering.
750 void setIROrder(unsigned Order) { IROrder = Order; }
751
752 /// Return the source location info.
753 const DebugLoc &getDebugLoc() const { return debugLoc; }
754
755 /// Set source location info. Try to avoid this, putting
756 /// it in the constructor is preferable.
757 void setDebugLoc(DebugLoc dl) { debugLoc = std::move(dl); }
758
759 /// This class provides iterator support for SDUse
760 /// operands that use a specific SDNode.
761 class use_iterator
762 : public std::iterator<std::forward_iterator_tag, SDUse, ptrdiff_t> {
763 friend class SDNode;
764
765 SDUse *Op = nullptr;
766
767 explicit use_iterator(SDUse *op) : Op(op) {}
768
769 public:
770 using reference = std::iterator<std::forward_iterator_tag,
771 SDUse, ptrdiff_t>::reference;
772 using pointer = std::iterator<std::forward_iterator_tag,
773 SDUse, ptrdiff_t>::pointer;
774
775 use_iterator() = default;
776 use_iterator(const use_iterator &I) : Op(I.Op) {}
777
778 bool operator==(const use_iterator &x) const {
779 return Op == x.Op;
780 }
781 bool operator!=(const use_iterator &x) const {
782 return !operator==(x);
783 }
784
785 /// Return true if this iterator is at the end of uses list.
786 bool atEnd() const { return Op == nullptr; }
787
788 // Iterator traversal: forward iteration only.
789 use_iterator &operator++() { // Preincrement
790 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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 790, __PRETTY_FUNCTION__))
;
791 Op = Op->getNext();
792 return *this;
793 }
794
795 use_iterator operator++(int) { // Postincrement
796 use_iterator tmp = *this; ++*this; return tmp;
797 }
798
799 /// Retrieve a pointer to the current user node.
800 SDNode *operator*() const {
801 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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 801, __PRETTY_FUNCTION__))
;
802 return Op->getUser();
803 }
804
805 SDNode *operator->() const { return operator*(); }
806
807 SDUse &getUse() const { return *Op; }
808
809 /// Retrieve the operand # of this use in its user.
810 unsigned getOperandNo() const {
811 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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 811, __PRETTY_FUNCTION__))
;
812 return (unsigned)(Op - Op->getUser()->OperandList);
813 }
814 };
815
816 /// Provide iteration support to walk over all uses of an SDNode.
817 use_iterator use_begin() const {
818 return use_iterator(UseList);
819 }
820
821 static use_iterator use_end() { return use_iterator(nullptr); }
822
823 inline iterator_range<use_iterator> uses() {
824 return make_range(use_begin(), use_end());
825 }
826 inline iterator_range<use_iterator> uses() const {
827 return make_range(use_begin(), use_end());
828 }
829
830 /// Return true if there are exactly NUSES uses of the indicated value.
831 /// This method ignores uses of other values defined by this operation.
832 bool hasNUsesOfValue(unsigned NUses, unsigned Value) const;
833
834 /// Return true if there are any use of the indicated value.
835 /// This method ignores uses of other values defined by this operation.
836 bool hasAnyUseOfValue(unsigned Value) const;
837
838 /// Return true if this node is the only use of N.
839 bool isOnlyUserOf(const SDNode *N) const;
840
841 /// Return true if this node is an operand of N.
842 bool isOperandOf(const SDNode *N) const;
843
844 /// Return true if this node is a predecessor of N.
845 /// NOTE: Implemented on top of hasPredecessor and every bit as
846 /// expensive. Use carefully.
847 bool isPredecessorOf(const SDNode *N) const {
848 return N->hasPredecessor(this);
849 }
850
851 /// Return true if N is a predecessor of this node.
852 /// N is either an operand of this node, or can be reached by recursively
853 /// traversing up the operands.
854 /// NOTE: This is an expensive method. Use it carefully.
855 bool hasPredecessor(const SDNode *N) const;
856
857 /// Returns true if N is a predecessor of any node in Worklist. This
858 /// helper keeps Visited and Worklist sets externally to allow unions
859 /// searches to be performed in parallel, caching of results across
860 /// queries and incremental addition to Worklist. Stops early if N is
861 /// found but will resume. Remember to clear Visited and Worklists
862 /// if DAG changes. MaxSteps gives a maximum number of nodes to visit before
863 /// giving up. The TopologicalPrune flag signals that positive NodeIds are
864 /// topologically ordered (Operands have strictly smaller node id) and search
865 /// can be pruned leveraging this.
866 static bool hasPredecessorHelper(const SDNode *N,
867 SmallPtrSetImpl<const SDNode *> &Visited,
868 SmallVectorImpl<const SDNode *> &Worklist,
869 unsigned int MaxSteps = 0,
870 bool TopologicalPrune = false) {
871 SmallVector<const SDNode *, 8> DeferredNodes;
872 if (Visited.count(N))
873 return true;
874
875 // Node Id's are assigned in three places: As a topological
876 // ordering (> 0), during legalization (results in values set to
877 // 0), new nodes (set to -1). If N has a topolgical id then we
878 // know that all nodes with ids smaller than it cannot be
879 // successors and we need not check them. Filter out all node
880 // that can't be matches. We add them to the worklist before exit
881 // in case of multiple calls. Note that during selection the topological id
882 // may be violated if a node's predecessor is selected before it. We mark
883 // this at selection negating the id of unselected successors and
884 // restricting topological pruning to positive ids.
885
886 int NId = N->getNodeId();
887 // If we Invalidated the Id, reconstruct original NId.
888 if (NId < -1)
889 NId = -(NId + 1);
890
891 bool Found = false;
892 while (!Worklist.empty()) {
893 const SDNode *M = Worklist.pop_back_val();
894 int MId = M->getNodeId();
895 if (TopologicalPrune && M->getOpcode() != ISD::TokenFactor && (NId > 0) &&
896 (MId > 0) && (MId < NId)) {
897 DeferredNodes.push_back(M);
898 continue;
899 }
900 for (const SDValue &OpV : M->op_values()) {
901 SDNode *Op = OpV.getNode();
902 if (Visited.insert(Op).second)
903 Worklist.push_back(Op);
904 if (Op == N)
905 Found = true;
906 }
907 if (Found)
908 break;
909 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
910 break;
911 }
912 // Push deferred nodes back on worklist.
913 Worklist.append(DeferredNodes.begin(), DeferredNodes.end());
914 // If we bailed early, conservatively return found.
915 if (MaxSteps != 0 && Visited.size() >= MaxSteps)
916 return true;
917 return Found;
918 }
919
920 /// Return true if all the users of N are contained in Nodes.
921 /// NOTE: Requires at least one match, but doesn't require them all.
922 static bool areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N);
923
924 /// Return the number of values used by this operation.
925 unsigned getNumOperands() const { return NumOperands; }
926
927 /// Return the maximum number of operands that a SDNode can hold.
928 static constexpr size_t getMaxNumOperands() {
929 return std::numeric_limits<decltype(SDNode::NumOperands)>::max();
930 }
931
932 /// Helper method returns the integer value of a ConstantSDNode operand.
933 inline uint64_t getConstantOperandVal(unsigned Num) const;
934
935 /// Helper method returns the APInt of a ConstantSDNode operand.
936 inline const APInt &getConstantOperandAPInt(unsigned Num) const;
937
938 const SDValue &getOperand(unsigned Num) const {
939 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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 939, __PRETTY_FUNCTION__))
;
940 return OperandList[Num];
941 }
942
943 using op_iterator = SDUse *;
944
945 op_iterator op_begin() const { return OperandList; }
946 op_iterator op_end() const { return OperandList+NumOperands; }
947 ArrayRef<SDUse> ops() const { return makeArrayRef(op_begin(), op_end()); }
948
949 /// Iterator for directly iterating over the operand SDValue's.
950 struct value_op_iterator
951 : iterator_adaptor_base<value_op_iterator, op_iterator,
952 std::random_access_iterator_tag, SDValue,
953 ptrdiff_t, value_op_iterator *,
954 value_op_iterator *> {
955 explicit value_op_iterator(SDUse *U = nullptr)
956 : iterator_adaptor_base(U) {}
957
958 const SDValue &operator*() const { return I->get(); }
959 };
960
961 iterator_range<value_op_iterator> op_values() const {
962 return make_range(value_op_iterator(op_begin()),
963 value_op_iterator(op_end()));
964 }
965
966 SDVTList getVTList() const {
967 SDVTList X = { ValueList, NumValues };
968 return X;
969 }
970
971 /// If this node has a glue operand, return the node
972 /// to which the glue operand points. Otherwise return NULL.
973 SDNode *getGluedNode() const {
974 if (getNumOperands() != 0 &&
975 getOperand(getNumOperands()-1).getValueType() == MVT::Glue)
976 return getOperand(getNumOperands()-1).getNode();
977 return nullptr;
978 }
979
980 /// If this node has a glue value with a user, return
981 /// the user (there is at most one). Otherwise return NULL.
982 SDNode *getGluedUser() const {
983 for (use_iterator UI = use_begin(), UE = use_end(); UI != UE; ++UI)
984 if (UI.getUse().get().getValueType() == MVT::Glue)
985 return *UI;
986 return nullptr;
987 }
988
989 const SDNodeFlags getFlags() const { return Flags; }
990 void setFlags(SDNodeFlags NewFlags) { Flags = NewFlags; }
991 bool isFast() { return Flags.isFast(); }
992
993 /// Clear any flags in this node that aren't also set in Flags.
994 /// If Flags is not in a defined state then this has no effect.
995 void intersectFlagsWith(const SDNodeFlags Flags);
996
997 /// Return the number of values defined/returned by this operator.
998 unsigned getNumValues() const { return NumValues; }
999
1000 /// Return the type of a specified result.
1001 EVT getValueType(unsigned ResNo) const {
1002 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-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1002, __PRETTY_FUNCTION__))
;
1003 return ValueList[ResNo];
1004 }
1005
1006 /// Return the type of a specified result as a simple type.
1007 MVT getSimpleValueType(unsigned ResNo) const {
1008 return getValueType(ResNo).getSimpleVT();
1009 }
1010
1011 /// Returns MVT::getSizeInBits(getValueType(ResNo)).
1012 ///
1013 /// If the value type is a scalable vector type, the scalable property will
1014 /// be set and the runtime size will be a positive integer multiple of the
1015 /// base size.
1016 TypeSize getValueSizeInBits(unsigned ResNo) const {
1017 return getValueType(ResNo).getSizeInBits();
1018 }
1019
1020 using value_iterator = const EVT *;
1021
1022 value_iterator value_begin() const { return ValueList; }
1023 value_iterator value_end() const { return ValueList+NumValues; }
1024
1025 /// Return the opcode of this operation for printing.
1026 std::string getOperationName(const SelectionDAG *G = nullptr) const;
1027 static const char* getIndexedModeName(ISD::MemIndexedMode AM);
1028 void print_types(raw_ostream &OS, const SelectionDAG *G) const;
1029 void print_details(raw_ostream &OS, const SelectionDAG *G) const;
1030 void print(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1031 void printr(raw_ostream &OS, const SelectionDAG *G = nullptr) const;
1032
1033 /// Print a SelectionDAG node and all children down to
1034 /// the leaves. The given SelectionDAG allows target-specific nodes
1035 /// to be printed in human-readable form. Unlike printr, this will
1036 /// print the whole DAG, including children that appear multiple
1037 /// times.
1038 ///
1039 void printrFull(raw_ostream &O, const SelectionDAG *G = nullptr) const;
1040
1041 /// Print a SelectionDAG node and children up to
1042 /// depth "depth." The given SelectionDAG allows target-specific
1043 /// nodes to be printed in human-readable form. Unlike printr, this
1044 /// will print children that appear multiple times wherever they are
1045 /// used.
1046 ///
1047 void printrWithDepth(raw_ostream &O, const SelectionDAG *G = nullptr,
1048 unsigned depth = 100) const;
1049
1050 /// Dump this node, for debugging.
1051 void dump() const;
1052
1053 /// Dump (recursively) this node and its use-def subgraph.
1054 void dumpr() const;
1055
1056 /// Dump this node, for debugging.
1057 /// The given SelectionDAG allows target-specific nodes to be printed
1058 /// in human-readable form.
1059 void dump(const SelectionDAG *G) const;
1060
1061 /// Dump (recursively) this node and its use-def subgraph.
1062 /// The given SelectionDAG allows target-specific nodes to be printed
1063 /// in human-readable form.
1064 void dumpr(const SelectionDAG *G) const;
1065
1066 /// printrFull to dbgs(). The given SelectionDAG allows
1067 /// target-specific nodes to be printed in human-readable form.
1068 /// Unlike dumpr, this will print the whole DAG, including children
1069 /// that appear multiple times.
1070 void dumprFull(const SelectionDAG *G = nullptr) const;
1071
1072 /// printrWithDepth to dbgs(). The given
1073 /// SelectionDAG allows target-specific nodes to be printed in
1074 /// human-readable form. Unlike dumpr, this will print children
1075 /// that appear multiple times wherever they are used.
1076 ///
1077 void dumprWithDepth(const SelectionDAG *G = nullptr,
1078 unsigned depth = 100) const;
1079
1080 /// Gather unique data for the node.
1081 void Profile(FoldingSetNodeID &ID) const;
1082
1083 /// This method should only be used by the SDUse class.
1084 void addUse(SDUse &U) { U.addToList(&UseList); }
1085
1086protected:
1087 static SDVTList getSDVTList(EVT VT) {
1088 SDVTList Ret = { getValueTypeList(VT), 1 };
1089 return Ret;
1090 }
1091
1092 /// Create an SDNode.
1093 ///
1094 /// SDNodes are created without any operands, and never own the operand
1095 /// storage. To add operands, see SelectionDAG::createOperands.
1096 SDNode(unsigned Opc, unsigned Order, DebugLoc dl, SDVTList VTs)
1097 : NodeType(Opc), ValueList(VTs.VTs), NumValues(VTs.NumVTs),
1098 IROrder(Order), debugLoc(std::move(dl)) {
1099 memset(&RawSDNodeBits, 0, sizeof(RawSDNodeBits));
1100 assert(debugLoc.hasTrivialDestructor() && "Expected trivial destructor")((debugLoc.hasTrivialDestructor() && "Expected trivial destructor"
) ? static_cast<void> (0) : __assert_fail ("debugLoc.hasTrivialDestructor() && \"Expected trivial destructor\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1100, __PRETTY_FUNCTION__))
;
1101 assert(NumValues == VTs.NumVTs &&((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!"
) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1102, __PRETTY_FUNCTION__))
1102 "NumValues wasn't wide enough for its operands!")((NumValues == VTs.NumVTs && "NumValues wasn't wide enough for its operands!"
) ? static_cast<void> (0) : __assert_fail ("NumValues == VTs.NumVTs && \"NumValues wasn't wide enough for its operands!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1102, __PRETTY_FUNCTION__))
;
1103 }
1104
1105 /// Release the operands and set this node to have zero operands.
1106 void DropOperands();
1107};
1108
1109/// Wrapper class for IR location info (IR ordering and DebugLoc) to be passed
1110/// into SDNode creation functions.
1111/// When an SDNode is created from the DAGBuilder, the DebugLoc is extracted
1112/// from the original Instruction, and IROrder is the ordinal position of
1113/// the instruction.
1114/// When an SDNode is created after the DAG is being built, both DebugLoc and
1115/// the IROrder are propagated from the original SDNode.
1116/// So SDLoc class provides two constructors besides the default one, one to
1117/// be used by the DAGBuilder, the other to be used by others.
1118class SDLoc {
1119private:
1120 DebugLoc DL;
1121 int IROrder = 0;
1122
1123public:
1124 SDLoc() = default;
1125 SDLoc(const SDNode *N) : DL(N->getDebugLoc()), IROrder(N->getIROrder()) {}
1126 SDLoc(const SDValue V) : SDLoc(V.getNode()) {}
1127 SDLoc(const Instruction *I, int Order) : IROrder(Order) {
1128 assert(Order >= 0 && "bad IROrder")((Order >= 0 && "bad IROrder") ? static_cast<void
> (0) : __assert_fail ("Order >= 0 && \"bad IROrder\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1128, __PRETTY_FUNCTION__))
;
1129 if (I)
1130 DL = I->getDebugLoc();
1131 }
1132
1133 unsigned getIROrder() const { return IROrder; }
1134 const DebugLoc &getDebugLoc() const { return DL; }
1135};
1136
1137// Define inline functions from the SDValue class.
1138
1139inline SDValue::SDValue(SDNode *node, unsigned resno)
1140 : Node(node), ResNo(resno) {
1141 // Explicitly check for !ResNo to avoid use-after-free, because there are
1142 // callers that use SDValue(N, 0) with a deleted N to indicate successful
1143 // combines.
1144 assert((!Node || !ResNo || ResNo < Node->getNumValues()) &&(((!Node || !ResNo || ResNo < Node->getNumValues()) &&
"Invalid result number for the given node!") ? static_cast<
void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1145, __PRETTY_FUNCTION__))
1145 "Invalid result number for the given node!")(((!Node || !ResNo || ResNo < Node->getNumValues()) &&
"Invalid result number for the given node!") ? static_cast<
void> (0) : __assert_fail ("(!Node || !ResNo || ResNo < Node->getNumValues()) && \"Invalid result number for the given node!\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1145, __PRETTY_FUNCTION__))
;
1146 assert(ResNo < -2U && "Cannot use result numbers reserved for DenseMaps.")((ResNo < -2U && "Cannot use result numbers reserved for DenseMaps."
) ? static_cast<void> (0) : __assert_fail ("ResNo < -2U && \"Cannot use result numbers reserved for DenseMaps.\""
, "/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include/llvm/CodeGen/SelectionDAGNodes.h"
, 1146, __PRETTY_FUNCTION__))
;
1147}
1148
1149inline unsigned SDValue::getOpcode() const {
1150 return Node->getOpcode();
1151}
1152
1153inline EVT SDValue::getValueType() const {
1154 return Node->getValueType(ResNo);
16
Called C++ object pointer is null
1155}
1156
1157inline unsigned SDValue::getNumOperands() const {
1158 return Node->getNumOperands();
1159}
1160
1161inline const SDValue &SDValue::getOperand(unsigned i) const {
1162 return Node->getOperand(i);
1163}
1164
1165inline uint64_t SDValue::getConstantOperandVal(unsigned i) const {
1166 return Node->getConstantOperandVal(i);
1167}
1168
1169inline const APInt &SDValue::getConstantOperandAPInt(unsigned i) const {
1170 return Node->getConstantOperandAPInt(i);
1171}
1172
1173inline bool SDValue::isTargetOpcode() const {
1174 return Node->isTargetOpcode();
1175}
1176
1177inline bool SDValue::isTargetMemoryOpcode() const {
1178 return Node->isTargetMemoryOpcode();
1179}
1180
1181inline bool SDValue::isMachineOpcode() const {
1182 return Node->isMachineOpcode();
1183}
1184
1185inline unsigned SDValue::getMachineOpcode() const {
1186 return Node->getMachineOpcode();
1187}
1188
1189inline bool SDValue::isUndef() const {
1190 return Node->isUndef();
1191}
1192
1193inline bool SDValue::use_empty() const {
1194 return !Node->hasAnyUseOfValue(ResNo);
1195}
1196
1197inline bool SDValue::hasOneUse() const {
1198 return Node->hasNUsesOfValue(1, ResNo);
1199}
1200
1201inline const DebugLoc &SDValue::getDebugLoc() const {
1202 return Node->getDebugLoc();
1203}
1204
1205inline void SDValue::dump() const {
1206 return Node->dump();
1207}
1208
1209inline void SDValue::dump(const SelectionDAG *G) const {
1210 return Node->dump(G);
1211}
1212
1213inline void SDValue::dumpr() const {
1214 return Node->dumpr();
1215}
1216
1217inline void SDValue::dumpr(const SelectionDAG *G) const {
1218 return Node->dumpr(G);
1219}
1220
1221// Define inline functions from the SDUse class.
1222
1223inline void SDUse::set(const SDValue &V) {
1224 if (Val.getNode()) removeFromList();
1225 Val = V;
1226 if (V.getNode()) V.getNode()->addUse(*this);
1227}
1228
1229inline void SDUse::setInitial(const SDValue &V) {
1230 Val = V;
1231 V.getNode()->addUse(*this);
1232}
1233
1234inline void SDUse::setNode(SDNode *N) {
1235 if (Val.getNode()) removeFromList();
1236 Val.setNode(N);
1237 if (N) N->addUse(*this);
1238}
1239
1240/// This class is used to form a handle around another node that
1241/// is persistent and is updated across invocations of replaceAllUsesWith on its
1242/// operand. This node should be directly created by end-users and not added to
1243/// the AllNodes list.
1244class HandleSDNode : public SDNode {
1245 SDUse Op;
1246
1247public:
1248 explicit HandleSDNode(SDValue X)
1249 : SDNode(ISD::HANDLENODE, 0, DebugLoc(), getSDVTList(MVT::Other)) {
1250 // HandleSDNodes are never inserted into the DAG, so they won't be
1251 // auto-numbered. Use ID 65535 as a sentinel.
1252 PersistentId = 0xffff;
1253
1254 // Manually set up the operand list. This node type is special in that it's
1255 // always stack allocated and SelectionDAG does not manage its operands.
1256 // TODO: This should either (a) not be in the SDNode hierarchy, or (b) not
1257 // be so special.
1258 Op.setUser(this);
1259 Op.setInitial(X);
1260 NumOperands = 1;
1261 OperandList = &Op;
1262 }
1263 ~HandleSDNode();
1264
1265 const SDValue &getValue() const { return Op; }
1266};
1267
1268class AddrSpaceCastSDNode : public SDNode {
1269private:
1270 unsigned SrcAddrSpace;
1271 unsigned DestAddrSpace;
1272
1273public:
1274 AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl, EVT VT,
1275 unsigned SrcAS, unsigned DestAS);
1276
1277 unsigned getSrcAddressSpace() const { return SrcAddrSpace; }
1278 unsigned getDestAddressSpace() const { return DestAddrSpace; }