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