1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
44 #define DEBUG_TYPE "mips-lower"
46 STATISTIC(NumTailCalls, "Number of tail calls");
49 LargeGOT("mxgot", cl::Hidden,
50 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
53 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
54 cl::desc("MIPS: Don't trap on integer division by zero."),
57 static const MCPhysReg Mips64DPRegs[8] = {
58 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
59 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
62 // If I is a shifted mask, set the size (Size) and the first bit of the
63 // mask (Pos), and return true.
64 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
65 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
66 if (!isShiftedMask_64(I))
69 Size = countPopulation(I);
70 Pos = countTrailingZeros(I);
74 // The MIPS MSA ABI passes vector arguments in the integer register set.
75 // The number of integer registers used is dependant on the ABI used.
76 MVT MipsTargetLowering::getRegisterTypeForCallingConv(MVT VT) const {
77 if (VT.isVector() && Subtarget.hasMSA())
78 return Subtarget.isABI_O32() ? MVT::i32 : MVT::i64;
79 return MipsTargetLowering::getRegisterType(VT);
82 MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
85 if (Subtarget.isABI_O32()) {
88 return (VT.getSizeInBits() == 32) ? MVT::i32 : MVT::i64;
91 return MipsTargetLowering::getRegisterType(Context, VT);
94 unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
97 return std::max((VT.getSizeInBits() / (Subtarget.isABI_O32() ? 32 : 64)),
99 return MipsTargetLowering::getNumRegisters(Context, VT);
102 unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv(
103 LLVMContext &Context, EVT VT, EVT &IntermediateVT,
104 unsigned &NumIntermediates, MVT &RegisterVT) const {
106 // Break down vector types to either 2 i64s or 4 i32s.
107 RegisterVT = getRegisterTypeForCallingConv(Context, VT) ;
108 IntermediateVT = RegisterVT;
109 NumIntermediates = VT.getSizeInBits() < RegisterVT.getSizeInBits()
110 ? VT.getVectorNumElements()
111 : VT.getSizeInBits() / RegisterVT.getSizeInBits();
113 return NumIntermediates;
116 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
117 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
118 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
121 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
123 unsigned Flag) const {
124 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
127 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
129 unsigned Flag) const {
130 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
133 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
135 unsigned Flag) const {
136 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
139 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
141 unsigned Flag) const {
142 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
145 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
147 unsigned Flag) const {
148 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
149 N->getOffset(), Flag);
152 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
153 switch ((MipsISD::NodeType)Opcode) {
154 case MipsISD::FIRST_NUMBER: break;
155 case MipsISD::JmpLink: return "MipsISD::JmpLink";
156 case MipsISD::TailCall: return "MipsISD::TailCall";
157 case MipsISD::Highest: return "MipsISD::Highest";
158 case MipsISD::Higher: return "MipsISD::Higher";
159 case MipsISD::Hi: return "MipsISD::Hi";
160 case MipsISD::Lo: return "MipsISD::Lo";
161 case MipsISD::GotHi: return "MipsISD::GotHi";
162 case MipsISD::GPRel: return "MipsISD::GPRel";
163 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
164 case MipsISD::Ret: return "MipsISD::Ret";
165 case MipsISD::ERet: return "MipsISD::ERet";
166 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
167 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
168 case MipsISD::FPCmp: return "MipsISD::FPCmp";
169 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
170 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
171 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
172 case MipsISD::MFHI: return "MipsISD::MFHI";
173 case MipsISD::MFLO: return "MipsISD::MFLO";
174 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
175 case MipsISD::Mult: return "MipsISD::Mult";
176 case MipsISD::Multu: return "MipsISD::Multu";
177 case MipsISD::MAdd: return "MipsISD::MAdd";
178 case MipsISD::MAddu: return "MipsISD::MAddu";
179 case MipsISD::MSub: return "MipsISD::MSub";
180 case MipsISD::MSubu: return "MipsISD::MSubu";
181 case MipsISD::DivRem: return "MipsISD::DivRem";
182 case MipsISD::DivRemU: return "MipsISD::DivRemU";
183 case MipsISD::DivRem16: return "MipsISD::DivRem16";
184 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
185 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
186 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
187 case MipsISD::Wrapper: return "MipsISD::Wrapper";
188 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
189 case MipsISD::Sync: return "MipsISD::Sync";
190 case MipsISD::Ext: return "MipsISD::Ext";
191 case MipsISD::Ins: return "MipsISD::Ins";
192 case MipsISD::CIns: return "MipsISD::CIns";
193 case MipsISD::LWL: return "MipsISD::LWL";
194 case MipsISD::LWR: return "MipsISD::LWR";
195 case MipsISD::SWL: return "MipsISD::SWL";
196 case MipsISD::SWR: return "MipsISD::SWR";
197 case MipsISD::LDL: return "MipsISD::LDL";
198 case MipsISD::LDR: return "MipsISD::LDR";
199 case MipsISD::SDL: return "MipsISD::SDL";
200 case MipsISD::SDR: return "MipsISD::SDR";
201 case MipsISD::EXTP: return "MipsISD::EXTP";
202 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
203 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
204 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
205 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
206 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
207 case MipsISD::SHILO: return "MipsISD::SHILO";
208 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
209 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
210 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
211 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
212 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
213 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
214 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
215 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
216 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
217 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
218 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
219 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
220 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
221 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
222 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
223 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
224 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
225 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
226 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
227 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
228 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
229 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
230 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
231 case MipsISD::MULT: return "MipsISD::MULT";
232 case MipsISD::MULTU: return "MipsISD::MULTU";
233 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
234 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
235 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
236 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
237 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
238 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
239 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
240 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
241 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
242 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
243 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
244 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
245 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
246 case MipsISD::VCEQ: return "MipsISD::VCEQ";
247 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
248 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
249 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
250 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
251 case MipsISD::VSMAX: return "MipsISD::VSMAX";
252 case MipsISD::VSMIN: return "MipsISD::VSMIN";
253 case MipsISD::VUMAX: return "MipsISD::VUMAX";
254 case MipsISD::VUMIN: return "MipsISD::VUMIN";
255 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
256 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
257 case MipsISD::VNOR: return "MipsISD::VNOR";
258 case MipsISD::VSHF: return "MipsISD::VSHF";
259 case MipsISD::SHF: return "MipsISD::SHF";
260 case MipsISD::ILVEV: return "MipsISD::ILVEV";
261 case MipsISD::ILVOD: return "MipsISD::ILVOD";
262 case MipsISD::ILVL: return "MipsISD::ILVL";
263 case MipsISD::ILVR: return "MipsISD::ILVR";
264 case MipsISD::PCKEV: return "MipsISD::PCKEV";
265 case MipsISD::PCKOD: return "MipsISD::PCKOD";
266 case MipsISD::INSVE: return "MipsISD::INSVE";
271 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
272 const MipsSubtarget &STI)
273 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
274 // Mips does not have i1 type, so use i32 for
275 // setcc operations results (slt, sgt, ...).
276 setBooleanContents(ZeroOrOneBooleanContent);
277 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
278 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
279 // does. Integer booleans still use 0 and 1.
280 if (Subtarget.hasMips32r6())
281 setBooleanContents(ZeroOrOneBooleanContent,
282 ZeroOrNegativeOneBooleanContent);
284 // Load extented operations for i1 types must be promoted
285 for (MVT VT : MVT::integer_valuetypes()) {
286 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
287 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
288 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
291 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
293 for (MVT VT : MVT::fp_valuetypes()) {
294 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
295 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
298 // Set LoadExtAction for f16 vectors to Expand
299 for (MVT VT : MVT::fp_vector_valuetypes()) {
300 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
302 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
305 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
306 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
308 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
310 // Used by legalize types to correctly generate the setcc result.
311 // Without this, every float setcc comes with a AND/OR with the result,
312 // we don't want this, since the fpcmp result goes to a flag register,
313 // which is used implicitly by brcond and select operations.
314 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
316 // Mips Custom Operations
317 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
318 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
319 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
320 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
321 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
322 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
323 setOperationAction(ISD::SELECT, MVT::f32, Custom);
324 setOperationAction(ISD::SELECT, MVT::f64, Custom);
325 setOperationAction(ISD::SELECT, MVT::i32, Custom);
326 setOperationAction(ISD::SETCC, MVT::f32, Custom);
327 setOperationAction(ISD::SETCC, MVT::f64, Custom);
328 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
330 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
331 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
333 if (Subtarget.isGP64bit()) {
334 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
335 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
336 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
337 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
338 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
339 setOperationAction(ISD::SELECT, MVT::i64, Custom);
340 setOperationAction(ISD::LOAD, MVT::i64, Custom);
341 setOperationAction(ISD::STORE, MVT::i64, Custom);
342 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
343 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
344 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
345 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
348 if (!Subtarget.isGP64bit()) {
349 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
350 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
351 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
354 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
355 if (Subtarget.isGP64bit())
356 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
358 setOperationAction(ISD::SDIV, MVT::i32, Expand);
359 setOperationAction(ISD::SREM, MVT::i32, Expand);
360 setOperationAction(ISD::UDIV, MVT::i32, Expand);
361 setOperationAction(ISD::UREM, MVT::i32, Expand);
362 setOperationAction(ISD::SDIV, MVT::i64, Expand);
363 setOperationAction(ISD::SREM, MVT::i64, Expand);
364 setOperationAction(ISD::UDIV, MVT::i64, Expand);
365 setOperationAction(ISD::UREM, MVT::i64, Expand);
367 if (!(Subtarget.hasDSP() && Subtarget.hasMips32r2())) {
368 setOperationAction(ISD::ADDC, MVT::i32, Expand);
369 setOperationAction(ISD::ADDE, MVT::i32, Expand);
372 setOperationAction(ISD::ADDC, MVT::i64, Expand);
373 setOperationAction(ISD::ADDE, MVT::i64, Expand);
374 setOperationAction(ISD::SUBC, MVT::i32, Expand);
375 setOperationAction(ISD::SUBE, MVT::i32, Expand);
376 setOperationAction(ISD::SUBC, MVT::i64, Expand);
377 setOperationAction(ISD::SUBE, MVT::i64, Expand);
379 // Operations not directly supported by Mips.
380 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
381 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
382 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
383 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
384 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
385 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
386 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
387 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
388 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
389 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
390 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
391 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
392 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
393 if (Subtarget.hasCnMips()) {
394 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
395 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
397 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
398 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
400 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
401 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
402 setOperationAction(ISD::ROTL, MVT::i32, Expand);
403 setOperationAction(ISD::ROTL, MVT::i64, Expand);
404 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
405 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
407 if (!Subtarget.hasMips32r2())
408 setOperationAction(ISD::ROTR, MVT::i32, Expand);
410 if (!Subtarget.hasMips64r2())
411 setOperationAction(ISD::ROTR, MVT::i64, Expand);
413 setOperationAction(ISD::FSIN, MVT::f32, Expand);
414 setOperationAction(ISD::FSIN, MVT::f64, Expand);
415 setOperationAction(ISD::FCOS, MVT::f32, Expand);
416 setOperationAction(ISD::FCOS, MVT::f64, Expand);
417 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
418 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
419 setOperationAction(ISD::FPOW, MVT::f32, Expand);
420 setOperationAction(ISD::FPOW, MVT::f64, Expand);
421 setOperationAction(ISD::FLOG, MVT::f32, Expand);
422 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
423 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
424 setOperationAction(ISD::FEXP, MVT::f32, Expand);
425 setOperationAction(ISD::FMA, MVT::f32, Expand);
426 setOperationAction(ISD::FMA, MVT::f64, Expand);
427 setOperationAction(ISD::FREM, MVT::f32, Expand);
428 setOperationAction(ISD::FREM, MVT::f64, Expand);
430 // Lower f16 conversion operations into library calls
431 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
432 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
433 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
434 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
436 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
438 setOperationAction(ISD::VASTART, MVT::Other, Custom);
439 setOperationAction(ISD::VAARG, MVT::Other, Custom);
440 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
441 setOperationAction(ISD::VAEND, MVT::Other, Expand);
443 // Use the default for now
444 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
445 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
447 if (!Subtarget.isGP64bit()) {
448 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
449 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
453 if (!Subtarget.hasMips32r2()) {
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
455 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
458 // MIPS16 lacks MIPS32's clz and clo instructions.
459 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
460 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
461 if (!Subtarget.hasMips64())
462 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
464 if (!Subtarget.hasMips32r2())
465 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
466 if (!Subtarget.hasMips64r2())
467 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
469 if (Subtarget.isGP64bit()) {
470 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
471 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
472 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
473 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
476 setOperationAction(ISD::TRAP, MVT::Other, Legal);
478 setTargetDAGCombine(ISD::SDIVREM);
479 setTargetDAGCombine(ISD::UDIVREM);
480 setTargetDAGCombine(ISD::SELECT);
481 setTargetDAGCombine(ISD::AND);
482 setTargetDAGCombine(ISD::OR);
483 setTargetDAGCombine(ISD::ADD);
484 setTargetDAGCombine(ISD::SUB);
485 setTargetDAGCombine(ISD::AssertZext);
486 setTargetDAGCombine(ISD::SHL);
489 // These libcalls are not available in 32-bit.
490 setLibcallName(RTLIB::SHL_I128, nullptr);
491 setLibcallName(RTLIB::SRL_I128, nullptr);
492 setLibcallName(RTLIB::SRA_I128, nullptr);
495 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
497 // The arguments on the stack are defined in terms of 4-byte slots on O32
498 // and 8-byte slots on N32/N64.
499 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
501 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
503 MaxStoresPerMemcpy = 16;
505 isMicroMips = Subtarget.inMicroMipsMode();
508 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
509 const MipsSubtarget &STI) {
510 if (STI.inMips16Mode())
511 return llvm::createMips16TargetLowering(TM, STI);
513 return llvm::createMipsSETargetLowering(TM, STI);
516 // Create a fast isel object.
518 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
519 const TargetLibraryInfo *libInfo) const {
520 const MipsTargetMachine &TM =
521 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
523 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
524 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
525 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
526 !Subtarget.inMicroMipsMode();
528 // Disable if either of the following is true:
529 // We do not generate PIC, the ABI is not O32, LargeGOT is being used.
530 if (!TM.isPositionIndependent() || !TM.getABI().IsO32() || LargeGOT)
533 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
536 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
540 return VT.changeVectorElementTypeToInteger();
543 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
544 TargetLowering::DAGCombinerInfo &DCI,
545 const MipsSubtarget &Subtarget) {
546 if (DCI.isBeforeLegalizeOps())
549 EVT Ty = N->getValueType(0);
550 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
551 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
552 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
556 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
557 N->getOperand(0), N->getOperand(1));
558 SDValue InChain = DAG.getEntryNode();
559 SDValue InGlue = DivRem;
562 if (N->hasAnyUseOfValue(0)) {
563 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
565 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
566 InChain = CopyFromLo.getValue(1);
567 InGlue = CopyFromLo.getValue(2);
571 if (N->hasAnyUseOfValue(1)) {
572 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
574 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
580 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
582 default: llvm_unreachable("Unknown fp condition code!");
584 case ISD::SETOEQ: return Mips::FCOND_OEQ;
585 case ISD::SETUNE: return Mips::FCOND_UNE;
587 case ISD::SETOLT: return Mips::FCOND_OLT;
589 case ISD::SETOGT: return Mips::FCOND_OGT;
591 case ISD::SETOLE: return Mips::FCOND_OLE;
593 case ISD::SETOGE: return Mips::FCOND_OGE;
594 case ISD::SETULT: return Mips::FCOND_ULT;
595 case ISD::SETULE: return Mips::FCOND_ULE;
596 case ISD::SETUGT: return Mips::FCOND_UGT;
597 case ISD::SETUGE: return Mips::FCOND_UGE;
598 case ISD::SETUO: return Mips::FCOND_UN;
599 case ISD::SETO: return Mips::FCOND_OR;
601 case ISD::SETONE: return Mips::FCOND_ONE;
602 case ISD::SETUEQ: return Mips::FCOND_UEQ;
607 /// This function returns true if the floating point conditional branches and
608 /// conditional moves which use condition code CC should be inverted.
609 static bool invertFPCondCodeUser(Mips::CondCode CC) {
610 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
613 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
614 "Illegal Condition Code");
619 // Creates and returns an FPCmp node from a setcc node.
620 // Returns Op if setcc is not a floating point comparison.
621 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
622 // must be a SETCC node
623 if (Op.getOpcode() != ISD::SETCC)
626 SDValue LHS = Op.getOperand(0);
628 if (!LHS.getValueType().isFloatingPoint())
631 SDValue RHS = Op.getOperand(1);
634 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
635 // node if necessary.
636 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
638 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
639 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
642 // Creates and returns a CMovFPT/F node.
643 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
644 SDValue False, const SDLoc &DL) {
645 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
646 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
647 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
649 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
650 True.getValueType(), True, FCC0, False, Cond);
653 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
654 TargetLowering::DAGCombinerInfo &DCI,
655 const MipsSubtarget &Subtarget) {
656 if (DCI.isBeforeLegalizeOps())
659 SDValue SetCC = N->getOperand(0);
661 if ((SetCC.getOpcode() != ISD::SETCC) ||
662 !SetCC.getOperand(0).getValueType().isInteger())
665 SDValue False = N->getOperand(2);
666 EVT FalseTy = False.getValueType();
668 if (!FalseTy.isInteger())
671 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
673 // If the RHS (False) is 0, we swap the order of the operands
674 // of ISD::SELECT (obviously also inverting the condition) so that we can
675 // take advantage of conditional moves using the $0 register.
677 // return (a != 0) ? x : 0;
685 if (!FalseC->getZExtValue()) {
686 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
687 SDValue True = N->getOperand(1);
689 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
690 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
692 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
695 // If both operands are integer constants there's a possibility that we
696 // can do some interesting optimizations.
697 SDValue True = N->getOperand(1);
698 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
700 if (!TrueC || !True.getValueType().isInteger())
703 // We'll also ignore MVT::i64 operands as this optimizations proves
704 // to be ineffective because of the required sign extensions as the result
705 // of a SETCC operator is always MVT::i32 for non-vector types.
706 if (True.getValueType() == MVT::i64)
709 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
711 // 1) (a < x) ? y : y-1
713 // addiu $reg2, $reg1, y-1
715 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
717 // 2) (a < x) ? y-1 : y
719 // xor $reg1, $reg1, 1
720 // addiu $reg2, $reg1, y-1
722 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
723 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
724 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
725 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
728 // Couldn't optimize.
732 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
733 TargetLowering::DAGCombinerInfo &DCI,
734 const MipsSubtarget &Subtarget) {
735 if (DCI.isBeforeLegalizeOps())
738 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
740 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
741 if (!FalseC || FalseC->getZExtValue())
744 // Since RHS (False) is 0, we swap the order of the True/False operands
745 // (obviously also inverting the condition) so that we can
746 // take advantage of conditional moves using the $0 register.
748 // return (a != 0) ? x : 0;
751 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
754 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
755 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
756 ValueIfFalse, FCC, ValueIfTrue, Glue);
759 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
760 TargetLowering::DAGCombinerInfo &DCI,
761 const MipsSubtarget &Subtarget) {
762 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
765 SDValue FirstOperand = N->getOperand(0);
766 unsigned FirstOperandOpc = FirstOperand.getOpcode();
767 SDValue Mask = N->getOperand(1);
768 EVT ValTy = N->getValueType(0);
771 uint64_t Pos = 0, SMPos, SMSize;
776 // Op's second operand must be a shifted mask.
777 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
778 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
781 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
782 // Pattern match EXT.
783 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
784 // => ext $dst, $src, pos, size
786 // The second operand of the shift must be an immediate.
787 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
790 Pos = CN->getZExtValue();
792 // Return if the shifted mask does not start at bit 0 or the sum of its size
793 // and Pos exceeds the word's size.
794 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
798 NewOperand = FirstOperand.getOperand(0);
799 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
800 // Pattern match CINS.
801 // $dst = and (shl $src , pos), mask
802 // => cins $dst, $src, pos, size
803 // mask is a shifted mask with consecutive 1's, pos = shift amount,
804 // size = population count.
806 // The second operand of the shift must be an immediate.
807 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
810 Pos = CN->getZExtValue();
812 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
813 Pos + SMSize > ValTy.getSizeInBits())
816 NewOperand = FirstOperand.getOperand(0);
817 // SMSize is 'location' (position) in this case, not size.
821 // Pattern match EXT.
822 // $dst = and $src, (2**size - 1) , if size > 16
823 // => ext $dst, $src, pos, size , pos = 0
825 // If the mask is <= 0xffff, andi can be used instead.
826 if (CN->getZExtValue() <= 0xffff)
829 // Return if the mask doesn't start at position 0.
834 NewOperand = FirstOperand;
836 return DAG.getNode(Opc, DL, ValTy, NewOperand,
837 DAG.getConstant(Pos, DL, MVT::i32),
838 DAG.getConstant(SMSize, DL, MVT::i32));
841 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
842 TargetLowering::DAGCombinerInfo &DCI,
843 const MipsSubtarget &Subtarget) {
844 // Pattern match INS.
845 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
846 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
847 // => ins $dst, $src, size, pos, $src1
848 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
851 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
852 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
853 ConstantSDNode *CN, *CN1;
855 // See if Op's first operand matches (and $src1 , mask0).
856 if (And0.getOpcode() != ISD::AND)
859 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
860 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
863 // See if Op's second operand matches (and (shl $src, pos), mask1).
864 if (And1.getOpcode() == ISD::AND &&
865 And1.getOperand(0).getOpcode() == ISD::SHL) {
867 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
868 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
871 // The shift masks must have the same position and size.
872 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
875 SDValue Shl = And1.getOperand(0);
877 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
880 unsigned Shamt = CN->getZExtValue();
882 // Return if the shift amount and the first bit position of mask are not the
884 EVT ValTy = N->getValueType(0);
885 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
889 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
890 DAG.getConstant(SMPos0, DL, MVT::i32),
891 DAG.getConstant(SMSize0, DL, MVT::i32),
894 // Pattern match DINS.
895 // $dst = or (and $src, mask0), mask1
896 // where mask0 = ((1 << SMSize0) -1) << SMPos0
897 // => dins $dst, $src, pos, size
898 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
899 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
900 (SMSize0 + SMPos0 <= 32))) {
901 // Check if AND instruction has constant as argument
902 bool isConstCase = And1.getOpcode() != ISD::AND;
903 if (And1.getOpcode() == ISD::AND) {
904 if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
907 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
910 // Don't generate INS if constant OR operand doesn't fit into bits
911 // cleared by constant AND operand.
912 if (CN->getSExtValue() & CN1->getSExtValue())
916 EVT ValTy = N->getOperand(0)->getValueType(0);
920 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
921 SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
924 MipsISD::Ins, DL, N->getValueType(0),
926 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
928 DAG.getConstant(SMPos0, DL, MVT::i32),
929 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
932 And0->getOperand(0));
939 static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG,
940 const MipsSubtarget &Subtarget) {
941 // ROOTNode must have a multiplication as an operand for the match to be
943 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
944 ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
947 // We don't handle vector types here.
948 if (ROOTNode->getValueType(0).isVector())
951 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
953 // (add (mul a b) c) =>
954 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
955 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
957 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
959 // The overhead of setting up the Hi/Lo registers and reassembling the
960 // result makes this a dubious optimzation for MIPS64. The core of the
961 // problem is that Hi/Lo contain the upper and lower 32 bits of the
962 // operand and result.
964 // It requires a chain of 4 add/mul for MIPS64R2 to get better code
965 // density than doing it naively, 5 for MIPS64. Additionally, using
966 // madd/msub on MIPS64 requires the operands actually be 32 bit sign
967 // extended operands, not true 64 bit values.
969 // FIXME: For the moment, disable this completely for MIPS64.
970 if (Subtarget.hasMips64())
973 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
974 ? ROOTNode->getOperand(0)
975 : ROOTNode->getOperand(1);
977 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
978 ? ROOTNode->getOperand(1)
979 : ROOTNode->getOperand(0);
981 // Transform this to a MADD only if the user of this node is the add.
982 // If there are other users of the mul, this function returns here.
983 if (!Mult.hasOneUse())
986 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
987 // must be in canonical form, i.e. sign extended. For MIPS32, the operands
988 // of the multiply must have 32 or more sign bits, otherwise we cannot
989 // perform this optimization. We have to check this here as we're performing
990 // this optimization pre-legalization.
991 SDValue MultLHS = Mult->getOperand(0);
992 SDValue MultRHS = Mult->getOperand(1);
993 unsigned LHSSB = CurDAG.ComputeNumSignBits(MultLHS);
994 unsigned RHSSB = CurDAG.ComputeNumSignBits(MultRHS);
996 if (LHSSB < 32 || RHSSB < 32)
1000 APInt::getHighBitsSet(Mult->getValueType(0).getScalarSizeInBits(), 32);
1001 bool IsUnsigned = CurDAG.MaskedValueIsZero(Mult->getOperand(0), HighMask) &&
1002 CurDAG.MaskedValueIsZero(Mult->getOperand(1), HighMask) &&
1003 CurDAG.MaskedValueIsZero(AddOperand, HighMask);
1005 // Initialize accumulator.
1009 BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1010 CurDAG.getIntPtrConstant(0, DL));
1012 TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1013 CurDAG.getIntPtrConstant(1, DL));
1014 SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
1018 // Create MipsMAdd(u) / MipsMSub(u) node.
1019 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1020 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1021 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1022 SDValue MAddOps[3] = {
1023 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1024 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1025 EVT VTs[2] = {MVT::i32, MVT::i32};
1026 SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1028 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1029 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1031 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1035 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG,
1036 TargetLowering::DAGCombinerInfo &DCI,
1037 const MipsSubtarget &Subtarget) {
1038 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1039 if (DCI.isBeforeLegalizeOps()) {
1040 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1041 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1042 return performMADD_MSUBCombine(N, DAG, Subtarget);
1050 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
1051 TargetLowering::DAGCombinerInfo &DCI,
1052 const MipsSubtarget &Subtarget) {
1053 // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1054 if (DCI.isBeforeLegalizeOps()) {
1055 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1056 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1057 return performMADD_MSUBCombine(N, DAG, Subtarget);
1062 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1063 SDValue Add = N->getOperand(1);
1065 if (Add.getOpcode() != ISD::ADD)
1068 SDValue Lo = Add.getOperand(1);
1070 if ((Lo.getOpcode() != MipsISD::Lo) ||
1071 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1074 EVT ValTy = N->getValueType(0);
1077 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1079 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1082 static SDValue performAssertZextCombine(SDNode *N, SelectionDAG &DAG,
1083 TargetLowering::DAGCombinerInfo &DCI,
1084 const MipsSubtarget &Subtarget) {
1085 SDValue N0 = N->getOperand(0);
1086 EVT NarrowerVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1088 if (N0.getOpcode() != ISD::TRUNCATE)
1091 if (N0.getOperand(0).getOpcode() != ISD::AssertZext)
1094 // fold (AssertZext (trunc (AssertZext x))) -> (trunc (AssertZext x))
1095 // if the type of the extension of the innermost AssertZext node is
1096 // smaller from that of the outermost node, eg:
1097 // (AssertZext:i32 (trunc:i32 (AssertZext:i64 X, i32)), i8)
1098 // -> (trunc:i32 (AssertZext X, i8))
1099 SDValue WiderAssertZext = N0.getOperand(0);
1100 EVT WiderVT = cast<VTSDNode>(WiderAssertZext->getOperand(1))->getVT();
1102 if (NarrowerVT.bitsLT(WiderVT)) {
1103 SDValue NewAssertZext = DAG.getNode(
1104 ISD::AssertZext, SDLoc(N), WiderAssertZext.getValueType(),
1105 WiderAssertZext.getOperand(0), DAG.getValueType(NarrowerVT));
1106 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0),
1114 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
1115 TargetLowering::DAGCombinerInfo &DCI,
1116 const MipsSubtarget &Subtarget) {
1117 // Pattern match CINS.
1118 // $dst = shl (and $src , imm), pos
1119 // => cins $dst, $src, pos, size
1121 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1124 SDValue FirstOperand = N->getOperand(0);
1125 unsigned FirstOperandOpc = FirstOperand.getOpcode();
1126 SDValue SecondOperand = N->getOperand(1);
1127 EVT ValTy = N->getValueType(0);
1130 uint64_t Pos = 0, SMPos, SMSize;
1134 // The second operand of the shift must be an immediate.
1135 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1138 Pos = CN->getZExtValue();
1140 if (Pos >= ValTy.getSizeInBits())
1143 if (FirstOperandOpc != ISD::AND)
1146 // AND's second operand must be a shifted mask.
1147 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1148 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
1151 // Return if the shifted mask does not start at bit 0 or the sum of its size
1152 // and Pos exceeds the word's size.
1153 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1156 NewOperand = FirstOperand.getOperand(0);
1157 // SMSize is 'location' (position) in this case, not size.
1160 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1161 DAG.getConstant(Pos, DL, MVT::i32),
1162 DAG.getConstant(SMSize, DL, MVT::i32));
1165 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
1167 SelectionDAG &DAG = DCI.DAG;
1168 unsigned Opc = N->getOpcode();
1174 return performDivRemCombine(N, DAG, DCI, Subtarget);
1176 return performSELECTCombine(N, DAG, DCI, Subtarget);
1177 case MipsISD::CMovFP_F:
1178 case MipsISD::CMovFP_T:
1179 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1181 return performANDCombine(N, DAG, DCI, Subtarget);
1183 return performORCombine(N, DAG, DCI, Subtarget);
1185 return performADDCombine(N, DAG, DCI, Subtarget);
1186 case ISD::AssertZext:
1187 return performAssertZextCombine(N, DAG, DCI, Subtarget);
1189 return performSHLCombine(N, DAG, DCI, Subtarget);
1191 return performSUBCombine(N, DAG, DCI, Subtarget);
1197 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1198 return Subtarget.hasMips32();
1201 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1202 return Subtarget.hasMips32();
1206 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1207 SmallVectorImpl<SDValue> &Results,
1208 SelectionDAG &DAG) const {
1209 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1211 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1212 Results.push_back(Res.getValue(I));
1216 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1217 SmallVectorImpl<SDValue> &Results,
1218 SelectionDAG &DAG) const {
1219 return LowerOperationWrapper(N, Results, DAG);
1222 SDValue MipsTargetLowering::
1223 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1225 switch (Op.getOpcode())
1227 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1228 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1229 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1230 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1231 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1232 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1233 case ISD::SELECT: return lowerSELECT(Op, DAG);
1234 case ISD::SETCC: return lowerSETCC(Op, DAG);
1235 case ISD::VASTART: return lowerVASTART(Op, DAG);
1236 case ISD::VAARG: return lowerVAARG(Op, DAG);
1237 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1238 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1239 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1240 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1241 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1242 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1243 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1244 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1245 case ISD::LOAD: return lowerLOAD(Op, DAG);
1246 case ISD::STORE: return lowerSTORE(Op, DAG);
1247 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1248 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1253 //===----------------------------------------------------------------------===//
1254 // Lower helper functions
1255 //===----------------------------------------------------------------------===//
1257 // addLiveIn - This helper function adds the specified physical register to the
1258 // MachineFunction as a live in value. It also creates a corresponding
1259 // virtual register for it.
1261 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1263 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1264 MF.getRegInfo().addLiveIn(PReg, VReg);
1268 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1269 MachineBasicBlock &MBB,
1270 const TargetInstrInfo &TII,
1271 bool Is64Bit, bool IsMicroMips) {
1275 // Insert instruction "teq $divisor_reg, $zero, 7".
1276 MachineBasicBlock::iterator I(MI);
1277 MachineInstrBuilder MIB;
1278 MachineOperand &Divisor = MI.getOperand(2);
1279 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1280 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1281 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1285 // Use the 32-bit sub-register if this is a 64-bit division.
1287 MIB->getOperand(0).setSubReg(Mips::sub_32);
1289 // Clear Divisor's kill flag.
1290 Divisor.setIsKill(false);
1292 // We would normally delete the original instruction here but in this case
1293 // we only needed to inject an additional instruction rather than replace it.
1299 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1300 MachineBasicBlock *BB) const {
1301 switch (MI.getOpcode()) {
1303 llvm_unreachable("Unexpected instr type to insert");
1304 case Mips::ATOMIC_LOAD_ADD_I8:
1305 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1306 case Mips::ATOMIC_LOAD_ADD_I16:
1307 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1308 case Mips::ATOMIC_LOAD_ADD_I32:
1309 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
1310 case Mips::ATOMIC_LOAD_ADD_I64:
1311 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
1313 case Mips::ATOMIC_LOAD_AND_I8:
1314 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1315 case Mips::ATOMIC_LOAD_AND_I16:
1316 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1317 case Mips::ATOMIC_LOAD_AND_I32:
1318 return emitAtomicBinary(MI, BB, 4, Mips::AND);
1319 case Mips::ATOMIC_LOAD_AND_I64:
1320 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
1322 case Mips::ATOMIC_LOAD_OR_I8:
1323 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1324 case Mips::ATOMIC_LOAD_OR_I16:
1325 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1326 case Mips::ATOMIC_LOAD_OR_I32:
1327 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1328 case Mips::ATOMIC_LOAD_OR_I64:
1329 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1331 case Mips::ATOMIC_LOAD_XOR_I8:
1332 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1333 case Mips::ATOMIC_LOAD_XOR_I16:
1334 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1335 case Mips::ATOMIC_LOAD_XOR_I32:
1336 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1337 case Mips::ATOMIC_LOAD_XOR_I64:
1338 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1340 case Mips::ATOMIC_LOAD_NAND_I8:
1341 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1342 case Mips::ATOMIC_LOAD_NAND_I16:
1343 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1344 case Mips::ATOMIC_LOAD_NAND_I32:
1345 return emitAtomicBinary(MI, BB, 4, 0, true);
1346 case Mips::ATOMIC_LOAD_NAND_I64:
1347 return emitAtomicBinary(MI, BB, 8, 0, true);
1349 case Mips::ATOMIC_LOAD_SUB_I8:
1350 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1351 case Mips::ATOMIC_LOAD_SUB_I16:
1352 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1353 case Mips::ATOMIC_LOAD_SUB_I32:
1354 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1355 case Mips::ATOMIC_LOAD_SUB_I64:
1356 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1358 case Mips::ATOMIC_SWAP_I8:
1359 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1360 case Mips::ATOMIC_SWAP_I16:
1361 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1362 case Mips::ATOMIC_SWAP_I32:
1363 return emitAtomicBinary(MI, BB, 4, 0);
1364 case Mips::ATOMIC_SWAP_I64:
1365 return emitAtomicBinary(MI, BB, 8, 0);
1367 case Mips::ATOMIC_CMP_SWAP_I8:
1368 return emitAtomicCmpSwapPartword(MI, BB, 1);
1369 case Mips::ATOMIC_CMP_SWAP_I16:
1370 return emitAtomicCmpSwapPartword(MI, BB, 2);
1371 case Mips::ATOMIC_CMP_SWAP_I32:
1372 return emitAtomicCmpSwap(MI, BB, 4);
1373 case Mips::ATOMIC_CMP_SWAP_I64:
1374 return emitAtomicCmpSwap(MI, BB, 8);
1375 case Mips::PseudoSDIV:
1376 case Mips::PseudoUDIV:
1381 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1383 case Mips::SDIV_MM_Pseudo:
1384 case Mips::UDIV_MM_Pseudo:
1387 case Mips::DIV_MMR6:
1388 case Mips::DIVU_MMR6:
1389 case Mips::MOD_MMR6:
1390 case Mips::MODU_MMR6:
1391 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1392 case Mips::PseudoDSDIV:
1393 case Mips::PseudoDUDIV:
1398 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1399 case Mips::DDIV_MM64R6:
1400 case Mips::DDIVU_MM64R6:
1401 case Mips::DMOD_MM64R6:
1402 case Mips::DMODU_MM64R6:
1403 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, true);
1405 case Mips::SEL_D_MMR6:
1406 return emitSEL_D(MI, BB);
1408 case Mips::PseudoSELECT_I:
1409 case Mips::PseudoSELECT_I64:
1410 case Mips::PseudoSELECT_S:
1411 case Mips::PseudoSELECT_D32:
1412 case Mips::PseudoSELECT_D64:
1413 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1414 case Mips::PseudoSELECTFP_F_I:
1415 case Mips::PseudoSELECTFP_F_I64:
1416 case Mips::PseudoSELECTFP_F_S:
1417 case Mips::PseudoSELECTFP_F_D32:
1418 case Mips::PseudoSELECTFP_F_D64:
1419 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1420 case Mips::PseudoSELECTFP_T_I:
1421 case Mips::PseudoSELECTFP_T_I64:
1422 case Mips::PseudoSELECTFP_T_S:
1423 case Mips::PseudoSELECTFP_T_D32:
1424 case Mips::PseudoSELECTFP_T_D64:
1425 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1429 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1430 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1431 MachineBasicBlock *MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1432 MachineBasicBlock *BB,
1436 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1438 MachineFunction *MF = BB->getParent();
1439 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1440 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1441 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1442 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1443 DebugLoc DL = MI.getDebugLoc();
1444 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1451 LL = Subtarget.hasMips32r6()
1452 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1453 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1454 SC = Subtarget.hasMips32r6()
1455 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1456 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1464 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1465 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1468 ZERO = Mips::ZERO_64;
1472 unsigned OldVal = MI.getOperand(0).getReg();
1473 unsigned Ptr = MI.getOperand(1).getReg();
1474 unsigned Incr = MI.getOperand(2).getReg();
1476 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1477 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1478 unsigned Success = RegInfo.createVirtualRegister(RC);
1480 // insert new blocks after the current block
1481 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1482 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1483 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1484 MachineFunction::iterator It = ++BB->getIterator();
1485 MF->insert(It, loopMBB);
1486 MF->insert(It, exitMBB);
1488 // Transfer the remainder of BB and its successor edges to exitMBB.
1489 exitMBB->splice(exitMBB->begin(), BB,
1490 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1491 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1495 // fallthrough --> loopMBB
1496 BB->addSuccessor(loopMBB);
1497 loopMBB->addSuccessor(loopMBB);
1498 loopMBB->addSuccessor(exitMBB);
1501 // ll oldval, 0(ptr)
1502 // <binop> storeval, oldval, incr
1503 // sc success, storeval, 0(ptr)
1504 // beq success, $0, loopMBB
1506 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1508 // and andres, oldval, incr
1509 // nor storeval, $0, andres
1510 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1511 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1512 } else if (BinOpcode) {
1513 // <binop> storeval, oldval, incr
1514 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1518 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1519 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1521 MI.eraseFromParent(); // The instruction is gone now.
1526 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1527 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1528 unsigned SrcReg) const {
1529 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1530 const DebugLoc &DL = MI.getDebugLoc();
1532 if (Subtarget.hasMips32r2() && Size == 1) {
1533 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1537 if (Subtarget.hasMips32r2() && Size == 2) {
1538 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1542 MachineFunction *MF = BB->getParent();
1543 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1544 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1545 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1548 int64_t ShiftImm = 32 - (Size * 8);
1550 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1551 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1556 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1557 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1559 assert((Size == 1 || Size == 2) &&
1560 "Unsupported size for EmitAtomicBinaryPartial.");
1562 MachineFunction *MF = BB->getParent();
1563 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1564 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1565 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1566 const TargetRegisterClass *RCp =
1567 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1568 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1569 DebugLoc DL = MI.getDebugLoc();
1571 unsigned Dest = MI.getOperand(0).getReg();
1572 unsigned Ptr = MI.getOperand(1).getReg();
1573 unsigned Incr = MI.getOperand(2).getReg();
1575 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1576 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1577 unsigned Mask = RegInfo.createVirtualRegister(RC);
1578 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1579 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1580 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1581 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1582 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1583 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1584 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1585 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1586 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1587 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1588 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1589 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1590 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1591 unsigned Success = RegInfo.createVirtualRegister(RC);
1598 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1599 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1600 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1601 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1604 // insert new blocks after the current block
1605 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1606 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1607 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1608 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1609 MachineFunction::iterator It = ++BB->getIterator();
1610 MF->insert(It, loopMBB);
1611 MF->insert(It, sinkMBB);
1612 MF->insert(It, exitMBB);
1614 // Transfer the remainder of BB and its successor edges to exitMBB.
1615 exitMBB->splice(exitMBB->begin(), BB,
1616 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1617 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1619 BB->addSuccessor(loopMBB);
1620 loopMBB->addSuccessor(loopMBB);
1621 loopMBB->addSuccessor(sinkMBB);
1622 sinkMBB->addSuccessor(exitMBB);
1625 // addiu masklsb2,$0,-4 # 0xfffffffc
1626 // and alignedaddr,ptr,masklsb2
1627 // andi ptrlsb2,ptr,3
1628 // sll shiftamt,ptrlsb2,3
1629 // ori maskupper,$0,255 # 0xff
1630 // sll mask,maskupper,shiftamt
1631 // nor mask2,$0,mask
1632 // sll incr2,incr,shiftamt
1634 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1635 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1636 .addReg(ABI.GetNullPtr()).addImm(-4);
1637 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1638 .addReg(Ptr).addReg(MaskLSB2);
1639 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1640 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1641 if (Subtarget.isLittle()) {
1642 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1644 unsigned Off = RegInfo.createVirtualRegister(RC);
1645 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1646 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1647 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1649 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1650 .addReg(Mips::ZERO).addImm(MaskImm);
1651 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1652 .addReg(MaskUpper).addReg(ShiftAmt);
1653 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1654 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1656 // atomic.load.binop
1658 // ll oldval,0(alignedaddr)
1659 // binop binopres,oldval,incr2
1660 // and newval,binopres,mask
1661 // and maskedoldval0,oldval,mask2
1662 // or storeval,maskedoldval0,newval
1663 // sc success,storeval,0(alignedaddr)
1664 // beq success,$0,loopMBB
1668 // ll oldval,0(alignedaddr)
1669 // and newval,incr2,mask
1670 // and maskedoldval0,oldval,mask2
1671 // or storeval,maskedoldval0,newval
1672 // sc success,storeval,0(alignedaddr)
1673 // beq success,$0,loopMBB
1676 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1678 // and andres, oldval, incr2
1679 // nor binopres, $0, andres
1680 // and newval, binopres, mask
1681 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1682 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1683 .addReg(Mips::ZERO).addReg(AndRes);
1684 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1685 } else if (BinOpcode) {
1686 // <binop> binopres, oldval, incr2
1687 // and newval, binopres, mask
1688 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1689 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1690 } else { // atomic.swap
1691 // and newval, incr2, mask
1692 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1695 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1696 .addReg(OldVal).addReg(Mask2);
1697 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1698 .addReg(MaskedOldVal0).addReg(NewVal);
1699 BuildMI(BB, DL, TII->get(SC), Success)
1700 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1701 BuildMI(BB, DL, TII->get(Mips::BEQ))
1702 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1705 // and maskedoldval1,oldval,mask
1706 // srl srlres,maskedoldval1,shiftamt
1707 // sign_extend dest,srlres
1710 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1711 .addReg(OldVal).addReg(Mask);
1712 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1713 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1714 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1716 MI.eraseFromParent(); // The instruction is gone now.
1721 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1722 MachineBasicBlock *BB,
1723 unsigned Size) const {
1724 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1726 MachineFunction *MF = BB->getParent();
1727 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1728 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1729 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1730 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1731 DebugLoc DL = MI.getDebugLoc();
1732 unsigned LL, SC, ZERO, BNE, BEQ;
1739 LL = Subtarget.hasMips32r6()
1740 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1741 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1742 SC = Subtarget.hasMips32r6()
1743 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1744 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1751 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1752 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1753 ZERO = Mips::ZERO_64;
1758 unsigned Dest = MI.getOperand(0).getReg();
1759 unsigned Ptr = MI.getOperand(1).getReg();
1760 unsigned OldVal = MI.getOperand(2).getReg();
1761 unsigned NewVal = MI.getOperand(3).getReg();
1763 unsigned Success = RegInfo.createVirtualRegister(RC);
1765 // insert new blocks after the current block
1766 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1767 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1768 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1769 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1770 MachineFunction::iterator It = ++BB->getIterator();
1771 MF->insert(It, loop1MBB);
1772 MF->insert(It, loop2MBB);
1773 MF->insert(It, exitMBB);
1775 // Transfer the remainder of BB and its successor edges to exitMBB.
1776 exitMBB->splice(exitMBB->begin(), BB,
1777 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1778 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1782 // fallthrough --> loop1MBB
1783 BB->addSuccessor(loop1MBB);
1784 loop1MBB->addSuccessor(exitMBB);
1785 loop1MBB->addSuccessor(loop2MBB);
1786 loop2MBB->addSuccessor(loop1MBB);
1787 loop2MBB->addSuccessor(exitMBB);
1791 // bne dest, oldval, exitMBB
1793 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1794 BuildMI(BB, DL, TII->get(BNE))
1795 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1798 // sc success, newval, 0(ptr)
1799 // beq success, $0, loop1MBB
1801 BuildMI(BB, DL, TII->get(SC), Success)
1802 .addReg(NewVal).addReg(Ptr).addImm(0);
1803 BuildMI(BB, DL, TII->get(BEQ))
1804 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1806 MI.eraseFromParent(); // The instruction is gone now.
1811 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1812 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1813 assert((Size == 1 || Size == 2) &&
1814 "Unsupported size for EmitAtomicCmpSwapPartial.");
1816 MachineFunction *MF = BB->getParent();
1817 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1818 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1819 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1820 const TargetRegisterClass *RCp =
1821 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1822 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1823 DebugLoc DL = MI.getDebugLoc();
1825 unsigned Dest = MI.getOperand(0).getReg();
1826 unsigned Ptr = MI.getOperand(1).getReg();
1827 unsigned CmpVal = MI.getOperand(2).getReg();
1828 unsigned NewVal = MI.getOperand(3).getReg();
1830 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1831 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1832 unsigned Mask = RegInfo.createVirtualRegister(RC);
1833 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1834 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1835 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1836 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1837 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1838 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1839 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1840 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1841 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1842 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1843 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1844 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1845 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1846 unsigned Success = RegInfo.createVirtualRegister(RC);
1853 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1854 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1855 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1856 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1859 // insert new blocks after the current block
1860 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1861 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1862 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1863 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1864 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1865 MachineFunction::iterator It = ++BB->getIterator();
1866 MF->insert(It, loop1MBB);
1867 MF->insert(It, loop2MBB);
1868 MF->insert(It, sinkMBB);
1869 MF->insert(It, exitMBB);
1871 // Transfer the remainder of BB and its successor edges to exitMBB.
1872 exitMBB->splice(exitMBB->begin(), BB,
1873 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1874 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1876 BB->addSuccessor(loop1MBB);
1877 loop1MBB->addSuccessor(sinkMBB);
1878 loop1MBB->addSuccessor(loop2MBB);
1879 loop2MBB->addSuccessor(loop1MBB);
1880 loop2MBB->addSuccessor(sinkMBB);
1881 sinkMBB->addSuccessor(exitMBB);
1883 // FIXME: computation of newval2 can be moved to loop2MBB.
1885 // addiu masklsb2,$0,-4 # 0xfffffffc
1886 // and alignedaddr,ptr,masklsb2
1887 // andi ptrlsb2,ptr,3
1888 // xori ptrlsb2,ptrlsb2,3 # Only for BE
1889 // sll shiftamt,ptrlsb2,3
1890 // ori maskupper,$0,255 # 0xff
1891 // sll mask,maskupper,shiftamt
1892 // nor mask2,$0,mask
1893 // andi maskedcmpval,cmpval,255
1894 // sll shiftedcmpval,maskedcmpval,shiftamt
1895 // andi maskednewval,newval,255
1896 // sll shiftednewval,maskednewval,shiftamt
1897 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1898 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1899 .addReg(ABI.GetNullPtr()).addImm(-4);
1900 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1901 .addReg(Ptr).addReg(MaskLSB2);
1902 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1903 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1904 if (Subtarget.isLittle()) {
1905 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1907 unsigned Off = RegInfo.createVirtualRegister(RC);
1908 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1909 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1910 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1912 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1913 .addReg(Mips::ZERO).addImm(MaskImm);
1914 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1915 .addReg(MaskUpper).addReg(ShiftAmt);
1916 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1917 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1918 .addReg(CmpVal).addImm(MaskImm);
1919 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1920 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1921 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1922 .addReg(NewVal).addImm(MaskImm);
1923 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1924 .addReg(MaskedNewVal).addReg(ShiftAmt);
1927 // ll oldval,0(alginedaddr)
1928 // and maskedoldval0,oldval,mask
1929 // bne maskedoldval0,shiftedcmpval,sinkMBB
1931 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1932 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1933 .addReg(OldVal).addReg(Mask);
1934 BuildMI(BB, DL, TII->get(Mips::BNE))
1935 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1938 // and maskedoldval1,oldval,mask2
1939 // or storeval,maskedoldval1,shiftednewval
1940 // sc success,storeval,0(alignedaddr)
1941 // beq success,$0,loop1MBB
1943 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1944 .addReg(OldVal).addReg(Mask2);
1945 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1946 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1947 BuildMI(BB, DL, TII->get(SC), Success)
1948 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1949 BuildMI(BB, DL, TII->get(Mips::BEQ))
1950 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1953 // srl srlres,maskedoldval0,shiftamt
1954 // sign_extend dest,srlres
1957 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1958 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1959 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1961 MI.eraseFromParent(); // The instruction is gone now.
1966 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr &MI,
1967 MachineBasicBlock *BB) const {
1968 MachineFunction *MF = BB->getParent();
1969 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1970 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1971 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1972 DebugLoc DL = MI.getDebugLoc();
1973 MachineBasicBlock::iterator II(MI);
1975 unsigned Fc = MI.getOperand(1).getReg();
1976 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1978 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1980 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1983 .addImm(Mips::sub_lo);
1985 // We don't erase the original instruction, we just replace the condition
1986 // register with the 64-bit super-register.
1987 MI.getOperand(1).setReg(Fc2);
1992 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1993 // The first operand is the chain, the second is the condition, the third is
1994 // the block to branch to if the condition is true.
1995 SDValue Chain = Op.getOperand(0);
1996 SDValue Dest = Op.getOperand(2);
1999 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2000 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2002 // Return if flag is not set by a floating point comparison.
2003 if (CondRes.getOpcode() != MipsISD::FPCmp)
2006 SDValue CCNode = CondRes.getOperand(2);
2008 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2009 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
2010 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2011 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2012 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2013 FCC0, Dest, CondRes);
2016 SDValue MipsTargetLowering::
2017 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2019 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2020 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2022 // Return if flag is not set by a floating point comparison.
2023 if (Cond.getOpcode() != MipsISD::FPCmp)
2026 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2030 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2031 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2032 SDValue Cond = createFPCmp(DAG, Op);
2034 assert(Cond.getOpcode() == MipsISD::FPCmp &&
2035 "Floating point operand expected.");
2038 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2039 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2041 return createCMovFP(DAG, Cond, True, False, DL);
2044 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2045 SelectionDAG &DAG) const {
2046 EVT Ty = Op.getValueType();
2047 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2048 const GlobalValue *GV = N->getGlobal();
2050 if (!isPositionIndependent()) {
2051 const MipsTargetObjectFile *TLOF =
2052 static_cast<const MipsTargetObjectFile *>(
2053 getTargetMachine().getObjFileLowering());
2054 const GlobalObject *GO = GV->getBaseObject();
2055 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2056 // %gp_rel relocation
2057 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2059 // %hi/%lo relocation
2060 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2061 // %highest/%higher/%hi/%lo relocation
2062 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2065 // Every other architecture would use shouldAssumeDSOLocal in here, but
2067 // * In PIC code mips requires got loads even for local statics!
2068 // * To save on got entries, for local statics the got entry contains the
2069 // page and an additional add instruction takes care of the low bits.
2070 // * It is legal to access a hidden symbol with a non hidden undefined,
2071 // so one cannot guarantee that all access to a hidden symbol will know
2073 // * Mips linkers don't support creating a page and a full got entry for
2075 // * Given all that, we have to use a full got entry for hidden symbols :-(
2076 if (GV->hasLocalLinkage())
2077 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2080 return getAddrGlobalLargeGOT(
2081 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2083 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2085 return getAddrGlobal(
2086 N, SDLoc(N), Ty, DAG,
2087 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2088 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2091 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2092 SelectionDAG &DAG) const {
2093 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2094 EVT Ty = Op.getValueType();
2096 if (!isPositionIndependent())
2097 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2098 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2100 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2103 SDValue MipsTargetLowering::
2104 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2106 // If the relocation model is PIC, use the General Dynamic TLS Model or
2107 // Local Dynamic TLS model, otherwise use the Initial Exec or
2108 // Local Exec TLS Model.
2110 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2111 if (DAG.getTarget().Options.EmulatedTLS)
2112 return LowerToTLSEmulatedModel(GA, DAG);
2115 const GlobalValue *GV = GA->getGlobal();
2116 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2118 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2120 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2121 // General Dynamic and Local Dynamic TLS Model.
2122 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2125 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2126 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2127 getGlobalReg(DAG, PtrVT), TGA);
2128 unsigned PtrSize = PtrVT.getSizeInBits();
2129 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2131 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2135 Entry.Node = Argument;
2137 Args.push_back(Entry);
2139 TargetLowering::CallLoweringInfo CLI(DAG);
2141 .setChain(DAG.getEntryNode())
2142 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2143 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2145 SDValue Ret = CallResult.first;
2147 if (model != TLSModel::LocalDynamic)
2150 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2151 MipsII::MO_DTPREL_HI);
2152 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2153 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2154 MipsII::MO_DTPREL_LO);
2155 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2156 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2157 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2161 if (model == TLSModel::InitialExec) {
2162 // Initial Exec TLS Model
2163 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2164 MipsII::MO_GOTTPREL);
2165 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2168 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2170 // Local Exec TLS Model
2171 assert(model == TLSModel::LocalExec);
2172 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2173 MipsII::MO_TPREL_HI);
2174 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2175 MipsII::MO_TPREL_LO);
2176 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2177 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2178 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2181 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2182 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2185 SDValue MipsTargetLowering::
2186 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2188 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2189 EVT Ty = Op.getValueType();
2191 if (!isPositionIndependent())
2192 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2193 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2195 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2198 SDValue MipsTargetLowering::
2199 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2201 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2202 EVT Ty = Op.getValueType();
2204 if (!isPositionIndependent()) {
2205 const MipsTargetObjectFile *TLOF =
2206 static_cast<const MipsTargetObjectFile *>(
2207 getTargetMachine().getObjFileLowering());
2209 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2210 getTargetMachine()))
2211 // %gp_rel relocation
2212 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2214 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2215 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2218 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2221 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2222 MachineFunction &MF = DAG.getMachineFunction();
2223 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2226 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2227 getPointerTy(MF.getDataLayout()));
2229 // vastart just stores the address of the VarArgsFrameIndex slot into the
2230 // memory location argument.
2231 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2232 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2233 MachinePointerInfo(SV));
2236 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2237 SDNode *Node = Op.getNode();
2238 EVT VT = Node->getValueType(0);
2239 SDValue Chain = Node->getOperand(0);
2240 SDValue VAListPtr = Node->getOperand(1);
2241 unsigned Align = Node->getConstantOperandVal(3);
2242 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2244 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2246 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2247 VAListPtr, MachinePointerInfo(SV));
2248 SDValue VAList = VAListLoad;
2250 // Re-align the pointer if necessary.
2251 // It should only ever be necessary for 64-bit types on O32 since the minimum
2252 // argument alignment is the same as the maximum type alignment for N32/N64.
2254 // FIXME: We currently align too often. The code generator doesn't notice
2255 // when the pointer is still aligned from the last va_arg (or pair of
2256 // va_args for the i64 on O32 case).
2257 if (Align > getMinStackArgumentAlignment()) {
2258 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2260 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2261 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
2263 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2264 DAG.getConstant(-(int64_t)Align, DL,
2265 VAList.getValueType()));
2268 // Increment the pointer, VAList, to the next vaarg.
2269 auto &TD = DAG.getDataLayout();
2270 unsigned ArgSizeInBytes =
2271 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2273 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2274 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2275 DL, VAList.getValueType()));
2276 // Store the incremented VAList to the legalized pointer
2277 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2278 MachinePointerInfo(SV));
2280 // In big-endian mode we must adjust the pointer when the load size is smaller
2281 // than the argument slot size. We must also reduce the known alignment to
2282 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2283 // the correct half of the slot, and reduce the alignment from 8 (slot
2284 // alignment) down to 4 (type alignment).
2285 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2286 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2287 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2288 DAG.getIntPtrConstant(Adjustment, DL));
2290 // Load the actual argument out of the pointer VAList
2291 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2294 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2295 bool HasExtractInsert) {
2296 EVT TyX = Op.getOperand(0).getValueType();
2297 EVT TyY = Op.getOperand(1).getValueType();
2299 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2300 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2303 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2305 SDValue X = (TyX == MVT::f32) ?
2306 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2307 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2309 SDValue Y = (TyY == MVT::f32) ?
2310 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2311 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2314 if (HasExtractInsert) {
2315 // ext E, Y, 31, 1 ; extract bit31 of Y
2316 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2317 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2318 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2321 // srl SrlX, SllX, 1
2323 // sll SllY, SrlX, 31
2324 // or Or, SrlX, SllY
2325 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2326 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2327 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2328 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2329 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2332 if (TyX == MVT::f32)
2333 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2335 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2337 DAG.getConstant(0, DL, MVT::i32));
2338 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2341 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2342 bool HasExtractInsert) {
2343 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2344 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2345 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2347 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2349 // Bitcast to integer nodes.
2350 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2351 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2353 if (HasExtractInsert) {
2354 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2355 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2356 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2357 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2359 if (WidthX > WidthY)
2360 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2361 else if (WidthY > WidthX)
2362 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2364 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2365 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2367 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2370 // (d)sll SllX, X, 1
2371 // (d)srl SrlX, SllX, 1
2372 // (d)srl SrlY, Y, width(Y)-1
2373 // (d)sll SllY, SrlX, width(Y)-1
2374 // or Or, SrlX, SllY
2375 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2376 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2377 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2378 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2380 if (WidthX > WidthY)
2381 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2382 else if (WidthY > WidthX)
2383 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2385 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2386 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2387 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2388 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2392 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2393 if (Subtarget.isGP64bit())
2394 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2396 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2399 SDValue MipsTargetLowering::
2400 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2402 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2403 "Frame address can only be determined for current frame.");
2405 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2406 MFI.setFrameAddressIsTaken(true);
2407 EVT VT = Op.getValueType();
2409 SDValue FrameAddr = DAG.getCopyFromReg(
2410 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2414 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2415 SelectionDAG &DAG) const {
2416 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2420 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2421 "Return address can be determined only for current frame.");
2423 MachineFunction &MF = DAG.getMachineFunction();
2424 MachineFrameInfo &MFI = MF.getFrameInfo();
2425 MVT VT = Op.getSimpleValueType();
2426 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2427 MFI.setReturnAddressIsTaken(true);
2429 // Return RA, which contains the return address. Mark it an implicit live-in.
2430 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2431 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2434 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2435 // generated from __builtin_eh_return (offset, handler)
2436 // The effect of this is to adjust the stack pointer by "offset"
2437 // and then branch to "handler".
2438 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2440 MachineFunction &MF = DAG.getMachineFunction();
2441 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2443 MipsFI->setCallsEhReturn();
2444 SDValue Chain = Op.getOperand(0);
2445 SDValue Offset = Op.getOperand(1);
2446 SDValue Handler = Op.getOperand(2);
2448 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2450 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2451 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2452 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2453 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2454 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2455 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2456 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2457 DAG.getRegister(OffsetReg, Ty),
2458 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2462 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2463 SelectionDAG &DAG) const {
2464 // FIXME: Need pseudo-fence for 'singlethread' fences
2465 // FIXME: Set SType for weaker fences where supported/appropriate.
2468 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2469 DAG.getConstant(SType, DL, MVT::i32));
2472 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2473 SelectionDAG &DAG) const {
2475 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2477 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2478 SDValue Shamt = Op.getOperand(2);
2479 // if shamt < (VT.bits):
2480 // lo = (shl lo, shamt)
2481 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2484 // hi = (shl lo, shamt[4:0])
2485 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2486 DAG.getConstant(-1, DL, MVT::i32));
2487 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2488 DAG.getConstant(1, DL, VT));
2489 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2490 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2491 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2492 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2493 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2494 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2495 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2496 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2497 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2499 SDValue Ops[2] = {Lo, Hi};
2500 return DAG.getMergeValues(Ops, DL);
2503 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2506 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2507 SDValue Shamt = Op.getOperand(2);
2508 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2510 // if shamt < (VT.bits):
2511 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2513 // hi = (sra hi, shamt)
2515 // hi = (srl hi, shamt)
2518 // lo = (sra hi, shamt[4:0])
2519 // hi = (sra hi, 31)
2521 // lo = (srl hi, shamt[4:0])
2523 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2524 DAG.getConstant(-1, DL, MVT::i32));
2525 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2526 DAG.getConstant(1, DL, VT));
2527 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2528 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2529 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2530 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2532 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2533 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2534 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2535 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2536 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2537 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2538 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2540 SDValue Ops[2] = {Lo, Hi};
2541 return DAG.getMergeValues(Ops, DL);
2544 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2545 SDValue Chain, SDValue Src, unsigned Offset) {
2546 SDValue Ptr = LD->getBasePtr();
2547 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2548 EVT BasePtrVT = Ptr.getValueType();
2550 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2553 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2554 DAG.getConstant(Offset, DL, BasePtrVT));
2556 SDValue Ops[] = { Chain, Ptr, Src };
2557 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2558 LD->getMemOperand());
2561 // Expand an unaligned 32 or 64-bit integer load node.
2562 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2563 LoadSDNode *LD = cast<LoadSDNode>(Op);
2564 EVT MemVT = LD->getMemoryVT();
2566 if (Subtarget.systemSupportsUnalignedAccess())
2569 // Return if load is aligned or if MemVT is neither i32 nor i64.
2570 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2571 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2574 bool IsLittle = Subtarget.isLittle();
2575 EVT VT = Op.getValueType();
2576 ISD::LoadExtType ExtType = LD->getExtensionType();
2577 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2579 assert((VT == MVT::i32) || (VT == MVT::i64));
2582 // (set dst, (i64 (load baseptr)))
2584 // (set tmp, (ldl (add baseptr, 7), undef))
2585 // (set dst, (ldr baseptr, tmp))
2586 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2587 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2589 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2593 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2595 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2599 // (set dst, (i32 (load baseptr))) or
2600 // (set dst, (i64 (sextload baseptr))) or
2601 // (set dst, (i64 (extload baseptr)))
2603 // (set tmp, (lwl (add baseptr, 3), undef))
2604 // (set dst, (lwr baseptr, tmp))
2605 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2606 (ExtType == ISD::EXTLOAD))
2609 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2612 // (set dst, (i64 (zextload baseptr)))
2614 // (set tmp0, (lwl (add baseptr, 3), undef))
2615 // (set tmp1, (lwr baseptr, tmp0))
2616 // (set tmp2, (shl tmp1, 32))
2617 // (set dst, (srl tmp2, 32))
2619 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2620 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2621 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2622 SDValue Ops[] = { SRL, LWR.getValue(1) };
2623 return DAG.getMergeValues(Ops, DL);
2626 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2627 SDValue Chain, unsigned Offset) {
2628 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2629 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2631 SDVTList VTList = DAG.getVTList(MVT::Other);
2634 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2635 DAG.getConstant(Offset, DL, BasePtrVT));
2637 SDValue Ops[] = { Chain, Value, Ptr };
2638 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2639 SD->getMemOperand());
2642 // Expand an unaligned 32 or 64-bit integer store node.
2643 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2645 SDValue Value = SD->getValue(), Chain = SD->getChain();
2646 EVT VT = Value.getValueType();
2649 // (store val, baseptr) or
2650 // (truncstore val, baseptr)
2652 // (swl val, (add baseptr, 3))
2653 // (swr val, baseptr)
2654 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2655 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2657 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2660 assert(VT == MVT::i64);
2663 // (store val, baseptr)
2665 // (sdl val, (add baseptr, 7))
2666 // (sdr val, baseptr)
2667 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2668 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2671 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2672 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2673 SDValue Val = SD->getValue();
2675 if (Val.getOpcode() != ISD::FP_TO_SINT)
2678 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2679 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2681 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2682 SD->getPointerInfo(), SD->getAlignment(),
2683 SD->getMemOperand()->getFlags());
2686 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2687 StoreSDNode *SD = cast<StoreSDNode>(Op);
2688 EVT MemVT = SD->getMemoryVT();
2690 // Lower unaligned integer stores.
2691 if (!Subtarget.systemSupportsUnalignedAccess() &&
2692 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2693 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2694 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2696 return lowerFP_TO_SINT_STORE(SD, DAG);
2699 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2700 SelectionDAG &DAG) const {
2702 // Return a fixed StackObject with offset 0 which points to the old stack
2704 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2705 EVT ValTy = Op->getValueType(0);
2706 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2707 return DAG.getFrameIndex(FI, ValTy);
2710 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2711 SelectionDAG &DAG) const {
2712 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2713 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2715 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2718 //===----------------------------------------------------------------------===//
2719 // Calling Convention Implementation
2720 //===----------------------------------------------------------------------===//
2722 //===----------------------------------------------------------------------===//
2723 // TODO: Implement a generic logic using tblgen that can support this.
2724 // Mips O32 ABI rules:
2726 // i32 - Passed in A0, A1, A2, A3 and stack
2727 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2728 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2729 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2730 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2731 // not used, it must be shadowed. If only A3 is available, shadow it and
2733 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2734 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2735 // with the remainder spilled to the stack.
2736 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2737 // spilling the remainder to the stack.
2739 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2740 //===----------------------------------------------------------------------===//
2742 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2743 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2744 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2745 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2746 State.getMachineFunction().getSubtarget());
2748 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2750 const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2752 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2754 static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2756 // Do not process byval args here.
2757 if (ArgFlags.isByVal())
2760 // Promote i8 and i16
2761 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2762 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2764 if (ArgFlags.isSExt())
2765 LocInfo = CCValAssign::SExtUpper;
2766 else if (ArgFlags.isZExt())
2767 LocInfo = CCValAssign::ZExtUpper;
2769 LocInfo = CCValAssign::AExtUpper;
2773 // Promote i8 and i16
2774 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2776 if (ArgFlags.isSExt())
2777 LocInfo = CCValAssign::SExt;
2778 else if (ArgFlags.isZExt())
2779 LocInfo = CCValAssign::ZExt;
2781 LocInfo = CCValAssign::AExt;
2786 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2787 // is true: function is vararg, argument is 3rd or higher, there is previous
2788 // argument which is not f32 or f64.
2789 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2790 State.getFirstUnallocated(F32Regs) != ValNo;
2791 unsigned OrigAlign = ArgFlags.getOrigAlign();
2792 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2793 bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2795 // The MIPS vector ABI for floats passes them in a pair of registers
2796 if (ValVT == MVT::i32 && isVectorFloat) {
2797 // This is the start of an vector that was scalarized into an unknown number
2798 // of components. It doesn't matter how many there are. Allocate one of the
2799 // notional 8 byte aligned registers which map onto the argument stack, and
2800 // shadow the register lost to alignment requirements.
2801 if (ArgFlags.isSplit()) {
2802 Reg = State.AllocateReg(FloatVectorIntRegs);
2803 if (Reg == Mips::A2)
2804 State.AllocateReg(Mips::A1);
2806 State.AllocateReg(Mips::A3);
2808 // If we're an intermediate component of the split, we can just attempt to
2809 // allocate a register directly.
2810 Reg = State.AllocateReg(IntRegs);
2812 } else if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2813 Reg = State.AllocateReg(IntRegs);
2814 // If this is the first part of an i64 arg,
2815 // the allocated register must be either A0 or A2.
2816 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2817 Reg = State.AllocateReg(IntRegs);
2819 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2820 // Allocate int register and shadow next int register. If first
2821 // available register is Mips::A1 or Mips::A3, shadow it too.
2822 Reg = State.AllocateReg(IntRegs);
2823 if (Reg == Mips::A1 || Reg == Mips::A3)
2824 Reg = State.AllocateReg(IntRegs);
2825 State.AllocateReg(IntRegs);
2827 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2828 // we are guaranteed to find an available float register
2829 if (ValVT == MVT::f32) {
2830 Reg = State.AllocateReg(F32Regs);
2831 // Shadow int register
2832 State.AllocateReg(IntRegs);
2834 Reg = State.AllocateReg(F64Regs);
2835 // Shadow int registers
2836 unsigned Reg2 = State.AllocateReg(IntRegs);
2837 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2838 State.AllocateReg(IntRegs);
2839 State.AllocateReg(IntRegs);
2842 llvm_unreachable("Cannot handle this ValVT.");
2845 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2847 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2849 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2854 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2855 MVT LocVT, CCValAssign::LocInfo LocInfo,
2856 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2857 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2859 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2862 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2863 MVT LocVT, CCValAssign::LocInfo LocInfo,
2864 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2865 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2867 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2870 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2871 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2872 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2874 #include "MipsGenCallingConv.inc"
2876 //===----------------------------------------------------------------------===//
2877 // Call Calling Convention Implementation
2878 //===----------------------------------------------------------------------===//
2880 // Return next O32 integer argument register.
2881 static unsigned getNextIntArgReg(unsigned Reg) {
2882 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2883 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2886 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2887 SDValue Chain, SDValue Arg,
2888 const SDLoc &DL, bool IsTailCall,
2889 SelectionDAG &DAG) const {
2892 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2893 DAG.getIntPtrConstant(Offset, DL));
2894 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
2897 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2898 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2899 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2900 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2901 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
2904 void MipsTargetLowering::
2905 getOpndList(SmallVectorImpl<SDValue> &Ops,
2906 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2907 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2908 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2909 SDValue Chain) const {
2910 // Insert node "GP copy globalreg" before call to function.
2912 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2913 // in PIC mode) allow symbols to be resolved via lazy binding.
2914 // The lazy binding stub requires GP to point to the GOT.
2915 // Note that we don't need GP to point to the GOT for indirect calls
2916 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2917 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2918 // used for the function (that is, Mips linker doesn't generate lazy binding
2919 // stub for a function whose address is taken in the program).
2920 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2921 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2922 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2923 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2926 // Build a sequence of copy-to-reg nodes chained together with token
2927 // chain and flag operands which copy the outgoing args into registers.
2928 // The InFlag in necessary since all emitted instructions must be
2932 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2933 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2934 RegsToPass[i].second, InFlag);
2935 InFlag = Chain.getValue(1);
2938 // Add argument registers to the end of the list so that they are
2939 // known live into the call.
2940 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2941 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2942 RegsToPass[i].second.getValueType()));
2944 // Add a register mask operand representing the call-preserved registers.
2945 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2946 const uint32_t *Mask =
2947 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2948 assert(Mask && "Missing call preserved mask for calling convention");
2949 if (Subtarget.inMips16HardFloat()) {
2950 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2951 llvm::StringRef Sym = G->getGlobal()->getName();
2952 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2953 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2954 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2958 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2960 if (InFlag.getNode())
2961 Ops.push_back(InFlag);
2964 /// LowerCall - functions arguments are copied from virtual regs to
2965 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2967 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2968 SmallVectorImpl<SDValue> &InVals) const {
2969 SelectionDAG &DAG = CLI.DAG;
2971 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2972 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2973 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2974 SDValue Chain = CLI.Chain;
2975 SDValue Callee = CLI.Callee;
2976 bool &IsTailCall = CLI.IsTailCall;
2977 CallingConv::ID CallConv = CLI.CallConv;
2978 bool IsVarArg = CLI.IsVarArg;
2980 MachineFunction &MF = DAG.getMachineFunction();
2981 MachineFrameInfo &MFI = MF.getFrameInfo();
2982 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2983 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2984 bool IsPIC = isPositionIndependent();
2986 // Analyze operands of the call, assigning locations to each operand.
2987 SmallVector<CCValAssign, 16> ArgLocs;
2989 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2990 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2992 // Allocate the reserved argument area. It seems strange to do this from the
2993 // caller side but removing it breaks the frame size calculation.
2994 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2996 const ExternalSymbolSDNode *ES =
2997 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
2998 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
2999 ES ? ES->getSymbol() : nullptr);
3001 // Get a count of how many bytes are to be pushed on the stack.
3002 unsigned NextStackOffset = CCInfo.getNextStackOffset();
3004 // Check if it's really possible to do a tail call. Restrict it to functions
3005 // that are part of this compilation unit.
3006 bool InternalLinkage = false;
3008 IsTailCall = isEligibleForTailCallOptimization(
3009 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3010 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3011 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3012 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3013 G->getGlobal()->hasPrivateLinkage() ||
3014 G->getGlobal()->hasHiddenVisibility() ||
3015 G->getGlobal()->hasProtectedVisibility());
3018 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3019 report_fatal_error("failed to perform tail call elimination on a call "
3020 "site marked musttail");
3025 // Chain is the output chain of the last Load/Store or CopyToReg node.
3026 // ByValChain is the output chain of the last Memcpy node created for copying
3027 // byval arguments to the stack.
3028 unsigned StackAlignment = TFL->getStackAlignment();
3029 NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3030 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3033 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3036 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3037 getPointerTy(DAG.getDataLayout()));
3039 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3040 SmallVector<SDValue, 8> MemOpChains;
3042 CCInfo.rewindByValRegsInfo();
3044 // Walk the register/memloc assignments, inserting copies/loads.
3045 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3046 SDValue Arg = OutVals[i];
3047 CCValAssign &VA = ArgLocs[i];
3048 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3049 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3050 bool UseUpperBits = false;
3053 if (Flags.isByVal()) {
3054 unsigned FirstByValReg, LastByValReg;
3055 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3056 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3058 assert(Flags.getByValSize() &&
3059 "ByVal args of size 0 should have been ignored by front-end.");
3060 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3061 assert(!IsTailCall &&
3062 "Do not tail-call optimize if there is a byval argument.");
3063 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3064 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3066 CCInfo.nextInRegsParam();
3070 // Promote the value if needed.
3071 switch (VA.getLocInfo()) {
3073 llvm_unreachable("Unknown loc info!");
3074 case CCValAssign::Full:
3075 if (VA.isRegLoc()) {
3076 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3077 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3078 (ValVT == MVT::i64 && LocVT == MVT::f64))
3079 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3080 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3081 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3082 Arg, DAG.getConstant(0, DL, MVT::i32));
3083 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3084 Arg, DAG.getConstant(1, DL, MVT::i32));
3085 if (!Subtarget.isLittle())
3087 unsigned LocRegLo = VA.getLocReg();
3088 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3089 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3090 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3095 case CCValAssign::BCvt:
3096 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3098 case CCValAssign::SExtUpper:
3099 UseUpperBits = true;
3101 case CCValAssign::SExt:
3102 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3104 case CCValAssign::ZExtUpper:
3105 UseUpperBits = true;
3107 case CCValAssign::ZExt:
3108 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3110 case CCValAssign::AExtUpper:
3111 UseUpperBits = true;
3113 case CCValAssign::AExt:
3114 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3119 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3120 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3122 ISD::SHL, DL, VA.getLocVT(), Arg,
3123 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3126 // Arguments that can be passed on register must be kept at
3127 // RegsToPass vector
3128 if (VA.isRegLoc()) {
3129 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3133 // Register can't get to this point...
3134 assert(VA.isMemLoc());
3136 // emit ISD::STORE whichs stores the
3137 // parameter value to a stack Location
3138 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3139 Chain, Arg, DL, IsTailCall, DAG));
3142 // Transform all store nodes into one single node because all store
3143 // nodes are independent of each other.
3144 if (!MemOpChains.empty())
3145 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3147 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3148 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3149 // node so that legalize doesn't hack it.
3152 EVT Ty = Callee.getValueType();
3153 bool GlobalOrExternal = false, IsCallReloc = false;
3155 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3157 const GlobalValue *Val = G->getGlobal();
3158 InternalLinkage = Val->hasInternalLinkage();
3160 if (InternalLinkage)
3161 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3162 else if (LargeGOT) {
3163 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3164 MipsII::MO_CALL_LO16, Chain,
3165 FuncInfo->callPtrInfo(Val));
3168 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3169 FuncInfo->callPtrInfo(Val));
3173 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3174 getPointerTy(DAG.getDataLayout()), 0,
3175 MipsII::MO_NO_FLAG);
3176 GlobalOrExternal = true;
3178 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3179 const char *Sym = S->getSymbol();
3181 if (!IsPIC) // static
3182 Callee = DAG.getTargetExternalSymbol(
3183 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
3184 else if (LargeGOT) {
3185 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3186 MipsII::MO_CALL_LO16, Chain,
3187 FuncInfo->callPtrInfo(Sym));
3190 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3191 FuncInfo->callPtrInfo(Sym));
3195 GlobalOrExternal = true;
3198 SmallVector<SDValue, 8> Ops(1, Chain);
3199 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3201 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3202 IsCallReloc, CLI, Callee, Chain);
3205 MF.getFrameInfo().setHasTailCall();
3206 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3209 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3210 SDValue InFlag = Chain.getValue(1);
3212 // Create the CALLSEQ_END node.
3213 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3214 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3215 InFlag = Chain.getValue(1);
3217 // Handle result values, copying them out of physregs into vregs that we
3219 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3223 /// LowerCallResult - Lower the result values of a call into the
3224 /// appropriate copies out of appropriate physical registers.
3225 SDValue MipsTargetLowering::LowerCallResult(
3226 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3227 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3228 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3229 TargetLowering::CallLoweringInfo &CLI) const {
3230 // Assign locations to each value returned by this call.
3231 SmallVector<CCValAssign, 16> RVLocs;
3232 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3235 const ExternalSymbolSDNode *ES =
3236 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3237 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3238 ES ? ES->getSymbol() : nullptr);
3240 // Copy all of the result registers out of their specified physreg.
3241 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3242 CCValAssign &VA = RVLocs[i];
3243 assert(VA.isRegLoc() && "Can only return in registers!");
3245 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3246 RVLocs[i].getLocVT(), InFlag);
3247 Chain = Val.getValue(1);
3248 InFlag = Val.getValue(2);
3250 if (VA.isUpperBitsInLoc()) {
3251 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3252 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3254 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3256 Shift, DL, VA.getLocVT(), Val,
3257 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3260 switch (VA.getLocInfo()) {
3262 llvm_unreachable("Unknown loc info!");
3263 case CCValAssign::Full:
3265 case CCValAssign::BCvt:
3266 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3268 case CCValAssign::AExt:
3269 case CCValAssign::AExtUpper:
3270 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3272 case CCValAssign::ZExt:
3273 case CCValAssign::ZExtUpper:
3274 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3275 DAG.getValueType(VA.getValVT()));
3276 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3278 case CCValAssign::SExt:
3279 case CCValAssign::SExtUpper:
3280 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3281 DAG.getValueType(VA.getValVT()));
3282 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3286 InVals.push_back(Val);
3292 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3293 EVT ArgVT, const SDLoc &DL,
3294 SelectionDAG &DAG) {
3295 MVT LocVT = VA.getLocVT();
3296 EVT ValVT = VA.getValVT();
3298 // Shift into the upper bits if necessary.
3299 switch (VA.getLocInfo()) {
3302 case CCValAssign::AExtUpper:
3303 case CCValAssign::SExtUpper:
3304 case CCValAssign::ZExtUpper: {
3305 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3306 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3308 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3310 Opcode, DL, VA.getLocVT(), Val,
3311 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3316 // If this is an value smaller than the argument slot size (32-bit for O32,
3317 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3318 // size. Extract the value and insert any appropriate assertions regarding
3319 // sign/zero extension.
3320 switch (VA.getLocInfo()) {
3322 llvm_unreachable("Unknown loc info!");
3323 case CCValAssign::Full:
3325 case CCValAssign::AExtUpper:
3326 case CCValAssign::AExt:
3327 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3329 case CCValAssign::SExtUpper:
3330 case CCValAssign::SExt:
3331 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3332 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3334 case CCValAssign::ZExtUpper:
3335 case CCValAssign::ZExt:
3336 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3337 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3339 case CCValAssign::BCvt:
3340 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3347 //===----------------------------------------------------------------------===//
3348 // Formal Arguments Calling Convention Implementation
3349 //===----------------------------------------------------------------------===//
3350 /// LowerFormalArguments - transform physical registers into virtual registers
3351 /// and generate load operations for arguments places on the stack.
3352 SDValue MipsTargetLowering::LowerFormalArguments(
3353 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3354 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3355 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3356 MachineFunction &MF = DAG.getMachineFunction();
3357 MachineFrameInfo &MFI = MF.getFrameInfo();
3358 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3360 MipsFI->setVarArgsFrameIndex(0);
3362 // Used with vargs to acumulate store chains.
3363 std::vector<SDValue> OutChains;
3365 // Assign locations to all of the incoming arguments.
3366 SmallVector<CCValAssign, 16> ArgLocs;
3367 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3369 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3370 const Function *Func = DAG.getMachineFunction().getFunction();
3371 Function::const_arg_iterator FuncArg = Func->arg_begin();
3373 if (Func->hasFnAttribute("interrupt") && !Func->arg_empty())
3375 "Functions with the interrupt attribute cannot have arguments!");
3377 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3378 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3379 CCInfo.getInRegsParamsCount() > 0);
3381 unsigned CurArgIdx = 0;
3382 CCInfo.rewindByValRegsInfo();
3384 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3385 CCValAssign &VA = ArgLocs[i];
3386 if (Ins[i].isOrigArg()) {
3387 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3388 CurArgIdx = Ins[i].getOrigArgIndex();
3390 EVT ValVT = VA.getValVT();
3391 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3392 bool IsRegLoc = VA.isRegLoc();
3394 if (Flags.isByVal()) {
3395 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3396 unsigned FirstByValReg, LastByValReg;
3397 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3398 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3400 assert(Flags.getByValSize() &&
3401 "ByVal args of size 0 should have been ignored by front-end.");
3402 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3403 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3404 FirstByValReg, LastByValReg, VA, CCInfo);
3405 CCInfo.nextInRegsParam();
3409 // Arguments stored on registers
3411 MVT RegVT = VA.getLocVT();
3412 unsigned ArgReg = VA.getLocReg();
3413 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3415 // Transform the arguments stored on
3416 // physical registers into virtual ones
3417 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3418 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3420 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3422 // Handle floating point arguments passed in integer registers and
3423 // long double arguments passed in floating point registers.
3424 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3425 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3426 (RegVT == MVT::f64 && ValVT == MVT::i64))
3427 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3428 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3429 ValVT == MVT::f64) {
3430 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3431 getNextIntArgReg(ArgReg), RC);
3432 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3433 if (!Subtarget.isLittle())
3434 std::swap(ArgValue, ArgValue2);
3435 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3436 ArgValue, ArgValue2);
3439 InVals.push_back(ArgValue);
3440 } else { // VA.isRegLoc()
3441 MVT LocVT = VA.getLocVT();
3444 // We ought to be able to use LocVT directly but O32 sets it to i32
3445 // when allocating floating point values to integer registers.
3446 // This shouldn't influence how we load the value into registers unless
3447 // we are targeting softfloat.
3448 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3449 LocVT = VA.getValVT();
3453 assert(VA.isMemLoc());
3455 // The stack pointer offset is relative to the caller stack frame.
3456 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3457 VA.getLocMemOffset(), true);
3459 // Create load nodes to retrieve arguments from the stack
3460 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3461 SDValue ArgValue = DAG.getLoad(
3462 LocVT, DL, Chain, FIN,
3463 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3464 OutChains.push_back(ArgValue.getValue(1));
3466 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3468 InVals.push_back(ArgValue);
3472 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3473 // The mips ABIs for returning structs by value requires that we copy
3474 // the sret argument into $v0 for the return. Save the argument into
3475 // a virtual register so that we can access it from the return points.
3476 if (Ins[i].Flags.isSRet()) {
3477 unsigned Reg = MipsFI->getSRetReturnReg();
3479 Reg = MF.getRegInfo().createVirtualRegister(
3480 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3481 MipsFI->setSRetReturnReg(Reg);
3483 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3484 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3490 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3492 // All stores are grouped in one node to allow the matching between
3493 // the size of Ins and InVals. This only happens when on varg functions
3494 if (!OutChains.empty()) {
3495 OutChains.push_back(Chain);
3496 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3502 //===----------------------------------------------------------------------===//
3503 // Return Value Calling Convention Implementation
3504 //===----------------------------------------------------------------------===//
3507 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3508 MachineFunction &MF, bool IsVarArg,
3509 const SmallVectorImpl<ISD::OutputArg> &Outs,
3510 LLVMContext &Context) const {
3511 SmallVector<CCValAssign, 16> RVLocs;
3512 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3513 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3517 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3518 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3519 if (Type == MVT::i32)
3526 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3528 SelectionDAG &DAG) const {
3530 MachineFunction &MF = DAG.getMachineFunction();
3531 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3535 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3539 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3541 const SmallVectorImpl<ISD::OutputArg> &Outs,
3542 const SmallVectorImpl<SDValue> &OutVals,
3543 const SDLoc &DL, SelectionDAG &DAG) const {
3544 // CCValAssign - represent the assignment of
3545 // the return value to a location
3546 SmallVector<CCValAssign, 16> RVLocs;
3547 MachineFunction &MF = DAG.getMachineFunction();
3549 // CCState - Info about the registers and stack slot.
3550 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3552 // Analyze return values.
3553 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3556 SmallVector<SDValue, 4> RetOps(1, Chain);
3558 // Copy the result values into the output registers.
3559 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3560 SDValue Val = OutVals[i];
3561 CCValAssign &VA = RVLocs[i];
3562 assert(VA.isRegLoc() && "Can only return in registers!");
3563 bool UseUpperBits = false;
3565 switch (VA.getLocInfo()) {
3567 llvm_unreachable("Unknown loc info!");
3568 case CCValAssign::Full:
3570 case CCValAssign::BCvt:
3571 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3573 case CCValAssign::AExtUpper:
3574 UseUpperBits = true;
3576 case CCValAssign::AExt:
3577 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3579 case CCValAssign::ZExtUpper:
3580 UseUpperBits = true;
3582 case CCValAssign::ZExt:
3583 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3585 case CCValAssign::SExtUpper:
3586 UseUpperBits = true;
3588 case CCValAssign::SExt:
3589 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3594 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3595 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3597 ISD::SHL, DL, VA.getLocVT(), Val,
3598 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3601 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3603 // Guarantee that all emitted copies are stuck together with flags.
3604 Flag = Chain.getValue(1);
3605 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3608 // The mips ABIs for returning structs by value requires that we copy
3609 // the sret argument into $v0 for the return. We saved the argument into
3610 // a virtual register in the entry block, so now we copy the value out
3612 if (MF.getFunction()->hasStructRetAttr()) {
3613 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3614 unsigned Reg = MipsFI->getSRetReturnReg();
3617 llvm_unreachable("sret virtual register not created in the entry block");
3619 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3620 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3622 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3623 Flag = Chain.getValue(1);
3624 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3627 RetOps[0] = Chain; // Update chain.
3629 // Add the flag if we have it.
3631 RetOps.push_back(Flag);
3633 // ISRs must use "eret".
3634 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
3635 return LowerInterruptReturn(RetOps, DL, DAG);
3637 // Standard return on Mips is a "jr $ra"
3638 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3641 //===----------------------------------------------------------------------===//
3642 // Mips Inline Assembly Support
3643 //===----------------------------------------------------------------------===//
3645 /// getConstraintType - Given a constraint letter, return the type of
3646 /// constraint it is for this target.
3647 MipsTargetLowering::ConstraintType
3648 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3649 // Mips specific constraints
3650 // GCC config/mips/constraints.md
3652 // 'd' : An address register. Equivalent to r
3653 // unless generating MIPS16 code.
3654 // 'y' : Equivalent to r; retained for
3655 // backwards compatibility.
3656 // 'c' : A register suitable for use in an indirect
3657 // jump. This will always be $25 for -mabicalls.
3658 // 'l' : The lo register. 1 word storage.
3659 // 'x' : The hilo register pair. Double word storage.
3660 if (Constraint.size() == 1) {
3661 switch (Constraint[0]) {
3669 return C_RegisterClass;
3675 if (Constraint == "ZC")
3678 return TargetLowering::getConstraintType(Constraint);
3681 /// Examine constraint type and operand type and determine a weight value.
3682 /// This object must already have been set up with the operand type
3683 /// and the current alternative constraint selected.
3684 TargetLowering::ConstraintWeight
3685 MipsTargetLowering::getSingleConstraintMatchWeight(
3686 AsmOperandInfo &info, const char *constraint) const {
3687 ConstraintWeight weight = CW_Invalid;
3688 Value *CallOperandVal = info.CallOperandVal;
3689 // If we don't have a value, we can't do a match,
3690 // but allow it at the lowest weight.
3691 if (!CallOperandVal)
3693 Type *type = CallOperandVal->getType();
3694 // Look at the constraint type.
3695 switch (*constraint) {
3697 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3701 if (type->isIntegerTy())
3702 weight = CW_Register;
3704 case 'f': // FPU or MSA register
3705 if (Subtarget.hasMSA() && type->isVectorTy() &&
3706 cast<VectorType>(type)->getBitWidth() == 128)
3707 weight = CW_Register;
3708 else if (type->isFloatTy())
3709 weight = CW_Register;
3711 case 'c': // $25 for indirect jumps
3712 case 'l': // lo register
3713 case 'x': // hilo register pair
3714 if (type->isIntegerTy())
3715 weight = CW_SpecificReg;
3717 case 'I': // signed 16 bit immediate
3718 case 'J': // integer zero
3719 case 'K': // unsigned 16 bit immediate
3720 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3721 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3722 case 'O': // signed 15 bit immediate (+- 16383)
3723 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3724 if (isa<ConstantInt>(CallOperandVal))
3725 weight = CW_Constant;
3734 /// This is a helper function to parse a physical register string and split it
3735 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3736 /// that is returned indicates whether parsing was successful. The second flag
3737 /// is true if the numeric part exists.
3738 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3739 unsigned long long &Reg) {
3740 if (C.front() != '{' || C.back() != '}')
3741 return std::make_pair(false, false);
3743 // Search for the first numeric character.
3744 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3745 I = std::find_if(B, E, isdigit);
3747 Prefix = StringRef(B, I - B);
3749 // The second flag is set to false if no numeric characters were found.
3751 return std::make_pair(true, false);
3753 // Parse the numeric characters.
3754 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3758 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3759 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3760 const TargetRegisterInfo *TRI =
3761 Subtarget.getRegisterInfo();
3762 const TargetRegisterClass *RC;
3764 unsigned long long Reg;
3766 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3769 return std::make_pair(0U, nullptr);
3771 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3772 // No numeric characters follow "hi" or "lo".
3774 return std::make_pair(0U, nullptr);
3776 RC = TRI->getRegClass(Prefix == "hi" ?
3777 Mips::HI32RegClassID : Mips::LO32RegClassID);
3778 return std::make_pair(*(RC->begin()), RC);
3779 } else if (Prefix.startswith("$msa")) {
3780 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3782 // No numeric characters follow the name.
3784 return std::make_pair(0U, nullptr);
3786 Reg = StringSwitch<unsigned long long>(Prefix)
3787 .Case("$msair", Mips::MSAIR)
3788 .Case("$msacsr", Mips::MSACSR)
3789 .Case("$msaaccess", Mips::MSAAccess)
3790 .Case("$msasave", Mips::MSASave)
3791 .Case("$msamodify", Mips::MSAModify)
3792 .Case("$msarequest", Mips::MSARequest)
3793 .Case("$msamap", Mips::MSAMap)
3794 .Case("$msaunmap", Mips::MSAUnmap)
3798 return std::make_pair(0U, nullptr);
3800 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3801 return std::make_pair(Reg, RC);
3805 return std::make_pair(0U, nullptr);
3807 if (Prefix == "$f") { // Parse $f0-$f31.
3808 // If the size of FP registers is 64-bit or Reg is an even number, select
3809 // the 64-bit register class. Otherwise, select the 32-bit register class.
3810 if (VT == MVT::Other)
3811 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3813 RC = getRegClassFor(VT);
3815 if (RC == &Mips::AFGR64RegClass) {
3816 assert(Reg % 2 == 0);
3819 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3820 RC = TRI->getRegClass(Mips::FCCRegClassID);
3821 else if (Prefix == "$w") { // Parse $w0-$w31.
3822 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3823 } else { // Parse $0-$31.
3824 assert(Prefix == "$");
3825 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3828 assert(Reg < RC->getNumRegs());
3829 return std::make_pair(*(RC->begin() + Reg), RC);
3832 /// Given a register class constraint, like 'r', if this corresponds directly
3833 /// to an LLVM register class, return a register of 0 and the register class
3835 std::pair<unsigned, const TargetRegisterClass *>
3836 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3837 StringRef Constraint,
3839 if (Constraint.size() == 1) {
3840 switch (Constraint[0]) {
3841 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3842 case 'y': // Same as 'r'. Exists for compatibility.
3844 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3845 if (Subtarget.inMips16Mode())
3846 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3847 return std::make_pair(0U, &Mips::GPR32RegClass);
3849 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3850 return std::make_pair(0U, &Mips::GPR32RegClass);
3851 if (VT == MVT::i64 && Subtarget.isGP64bit())
3852 return std::make_pair(0U, &Mips::GPR64RegClass);
3853 // This will generate an error message
3854 return std::make_pair(0U, nullptr);
3855 case 'f': // FPU or MSA register
3856 if (VT == MVT::v16i8)
3857 return std::make_pair(0U, &Mips::MSA128BRegClass);
3858 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3859 return std::make_pair(0U, &Mips::MSA128HRegClass);
3860 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3861 return std::make_pair(0U, &Mips::MSA128WRegClass);
3862 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3863 return std::make_pair(0U, &Mips::MSA128DRegClass);
3864 else if (VT == MVT::f32)
3865 return std::make_pair(0U, &Mips::FGR32RegClass);
3866 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3867 if (Subtarget.isFP64bit())
3868 return std::make_pair(0U, &Mips::FGR64RegClass);
3869 return std::make_pair(0U, &Mips::AFGR64RegClass);
3872 case 'c': // register suitable for indirect jump
3874 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3875 assert(VT == MVT::i64 && "Unexpected type.");
3876 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3877 case 'l': // register suitable for indirect jump
3879 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3880 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3881 case 'x': // register suitable for indirect jump
3882 // Fixme: Not triggering the use of both hi and low
3883 // This will generate an error message
3884 return std::make_pair(0U, nullptr);
3888 std::pair<unsigned, const TargetRegisterClass *> R;
3889 R = parseRegForInlineAsmConstraint(Constraint, VT);
3894 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3897 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3898 /// vector. If it is invalid, don't add anything to Ops.
3899 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3900 std::string &Constraint,
3901 std::vector<SDValue>&Ops,
3902 SelectionDAG &DAG) const {
3906 // Only support length 1 constraints for now.
3907 if (Constraint.length() > 1) return;
3909 char ConstraintLetter = Constraint[0];
3910 switch (ConstraintLetter) {
3911 default: break; // This will fall through to the generic implementation
3912 case 'I': // Signed 16 bit constant
3913 // If this fails, the parent routine will give an error
3914 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3915 EVT Type = Op.getValueType();
3916 int64_t Val = C->getSExtValue();
3917 if (isInt<16>(Val)) {
3918 Result = DAG.getTargetConstant(Val, DL, Type);
3923 case 'J': // integer zero
3924 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3925 EVT Type = Op.getValueType();
3926 int64_t Val = C->getZExtValue();
3928 Result = DAG.getTargetConstant(0, DL, Type);
3933 case 'K': // unsigned 16 bit immediate
3934 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3935 EVT Type = Op.getValueType();
3936 uint64_t Val = (uint64_t)C->getZExtValue();
3937 if (isUInt<16>(Val)) {
3938 Result = DAG.getTargetConstant(Val, DL, Type);
3943 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3945 EVT Type = Op.getValueType();
3946 int64_t Val = C->getSExtValue();
3947 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3948 Result = DAG.getTargetConstant(Val, DL, Type);
3953 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3954 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3955 EVT Type = Op.getValueType();
3956 int64_t Val = C->getSExtValue();
3957 if ((Val >= -65535) && (Val <= -1)) {
3958 Result = DAG.getTargetConstant(Val, DL, Type);
3963 case 'O': // signed 15 bit immediate
3964 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3965 EVT Type = Op.getValueType();
3966 int64_t Val = C->getSExtValue();
3967 if ((isInt<15>(Val))) {
3968 Result = DAG.getTargetConstant(Val, DL, Type);
3973 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3974 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3975 EVT Type = Op.getValueType();
3976 int64_t Val = C->getSExtValue();
3977 if ((Val <= 65535) && (Val >= 1)) {
3978 Result = DAG.getTargetConstant(Val, DL, Type);
3985 if (Result.getNode()) {
3986 Ops.push_back(Result);
3990 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3993 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3994 const AddrMode &AM, Type *Ty,
3995 unsigned AS) const {
3996 // No global is ever allowed as a base.
4001 case 0: // "r+i" or just "i", depending on HasBaseReg.
4004 if (!AM.HasBaseReg) // allow "r+i".
4006 return false; // disallow "r+r" or "r+r+i".
4015 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4016 // The Mips target isn't yet aware of offsets.
4020 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
4022 bool IsMemset, bool ZeroMemset,
4024 MachineFunction &MF) const {
4025 if (Subtarget.hasMips64())
4031 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4032 if (VT != MVT::f32 && VT != MVT::f64)
4034 if (Imm.isNegZero())
4036 return Imm.isZero();
4039 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4041 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4042 if (ABI.IsN64() && isPositionIndependent())
4043 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4045 return TargetLowering::getJumpTableEncoding();
4048 bool MipsTargetLowering::useSoftFloat() const {
4049 return Subtarget.useSoftFloat();
4052 void MipsTargetLowering::copyByValRegs(
4053 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4054 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4055 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4056 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4057 MipsCCState &State) const {
4058 MachineFunction &MF = DAG.getMachineFunction();
4059 MachineFrameInfo &MFI = MF.getFrameInfo();
4060 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4061 unsigned NumRegs = LastReg - FirstReg;
4062 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4063 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4065 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4069 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4070 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4072 FrameObjOffset = VA.getLocMemOffset();
4074 // Create frame object.
4075 EVT PtrTy = getPointerTy(DAG.getDataLayout());
4076 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, true);
4077 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4078 InVals.push_back(FIN);
4083 // Copy arg registers.
4084 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4085 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4087 for (unsigned I = 0; I < NumRegs; ++I) {
4088 unsigned ArgReg = ByValArgRegs[FirstReg + I];
4089 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4090 unsigned Offset = I * GPRSizeInBytes;
4091 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4092 DAG.getConstant(Offset, DL, PtrTy));
4093 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4094 StorePtr, MachinePointerInfo(FuncArg, Offset));
4095 OutChains.push_back(Store);
4099 // Copy byVal arg to registers and stack.
4100 void MipsTargetLowering::passByValArg(
4101 SDValue Chain, const SDLoc &DL,
4102 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4103 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4104 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4105 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4106 const CCValAssign &VA) const {
4107 unsigned ByValSizeInBytes = Flags.getByValSize();
4108 unsigned OffsetInBytes = 0; // From beginning of struct
4109 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4110 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
4111 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4112 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4113 unsigned NumRegs = LastReg - FirstReg;
4116 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4117 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4120 // Copy words to registers.
4121 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4122 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4123 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4124 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4125 MachinePointerInfo(), Alignment);
4126 MemOpChains.push_back(LoadVal.getValue(1));
4127 unsigned ArgReg = ArgRegs[FirstReg + I];
4128 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4131 // Return if the struct has been fully copied.
4132 if (ByValSizeInBytes == OffsetInBytes)
4135 // Copy the remainder of the byval argument with sub-word loads and shifts.
4136 if (LeftoverBytes) {
4139 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4140 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4141 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4143 if (RemainingSizeInBytes < LoadSizeInBytes)
4147 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4148 DAG.getConstant(OffsetInBytes, DL,
4150 SDValue LoadVal = DAG.getExtLoad(
4151 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4152 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4153 MemOpChains.push_back(LoadVal.getValue(1));
4155 // Shift the loaded value.
4159 Shamt = TotalBytesLoaded * 8;
4161 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4163 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4164 DAG.getConstant(Shamt, DL, MVT::i32));
4167 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4171 OffsetInBytes += LoadSizeInBytes;
4172 TotalBytesLoaded += LoadSizeInBytes;
4173 Alignment = std::min(Alignment, LoadSizeInBytes);
4176 unsigned ArgReg = ArgRegs[FirstReg + I];
4177 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4182 // Copy remainder of byval arg to it with memcpy.
4183 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4184 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4185 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4186 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4187 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4188 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4189 DAG.getConstant(MemCpySize, DL, PtrTy),
4190 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4191 /*isTailCall=*/false,
4192 MachinePointerInfo(), MachinePointerInfo());
4193 MemOpChains.push_back(Chain);
4196 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4197 SDValue Chain, const SDLoc &DL,
4199 CCState &State) const {
4200 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
4201 unsigned Idx = State.getFirstUnallocated(ArgRegs);
4202 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4203 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4204 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4205 MachineFunction &MF = DAG.getMachineFunction();
4206 MachineFrameInfo &MFI = MF.getFrameInfo();
4207 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4209 // Offset of the first variable argument from stack pointer.
4212 if (ArgRegs.size() == Idx)
4213 VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4216 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4217 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4220 // Record the frame index of the first variable argument
4221 // which is a value necessary to VASTART.
4222 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4223 MipsFI->setVarArgsFrameIndex(FI);
4225 // Copy the integer registers that have not been used for argument passing
4226 // to the argument register save area. For O32, the save area is allocated
4227 // in the caller's stack frame, while for N32/64, it is allocated in the
4228 // callee's stack frame.
4229 for (unsigned I = Idx; I < ArgRegs.size();
4230 ++I, VaArgOffset += RegSizeInBytes) {
4231 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4232 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4233 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4234 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4236 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4237 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4239 OutChains.push_back(Store);
4243 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4244 unsigned Align) const {
4245 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4247 assert(Size && "Byval argument's size shouldn't be 0.");
4249 Align = std::min(Align, TFL->getStackAlignment());
4251 unsigned FirstReg = 0;
4252 unsigned NumRegs = 0;
4254 if (State->getCallingConv() != CallingConv::Fast) {
4255 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4256 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4257 // FIXME: The O32 case actually describes no shadow registers.
4258 const MCPhysReg *ShadowRegs =
4259 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4261 // We used to check the size as well but we can't do that anymore since
4262 // CCState::HandleByVal() rounds up the size after calling this function.
4263 assert(!(Align % RegSizeInBytes) &&
4264 "Byval argument's alignment should be a multiple of"
4267 FirstReg = State->getFirstUnallocated(IntArgRegs);
4269 // If Align > RegSizeInBytes, the first arg register must be even.
4270 // FIXME: This condition happens to do the right thing but it's not the
4271 // right way to test it. We want to check that the stack frame offset
4272 // of the register is aligned.
4273 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4274 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4278 // Mark the registers allocated.
4279 Size = alignTo(Size, RegSizeInBytes);
4280 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4281 Size -= RegSizeInBytes, ++I, ++NumRegs)
4282 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4285 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4288 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4289 MachineBasicBlock *BB,
4291 unsigned Opc) const {
4292 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4293 "Subtarget already supports SELECT nodes with the use of"
4294 "conditional-move instructions.");
4296 const TargetInstrInfo *TII =
4297 Subtarget.getInstrInfo();
4298 DebugLoc DL = MI.getDebugLoc();
4300 // To "insert" a SELECT instruction, we actually have to insert the
4301 // diamond control-flow pattern. The incoming instruction knows the
4302 // destination vreg to set, the condition code register to branch on, the
4303 // true/false values to select between, and a branch opcode to use.
4304 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4305 MachineFunction::iterator It = ++BB->getIterator();
4311 // bNE r1, r0, copy1MBB
4312 // fallthrough --> copy0MBB
4313 MachineBasicBlock *thisMBB = BB;
4314 MachineFunction *F = BB->getParent();
4315 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4316 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4317 F->insert(It, copy0MBB);
4318 F->insert(It, sinkMBB);
4320 // Transfer the remainder of BB and its successor edges to sinkMBB.
4321 sinkMBB->splice(sinkMBB->begin(), BB,
4322 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4323 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4325 // Next, add the true and fallthrough blocks as its successors.
4326 BB->addSuccessor(copy0MBB);
4327 BB->addSuccessor(sinkMBB);
4330 // bc1[tf] cc, sinkMBB
4331 BuildMI(BB, DL, TII->get(Opc))
4332 .addReg(MI.getOperand(1).getReg())
4335 // bne rs, $0, sinkMBB
4336 BuildMI(BB, DL, TII->get(Opc))
4337 .addReg(MI.getOperand(1).getReg())
4343 // %FalseValue = ...
4344 // # fallthrough to sinkMBB
4347 // Update machine-CFG edges
4348 BB->addSuccessor(sinkMBB);
4351 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4355 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4356 .addReg(MI.getOperand(2).getReg())
4358 .addReg(MI.getOperand(3).getReg())
4361 MI.eraseFromParent(); // The pseudo instruction is gone now.
4366 // FIXME? Maybe this could be a TableGen attribute on some registers and
4367 // this table could be generated automatically from RegInfo.
4368 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4369 SelectionDAG &DAG) const {
4370 // Named registers is expected to be fairly rare. For now, just support $28
4371 // since the linux kernel uses it.
4372 if (Subtarget.isGP64bit()) {
4373 unsigned Reg = StringSwitch<unsigned>(RegName)
4374 .Case("$28", Mips::GP_64)
4379 unsigned Reg = StringSwitch<unsigned>(RegName)
4380 .Case("$28", Mips::GP)
4385 report_fatal_error("Invalid register name global variable");