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 "MipsMachineFunction.h"
18 #include "MipsSubtarget.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsTargetObjectFile.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "mips-lower"
44 STATISTIC(NumTailCalls, "Number of tail calls");
47 LargeGOT("mxgot", cl::Hidden,
48 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
51 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
52 cl::desc("MIPS: Don't trap on integer division by zero."),
56 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
57 cl::desc("Allow mips-fast-isel to be used"),
60 static const MCPhysReg O32IntRegs[4] = {
61 Mips::A0, Mips::A1, Mips::A2, Mips::A3
64 static const MCPhysReg Mips64IntRegs[8] = {
65 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
66 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
69 static const MCPhysReg Mips64DPRegs[8] = {
70 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
71 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
74 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode);
77 class MipsCCState : public CCState {
79 /// Identify lowered values that originated from f128 arguments and record
80 /// this for use by RetCC_MipsN.
82 PreAnalyzeCallResultForF128(const SmallVectorImpl<ISD::InputArg> &Ins,
83 const TargetLowering::CallLoweringInfo &CLI) {
84 for (unsigned i = 0; i < Ins.size(); ++i)
85 OriginalArgWasF128.push_back(
86 originalTypeIsF128(CLI.RetTy, CLI.Callee.getNode()));
89 /// Identify lowered values that originated from f128 arguments and record
90 /// this for use by RetCC_MipsN.
91 void PreAnalyzeReturnForF128(const SmallVectorImpl<ISD::OutputArg> &Outs) {
92 const MachineFunction &MF = getMachineFunction();
93 for (unsigned i = 0; i < Outs.size(); ++i)
94 OriginalArgWasF128.push_back(
95 originalTypeIsF128(MF.getFunction()->getReturnType(), nullptr));
98 /// Identify lowered values that originated from f128 arguments and record
100 void PreAnalyzeCallOperandsForF128(
101 const SmallVectorImpl<ISD::OutputArg> &Outs,
102 std::vector<TargetLowering::ArgListEntry> &FuncArgs, SDNode *CallNode) {
103 for (unsigned i = 0; i < Outs.size(); ++i)
104 OriginalArgWasF128.push_back(
105 originalTypeIsF128(FuncArgs[Outs[i].OrigArgIndex].Ty, CallNode));
108 /// Identify lowered values that originated from f128 arguments and record
111 PreAnalyzeFormalArgumentsForF128(const SmallVectorImpl<ISD::InputArg> &Ins) {
112 const MachineFunction &MF = getMachineFunction();
113 for (unsigned i = 0; i < Ins.size(); ++i) {
114 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
116 // SRet arguments cannot originate from f128 or {f128} returns so we just
117 // push false. We have to handle this specially since SRet arguments
118 // aren't mapped to an original argument.
119 if (Ins[i].Flags.isSRet()) {
120 OriginalArgWasF128.push_back(false);
124 assert(Ins[i].OrigArgIndex < MF.getFunction()->arg_size());
125 std::advance(FuncArg, Ins[i].OrigArgIndex);
126 OriginalArgWasF128.push_back(
127 originalTypeIsF128(FuncArg->getType(), nullptr));
131 /// Records whether the value has been lowered from an f128.
132 SmallVector<bool, 4> OriginalArgWasF128;
135 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
136 // to allow analyzeCallOperands to be removed incrementally.
137 void PreAnalyzeCallOperandsForF128_(
138 const SmallVectorImpl<ISD::OutputArg> &Outs,
139 std::vector<TargetLowering::ArgListEntry> &FuncArgs, SDNode *CallNode) {
140 PreAnalyzeCallOperandsForF128(Outs, FuncArgs, CallNode);
142 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
143 // to allow analyzeFormalArguments to be removed incrementally.
145 PreAnalyzeFormalArgumentsForF128_(const SmallVectorImpl<ISD::InputArg> &Ins) {
146 PreAnalyzeFormalArgumentsForF128(Ins);
148 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
149 // to clean up after the above functions.
150 void ClearOriginalArgWasF128() { OriginalArgWasF128.clear(); }
152 MipsCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
153 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C)
154 : CCState(CC, isVarArg, MF, locs, C) {}
156 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
158 const TargetLowering::CallLoweringInfo &CLI) {
159 PreAnalyzeCallResultForF128(Ins, CLI);
160 CCState::AnalyzeCallResult(Ins, Fn);
161 OriginalArgWasF128.clear();
164 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
166 PreAnalyzeReturnForF128(Outs);
167 CCState::AnalyzeReturn(Outs, Fn);
168 OriginalArgWasF128.clear();
171 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
173 PreAnalyzeReturnForF128(ArgsFlags);
174 bool Return = CCState::CheckReturn(ArgsFlags, Fn);
175 OriginalArgWasF128.clear();
179 bool WasOriginalArgF128(unsigned ValNo) { return OriginalArgWasF128[ValNo]; }
183 // If I is a shifted mask, set the size (Size) and the first bit of the
184 // mask (Pos), and return true.
185 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
186 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
187 if (!isShiftedMask_64(I))
190 Size = CountPopulation_64(I);
191 Pos = countTrailingZeros(I);
195 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
196 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
197 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
200 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
202 unsigned Flag) const {
203 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
206 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
208 unsigned Flag) const {
209 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
212 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
214 unsigned Flag) const {
215 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
218 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
220 unsigned Flag) const {
221 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
224 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
226 unsigned Flag) const {
227 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
228 N->getOffset(), Flag);
231 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
233 case MipsISD::JmpLink: return "MipsISD::JmpLink";
234 case MipsISD::TailCall: return "MipsISD::TailCall";
235 case MipsISD::Hi: return "MipsISD::Hi";
236 case MipsISD::Lo: return "MipsISD::Lo";
237 case MipsISD::GPRel: return "MipsISD::GPRel";
238 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
239 case MipsISD::Ret: return "MipsISD::Ret";
240 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
241 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
242 case MipsISD::FPCmp: return "MipsISD::FPCmp";
243 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
244 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
245 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
246 case MipsISD::MFHI: return "MipsISD::MFHI";
247 case MipsISD::MFLO: return "MipsISD::MFLO";
248 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
249 case MipsISD::Mult: return "MipsISD::Mult";
250 case MipsISD::Multu: return "MipsISD::Multu";
251 case MipsISD::MAdd: return "MipsISD::MAdd";
252 case MipsISD::MAddu: return "MipsISD::MAddu";
253 case MipsISD::MSub: return "MipsISD::MSub";
254 case MipsISD::MSubu: return "MipsISD::MSubu";
255 case MipsISD::DivRem: return "MipsISD::DivRem";
256 case MipsISD::DivRemU: return "MipsISD::DivRemU";
257 case MipsISD::DivRem16: return "MipsISD::DivRem16";
258 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
259 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
260 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
261 case MipsISD::Wrapper: return "MipsISD::Wrapper";
262 case MipsISD::Sync: return "MipsISD::Sync";
263 case MipsISD::Ext: return "MipsISD::Ext";
264 case MipsISD::Ins: return "MipsISD::Ins";
265 case MipsISD::LWL: return "MipsISD::LWL";
266 case MipsISD::LWR: return "MipsISD::LWR";
267 case MipsISD::SWL: return "MipsISD::SWL";
268 case MipsISD::SWR: return "MipsISD::SWR";
269 case MipsISD::LDL: return "MipsISD::LDL";
270 case MipsISD::LDR: return "MipsISD::LDR";
271 case MipsISD::SDL: return "MipsISD::SDL";
272 case MipsISD::SDR: return "MipsISD::SDR";
273 case MipsISD::EXTP: return "MipsISD::EXTP";
274 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
275 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
276 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
277 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
278 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
279 case MipsISD::SHILO: return "MipsISD::SHILO";
280 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
281 case MipsISD::MULT: return "MipsISD::MULT";
282 case MipsISD::MULTU: return "MipsISD::MULTU";
283 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
284 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
285 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
286 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
287 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
288 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
289 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
290 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
291 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
292 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
293 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
294 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
295 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
296 case MipsISD::VCEQ: return "MipsISD::VCEQ";
297 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
298 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
299 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
300 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
301 case MipsISD::VSMAX: return "MipsISD::VSMAX";
302 case MipsISD::VSMIN: return "MipsISD::VSMIN";
303 case MipsISD::VUMAX: return "MipsISD::VUMAX";
304 case MipsISD::VUMIN: return "MipsISD::VUMIN";
305 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
306 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
307 case MipsISD::VNOR: return "MipsISD::VNOR";
308 case MipsISD::VSHF: return "MipsISD::VSHF";
309 case MipsISD::SHF: return "MipsISD::SHF";
310 case MipsISD::ILVEV: return "MipsISD::ILVEV";
311 case MipsISD::ILVOD: return "MipsISD::ILVOD";
312 case MipsISD::ILVL: return "MipsISD::ILVL";
313 case MipsISD::ILVR: return "MipsISD::ILVR";
314 case MipsISD::PCKEV: return "MipsISD::PCKEV";
315 case MipsISD::PCKOD: return "MipsISD::PCKOD";
316 case MipsISD::INSVE: return "MipsISD::INSVE";
317 default: return nullptr;
321 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
322 const MipsSubtarget &STI)
323 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
324 // Mips does not have i1 type, so use i32 for
325 // setcc operations results (slt, sgt, ...).
326 setBooleanContents(ZeroOrOneBooleanContent);
327 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
328 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
329 // does. Integer booleans still use 0 and 1.
330 if (Subtarget.hasMips32r6())
331 setBooleanContents(ZeroOrOneBooleanContent,
332 ZeroOrNegativeOneBooleanContent);
334 // Load extented operations for i1 types must be promoted
335 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
336 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
337 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
339 // MIPS doesn't have extending float->double load/store
340 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
341 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
343 // Used by legalize types to correctly generate the setcc result.
344 // Without this, every float setcc comes with a AND/OR with the result,
345 // we don't want this, since the fpcmp result goes to a flag register,
346 // which is used implicitly by brcond and select operations.
347 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
349 // Mips Custom Operations
350 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
351 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
352 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
353 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
354 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
355 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
356 setOperationAction(ISD::SELECT, MVT::f32, Custom);
357 setOperationAction(ISD::SELECT, MVT::f64, Custom);
358 setOperationAction(ISD::SELECT, MVT::i32, Custom);
359 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
360 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
361 setOperationAction(ISD::SETCC, MVT::f32, Custom);
362 setOperationAction(ISD::SETCC, MVT::f64, Custom);
363 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
364 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
365 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
366 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
368 if (Subtarget.isGP64bit()) {
369 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
370 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
371 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
372 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
373 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
374 setOperationAction(ISD::SELECT, MVT::i64, Custom);
375 setOperationAction(ISD::LOAD, MVT::i64, Custom);
376 setOperationAction(ISD::STORE, MVT::i64, Custom);
377 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
380 if (!Subtarget.isGP64bit()) {
381 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
382 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
383 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
386 setOperationAction(ISD::ADD, MVT::i32, Custom);
387 if (Subtarget.isGP64bit())
388 setOperationAction(ISD::ADD, MVT::i64, Custom);
390 setOperationAction(ISD::SDIV, MVT::i32, Expand);
391 setOperationAction(ISD::SREM, MVT::i32, Expand);
392 setOperationAction(ISD::UDIV, MVT::i32, Expand);
393 setOperationAction(ISD::UREM, MVT::i32, Expand);
394 setOperationAction(ISD::SDIV, MVT::i64, Expand);
395 setOperationAction(ISD::SREM, MVT::i64, Expand);
396 setOperationAction(ISD::UDIV, MVT::i64, Expand);
397 setOperationAction(ISD::UREM, MVT::i64, Expand);
399 // Operations not directly supported by Mips.
400 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
401 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
402 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
403 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
404 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
405 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
406 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
407 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
408 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
409 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
410 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
411 if (Subtarget.hasCnMips()) {
412 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
413 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
415 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
416 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
418 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
419 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
420 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
421 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
422 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
424 setOperationAction(ISD::ROTL, MVT::i32, Expand);
425 setOperationAction(ISD::ROTL, MVT::i64, Expand);
426 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
427 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
429 if (!Subtarget.hasMips32r2())
430 setOperationAction(ISD::ROTR, MVT::i32, Expand);
432 if (!Subtarget.hasMips64r2())
433 setOperationAction(ISD::ROTR, MVT::i64, Expand);
435 setOperationAction(ISD::FSIN, MVT::f32, Expand);
436 setOperationAction(ISD::FSIN, MVT::f64, Expand);
437 setOperationAction(ISD::FCOS, MVT::f32, Expand);
438 setOperationAction(ISD::FCOS, MVT::f64, Expand);
439 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
440 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
441 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
442 setOperationAction(ISD::FPOW, MVT::f32, Expand);
443 setOperationAction(ISD::FPOW, MVT::f64, Expand);
444 setOperationAction(ISD::FLOG, MVT::f32, Expand);
445 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
446 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
447 setOperationAction(ISD::FEXP, MVT::f32, Expand);
448 setOperationAction(ISD::FMA, MVT::f32, Expand);
449 setOperationAction(ISD::FMA, MVT::f64, Expand);
450 setOperationAction(ISD::FREM, MVT::f32, Expand);
451 setOperationAction(ISD::FREM, MVT::f64, Expand);
453 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
455 setOperationAction(ISD::VASTART, MVT::Other, Custom);
456 setOperationAction(ISD::VAARG, MVT::Other, Custom);
457 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
458 setOperationAction(ISD::VAEND, MVT::Other, Expand);
460 // Use the default for now
461 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
462 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
464 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
465 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
466 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
467 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
469 setInsertFencesForAtomic(true);
471 if (!Subtarget.hasMips32r2()) {
472 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
473 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
476 // MIPS16 lacks MIPS32's clz and clo instructions.
477 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
478 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
479 if (!Subtarget.hasMips64())
480 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
482 if (!Subtarget.hasMips32r2())
483 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
484 if (!Subtarget.hasMips64r2())
485 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
487 if (Subtarget.isGP64bit()) {
488 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
489 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
490 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
491 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
494 setOperationAction(ISD::TRAP, MVT::Other, Legal);
496 setTargetDAGCombine(ISD::SDIVREM);
497 setTargetDAGCombine(ISD::UDIVREM);
498 setTargetDAGCombine(ISD::SELECT);
499 setTargetDAGCombine(ISD::AND);
500 setTargetDAGCombine(ISD::OR);
501 setTargetDAGCombine(ISD::ADD);
503 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
505 // The arguments on the stack are defined in terms of 4-byte slots on O32
506 // and 8-byte slots on N32/N64.
507 setMinStackArgumentAlignment(
508 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
510 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
513 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
514 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
516 MaxStoresPerMemcpy = 16;
518 isMicroMips = Subtarget.inMicroMipsMode();
521 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
522 const MipsSubtarget &STI) {
523 if (STI.inMips16Mode())
524 return llvm::createMips16TargetLowering(TM, STI);
526 return llvm::createMipsSETargetLowering(TM, STI);
529 // Create a fast isel object.
531 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
532 const TargetLibraryInfo *libInfo) const {
533 if (!EnableMipsFastISel)
534 return TargetLowering::createFastISel(funcInfo, libInfo);
535 return Mips::createFastISel(funcInfo, libInfo);
538 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
541 return VT.changeVectorElementTypeToInteger();
544 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
545 TargetLowering::DAGCombinerInfo &DCI,
546 const MipsSubtarget &Subtarget) {
547 if (DCI.isBeforeLegalizeOps())
550 EVT Ty = N->getValueType(0);
551 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
552 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
553 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
557 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
558 N->getOperand(0), N->getOperand(1));
559 SDValue InChain = DAG.getEntryNode();
560 SDValue InGlue = DivRem;
563 if (N->hasAnyUseOfValue(0)) {
564 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
566 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
567 InChain = CopyFromLo.getValue(1);
568 InGlue = CopyFromLo.getValue(2);
572 if (N->hasAnyUseOfValue(1)) {
573 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
575 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
581 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
583 default: llvm_unreachable("Unknown fp condition code!");
585 case ISD::SETOEQ: return Mips::FCOND_OEQ;
586 case ISD::SETUNE: return Mips::FCOND_UNE;
588 case ISD::SETOLT: return Mips::FCOND_OLT;
590 case ISD::SETOGT: return Mips::FCOND_OGT;
592 case ISD::SETOLE: return Mips::FCOND_OLE;
594 case ISD::SETOGE: return Mips::FCOND_OGE;
595 case ISD::SETULT: return Mips::FCOND_ULT;
596 case ISD::SETULE: return Mips::FCOND_ULE;
597 case ISD::SETUGT: return Mips::FCOND_UGT;
598 case ISD::SETUGE: return Mips::FCOND_UGE;
599 case ISD::SETUO: return Mips::FCOND_UN;
600 case ISD::SETO: return Mips::FCOND_OR;
602 case ISD::SETONE: return Mips::FCOND_ONE;
603 case ISD::SETUEQ: return Mips::FCOND_UEQ;
608 /// This function returns true if the floating point conditional branches and
609 /// conditional moves which use condition code CC should be inverted.
610 static bool invertFPCondCodeUser(Mips::CondCode CC) {
611 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
614 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
615 "Illegal Condition Code");
620 // Creates and returns an FPCmp node from a setcc node.
621 // Returns Op if setcc is not a floating point comparison.
622 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
623 // must be a SETCC node
624 if (Op.getOpcode() != ISD::SETCC)
627 SDValue LHS = Op.getOperand(0);
629 if (!LHS.getValueType().isFloatingPoint())
632 SDValue RHS = Op.getOperand(1);
635 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
636 // node if necessary.
637 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
639 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
640 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
643 // Creates and returns a CMovFPT/F node.
644 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
645 SDValue False, SDLoc DL) {
646 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
647 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
648 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
650 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
651 True.getValueType(), True, FCC0, False, Cond);
654 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
655 TargetLowering::DAGCombinerInfo &DCI,
656 const MipsSubtarget &Subtarget) {
657 if (DCI.isBeforeLegalizeOps())
660 SDValue SetCC = N->getOperand(0);
662 if ((SetCC.getOpcode() != ISD::SETCC) ||
663 !SetCC.getOperand(0).getValueType().isInteger())
666 SDValue False = N->getOperand(2);
667 EVT FalseTy = False.getValueType();
669 if (!FalseTy.isInteger())
672 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
674 // If the RHS (False) is 0, we swap the order of the operands
675 // of ISD::SELECT (obviously also inverting the condition) so that we can
676 // take advantage of conditional moves using the $0 register.
678 // return (a != 0) ? x : 0;
686 if (!FalseC->getZExtValue()) {
687 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
688 SDValue True = N->getOperand(1);
690 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
691 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
693 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
696 // If both operands are integer constants there's a possibility that we
697 // can do some interesting optimizations.
698 SDValue True = N->getOperand(1);
699 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
701 if (!TrueC || !True.getValueType().isInteger())
704 // We'll also ignore MVT::i64 operands as this optimizations proves
705 // to be ineffective because of the required sign extensions as the result
706 // of a SETCC operator is always MVT::i32 for non-vector types.
707 if (True.getValueType() == MVT::i64)
710 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
712 // 1) (a < x) ? y : y-1
714 // addiu $reg2, $reg1, y-1
716 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
718 // 2) (a < x) ? y-1 : y
720 // xor $reg1, $reg1, 1
721 // addiu $reg2, $reg1, y-1
723 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
724 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
725 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
726 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
729 // Couldn't optimize.
733 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
734 TargetLowering::DAGCombinerInfo &DCI,
735 const MipsSubtarget &Subtarget) {
736 // Pattern match EXT.
737 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
738 // => ext $dst, $src, size, pos
739 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
742 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
743 unsigned ShiftRightOpc = ShiftRight.getOpcode();
745 // Op's first operand must be a shift right.
746 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
749 // The second operand of the shift must be an immediate.
751 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
754 uint64_t Pos = CN->getZExtValue();
755 uint64_t SMPos, SMSize;
757 // Op's second operand must be a shifted mask.
758 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
759 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
762 // Return if the shifted mask does not start at bit 0 or the sum of its size
763 // and Pos exceeds the word's size.
764 EVT ValTy = N->getValueType(0);
765 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
768 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
769 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
770 DAG.getConstant(SMSize, MVT::i32));
773 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
774 TargetLowering::DAGCombinerInfo &DCI,
775 const MipsSubtarget &Subtarget) {
776 // Pattern match INS.
777 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
778 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
779 // => ins $dst, $src, size, pos, $src1
780 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
783 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
784 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
787 // See if Op's first operand matches (and $src1 , mask0).
788 if (And0.getOpcode() != ISD::AND)
791 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
792 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
795 // See if Op's second operand matches (and (shl $src, pos), mask1).
796 if (And1.getOpcode() != ISD::AND)
799 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
800 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
803 // The shift masks must have the same position and size.
804 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
807 SDValue Shl = And1.getOperand(0);
808 if (Shl.getOpcode() != ISD::SHL)
811 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
814 unsigned Shamt = CN->getZExtValue();
816 // Return if the shift amount and the first bit position of mask are not the
818 EVT ValTy = N->getValueType(0);
819 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
822 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
823 DAG.getConstant(SMPos0, MVT::i32),
824 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
827 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
828 TargetLowering::DAGCombinerInfo &DCI,
829 const MipsSubtarget &Subtarget) {
830 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
832 if (DCI.isBeforeLegalizeOps())
835 SDValue Add = N->getOperand(1);
837 if (Add.getOpcode() != ISD::ADD)
840 SDValue Lo = Add.getOperand(1);
842 if ((Lo.getOpcode() != MipsISD::Lo) ||
843 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
846 EVT ValTy = N->getValueType(0);
849 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
851 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
854 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
856 SelectionDAG &DAG = DCI.DAG;
857 unsigned Opc = N->getOpcode();
863 return performDivRemCombine(N, DAG, DCI, Subtarget);
865 return performSELECTCombine(N, DAG, DCI, Subtarget);
867 return performANDCombine(N, DAG, DCI, Subtarget);
869 return performORCombine(N, DAG, DCI, Subtarget);
871 return performADDCombine(N, DAG, DCI, Subtarget);
878 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
879 SmallVectorImpl<SDValue> &Results,
880 SelectionDAG &DAG) const {
881 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
883 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
884 Results.push_back(Res.getValue(I));
888 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
889 SmallVectorImpl<SDValue> &Results,
890 SelectionDAG &DAG) const {
891 return LowerOperationWrapper(N, Results, DAG);
894 SDValue MipsTargetLowering::
895 LowerOperation(SDValue Op, SelectionDAG &DAG) const
897 switch (Op.getOpcode())
899 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
900 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
901 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
902 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
903 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
904 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
905 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
906 case ISD::SELECT: return lowerSELECT(Op, DAG);
907 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
908 case ISD::SETCC: return lowerSETCC(Op, DAG);
909 case ISD::VASTART: return lowerVASTART(Op, DAG);
910 case ISD::VAARG: return lowerVAARG(Op, DAG);
911 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
912 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
913 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
914 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
915 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
916 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
917 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
918 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
919 case ISD::LOAD: return lowerLOAD(Op, DAG);
920 case ISD::STORE: return lowerSTORE(Op, DAG);
921 case ISD::ADD: return lowerADD(Op, DAG);
922 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
927 //===----------------------------------------------------------------------===//
928 // Lower helper functions
929 //===----------------------------------------------------------------------===//
931 // addLiveIn - This helper function adds the specified physical register to the
932 // MachineFunction as a live in value. It also creates a corresponding
933 // virtual register for it.
935 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
937 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
938 MF.getRegInfo().addLiveIn(PReg, VReg);
942 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
943 MachineBasicBlock &MBB,
944 const TargetInstrInfo &TII,
949 // Insert instruction "teq $divisor_reg, $zero, 7".
950 MachineBasicBlock::iterator I(MI);
951 MachineInstrBuilder MIB;
952 MachineOperand &Divisor = MI->getOperand(2);
953 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
954 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
955 .addReg(Mips::ZERO).addImm(7);
957 // Use the 32-bit sub-register if this is a 64-bit division.
959 MIB->getOperand(0).setSubReg(Mips::sub_32);
961 // Clear Divisor's kill flag.
962 Divisor.setIsKill(false);
964 // We would normally delete the original instruction here but in this case
965 // we only needed to inject an additional instruction rather than replace it.
971 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
972 MachineBasicBlock *BB) const {
973 switch (MI->getOpcode()) {
975 llvm_unreachable("Unexpected instr type to insert");
976 case Mips::ATOMIC_LOAD_ADD_I8:
977 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
978 case Mips::ATOMIC_LOAD_ADD_I16:
979 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
980 case Mips::ATOMIC_LOAD_ADD_I32:
981 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
982 case Mips::ATOMIC_LOAD_ADD_I64:
983 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
985 case Mips::ATOMIC_LOAD_AND_I8:
986 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
987 case Mips::ATOMIC_LOAD_AND_I16:
988 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
989 case Mips::ATOMIC_LOAD_AND_I32:
990 return emitAtomicBinary(MI, BB, 4, Mips::AND);
991 case Mips::ATOMIC_LOAD_AND_I64:
992 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
994 case Mips::ATOMIC_LOAD_OR_I8:
995 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
996 case Mips::ATOMIC_LOAD_OR_I16:
997 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
998 case Mips::ATOMIC_LOAD_OR_I32:
999 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1000 case Mips::ATOMIC_LOAD_OR_I64:
1001 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1003 case Mips::ATOMIC_LOAD_XOR_I8:
1004 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1005 case Mips::ATOMIC_LOAD_XOR_I16:
1006 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1007 case Mips::ATOMIC_LOAD_XOR_I32:
1008 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1009 case Mips::ATOMIC_LOAD_XOR_I64:
1010 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1012 case Mips::ATOMIC_LOAD_NAND_I8:
1013 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1014 case Mips::ATOMIC_LOAD_NAND_I16:
1015 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1016 case Mips::ATOMIC_LOAD_NAND_I32:
1017 return emitAtomicBinary(MI, BB, 4, 0, true);
1018 case Mips::ATOMIC_LOAD_NAND_I64:
1019 return emitAtomicBinary(MI, BB, 8, 0, true);
1021 case Mips::ATOMIC_LOAD_SUB_I8:
1022 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1023 case Mips::ATOMIC_LOAD_SUB_I16:
1024 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1025 case Mips::ATOMIC_LOAD_SUB_I32:
1026 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1027 case Mips::ATOMIC_LOAD_SUB_I64:
1028 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1030 case Mips::ATOMIC_SWAP_I8:
1031 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1032 case Mips::ATOMIC_SWAP_I16:
1033 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1034 case Mips::ATOMIC_SWAP_I32:
1035 return emitAtomicBinary(MI, BB, 4, 0);
1036 case Mips::ATOMIC_SWAP_I64:
1037 return emitAtomicBinary(MI, BB, 8, 0);
1039 case Mips::ATOMIC_CMP_SWAP_I8:
1040 return emitAtomicCmpSwapPartword(MI, BB, 1);
1041 case Mips::ATOMIC_CMP_SWAP_I16:
1042 return emitAtomicCmpSwapPartword(MI, BB, 2);
1043 case Mips::ATOMIC_CMP_SWAP_I32:
1044 return emitAtomicCmpSwap(MI, BB, 4);
1045 case Mips::ATOMIC_CMP_SWAP_I64:
1046 return emitAtomicCmpSwap(MI, BB, 8);
1047 case Mips::PseudoSDIV:
1048 case Mips::PseudoUDIV:
1053 return insertDivByZeroTrap(
1054 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
1055 case Mips::PseudoDSDIV:
1056 case Mips::PseudoDUDIV:
1061 return insertDivByZeroTrap(
1062 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
1064 return emitSEL_D(MI, BB);
1068 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1069 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1071 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1072 unsigned Size, unsigned BinOpcode,
1074 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1076 MachineFunction *MF = BB->getParent();
1077 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1078 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1079 const TargetInstrInfo *TII =
1080 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1081 DebugLoc DL = MI->getDebugLoc();
1082 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1089 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1090 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1097 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1098 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1101 ZERO = Mips::ZERO_64;
1105 unsigned OldVal = MI->getOperand(0).getReg();
1106 unsigned Ptr = MI->getOperand(1).getReg();
1107 unsigned Incr = MI->getOperand(2).getReg();
1109 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1110 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1111 unsigned Success = RegInfo.createVirtualRegister(RC);
1113 // insert new blocks after the current block
1114 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1115 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1116 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1117 MachineFunction::iterator It = BB;
1119 MF->insert(It, loopMBB);
1120 MF->insert(It, exitMBB);
1122 // Transfer the remainder of BB and its successor edges to exitMBB.
1123 exitMBB->splice(exitMBB->begin(), BB,
1124 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1125 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1129 // fallthrough --> loopMBB
1130 BB->addSuccessor(loopMBB);
1131 loopMBB->addSuccessor(loopMBB);
1132 loopMBB->addSuccessor(exitMBB);
1135 // ll oldval, 0(ptr)
1136 // <binop> storeval, oldval, incr
1137 // sc success, storeval, 0(ptr)
1138 // beq success, $0, loopMBB
1140 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1142 // and andres, oldval, incr
1143 // nor storeval, $0, andres
1144 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1145 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1146 } else if (BinOpcode) {
1147 // <binop> storeval, oldval, incr
1148 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1152 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1153 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1155 MI->eraseFromParent(); // The instruction is gone now.
1160 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1161 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1162 unsigned SrcReg) const {
1163 const TargetInstrInfo *TII =
1164 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1165 DebugLoc DL = MI->getDebugLoc();
1167 if (Subtarget.hasMips32r2() && Size == 1) {
1168 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1172 if (Subtarget.hasMips32r2() && Size == 2) {
1173 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1177 MachineFunction *MF = BB->getParent();
1178 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1179 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1180 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1183 int64_t ShiftImm = 32 - (Size * 8);
1185 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1186 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1191 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1192 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1194 assert((Size == 1 || Size == 2) &&
1195 "Unsupported size for EmitAtomicBinaryPartial.");
1197 MachineFunction *MF = BB->getParent();
1198 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1199 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1200 const TargetInstrInfo *TII =
1201 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1202 DebugLoc DL = MI->getDebugLoc();
1204 unsigned Dest = MI->getOperand(0).getReg();
1205 unsigned Ptr = MI->getOperand(1).getReg();
1206 unsigned Incr = MI->getOperand(2).getReg();
1208 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1209 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1210 unsigned Mask = RegInfo.createVirtualRegister(RC);
1211 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1212 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1213 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1214 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1215 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1216 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1217 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1218 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1219 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1220 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1221 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1222 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1223 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1224 unsigned Success = RegInfo.createVirtualRegister(RC);
1226 // insert new blocks after the current block
1227 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1228 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1229 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1230 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1231 MachineFunction::iterator It = BB;
1233 MF->insert(It, loopMBB);
1234 MF->insert(It, sinkMBB);
1235 MF->insert(It, exitMBB);
1237 // Transfer the remainder of BB and its successor edges to exitMBB.
1238 exitMBB->splice(exitMBB->begin(), BB,
1239 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1240 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1242 BB->addSuccessor(loopMBB);
1243 loopMBB->addSuccessor(loopMBB);
1244 loopMBB->addSuccessor(sinkMBB);
1245 sinkMBB->addSuccessor(exitMBB);
1248 // addiu masklsb2,$0,-4 # 0xfffffffc
1249 // and alignedaddr,ptr,masklsb2
1250 // andi ptrlsb2,ptr,3
1251 // sll shiftamt,ptrlsb2,3
1252 // ori maskupper,$0,255 # 0xff
1253 // sll mask,maskupper,shiftamt
1254 // nor mask2,$0,mask
1255 // sll incr2,incr,shiftamt
1257 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1258 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1259 .addReg(Mips::ZERO).addImm(-4);
1260 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1261 .addReg(Ptr).addReg(MaskLSB2);
1262 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1263 if (Subtarget.isLittle()) {
1264 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1266 unsigned Off = RegInfo.createVirtualRegister(RC);
1267 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1268 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1269 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1271 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1272 .addReg(Mips::ZERO).addImm(MaskImm);
1273 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1274 .addReg(MaskUpper).addReg(ShiftAmt);
1275 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1276 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1278 // atomic.load.binop
1280 // ll oldval,0(alignedaddr)
1281 // binop binopres,oldval,incr2
1282 // and newval,binopres,mask
1283 // and maskedoldval0,oldval,mask2
1284 // or storeval,maskedoldval0,newval
1285 // sc success,storeval,0(alignedaddr)
1286 // beq success,$0,loopMBB
1290 // ll oldval,0(alignedaddr)
1291 // and newval,incr2,mask
1292 // and maskedoldval0,oldval,mask2
1293 // or storeval,maskedoldval0,newval
1294 // sc success,storeval,0(alignedaddr)
1295 // beq success,$0,loopMBB
1298 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1300 // and andres, oldval, incr2
1301 // nor binopres, $0, andres
1302 // and newval, binopres, mask
1303 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1304 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1305 .addReg(Mips::ZERO).addReg(AndRes);
1306 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1307 } else if (BinOpcode) {
1308 // <binop> binopres, oldval, incr2
1309 // and newval, binopres, mask
1310 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1311 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1312 } else { // atomic.swap
1313 // and newval, incr2, mask
1314 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1317 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1318 .addReg(OldVal).addReg(Mask2);
1319 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1320 .addReg(MaskedOldVal0).addReg(NewVal);
1321 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1322 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1323 BuildMI(BB, DL, TII->get(Mips::BEQ))
1324 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1327 // and maskedoldval1,oldval,mask
1328 // srl srlres,maskedoldval1,shiftamt
1329 // sign_extend dest,srlres
1332 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1333 .addReg(OldVal).addReg(Mask);
1334 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1335 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1336 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1338 MI->eraseFromParent(); // The instruction is gone now.
1343 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1344 MachineBasicBlock *BB,
1345 unsigned Size) const {
1346 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1348 MachineFunction *MF = BB->getParent();
1349 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1350 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1351 const TargetInstrInfo *TII =
1352 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1353 DebugLoc DL = MI->getDebugLoc();
1354 unsigned LL, SC, ZERO, BNE, BEQ;
1357 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1358 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1365 ZERO = Mips::ZERO_64;
1370 unsigned Dest = MI->getOperand(0).getReg();
1371 unsigned Ptr = MI->getOperand(1).getReg();
1372 unsigned OldVal = MI->getOperand(2).getReg();
1373 unsigned NewVal = MI->getOperand(3).getReg();
1375 unsigned Success = RegInfo.createVirtualRegister(RC);
1377 // insert new blocks after the current block
1378 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1379 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1380 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1381 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1382 MachineFunction::iterator It = BB;
1384 MF->insert(It, loop1MBB);
1385 MF->insert(It, loop2MBB);
1386 MF->insert(It, exitMBB);
1388 // Transfer the remainder of BB and its successor edges to exitMBB.
1389 exitMBB->splice(exitMBB->begin(), BB,
1390 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1391 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1395 // fallthrough --> loop1MBB
1396 BB->addSuccessor(loop1MBB);
1397 loop1MBB->addSuccessor(exitMBB);
1398 loop1MBB->addSuccessor(loop2MBB);
1399 loop2MBB->addSuccessor(loop1MBB);
1400 loop2MBB->addSuccessor(exitMBB);
1404 // bne dest, oldval, exitMBB
1406 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1407 BuildMI(BB, DL, TII->get(BNE))
1408 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1411 // sc success, newval, 0(ptr)
1412 // beq success, $0, loop1MBB
1414 BuildMI(BB, DL, TII->get(SC), Success)
1415 .addReg(NewVal).addReg(Ptr).addImm(0);
1416 BuildMI(BB, DL, TII->get(BEQ))
1417 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1419 MI->eraseFromParent(); // The instruction is gone now.
1425 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1426 MachineBasicBlock *BB,
1427 unsigned Size) const {
1428 assert((Size == 1 || Size == 2) &&
1429 "Unsupported size for EmitAtomicCmpSwapPartial.");
1431 MachineFunction *MF = BB->getParent();
1432 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1433 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1434 const TargetInstrInfo *TII =
1435 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1436 DebugLoc DL = MI->getDebugLoc();
1438 unsigned Dest = MI->getOperand(0).getReg();
1439 unsigned Ptr = MI->getOperand(1).getReg();
1440 unsigned CmpVal = MI->getOperand(2).getReg();
1441 unsigned NewVal = MI->getOperand(3).getReg();
1443 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1444 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1445 unsigned Mask = RegInfo.createVirtualRegister(RC);
1446 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1447 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1448 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1449 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1450 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1451 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1452 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1453 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1454 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1455 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1456 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1457 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1458 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1459 unsigned Success = RegInfo.createVirtualRegister(RC);
1461 // insert new blocks after the current block
1462 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1463 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1464 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1465 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1466 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1467 MachineFunction::iterator It = BB;
1469 MF->insert(It, loop1MBB);
1470 MF->insert(It, loop2MBB);
1471 MF->insert(It, sinkMBB);
1472 MF->insert(It, exitMBB);
1474 // Transfer the remainder of BB and its successor edges to exitMBB.
1475 exitMBB->splice(exitMBB->begin(), BB,
1476 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1477 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1479 BB->addSuccessor(loop1MBB);
1480 loop1MBB->addSuccessor(sinkMBB);
1481 loop1MBB->addSuccessor(loop2MBB);
1482 loop2MBB->addSuccessor(loop1MBB);
1483 loop2MBB->addSuccessor(sinkMBB);
1484 sinkMBB->addSuccessor(exitMBB);
1486 // FIXME: computation of newval2 can be moved to loop2MBB.
1488 // addiu masklsb2,$0,-4 # 0xfffffffc
1489 // and alignedaddr,ptr,masklsb2
1490 // andi ptrlsb2,ptr,3
1491 // sll shiftamt,ptrlsb2,3
1492 // ori maskupper,$0,255 # 0xff
1493 // sll mask,maskupper,shiftamt
1494 // nor mask2,$0,mask
1495 // andi maskedcmpval,cmpval,255
1496 // sll shiftedcmpval,maskedcmpval,shiftamt
1497 // andi maskednewval,newval,255
1498 // sll shiftednewval,maskednewval,shiftamt
1499 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1500 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1501 .addReg(Mips::ZERO).addImm(-4);
1502 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1503 .addReg(Ptr).addReg(MaskLSB2);
1504 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1505 if (Subtarget.isLittle()) {
1506 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1508 unsigned Off = RegInfo.createVirtualRegister(RC);
1509 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1510 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1511 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1513 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1514 .addReg(Mips::ZERO).addImm(MaskImm);
1515 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1516 .addReg(MaskUpper).addReg(ShiftAmt);
1517 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1518 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1519 .addReg(CmpVal).addImm(MaskImm);
1520 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1521 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1522 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1523 .addReg(NewVal).addImm(MaskImm);
1524 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1525 .addReg(MaskedNewVal).addReg(ShiftAmt);
1528 // ll oldval,0(alginedaddr)
1529 // and maskedoldval0,oldval,mask
1530 // bne maskedoldval0,shiftedcmpval,sinkMBB
1532 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1533 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1534 .addReg(OldVal).addReg(Mask);
1535 BuildMI(BB, DL, TII->get(Mips::BNE))
1536 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1539 // and maskedoldval1,oldval,mask2
1540 // or storeval,maskedoldval1,shiftednewval
1541 // sc success,storeval,0(alignedaddr)
1542 // beq success,$0,loop1MBB
1544 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1545 .addReg(OldVal).addReg(Mask2);
1546 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1547 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1548 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1549 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1550 BuildMI(BB, DL, TII->get(Mips::BEQ))
1551 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1554 // srl srlres,maskedoldval0,shiftamt
1555 // sign_extend dest,srlres
1558 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1559 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1560 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1562 MI->eraseFromParent(); // The instruction is gone now.
1567 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1568 MachineBasicBlock *BB) const {
1569 MachineFunction *MF = BB->getParent();
1570 const TargetRegisterInfo *TRI =
1571 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1572 const TargetInstrInfo *TII =
1573 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1574 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1575 DebugLoc DL = MI->getDebugLoc();
1576 MachineBasicBlock::iterator II(MI);
1578 unsigned Fc = MI->getOperand(1).getReg();
1579 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1581 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1583 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1586 .addImm(Mips::sub_lo);
1588 // We don't erase the original instruction, we just replace the condition
1589 // register with the 64-bit super-register.
1590 MI->getOperand(1).setReg(Fc2);
1595 //===----------------------------------------------------------------------===//
1596 // Misc Lower Operation implementation
1597 //===----------------------------------------------------------------------===//
1598 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1599 SDValue Chain = Op.getOperand(0);
1600 SDValue Table = Op.getOperand(1);
1601 SDValue Index = Op.getOperand(2);
1603 EVT PTy = getPointerTy();
1604 unsigned EntrySize =
1605 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1607 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1608 DAG.getConstant(EntrySize, PTy));
1609 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1611 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1612 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1613 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1615 Chain = Addr.getValue(1);
1617 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1618 Subtarget.isABI_N64()) {
1619 // For PIC, the sequence is:
1620 // BRIND(load(Jumptable + index) + RelocBase)
1621 // RelocBase can be JumpTable, GOT or some sort of global base.
1622 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1623 getPICJumpTableRelocBase(Table, DAG));
1626 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1629 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1630 // The first operand is the chain, the second is the condition, the third is
1631 // the block to branch to if the condition is true.
1632 SDValue Chain = Op.getOperand(0);
1633 SDValue Dest = Op.getOperand(2);
1636 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1637 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1639 // Return if flag is not set by a floating point comparison.
1640 if (CondRes.getOpcode() != MipsISD::FPCmp)
1643 SDValue CCNode = CondRes.getOperand(2);
1645 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1646 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1647 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1648 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1649 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1650 FCC0, Dest, CondRes);
1653 SDValue MipsTargetLowering::
1654 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1656 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1657 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1659 // Return if flag is not set by a floating point comparison.
1660 if (Cond.getOpcode() != MipsISD::FPCmp)
1663 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1667 SDValue MipsTargetLowering::
1668 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1671 EVT Ty = Op.getOperand(0).getValueType();
1672 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1673 getSetCCResultType(*DAG.getContext(), Ty),
1674 Op.getOperand(0), Op.getOperand(1),
1677 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1681 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1682 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1683 SDValue Cond = createFPCmp(DAG, Op);
1685 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1686 "Floating point operand expected.");
1688 SDValue True = DAG.getConstant(1, MVT::i32);
1689 SDValue False = DAG.getConstant(0, MVT::i32);
1691 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1694 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1695 SelectionDAG &DAG) const {
1696 EVT Ty = Op.getValueType();
1697 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1698 const GlobalValue *GV = N->getGlobal();
1700 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1701 !Subtarget.isABI_N64()) {
1702 const MipsTargetObjectFile &TLOF =
1703 (const MipsTargetObjectFile&)getObjFileLowering();
1705 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine()))
1706 // %gp_rel relocation
1707 return getAddrGPRel(N, Ty, DAG);
1709 // %hi/%lo relocation
1710 return getAddrNonPIC(N, Ty, DAG);
1713 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1714 return getAddrLocal(N, Ty, DAG,
1715 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1718 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1719 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1720 MachinePointerInfo::getGOT());
1722 return getAddrGlobal(N, Ty, DAG,
1723 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1724 ? MipsII::MO_GOT_DISP
1726 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1729 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1730 SelectionDAG &DAG) const {
1731 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1732 EVT Ty = Op.getValueType();
1734 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1735 !Subtarget.isABI_N64())
1736 return getAddrNonPIC(N, Ty, DAG);
1738 return getAddrLocal(N, Ty, DAG,
1739 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1742 SDValue MipsTargetLowering::
1743 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1745 // If the relocation model is PIC, use the General Dynamic TLS Model or
1746 // Local Dynamic TLS model, otherwise use the Initial Exec or
1747 // Local Exec TLS Model.
1749 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1751 const GlobalValue *GV = GA->getGlobal();
1752 EVT PtrVT = getPointerTy();
1754 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1756 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1757 // General Dynamic and Local Dynamic TLS Model.
1758 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1761 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1762 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1763 getGlobalReg(DAG, PtrVT), TGA);
1764 unsigned PtrSize = PtrVT.getSizeInBits();
1765 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1767 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1771 Entry.Node = Argument;
1773 Args.push_back(Entry);
1775 TargetLowering::CallLoweringInfo CLI(DAG);
1776 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1777 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1778 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1780 SDValue Ret = CallResult.first;
1782 if (model != TLSModel::LocalDynamic)
1785 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1786 MipsII::MO_DTPREL_HI);
1787 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1788 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1789 MipsII::MO_DTPREL_LO);
1790 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1791 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1792 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1796 if (model == TLSModel::InitialExec) {
1797 // Initial Exec TLS Model
1798 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1799 MipsII::MO_GOTTPREL);
1800 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1802 Offset = DAG.getLoad(PtrVT, DL,
1803 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1804 false, false, false, 0);
1806 // Local Exec TLS Model
1807 assert(model == TLSModel::LocalExec);
1808 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1809 MipsII::MO_TPREL_HI);
1810 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1811 MipsII::MO_TPREL_LO);
1812 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1813 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1814 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1817 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1818 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1821 SDValue MipsTargetLowering::
1822 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1824 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1825 EVT Ty = Op.getValueType();
1827 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1828 !Subtarget.isABI_N64())
1829 return getAddrNonPIC(N, Ty, DAG);
1831 return getAddrLocal(N, Ty, DAG,
1832 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1835 SDValue MipsTargetLowering::
1836 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1838 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1839 EVT Ty = Op.getValueType();
1841 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1842 !Subtarget.isABI_N64()) {
1843 const MipsTargetObjectFile &TLOF =
1844 (const MipsTargetObjectFile&)getObjFileLowering();
1846 if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1847 // %gp_rel relocation
1848 return getAddrGPRel(N, Ty, DAG);
1850 return getAddrNonPIC(N, Ty, DAG);
1853 return getAddrLocal(N, Ty, DAG,
1854 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1857 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1858 MachineFunction &MF = DAG.getMachineFunction();
1859 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1862 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1865 // vastart just stores the address of the VarArgsFrameIndex slot into the
1866 // memory location argument.
1867 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1868 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1869 MachinePointerInfo(SV), false, false, 0);
1872 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1873 SDNode *Node = Op.getNode();
1874 EVT VT = Node->getValueType(0);
1875 SDValue Chain = Node->getOperand(0);
1876 SDValue VAListPtr = Node->getOperand(1);
1877 unsigned Align = Node->getConstantOperandVal(3);
1878 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1880 unsigned ArgSlotSizeInBytes =
1881 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1883 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1884 MachinePointerInfo(SV), false, false, false,
1886 SDValue VAList = VAListLoad;
1888 // Re-align the pointer if necessary.
1889 // It should only ever be necessary for 64-bit types on O32 since the minimum
1890 // argument alignment is the same as the maximum type alignment for N32/N64.
1892 // FIXME: We currently align too often. The code generator doesn't notice
1893 // when the pointer is still aligned from the last va_arg (or pair of
1894 // va_args for the i64 on O32 case).
1895 if (Align > getMinStackArgumentAlignment()) {
1896 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1898 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1899 DAG.getConstant(Align - 1,
1900 VAList.getValueType()));
1902 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1903 DAG.getConstant(-(int64_t)Align,
1904 VAList.getValueType()));
1907 // Increment the pointer, VAList, to the next vaarg.
1908 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1909 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1910 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1911 VAList.getValueType()));
1912 // Store the incremented VAList to the legalized pointer
1913 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1914 MachinePointerInfo(SV), false, false, 0);
1916 // In big-endian mode we must adjust the pointer when the load size is smaller
1917 // than the argument slot size. We must also reduce the known alignment to
1918 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1919 // the correct half of the slot, and reduce the alignment from 8 (slot
1920 // alignment) down to 4 (type alignment).
1921 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1922 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1923 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1924 DAG.getIntPtrConstant(Adjustment));
1926 // Load the actual argument out of the pointer VAList
1927 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1931 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1932 bool HasExtractInsert) {
1933 EVT TyX = Op.getOperand(0).getValueType();
1934 EVT TyY = Op.getOperand(1).getValueType();
1935 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1936 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1940 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1942 SDValue X = (TyX == MVT::f32) ?
1943 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1944 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1946 SDValue Y = (TyY == MVT::f32) ?
1947 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1948 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1951 if (HasExtractInsert) {
1952 // ext E, Y, 31, 1 ; extract bit31 of Y
1953 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1954 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1955 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1958 // srl SrlX, SllX, 1
1960 // sll SllY, SrlX, 31
1961 // or Or, SrlX, SllY
1962 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1963 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1964 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1965 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1966 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1969 if (TyX == MVT::f32)
1970 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1972 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1973 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1974 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1977 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1978 bool HasExtractInsert) {
1979 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1980 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1981 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1982 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1985 // Bitcast to integer nodes.
1986 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1987 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1989 if (HasExtractInsert) {
1990 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1991 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1992 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1993 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1995 if (WidthX > WidthY)
1996 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1997 else if (WidthY > WidthX)
1998 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2000 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2001 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2002 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2005 // (d)sll SllX, X, 1
2006 // (d)srl SrlX, SllX, 1
2007 // (d)srl SrlY, Y, width(Y)-1
2008 // (d)sll SllY, SrlX, width(Y)-1
2009 // or Or, SrlX, SllY
2010 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2011 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2012 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2013 DAG.getConstant(WidthY - 1, MVT::i32));
2015 if (WidthX > WidthY)
2016 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2017 else if (WidthY > WidthX)
2018 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2020 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2021 DAG.getConstant(WidthX - 1, MVT::i32));
2022 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2023 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2027 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2028 if (Subtarget.isGP64bit())
2029 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2031 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2034 SDValue MipsTargetLowering::
2035 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2037 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2038 "Frame address can only be determined for current frame.");
2040 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2041 MFI->setFrameAddressIsTaken(true);
2042 EVT VT = Op.getValueType();
2045 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
2046 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
2050 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2051 SelectionDAG &DAG) const {
2052 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2056 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2057 "Return address can be determined only for current frame.");
2059 MachineFunction &MF = DAG.getMachineFunction();
2060 MachineFrameInfo *MFI = MF.getFrameInfo();
2061 MVT VT = Op.getSimpleValueType();
2062 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
2063 MFI->setReturnAddressIsTaken(true);
2065 // Return RA, which contains the return address. Mark it an implicit live-in.
2066 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2067 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2070 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2071 // generated from __builtin_eh_return (offset, handler)
2072 // The effect of this is to adjust the stack pointer by "offset"
2073 // and then branch to "handler".
2074 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2076 MachineFunction &MF = DAG.getMachineFunction();
2077 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2079 MipsFI->setCallsEhReturn();
2080 SDValue Chain = Op.getOperand(0);
2081 SDValue Offset = Op.getOperand(1);
2082 SDValue Handler = Op.getOperand(2);
2084 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2086 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2087 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2088 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
2089 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2090 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2091 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2092 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2093 DAG.getRegister(OffsetReg, Ty),
2094 DAG.getRegister(AddrReg, getPointerTy()),
2098 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2099 SelectionDAG &DAG) const {
2100 // FIXME: Need pseudo-fence for 'singlethread' fences
2101 // FIXME: Set SType for weaker fences where supported/appropriate.
2104 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2105 DAG.getConstant(SType, MVT::i32));
2108 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2109 SelectionDAG &DAG) const {
2111 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2112 SDValue Shamt = Op.getOperand(2);
2115 // lo = (shl lo, shamt)
2116 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2119 // hi = (shl lo, shamt[4:0])
2120 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2121 DAG.getConstant(-1, MVT::i32));
2122 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2123 DAG.getConstant(1, MVT::i32));
2124 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2126 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2127 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2128 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2129 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2130 DAG.getConstant(0x20, MVT::i32));
2131 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2132 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2133 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2135 SDValue Ops[2] = {Lo, Hi};
2136 return DAG.getMergeValues(Ops, DL);
2139 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2142 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2143 SDValue Shamt = Op.getOperand(2);
2146 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2148 // hi = (sra hi, shamt)
2150 // hi = (srl hi, shamt)
2153 // lo = (sra hi, shamt[4:0])
2154 // hi = (sra hi, 31)
2156 // lo = (srl hi, shamt[4:0])
2158 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2159 DAG.getConstant(-1, MVT::i32));
2160 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2161 DAG.getConstant(1, MVT::i32));
2162 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2163 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2164 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2165 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2167 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2168 DAG.getConstant(0x20, MVT::i32));
2169 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2170 DAG.getConstant(31, MVT::i32));
2171 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2172 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2173 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2176 SDValue Ops[2] = {Lo, Hi};
2177 return DAG.getMergeValues(Ops, DL);
2180 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2181 SDValue Chain, SDValue Src, unsigned Offset) {
2182 SDValue Ptr = LD->getBasePtr();
2183 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2184 EVT BasePtrVT = Ptr.getValueType();
2186 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2189 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2190 DAG.getConstant(Offset, BasePtrVT));
2192 SDValue Ops[] = { Chain, Ptr, Src };
2193 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2194 LD->getMemOperand());
2197 // Expand an unaligned 32 or 64-bit integer load node.
2198 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2199 LoadSDNode *LD = cast<LoadSDNode>(Op);
2200 EVT MemVT = LD->getMemoryVT();
2202 if (Subtarget.systemSupportsUnalignedAccess())
2205 // Return if load is aligned or if MemVT is neither i32 nor i64.
2206 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2207 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2210 bool IsLittle = Subtarget.isLittle();
2211 EVT VT = Op.getValueType();
2212 ISD::LoadExtType ExtType = LD->getExtensionType();
2213 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2215 assert((VT == MVT::i32) || (VT == MVT::i64));
2218 // (set dst, (i64 (load baseptr)))
2220 // (set tmp, (ldl (add baseptr, 7), undef))
2221 // (set dst, (ldr baseptr, tmp))
2222 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2223 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2225 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2229 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2231 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2235 // (set dst, (i32 (load baseptr))) or
2236 // (set dst, (i64 (sextload baseptr))) or
2237 // (set dst, (i64 (extload baseptr)))
2239 // (set tmp, (lwl (add baseptr, 3), undef))
2240 // (set dst, (lwr baseptr, tmp))
2241 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2242 (ExtType == ISD::EXTLOAD))
2245 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2248 // (set dst, (i64 (zextload baseptr)))
2250 // (set tmp0, (lwl (add baseptr, 3), undef))
2251 // (set tmp1, (lwr baseptr, tmp0))
2252 // (set tmp2, (shl tmp1, 32))
2253 // (set dst, (srl tmp2, 32))
2255 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2256 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2257 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2258 SDValue Ops[] = { SRL, LWR.getValue(1) };
2259 return DAG.getMergeValues(Ops, DL);
2262 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2263 SDValue Chain, unsigned Offset) {
2264 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2265 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2267 SDVTList VTList = DAG.getVTList(MVT::Other);
2270 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2271 DAG.getConstant(Offset, BasePtrVT));
2273 SDValue Ops[] = { Chain, Value, Ptr };
2274 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2275 SD->getMemOperand());
2278 // Expand an unaligned 32 or 64-bit integer store node.
2279 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2281 SDValue Value = SD->getValue(), Chain = SD->getChain();
2282 EVT VT = Value.getValueType();
2285 // (store val, baseptr) or
2286 // (truncstore val, baseptr)
2288 // (swl val, (add baseptr, 3))
2289 // (swr val, baseptr)
2290 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2291 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2293 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2296 assert(VT == MVT::i64);
2299 // (store val, baseptr)
2301 // (sdl val, (add baseptr, 7))
2302 // (sdr val, baseptr)
2303 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2304 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2307 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2308 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2309 SDValue Val = SD->getValue();
2311 if (Val.getOpcode() != ISD::FP_TO_SINT)
2314 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2315 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2318 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2319 SD->getPointerInfo(), SD->isVolatile(),
2320 SD->isNonTemporal(), SD->getAlignment());
2323 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2324 StoreSDNode *SD = cast<StoreSDNode>(Op);
2325 EVT MemVT = SD->getMemoryVT();
2327 // Lower unaligned integer stores.
2328 if (!Subtarget.systemSupportsUnalignedAccess() &&
2329 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2330 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2331 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2333 return lowerFP_TO_SINT_STORE(SD, DAG);
2336 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2337 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2338 || cast<ConstantSDNode>
2339 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2340 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2344 // (add (frameaddr 0), (frame_to_args_offset))
2345 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2346 // (add FrameObject, 0)
2347 // where FrameObject is a fixed StackObject with offset 0 which points to
2348 // the old stack pointer.
2349 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2350 EVT ValTy = Op->getValueType(0);
2351 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2352 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2353 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2354 DAG.getConstant(0, ValTy));
2357 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2358 SelectionDAG &DAG) const {
2359 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2360 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2362 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2365 //===----------------------------------------------------------------------===//
2366 // Calling Convention Implementation
2367 //===----------------------------------------------------------------------===//
2369 //===----------------------------------------------------------------------===//
2370 // TODO: Implement a generic logic using tblgen that can support this.
2371 // Mips O32 ABI rules:
2373 // i32 - Passed in A0, A1, A2, A3 and stack
2374 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2375 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2376 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2377 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2378 // not used, it must be shadowed. If only A3 is available, shadow it and
2381 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2382 //===----------------------------------------------------------------------===//
2384 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2385 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2386 CCState &State, const MCPhysReg *F64Regs) {
2388 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2390 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2391 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2393 // Do not process byval args here.
2394 if (ArgFlags.isByVal())
2397 // Promote i8 and i16
2398 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2400 if (ArgFlags.isSExt())
2401 LocInfo = CCValAssign::SExt;
2402 else if (ArgFlags.isZExt())
2403 LocInfo = CCValAssign::ZExt;
2405 LocInfo = CCValAssign::AExt;
2410 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2411 // is true: function is vararg, argument is 3rd or higher, there is previous
2412 // argument which is not f32 or f64.
2413 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2414 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2415 unsigned OrigAlign = ArgFlags.getOrigAlign();
2416 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2418 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2419 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2420 // If this is the first part of an i64 arg,
2421 // the allocated register must be either A0 or A2.
2422 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2423 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2425 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2426 // Allocate int register and shadow next int register. If first
2427 // available register is Mips::A1 or Mips::A3, shadow it too.
2428 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2429 if (Reg == Mips::A1 || Reg == Mips::A3)
2430 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2431 State.AllocateReg(IntRegs, IntRegsSize);
2433 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2434 // we are guaranteed to find an available float register
2435 if (ValVT == MVT::f32) {
2436 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2437 // Shadow int register
2438 State.AllocateReg(IntRegs, IntRegsSize);
2440 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2441 // Shadow int registers
2442 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2443 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2444 State.AllocateReg(IntRegs, IntRegsSize);
2445 State.AllocateReg(IntRegs, IntRegsSize);
2448 llvm_unreachable("Cannot handle this ValVT.");
2451 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2453 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2455 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2460 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2461 MVT LocVT, CCValAssign::LocInfo LocInfo,
2462 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2463 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2465 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2468 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2469 MVT LocVT, CCValAssign::LocInfo LocInfo,
2470 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2471 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2473 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2476 #include "MipsGenCallingConv.inc"
2478 //===----------------------------------------------------------------------===//
2479 // Call Calling Convention Implementation
2480 //===----------------------------------------------------------------------===//
2482 // Return next O32 integer argument register.
2483 static unsigned getNextIntArgReg(unsigned Reg) {
2484 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2485 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2489 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2490 SDValue Chain, SDValue Arg, SDLoc DL,
2491 bool IsTailCall, SelectionDAG &DAG) const {
2493 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2494 DAG.getIntPtrConstant(Offset));
2495 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2499 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2500 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2501 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2502 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2503 /*isVolatile=*/ true, false, 0);
2506 void MipsTargetLowering::
2507 getOpndList(SmallVectorImpl<SDValue> &Ops,
2508 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2509 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2510 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2511 SDValue Chain) const {
2512 // Insert node "GP copy globalreg" before call to function.
2514 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2515 // in PIC mode) allow symbols to be resolved via lazy binding.
2516 // The lazy binding stub requires GP to point to the GOT.
2517 // Note that we don't need GP to point to the GOT for indirect calls
2518 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2519 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2520 // used for the function (that is, Mips linker doesn't generate lazy binding
2521 // stub for a function whose address is taken in the program).
2522 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2523 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2524 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2525 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2528 // Build a sequence of copy-to-reg nodes chained together with token
2529 // chain and flag operands which copy the outgoing args into registers.
2530 // The InFlag in necessary since all emitted instructions must be
2534 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2535 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2536 RegsToPass[i].second, InFlag);
2537 InFlag = Chain.getValue(1);
2540 // Add argument registers to the end of the list so that they are
2541 // known live into the call.
2542 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2543 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2544 RegsToPass[i].second.getValueType()));
2546 // Add a register mask operand representing the call-preserved registers.
2547 const TargetRegisterInfo *TRI =
2548 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2549 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2550 assert(Mask && "Missing call preserved mask for calling convention");
2551 if (Subtarget.inMips16HardFloat()) {
2552 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2553 llvm::StringRef Sym = G->getGlobal()->getName();
2554 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2555 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2556 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2560 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2562 if (InFlag.getNode())
2563 Ops.push_back(InFlag);
2566 /// LowerCall - functions arguments are copied from virtual regs to
2567 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2569 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2570 SmallVectorImpl<SDValue> &InVals) const {
2571 SelectionDAG &DAG = CLI.DAG;
2573 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2574 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2575 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2576 SDValue Chain = CLI.Chain;
2577 SDValue Callee = CLI.Callee;
2578 bool &IsTailCall = CLI.IsTailCall;
2579 CallingConv::ID CallConv = CLI.CallConv;
2580 bool IsVarArg = CLI.IsVarArg;
2582 MachineFunction &MF = DAG.getMachineFunction();
2583 MachineFrameInfo *MFI = MF.getFrameInfo();
2584 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2585 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2586 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2588 // Analyze operands of the call, assigning locations to each operand.
2589 SmallVector<CCValAssign, 16> ArgLocs;
2590 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2592 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2594 CCInfo.PreAnalyzeCallOperandsForF128_(Outs, CLI.getArgs(), Callee.getNode());
2595 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg, Subtarget.abiUsesSoftFloat(),
2596 Callee.getNode(), CLI.getArgs(), CCInfo);
2597 CCInfo.ClearOriginalArgWasF128();
2599 // Get a count of how many bytes are to be pushed on the stack.
2600 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2602 // Check if it's really possible to do a tail call.
2604 IsTailCall = isEligibleForTailCallOptimization(
2605 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2607 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2608 report_fatal_error("failed to perform tail call elimination on a call "
2609 "site marked musttail");
2614 // Chain is the output chain of the last Load/Store or CopyToReg node.
2615 // ByValChain is the output chain of the last Memcpy node created for copying
2616 // byval arguments to the stack.
2617 unsigned StackAlignment = TFL->getStackAlignment();
2618 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2619 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2622 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2624 SDValue StackPtr = DAG.getCopyFromReg(
2625 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2628 // With EABI is it possible to have 16 args on registers.
2629 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2630 SmallVector<SDValue, 8> MemOpChains;
2632 CCInfo.rewindByValRegsInfo();
2634 // Walk the register/memloc assignments, inserting copies/loads.
2635 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2636 SDValue Arg = OutVals[i];
2637 CCValAssign &VA = ArgLocs[i];
2638 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2639 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2642 if (Flags.isByVal()) {
2643 unsigned FirstByValReg, LastByValReg;
2644 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2645 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2647 assert(Flags.getByValSize() &&
2648 "ByVal args of size 0 should have been ignored by front-end.");
2649 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2650 assert(!IsTailCall &&
2651 "Do not tail-call optimize if there is a byval argument.");
2652 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2653 MipsCCInfo, FirstByValReg, LastByValReg, Flags,
2654 Subtarget.isLittle(), VA);
2655 CCInfo.nextInRegsParam();
2659 // Promote the value if needed.
2660 switch (VA.getLocInfo()) {
2661 default: llvm_unreachable("Unknown loc info!");
2662 case CCValAssign::Full:
2663 if (VA.isRegLoc()) {
2664 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2665 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2666 (ValVT == MVT::i64 && LocVT == MVT::f64))
2667 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2668 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2669 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2670 Arg, DAG.getConstant(0, MVT::i32));
2671 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2672 Arg, DAG.getConstant(1, MVT::i32));
2673 if (!Subtarget.isLittle())
2675 unsigned LocRegLo = VA.getLocReg();
2676 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2677 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2678 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2683 case CCValAssign::BCvt:
2684 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2686 case CCValAssign::SExt:
2687 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2689 case CCValAssign::ZExt:
2690 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2692 case CCValAssign::AExt:
2693 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2697 // Arguments that can be passed on register must be kept at
2698 // RegsToPass vector
2699 if (VA.isRegLoc()) {
2700 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2704 // Register can't get to this point...
2705 assert(VA.isMemLoc());
2707 // emit ISD::STORE whichs stores the
2708 // parameter value to a stack Location
2709 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2710 Chain, Arg, DL, IsTailCall, DAG));
2713 // Transform all store nodes into one single node because all store
2714 // nodes are independent of each other.
2715 if (!MemOpChains.empty())
2716 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2718 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2719 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2720 // node so that legalize doesn't hack it.
2722 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2724 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2726 EVT Ty = Callee.getValueType();
2728 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2730 const GlobalValue *Val = G->getGlobal();
2731 InternalLinkage = Val->hasInternalLinkage();
2733 if (InternalLinkage)
2734 Callee = getAddrLocal(G, Ty, DAG,
2735 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2736 else if (LargeGOT) {
2737 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2738 MipsII::MO_CALL_LO16, Chain,
2739 FuncInfo->callPtrInfo(Val));
2742 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2743 FuncInfo->callPtrInfo(Val));
2747 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2748 MipsII::MO_NO_FLAG);
2749 GlobalOrExternal = true;
2751 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2752 const char *Sym = S->getSymbol();
2754 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2755 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2756 MipsII::MO_NO_FLAG);
2757 else if (LargeGOT) {
2758 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2759 MipsII::MO_CALL_LO16, Chain,
2760 FuncInfo->callPtrInfo(Sym));
2762 } else { // N64 || PIC
2763 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2764 FuncInfo->callPtrInfo(Sym));
2768 GlobalOrExternal = true;
2771 SmallVector<SDValue, 8> Ops(1, Chain);
2772 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2774 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2775 IsCallReloc, CLI, Callee, Chain);
2778 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2780 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2781 SDValue InFlag = Chain.getValue(1);
2783 // Create the CALLSEQ_END node.
2784 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2785 DAG.getIntPtrConstant(0, true), InFlag, DL);
2786 InFlag = Chain.getValue(1);
2788 // Handle result values, copying them out of physregs into vregs that we
2790 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2794 /// LowerCallResult - Lower the result values of a call into the
2795 /// appropriate copies out of appropriate physical registers.
2796 SDValue MipsTargetLowering::LowerCallResult(
2797 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2798 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2799 SmallVectorImpl<SDValue> &InVals,
2800 TargetLowering::CallLoweringInfo &CLI) const {
2801 // Assign locations to each value returned by this call.
2802 SmallVector<CCValAssign, 16> RVLocs;
2803 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2805 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2807 // Copy all of the result registers out of their specified physreg.
2808 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2809 CCValAssign &VA = RVLocs[i];
2810 assert(VA.isRegLoc() && "Can only return in registers!");
2812 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2813 RVLocs[i].getLocVT(), InFlag);
2814 Chain = Val.getValue(1);
2815 InFlag = Val.getValue(2);
2817 if (VA.isUpperBitsInLoc()) {
2818 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2819 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2821 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2823 Shift, DL, VA.getLocVT(), Val,
2824 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2827 switch (VA.getLocInfo()) {
2829 llvm_unreachable("Unknown loc info!");
2830 case CCValAssign::Full:
2832 case CCValAssign::BCvt:
2833 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2835 case CCValAssign::AExt:
2836 case CCValAssign::AExtUpper:
2837 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2839 case CCValAssign::ZExt:
2840 case CCValAssign::ZExtUpper:
2841 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2842 DAG.getValueType(VA.getValVT()));
2843 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2845 case CCValAssign::SExt:
2846 case CCValAssign::SExtUpper:
2847 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2848 DAG.getValueType(VA.getValVT()));
2849 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2853 InVals.push_back(Val);
2859 //===----------------------------------------------------------------------===//
2860 // Formal Arguments Calling Convention Implementation
2861 //===----------------------------------------------------------------------===//
2862 /// LowerFormalArguments - transform physical registers into virtual registers
2863 /// and generate load operations for arguments places on the stack.
2865 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2866 CallingConv::ID CallConv,
2868 const SmallVectorImpl<ISD::InputArg> &Ins,
2869 SDLoc DL, SelectionDAG &DAG,
2870 SmallVectorImpl<SDValue> &InVals)
2872 MachineFunction &MF = DAG.getMachineFunction();
2873 MachineFrameInfo *MFI = MF.getFrameInfo();
2874 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2876 MipsFI->setVarArgsFrameIndex(0);
2878 // Used with vargs to acumulate store chains.
2879 std::vector<SDValue> OutChains;
2881 // Assign locations to all of the incoming arguments.
2882 SmallVector<CCValAssign, 16> ArgLocs;
2883 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2885 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2886 Function::const_arg_iterator FuncArg =
2887 DAG.getMachineFunction().getFunction()->arg_begin();
2888 bool UseSoftFloat = Subtarget.abiUsesSoftFloat();
2890 CCInfo.PreAnalyzeFormalArgumentsForF128_(Ins);
2891 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, CCInfo);
2892 CCInfo.ClearOriginalArgWasF128();
2893 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2894 CCInfo.getInRegsParamsCount() > 0);
2896 unsigned CurArgIdx = 0;
2897 CCInfo.rewindByValRegsInfo();
2899 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2900 CCValAssign &VA = ArgLocs[i];
2901 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2902 CurArgIdx = Ins[i].OrigArgIndex;
2903 EVT ValVT = VA.getValVT();
2904 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2905 bool IsRegLoc = VA.isRegLoc();
2907 if (Flags.isByVal()) {
2908 unsigned FirstByValReg, LastByValReg;
2909 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2910 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2912 assert(Flags.getByValSize() &&
2913 "ByVal args of size 0 should have been ignored by front-end.");
2914 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2915 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2916 MipsCCInfo, FirstByValReg, LastByValReg, VA);
2917 CCInfo.nextInRegsParam();
2921 // Arguments stored on registers
2923 MVT RegVT = VA.getLocVT();
2924 unsigned ArgReg = VA.getLocReg();
2925 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2927 // Transform the arguments stored on
2928 // physical registers into virtual ones
2929 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2930 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2932 // If this is an 8 or 16-bit value, it has been passed promoted
2933 // to 32 bits. Insert an assert[sz]ext to capture this, then
2934 // truncate to the right size.
2935 switch (VA.getLocInfo()) {
2937 llvm_unreachable("Unknown loc info!");
2938 case CCValAssign::Full:
2940 case CCValAssign::SExt:
2941 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2942 DAG.getValueType(ValVT));
2943 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2945 case CCValAssign::ZExt:
2946 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2947 DAG.getValueType(ValVT));
2948 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2950 case CCValAssign::BCvt:
2951 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2955 // Handle floating point arguments passed in integer registers and
2956 // long double arguments passed in floating point registers.
2957 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2958 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2959 (RegVT == MVT::f64 && ValVT == MVT::i64))
2960 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2961 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2962 ValVT == MVT::f64) {
2963 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2964 getNextIntArgReg(ArgReg), RC);
2965 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2966 if (!Subtarget.isLittle())
2967 std::swap(ArgValue, ArgValue2);
2968 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2969 ArgValue, ArgValue2);
2972 InVals.push_back(ArgValue);
2973 } else { // VA.isRegLoc()
2976 assert(VA.isMemLoc());
2978 // The stack pointer offset is relative to the caller stack frame.
2979 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2980 VA.getLocMemOffset(), true);
2982 // Create load nodes to retrieve arguments from the stack
2983 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2984 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2985 MachinePointerInfo::getFixedStack(FI),
2986 false, false, false, 0);
2987 InVals.push_back(Load);
2988 OutChains.push_back(Load.getValue(1));
2992 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2993 // The mips ABIs for returning structs by value requires that we copy
2994 // the sret argument into $v0 for the return. Save the argument into
2995 // a virtual register so that we can access it from the return points.
2996 if (Ins[i].Flags.isSRet()) {
2997 unsigned Reg = MipsFI->getSRetReturnReg();
2999 Reg = MF.getRegInfo().createVirtualRegister(
3000 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
3001 MipsFI->setSRetReturnReg(Reg);
3003 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3004 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3010 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG, CCInfo);
3012 // All stores are grouped in one node to allow the matching between
3013 // the size of Ins and InVals. This only happens when on varg functions
3014 if (!OutChains.empty()) {
3015 OutChains.push_back(Chain);
3016 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3022 //===----------------------------------------------------------------------===//
3023 // Return Value Calling Convention Implementation
3024 //===----------------------------------------------------------------------===//
3027 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3028 MachineFunction &MF, bool IsVarArg,
3029 const SmallVectorImpl<ISD::OutputArg> &Outs,
3030 LLVMContext &Context) const {
3031 SmallVector<CCValAssign, 16> RVLocs;
3032 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3033 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3037 MipsTargetLowering::LowerReturn(SDValue Chain,
3038 CallingConv::ID CallConv, bool IsVarArg,
3039 const SmallVectorImpl<ISD::OutputArg> &Outs,
3040 const SmallVectorImpl<SDValue> &OutVals,
3041 SDLoc DL, SelectionDAG &DAG) const {
3042 // CCValAssign - represent the assignment of
3043 // the return value to a location
3044 SmallVector<CCValAssign, 16> RVLocs;
3045 MachineFunction &MF = DAG.getMachineFunction();
3047 // CCState - Info about the registers and stack slot.
3048 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3050 // Analyze return values.
3051 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3054 SmallVector<SDValue, 4> RetOps(1, Chain);
3056 // Copy the result values into the output registers.
3057 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3058 SDValue Val = OutVals[i];
3059 CCValAssign &VA = RVLocs[i];
3060 assert(VA.isRegLoc() && "Can only return in registers!");
3061 bool UseUpperBits = false;
3063 switch (VA.getLocInfo()) {
3065 llvm_unreachable("Unknown loc info!");
3066 case CCValAssign::Full:
3068 case CCValAssign::BCvt:
3069 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3071 case CCValAssign::AExtUpper:
3072 UseUpperBits = true;
3074 case CCValAssign::AExt:
3075 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3077 case CCValAssign::ZExtUpper:
3078 UseUpperBits = true;
3080 case CCValAssign::ZExt:
3081 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3083 case CCValAssign::SExtUpper:
3084 UseUpperBits = true;
3086 case CCValAssign::SExt:
3087 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3092 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3093 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3095 ISD::SHL, DL, VA.getLocVT(), Val,
3096 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3099 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3101 // Guarantee that all emitted copies are stuck together with flags.
3102 Flag = Chain.getValue(1);
3103 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3106 // The mips ABIs for returning structs by value requires that we copy
3107 // the sret argument into $v0 for the return. We saved the argument into
3108 // a virtual register in the entry block, so now we copy the value out
3110 if (MF.getFunction()->hasStructRetAttr()) {
3111 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3112 unsigned Reg = MipsFI->getSRetReturnReg();
3115 llvm_unreachable("sret virtual register not created in the entry block");
3116 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3117 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3119 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3120 Flag = Chain.getValue(1);
3121 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3124 RetOps[0] = Chain; // Update chain.
3126 // Add the flag if we have it.
3128 RetOps.push_back(Flag);
3130 // Return on Mips is always a "jr $ra"
3131 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3134 //===----------------------------------------------------------------------===//
3135 // Mips Inline Assembly Support
3136 //===----------------------------------------------------------------------===//
3138 /// getConstraintType - Given a constraint letter, return the type of
3139 /// constraint it is for this target.
3140 MipsTargetLowering::ConstraintType MipsTargetLowering::
3141 getConstraintType(const std::string &Constraint) const
3143 // Mips specific constraints
3144 // GCC config/mips/constraints.md
3146 // 'd' : An address register. Equivalent to r
3147 // unless generating MIPS16 code.
3148 // 'y' : Equivalent to r; retained for
3149 // backwards compatibility.
3150 // 'c' : A register suitable for use in an indirect
3151 // jump. This will always be $25 for -mabicalls.
3152 // 'l' : The lo register. 1 word storage.
3153 // 'x' : The hilo register pair. Double word storage.
3154 if (Constraint.size() == 1) {
3155 switch (Constraint[0]) {
3163 return C_RegisterClass;
3168 return TargetLowering::getConstraintType(Constraint);
3171 /// Examine constraint type and operand type and determine a weight value.
3172 /// This object must already have been set up with the operand type
3173 /// and the current alternative constraint selected.
3174 TargetLowering::ConstraintWeight
3175 MipsTargetLowering::getSingleConstraintMatchWeight(
3176 AsmOperandInfo &info, const char *constraint) const {
3177 ConstraintWeight weight = CW_Invalid;
3178 Value *CallOperandVal = info.CallOperandVal;
3179 // If we don't have a value, we can't do a match,
3180 // but allow it at the lowest weight.
3181 if (!CallOperandVal)
3183 Type *type = CallOperandVal->getType();
3184 // Look at the constraint type.
3185 switch (*constraint) {
3187 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3191 if (type->isIntegerTy())
3192 weight = CW_Register;
3194 case 'f': // FPU or MSA register
3195 if (Subtarget.hasMSA() && type->isVectorTy() &&
3196 cast<VectorType>(type)->getBitWidth() == 128)
3197 weight = CW_Register;
3198 else if (type->isFloatTy())
3199 weight = CW_Register;
3201 case 'c': // $25 for indirect jumps
3202 case 'l': // lo register
3203 case 'x': // hilo register pair
3204 if (type->isIntegerTy())
3205 weight = CW_SpecificReg;
3207 case 'I': // signed 16 bit immediate
3208 case 'J': // integer zero
3209 case 'K': // unsigned 16 bit immediate
3210 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3211 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3212 case 'O': // signed 15 bit immediate (+- 16383)
3213 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3214 if (isa<ConstantInt>(CallOperandVal))
3215 weight = CW_Constant;
3224 /// This is a helper function to parse a physical register string and split it
3225 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3226 /// that is returned indicates whether parsing was successful. The second flag
3227 /// is true if the numeric part exists.
3228 static std::pair<bool, bool>
3229 parsePhysicalReg(StringRef C, std::string &Prefix,
3230 unsigned long long &Reg) {
3231 if (C.front() != '{' || C.back() != '}')
3232 return std::make_pair(false, false);
3234 // Search for the first numeric character.
3235 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3236 I = std::find_if(B, E, std::ptr_fun(isdigit));
3238 Prefix.assign(B, I - B);
3240 // The second flag is set to false if no numeric characters were found.
3242 return std::make_pair(true, false);
3244 // Parse the numeric characters.
3245 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3249 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3250 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3251 const TargetRegisterInfo *TRI =
3252 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3253 const TargetRegisterClass *RC;
3255 unsigned long long Reg;
3257 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3260 return std::make_pair(0U, nullptr);
3262 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3263 // No numeric characters follow "hi" or "lo".
3265 return std::make_pair(0U, nullptr);
3267 RC = TRI->getRegClass(Prefix == "hi" ?
3268 Mips::HI32RegClassID : Mips::LO32RegClassID);
3269 return std::make_pair(*(RC->begin()), RC);
3270 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3271 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3273 // No numeric characters follow the name.
3275 return std::make_pair(0U, nullptr);
3277 Reg = StringSwitch<unsigned long long>(Prefix)
3278 .Case("$msair", Mips::MSAIR)
3279 .Case("$msacsr", Mips::MSACSR)
3280 .Case("$msaaccess", Mips::MSAAccess)
3281 .Case("$msasave", Mips::MSASave)
3282 .Case("$msamodify", Mips::MSAModify)
3283 .Case("$msarequest", Mips::MSARequest)
3284 .Case("$msamap", Mips::MSAMap)
3285 .Case("$msaunmap", Mips::MSAUnmap)
3289 return std::make_pair(0U, nullptr);
3291 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3292 return std::make_pair(Reg, RC);
3296 return std::make_pair(0U, nullptr);
3298 if (Prefix == "$f") { // Parse $f0-$f31.
3299 // If the size of FP registers is 64-bit or Reg is an even number, select
3300 // the 64-bit register class. Otherwise, select the 32-bit register class.
3301 if (VT == MVT::Other)
3302 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3304 RC = getRegClassFor(VT);
3306 if (RC == &Mips::AFGR64RegClass) {
3307 assert(Reg % 2 == 0);
3310 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3311 RC = TRI->getRegClass(Mips::FCCRegClassID);
3312 else if (Prefix == "$w") { // Parse $w0-$w31.
3313 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3314 } else { // Parse $0-$31.
3315 assert(Prefix == "$");
3316 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3319 assert(Reg < RC->getNumRegs());
3320 return std::make_pair(*(RC->begin() + Reg), RC);
3323 /// Given a register class constraint, like 'r', if this corresponds directly
3324 /// to an LLVM register class, return a register of 0 and the register class
3326 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3327 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3329 if (Constraint.size() == 1) {
3330 switch (Constraint[0]) {
3331 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3332 case 'y': // Same as 'r'. Exists for compatibility.
3334 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3335 if (Subtarget.inMips16Mode())
3336 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3337 return std::make_pair(0U, &Mips::GPR32RegClass);
3339 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3340 return std::make_pair(0U, &Mips::GPR32RegClass);
3341 if (VT == MVT::i64 && Subtarget.isGP64bit())
3342 return std::make_pair(0U, &Mips::GPR64RegClass);
3343 // This will generate an error message
3344 return std::make_pair(0U, nullptr);
3345 case 'f': // FPU or MSA register
3346 if (VT == MVT::v16i8)
3347 return std::make_pair(0U, &Mips::MSA128BRegClass);
3348 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3349 return std::make_pair(0U, &Mips::MSA128HRegClass);
3350 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3351 return std::make_pair(0U, &Mips::MSA128WRegClass);
3352 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3353 return std::make_pair(0U, &Mips::MSA128DRegClass);
3354 else if (VT == MVT::f32)
3355 return std::make_pair(0U, &Mips::FGR32RegClass);
3356 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3357 if (Subtarget.isFP64bit())
3358 return std::make_pair(0U, &Mips::FGR64RegClass);
3359 return std::make_pair(0U, &Mips::AFGR64RegClass);
3362 case 'c': // register suitable for indirect jump
3364 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3365 assert(VT == MVT::i64 && "Unexpected type.");
3366 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3367 case 'l': // register suitable for indirect jump
3369 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3370 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3371 case 'x': // register suitable for indirect jump
3372 // Fixme: Not triggering the use of both hi and low
3373 // This will generate an error message
3374 return std::make_pair(0U, nullptr);
3378 std::pair<unsigned, const TargetRegisterClass *> R;
3379 R = parseRegForInlineAsmConstraint(Constraint, VT);
3384 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3387 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3388 /// vector. If it is invalid, don't add anything to Ops.
3389 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3390 std::string &Constraint,
3391 std::vector<SDValue>&Ops,
3392 SelectionDAG &DAG) const {
3395 // Only support length 1 constraints for now.
3396 if (Constraint.length() > 1) return;
3398 char ConstraintLetter = Constraint[0];
3399 switch (ConstraintLetter) {
3400 default: break; // This will fall through to the generic implementation
3401 case 'I': // Signed 16 bit constant
3402 // If this fails, the parent routine will give an error
3403 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3404 EVT Type = Op.getValueType();
3405 int64_t Val = C->getSExtValue();
3406 if (isInt<16>(Val)) {
3407 Result = DAG.getTargetConstant(Val, Type);
3412 case 'J': // integer zero
3413 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3414 EVT Type = Op.getValueType();
3415 int64_t Val = C->getZExtValue();
3417 Result = DAG.getTargetConstant(0, Type);
3422 case 'K': // unsigned 16 bit immediate
3423 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3424 EVT Type = Op.getValueType();
3425 uint64_t Val = (uint64_t)C->getZExtValue();
3426 if (isUInt<16>(Val)) {
3427 Result = DAG.getTargetConstant(Val, Type);
3432 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3434 EVT Type = Op.getValueType();
3435 int64_t Val = C->getSExtValue();
3436 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3437 Result = DAG.getTargetConstant(Val, Type);
3442 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3443 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3444 EVT Type = Op.getValueType();
3445 int64_t Val = C->getSExtValue();
3446 if ((Val >= -65535) && (Val <= -1)) {
3447 Result = DAG.getTargetConstant(Val, Type);
3452 case 'O': // signed 15 bit immediate
3453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3454 EVT Type = Op.getValueType();
3455 int64_t Val = C->getSExtValue();
3456 if ((isInt<15>(Val))) {
3457 Result = DAG.getTargetConstant(Val, Type);
3462 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3463 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3464 EVT Type = Op.getValueType();
3465 int64_t Val = C->getSExtValue();
3466 if ((Val <= 65535) && (Val >= 1)) {
3467 Result = DAG.getTargetConstant(Val, Type);
3474 if (Result.getNode()) {
3475 Ops.push_back(Result);
3479 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3482 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3484 // No global is ever allowed as a base.
3489 case 0: // "r+i" or just "i", depending on HasBaseReg.
3492 if (!AM.HasBaseReg) // allow "r+i".
3494 return false; // disallow "r+r" or "r+r+i".
3503 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3504 // The Mips target isn't yet aware of offsets.
3508 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3510 bool IsMemset, bool ZeroMemset,
3512 MachineFunction &MF) const {
3513 if (Subtarget.hasMips64())
3519 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3520 if (VT != MVT::f32 && VT != MVT::f64)
3522 if (Imm.isNegZero())
3524 return Imm.isZero();
3527 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3528 if (Subtarget.isABI_N64())
3529 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3531 return TargetLowering::getJumpTableEncoding();
3534 /// This function returns true if CallSym is a long double emulation routine.
3535 static bool isF128SoftLibCall(const char *CallSym) {
3536 const char *const LibCalls[] =
3537 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3538 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3539 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3540 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3541 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3542 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3543 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3544 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3547 const char *const *End = LibCalls + array_lengthof(LibCalls);
3549 // Check that LibCalls is sorted alphabetically.
3550 MipsTargetLowering::LTStr Comp;
3553 for (const char *const *I = LibCalls; I < End - 1; ++I)
3554 assert(Comp(*I, *(I + 1)));
3557 return std::binary_search(LibCalls, End, CallSym, Comp);
3560 /// This function returns true if Ty is fp128, {f128} or i128 which was
3561 /// originally a fp128.
3562 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3563 if (Ty->isFP128Ty())
3566 if (Ty->isStructTy() && Ty->getStructNumElements() == 1 &&
3567 Ty->getStructElementType(0)->isFP128Ty())
3570 const ExternalSymbolSDNode *ES =
3571 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3573 // If the Ty is i128 and the function being called is a long double emulation
3574 // routine, then the original type is f128.
3575 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3578 MipsTargetLowering::MipsCC::SpecialCallingConvType
3579 MipsTargetLowering::MipsCC::getSpecialCallingConv(const SDNode *Callee) const {
3580 MipsCC::SpecialCallingConvType SpecialCallingConv =
3581 MipsCC::NoSpecialCallingConv;
3582 if (Subtarget.inMips16HardFloat()) {
3583 if (const GlobalAddressSDNode *G =
3584 dyn_cast<const GlobalAddressSDNode>(Callee)) {
3585 llvm::StringRef Sym = G->getGlobal()->getName();
3586 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3587 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3588 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3592 return SpecialCallingConv;
3595 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC,
3596 const MipsSubtarget &Subtarget_,
3598 : CallConv(CC), Subtarget(Subtarget_) {
3599 // Pre-allocate reserved argument area.
3600 Info.AllocateStack(reservedArgArea(), 1);
3603 void MipsTargetLowering::MipsCC::analyzeCallOperands(
3604 const SmallVectorImpl<ISD::OutputArg> &Args, bool IsVarArg,
3605 bool IsSoftFloat, const SDNode *CallNode,
3606 std::vector<ArgListEntry> &FuncArgs, CCState &State) {
3607 MipsCC::SpecialCallingConvType SpecialCallingConv =
3608 getSpecialCallingConv(CallNode);
3609 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3610 "CallingConv::Fast shouldn't be used for vararg functions.");
3612 unsigned NumOpnds = Args.size();
3613 llvm::CCAssignFn *FixedFn = CC_Mips_FixedArg;
3614 if (CallConv != CallingConv::Fast &&
3615 SpecialCallingConv == Mips16RetHelperConv)
3616 FixedFn = CC_Mips16RetHelper;
3618 for (unsigned I = 0; I != NumOpnds; ++I) {
3619 MVT ArgVT = Args[I].VT;
3620 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3623 if (IsVarArg && !Args[I].IsFixed)
3624 R = CC_Mips_VarArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
3626 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
3630 dbgs() << "Call operand #" << I << " has unhandled type "
3631 << EVT(ArgVT).getEVTString();
3633 llvm_unreachable(nullptr);
3638 void MipsTargetLowering::MipsCC::analyzeFormalArguments(
3639 const SmallVectorImpl<ISD::InputArg> &Args, bool IsSoftFloat,
3641 unsigned NumArgs = Args.size();
3643 for (unsigned I = 0; I != NumArgs; ++I) {
3644 MVT ArgVT = Args[I].VT;
3645 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3647 if (!CC_Mips_FixedArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State))
3651 dbgs() << "Formal Arg #" << I << " has unhandled type "
3652 << EVT(ArgVT).getEVTString();
3654 llvm_unreachable(nullptr);
3658 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3659 return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
3662 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
3663 if (Subtarget.isABI_O32())
3664 return makeArrayRef(O32IntRegs);
3665 return makeArrayRef(Mips64IntRegs);
3668 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3669 const SDNode *CallNode,
3670 bool IsSoftFloat) const {
3671 if (IsSoftFloat || Subtarget.isABI_O32())
3674 // Check if the original type was fp128.
3675 if (originalTypeIsF128(OrigTy, CallNode)) {
3676 assert(VT == MVT::i64);
3683 void MipsTargetLowering::copyByValRegs(
3684 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3685 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3686 const Argument *FuncArg, const MipsCC &CC, unsigned FirstReg,
3687 unsigned LastReg, const CCValAssign &VA) const {
3688 MachineFunction &MF = DAG.getMachineFunction();
3689 MachineFrameInfo *MFI = MF.getFrameInfo();
3690 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3691 unsigned NumRegs = LastReg - FirstReg;
3692 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3693 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3698 (int)CC.reservedArgArea() -
3699 (int)((CC.intArgRegs().size() - FirstReg) * GPRSizeInBytes);
3701 FrameObjOffset = VA.getLocMemOffset();
3703 // Create frame object.
3704 EVT PtrTy = getPointerTy();
3705 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3706 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3707 InVals.push_back(FIN);
3712 // Copy arg registers.
3713 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3714 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3716 for (unsigned I = 0; I < NumRegs; ++I) {
3717 unsigned ArgReg = CC.intArgRegs()[FirstReg + I];
3718 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3719 unsigned Offset = I * GPRSizeInBytes;
3720 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3721 DAG.getConstant(Offset, PtrTy));
3722 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3723 StorePtr, MachinePointerInfo(FuncArg, Offset),
3725 OutChains.push_back(Store);
3729 // Copy byVal arg to registers and stack.
3730 void MipsTargetLowering::passByValArg(
3731 SDValue Chain, SDLoc DL,
3732 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3733 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3734 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, const MipsCC &CC,
3735 unsigned FirstReg, unsigned LastReg, const ISD::ArgFlagsTy &Flags,
3736 bool isLittle, const CCValAssign &VA) const {
3737 unsigned ByValSizeInBytes = Flags.getByValSize();
3738 unsigned OffsetInBytes = 0; // From beginning of struct
3739 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3740 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3741 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3742 unsigned NumRegs = LastReg - FirstReg;
3745 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3746 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3749 // Copy words to registers.
3750 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3751 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3752 DAG.getConstant(OffsetInBytes, PtrTy));
3753 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3754 MachinePointerInfo(), false, false, false,
3756 MemOpChains.push_back(LoadVal.getValue(1));
3757 unsigned ArgReg = ArgRegs[FirstReg + I];
3758 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3761 // Return if the struct has been fully copied.
3762 if (ByValSizeInBytes == OffsetInBytes)
3765 // Copy the remainder of the byval argument with sub-word loads and shifts.
3766 if (LeftoverBytes) {
3769 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3770 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3771 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3773 if (RemainingSizeInBytes < LoadSizeInBytes)
3777 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3778 DAG.getConstant(OffsetInBytes, PtrTy));
3779 SDValue LoadVal = DAG.getExtLoad(
3780 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3781 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3783 MemOpChains.push_back(LoadVal.getValue(1));
3785 // Shift the loaded value.
3789 Shamt = TotalBytesLoaded * 8;
3791 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3793 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3794 DAG.getConstant(Shamt, MVT::i32));
3797 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3801 OffsetInBytes += LoadSizeInBytes;
3802 TotalBytesLoaded += LoadSizeInBytes;
3803 Alignment = std::min(Alignment, LoadSizeInBytes);
3806 unsigned ArgReg = ArgRegs[FirstReg + I];
3807 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3812 // Copy remainder of byval arg to it with memcpy.
3813 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3814 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3815 DAG.getConstant(OffsetInBytes, PtrTy));
3816 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3817 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3818 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3819 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3820 MachinePointerInfo(), MachinePointerInfo());
3821 MemOpChains.push_back(Chain);
3824 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3825 const MipsCC &CC, SDValue Chain,
3826 SDLoc DL, SelectionDAG &DAG,
3827 CCState &State) const {
3828 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3829 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3830 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3831 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3832 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3833 MachineFunction &MF = DAG.getMachineFunction();
3834 MachineFrameInfo *MFI = MF.getFrameInfo();
3835 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3837 // Offset of the first variable argument from stack pointer.
3840 if (ArgRegs.size() == Idx)
3842 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3844 VaArgOffset = (int)CC.reservedArgArea() -
3845 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3847 // Record the frame index of the first variable argument
3848 // which is a value necessary to VASTART.
3849 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3850 MipsFI->setVarArgsFrameIndex(FI);
3852 // Copy the integer registers that have not been used for argument passing
3853 // to the argument register save area. For O32, the save area is allocated
3854 // in the caller's stack frame, while for N32/64, it is allocated in the
3855 // callee's stack frame.
3856 for (unsigned I = Idx; I < ArgRegs.size();
3857 ++I, VaArgOffset += RegSizeInBytes) {
3858 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3859 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3860 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3861 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3862 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3863 MachinePointerInfo(), false, false, 0);
3864 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3866 OutChains.push_back(Store);
3870 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3871 unsigned Align) const {
3872 MachineFunction &MF = State->getMachineFunction();
3873 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3875 assert(Size && "Byval argument's size shouldn't be 0.");
3877 Align = std::min(Align, TFL->getStackAlignment());
3879 unsigned FirstReg = 0;
3880 unsigned NumRegs = 0;
3882 if (State->getCallingConv() != CallingConv::Fast) {
3883 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3884 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3885 // FIXME: The O32 case actually describes no shadow registers.
3886 const MCPhysReg *ShadowRegs =
3887 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3889 // We used to check the size as well but we can't do that anymore since
3890 // CCState::HandleByVal() rounds up the size after calling this function.
3891 assert(!(Align % RegSizeInBytes) &&
3892 "Byval argument's alignment should be a multiple of"
3895 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3897 // If Align > RegSizeInBytes, the first arg register must be even.
3898 // FIXME: This condition happens to do the right thing but it's not the
3899 // right way to test it. We want to check that the stack frame offset
3900 // of the register is aligned.
3901 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3902 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3906 // Mark the registers allocated.
3907 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3908 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3909 Size -= RegSizeInBytes, ++I, ++NumRegs)
3910 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3913 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);