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();
115 std::advance(FuncArg, Ins[i].OrigArgIndex);
117 OriginalArgWasF128.push_back(
118 originalTypeIsF128(FuncArg->getType(), nullptr));
122 /// Records whether the value has been lowered from an f128.
123 SmallVector<bool, 4> OriginalArgWasF128;
126 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
127 // to allow analyzeCallOperands to be removed incrementally.
128 void PreAnalyzeCallOperandsForF128_(
129 const SmallVectorImpl<ISD::OutputArg> &Outs,
130 std::vector<TargetLowering::ArgListEntry> &FuncArgs, SDNode *CallNode) {
131 PreAnalyzeCallOperandsForF128(Outs, FuncArgs, CallNode);
133 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
134 // to allow analyzeFormalArguments to be removed incrementally.
136 PreAnalyzeFormalArgumentsForF128_(const SmallVectorImpl<ISD::InputArg> &Ins) {
137 PreAnalyzeFormalArgumentsForF128(Ins);
139 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
140 // to clean up after the above functions.
141 void ClearOriginalArgWasF128() { OriginalArgWasF128.clear(); }
143 MipsCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
144 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C)
145 : CCState(CC, isVarArg, MF, locs, C) {}
147 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
149 const TargetLowering::CallLoweringInfo &CLI) {
150 PreAnalyzeCallResultForF128(Ins, CLI);
151 CCState::AnalyzeCallResult(Ins, Fn);
152 OriginalArgWasF128.clear();
155 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
157 PreAnalyzeReturnForF128(Outs);
158 CCState::AnalyzeReturn(Outs, Fn);
159 OriginalArgWasF128.clear();
162 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
164 PreAnalyzeReturnForF128(ArgsFlags);
165 bool Return = CCState::CheckReturn(ArgsFlags, Fn);
166 OriginalArgWasF128.clear();
170 bool WasOriginalArgF128(unsigned ValNo) { return OriginalArgWasF128[ValNo]; }
174 // If I is a shifted mask, set the size (Size) and the first bit of the
175 // mask (Pos), and return true.
176 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
177 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
178 if (!isShiftedMask_64(I))
181 Size = CountPopulation_64(I);
182 Pos = countTrailingZeros(I);
186 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
187 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
188 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
191 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
193 unsigned Flag) const {
194 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
197 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
199 unsigned Flag) const {
200 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
203 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
205 unsigned Flag) const {
206 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
209 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
211 unsigned Flag) const {
212 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
215 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
217 unsigned Flag) const {
218 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
219 N->getOffset(), Flag);
222 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
224 case MipsISD::JmpLink: return "MipsISD::JmpLink";
225 case MipsISD::TailCall: return "MipsISD::TailCall";
226 case MipsISD::Hi: return "MipsISD::Hi";
227 case MipsISD::Lo: return "MipsISD::Lo";
228 case MipsISD::GPRel: return "MipsISD::GPRel";
229 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
230 case MipsISD::Ret: return "MipsISD::Ret";
231 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
232 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
233 case MipsISD::FPCmp: return "MipsISD::FPCmp";
234 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
235 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
236 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
237 case MipsISD::MFHI: return "MipsISD::MFHI";
238 case MipsISD::MFLO: return "MipsISD::MFLO";
239 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
240 case MipsISD::Mult: return "MipsISD::Mult";
241 case MipsISD::Multu: return "MipsISD::Multu";
242 case MipsISD::MAdd: return "MipsISD::MAdd";
243 case MipsISD::MAddu: return "MipsISD::MAddu";
244 case MipsISD::MSub: return "MipsISD::MSub";
245 case MipsISD::MSubu: return "MipsISD::MSubu";
246 case MipsISD::DivRem: return "MipsISD::DivRem";
247 case MipsISD::DivRemU: return "MipsISD::DivRemU";
248 case MipsISD::DivRem16: return "MipsISD::DivRem16";
249 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
250 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
251 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
252 case MipsISD::Wrapper: return "MipsISD::Wrapper";
253 case MipsISD::Sync: return "MipsISD::Sync";
254 case MipsISD::Ext: return "MipsISD::Ext";
255 case MipsISD::Ins: return "MipsISD::Ins";
256 case MipsISD::LWL: return "MipsISD::LWL";
257 case MipsISD::LWR: return "MipsISD::LWR";
258 case MipsISD::SWL: return "MipsISD::SWL";
259 case MipsISD::SWR: return "MipsISD::SWR";
260 case MipsISD::LDL: return "MipsISD::LDL";
261 case MipsISD::LDR: return "MipsISD::LDR";
262 case MipsISD::SDL: return "MipsISD::SDL";
263 case MipsISD::SDR: return "MipsISD::SDR";
264 case MipsISD::EXTP: return "MipsISD::EXTP";
265 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
266 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
267 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
268 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
269 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
270 case MipsISD::SHILO: return "MipsISD::SHILO";
271 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
272 case MipsISD::MULT: return "MipsISD::MULT";
273 case MipsISD::MULTU: return "MipsISD::MULTU";
274 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
275 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
276 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
277 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
278 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
279 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
280 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
281 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
282 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
283 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
284 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
285 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
286 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
287 case MipsISD::VCEQ: return "MipsISD::VCEQ";
288 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
289 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
290 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
291 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
292 case MipsISD::VSMAX: return "MipsISD::VSMAX";
293 case MipsISD::VSMIN: return "MipsISD::VSMIN";
294 case MipsISD::VUMAX: return "MipsISD::VUMAX";
295 case MipsISD::VUMIN: return "MipsISD::VUMIN";
296 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
297 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
298 case MipsISD::VNOR: return "MipsISD::VNOR";
299 case MipsISD::VSHF: return "MipsISD::VSHF";
300 case MipsISD::SHF: return "MipsISD::SHF";
301 case MipsISD::ILVEV: return "MipsISD::ILVEV";
302 case MipsISD::ILVOD: return "MipsISD::ILVOD";
303 case MipsISD::ILVL: return "MipsISD::ILVL";
304 case MipsISD::ILVR: return "MipsISD::ILVR";
305 case MipsISD::PCKEV: return "MipsISD::PCKEV";
306 case MipsISD::PCKOD: return "MipsISD::PCKOD";
307 case MipsISD::INSVE: return "MipsISD::INSVE";
308 default: return nullptr;
312 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
313 const MipsSubtarget &STI)
314 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
315 // Mips does not have i1 type, so use i32 for
316 // setcc operations results (slt, sgt, ...).
317 setBooleanContents(ZeroOrOneBooleanContent);
318 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
319 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
320 // does. Integer booleans still use 0 and 1.
321 if (Subtarget.hasMips32r6())
322 setBooleanContents(ZeroOrOneBooleanContent,
323 ZeroOrNegativeOneBooleanContent);
325 // Load extented operations for i1 types must be promoted
326 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
327 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
328 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
330 // MIPS doesn't have extending float->double load/store
331 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
332 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
334 // Used by legalize types to correctly generate the setcc result.
335 // Without this, every float setcc comes with a AND/OR with the result,
336 // we don't want this, since the fpcmp result goes to a flag register,
337 // which is used implicitly by brcond and select operations.
338 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
340 // Mips Custom Operations
341 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
342 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
343 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
344 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
345 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
346 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
347 setOperationAction(ISD::SELECT, MVT::f32, Custom);
348 setOperationAction(ISD::SELECT, MVT::f64, Custom);
349 setOperationAction(ISD::SELECT, MVT::i32, Custom);
350 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
351 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
352 setOperationAction(ISD::SETCC, MVT::f32, Custom);
353 setOperationAction(ISD::SETCC, MVT::f64, Custom);
354 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
355 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
356 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
357 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
359 if (Subtarget.isGP64bit()) {
360 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
361 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
362 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
363 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
364 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
365 setOperationAction(ISD::SELECT, MVT::i64, Custom);
366 setOperationAction(ISD::LOAD, MVT::i64, Custom);
367 setOperationAction(ISD::STORE, MVT::i64, Custom);
368 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
371 if (!Subtarget.isGP64bit()) {
372 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
373 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
374 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
377 setOperationAction(ISD::ADD, MVT::i32, Custom);
378 if (Subtarget.isGP64bit())
379 setOperationAction(ISD::ADD, MVT::i64, Custom);
381 setOperationAction(ISD::SDIV, MVT::i32, Expand);
382 setOperationAction(ISD::SREM, MVT::i32, Expand);
383 setOperationAction(ISD::UDIV, MVT::i32, Expand);
384 setOperationAction(ISD::UREM, MVT::i32, Expand);
385 setOperationAction(ISD::SDIV, MVT::i64, Expand);
386 setOperationAction(ISD::SREM, MVT::i64, Expand);
387 setOperationAction(ISD::UDIV, MVT::i64, Expand);
388 setOperationAction(ISD::UREM, MVT::i64, Expand);
390 // Operations not directly supported by Mips.
391 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
392 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
393 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
394 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
395 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
396 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
397 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
398 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
399 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
400 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
401 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
402 if (Subtarget.hasCnMips()) {
403 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
404 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
406 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
407 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
409 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
410 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
411 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
412 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::ROTL, MVT::i32, Expand);
416 setOperationAction(ISD::ROTL, MVT::i64, Expand);
417 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
420 if (!Subtarget.hasMips32r2())
421 setOperationAction(ISD::ROTR, MVT::i32, Expand);
423 if (!Subtarget.hasMips64r2())
424 setOperationAction(ISD::ROTR, MVT::i64, Expand);
426 setOperationAction(ISD::FSIN, MVT::f32, Expand);
427 setOperationAction(ISD::FSIN, MVT::f64, Expand);
428 setOperationAction(ISD::FCOS, MVT::f32, Expand);
429 setOperationAction(ISD::FCOS, MVT::f64, Expand);
430 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
431 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
432 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
433 setOperationAction(ISD::FPOW, MVT::f32, Expand);
434 setOperationAction(ISD::FPOW, MVT::f64, Expand);
435 setOperationAction(ISD::FLOG, MVT::f32, Expand);
436 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
437 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
438 setOperationAction(ISD::FEXP, MVT::f32, Expand);
439 setOperationAction(ISD::FMA, MVT::f32, Expand);
440 setOperationAction(ISD::FMA, MVT::f64, Expand);
441 setOperationAction(ISD::FREM, MVT::f32, Expand);
442 setOperationAction(ISD::FREM, MVT::f64, Expand);
444 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
446 setOperationAction(ISD::VASTART, MVT::Other, Custom);
447 setOperationAction(ISD::VAARG, MVT::Other, Custom);
448 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
449 setOperationAction(ISD::VAEND, MVT::Other, Expand);
451 // Use the default for now
452 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
453 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
455 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
456 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
457 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
458 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
460 setInsertFencesForAtomic(true);
462 if (!Subtarget.hasMips32r2()) {
463 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
464 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
467 // MIPS16 lacks MIPS32's clz and clo instructions.
468 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
469 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
470 if (!Subtarget.hasMips64())
471 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
473 if (!Subtarget.hasMips32r2())
474 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
475 if (!Subtarget.hasMips64r2())
476 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
478 if (Subtarget.isGP64bit()) {
479 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
480 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
481 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
482 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
485 setOperationAction(ISD::TRAP, MVT::Other, Legal);
487 setTargetDAGCombine(ISD::SDIVREM);
488 setTargetDAGCombine(ISD::UDIVREM);
489 setTargetDAGCombine(ISD::SELECT);
490 setTargetDAGCombine(ISD::AND);
491 setTargetDAGCombine(ISD::OR);
492 setTargetDAGCombine(ISD::ADD);
494 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
496 // The arguments on the stack are defined in terms of 4-byte slots on O32
497 // and 8-byte slots on N32/N64.
498 setMinStackArgumentAlignment(
499 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
501 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
504 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
505 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
507 MaxStoresPerMemcpy = 16;
509 isMicroMips = Subtarget.inMicroMipsMode();
512 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
513 const MipsSubtarget &STI) {
514 if (STI.inMips16Mode())
515 return llvm::createMips16TargetLowering(TM, STI);
517 return llvm::createMipsSETargetLowering(TM, STI);
520 // Create a fast isel object.
522 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
523 const TargetLibraryInfo *libInfo) const {
524 if (!EnableMipsFastISel)
525 return TargetLowering::createFastISel(funcInfo, libInfo);
526 return Mips::createFastISel(funcInfo, libInfo);
529 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
532 return VT.changeVectorElementTypeToInteger();
535 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
536 TargetLowering::DAGCombinerInfo &DCI,
537 const MipsSubtarget &Subtarget) {
538 if (DCI.isBeforeLegalizeOps())
541 EVT Ty = N->getValueType(0);
542 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
543 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
544 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
548 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
549 N->getOperand(0), N->getOperand(1));
550 SDValue InChain = DAG.getEntryNode();
551 SDValue InGlue = DivRem;
554 if (N->hasAnyUseOfValue(0)) {
555 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
557 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
558 InChain = CopyFromLo.getValue(1);
559 InGlue = CopyFromLo.getValue(2);
563 if (N->hasAnyUseOfValue(1)) {
564 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
566 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
572 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
574 default: llvm_unreachable("Unknown fp condition code!");
576 case ISD::SETOEQ: return Mips::FCOND_OEQ;
577 case ISD::SETUNE: return Mips::FCOND_UNE;
579 case ISD::SETOLT: return Mips::FCOND_OLT;
581 case ISD::SETOGT: return Mips::FCOND_OGT;
583 case ISD::SETOLE: return Mips::FCOND_OLE;
585 case ISD::SETOGE: return Mips::FCOND_OGE;
586 case ISD::SETULT: return Mips::FCOND_ULT;
587 case ISD::SETULE: return Mips::FCOND_ULE;
588 case ISD::SETUGT: return Mips::FCOND_UGT;
589 case ISD::SETUGE: return Mips::FCOND_UGE;
590 case ISD::SETUO: return Mips::FCOND_UN;
591 case ISD::SETO: return Mips::FCOND_OR;
593 case ISD::SETONE: return Mips::FCOND_ONE;
594 case ISD::SETUEQ: return Mips::FCOND_UEQ;
599 /// This function returns true if the floating point conditional branches and
600 /// conditional moves which use condition code CC should be inverted.
601 static bool invertFPCondCodeUser(Mips::CondCode CC) {
602 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
605 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
606 "Illegal Condition Code");
611 // Creates and returns an FPCmp node from a setcc node.
612 // Returns Op if setcc is not a floating point comparison.
613 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
614 // must be a SETCC node
615 if (Op.getOpcode() != ISD::SETCC)
618 SDValue LHS = Op.getOperand(0);
620 if (!LHS.getValueType().isFloatingPoint())
623 SDValue RHS = Op.getOperand(1);
626 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
627 // node if necessary.
628 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
630 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
631 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
634 // Creates and returns a CMovFPT/F node.
635 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
636 SDValue False, SDLoc DL) {
637 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
638 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
639 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
641 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
642 True.getValueType(), True, FCC0, False, Cond);
645 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
646 TargetLowering::DAGCombinerInfo &DCI,
647 const MipsSubtarget &Subtarget) {
648 if (DCI.isBeforeLegalizeOps())
651 SDValue SetCC = N->getOperand(0);
653 if ((SetCC.getOpcode() != ISD::SETCC) ||
654 !SetCC.getOperand(0).getValueType().isInteger())
657 SDValue False = N->getOperand(2);
658 EVT FalseTy = False.getValueType();
660 if (!FalseTy.isInteger())
663 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
665 // If the RHS (False) is 0, we swap the order of the operands
666 // of ISD::SELECT (obviously also inverting the condition) so that we can
667 // take advantage of conditional moves using the $0 register.
669 // return (a != 0) ? x : 0;
677 if (!FalseC->getZExtValue()) {
678 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
679 SDValue True = N->getOperand(1);
681 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
682 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
684 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
687 // If both operands are integer constants there's a possibility that we
688 // can do some interesting optimizations.
689 SDValue True = N->getOperand(1);
690 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
692 if (!TrueC || !True.getValueType().isInteger())
695 // We'll also ignore MVT::i64 operands as this optimizations proves
696 // to be ineffective because of the required sign extensions as the result
697 // of a SETCC operator is always MVT::i32 for non-vector types.
698 if (True.getValueType() == MVT::i64)
701 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
703 // 1) (a < x) ? y : y-1
705 // addiu $reg2, $reg1, y-1
707 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
709 // 2) (a < x) ? y-1 : y
711 // xor $reg1, $reg1, 1
712 // addiu $reg2, $reg1, y-1
714 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
715 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
716 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
717 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
720 // Couldn't optimize.
724 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
725 TargetLowering::DAGCombinerInfo &DCI,
726 const MipsSubtarget &Subtarget) {
727 // Pattern match EXT.
728 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
729 // => ext $dst, $src, size, pos
730 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
733 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
734 unsigned ShiftRightOpc = ShiftRight.getOpcode();
736 // Op's first operand must be a shift right.
737 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
740 // The second operand of the shift must be an immediate.
742 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
745 uint64_t Pos = CN->getZExtValue();
746 uint64_t SMPos, SMSize;
748 // Op's second operand must be a shifted mask.
749 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
750 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
753 // Return if the shifted mask does not start at bit 0 or the sum of its size
754 // and Pos exceeds the word's size.
755 EVT ValTy = N->getValueType(0);
756 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
759 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
760 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
761 DAG.getConstant(SMSize, MVT::i32));
764 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
765 TargetLowering::DAGCombinerInfo &DCI,
766 const MipsSubtarget &Subtarget) {
767 // Pattern match INS.
768 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
769 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
770 // => ins $dst, $src, size, pos, $src1
771 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
774 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
775 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
778 // See if Op's first operand matches (and $src1 , mask0).
779 if (And0.getOpcode() != ISD::AND)
782 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
783 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
786 // See if Op's second operand matches (and (shl $src, pos), mask1).
787 if (And1.getOpcode() != ISD::AND)
790 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
791 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
794 // The shift masks must have the same position and size.
795 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
798 SDValue Shl = And1.getOperand(0);
799 if (Shl.getOpcode() != ISD::SHL)
802 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
805 unsigned Shamt = CN->getZExtValue();
807 // Return if the shift amount and the first bit position of mask are not the
809 EVT ValTy = N->getValueType(0);
810 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
813 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
814 DAG.getConstant(SMPos0, MVT::i32),
815 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
818 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
819 TargetLowering::DAGCombinerInfo &DCI,
820 const MipsSubtarget &Subtarget) {
821 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
823 if (DCI.isBeforeLegalizeOps())
826 SDValue Add = N->getOperand(1);
828 if (Add.getOpcode() != ISD::ADD)
831 SDValue Lo = Add.getOperand(1);
833 if ((Lo.getOpcode() != MipsISD::Lo) ||
834 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
837 EVT ValTy = N->getValueType(0);
840 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
842 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
845 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
847 SelectionDAG &DAG = DCI.DAG;
848 unsigned Opc = N->getOpcode();
854 return performDivRemCombine(N, DAG, DCI, Subtarget);
856 return performSELECTCombine(N, DAG, DCI, Subtarget);
858 return performANDCombine(N, DAG, DCI, Subtarget);
860 return performORCombine(N, DAG, DCI, Subtarget);
862 return performADDCombine(N, DAG, DCI, Subtarget);
869 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
870 SmallVectorImpl<SDValue> &Results,
871 SelectionDAG &DAG) const {
872 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
874 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
875 Results.push_back(Res.getValue(I));
879 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
880 SmallVectorImpl<SDValue> &Results,
881 SelectionDAG &DAG) const {
882 return LowerOperationWrapper(N, Results, DAG);
885 SDValue MipsTargetLowering::
886 LowerOperation(SDValue Op, SelectionDAG &DAG) const
888 switch (Op.getOpcode())
890 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
891 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
892 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
893 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
894 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
895 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
896 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
897 case ISD::SELECT: return lowerSELECT(Op, DAG);
898 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
899 case ISD::SETCC: return lowerSETCC(Op, DAG);
900 case ISD::VASTART: return lowerVASTART(Op, DAG);
901 case ISD::VAARG: return lowerVAARG(Op, DAG);
902 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
903 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
904 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
905 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
906 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
907 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
908 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
909 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
910 case ISD::LOAD: return lowerLOAD(Op, DAG);
911 case ISD::STORE: return lowerSTORE(Op, DAG);
912 case ISD::ADD: return lowerADD(Op, DAG);
913 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
918 //===----------------------------------------------------------------------===//
919 // Lower helper functions
920 //===----------------------------------------------------------------------===//
922 // addLiveIn - This helper function adds the specified physical register to the
923 // MachineFunction as a live in value. It also creates a corresponding
924 // virtual register for it.
926 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
928 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
929 MF.getRegInfo().addLiveIn(PReg, VReg);
933 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
934 MachineBasicBlock &MBB,
935 const TargetInstrInfo &TII,
940 // Insert instruction "teq $divisor_reg, $zero, 7".
941 MachineBasicBlock::iterator I(MI);
942 MachineInstrBuilder MIB;
943 MachineOperand &Divisor = MI->getOperand(2);
944 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
945 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
946 .addReg(Mips::ZERO).addImm(7);
948 // Use the 32-bit sub-register if this is a 64-bit division.
950 MIB->getOperand(0).setSubReg(Mips::sub_32);
952 // Clear Divisor's kill flag.
953 Divisor.setIsKill(false);
955 // We would normally delete the original instruction here but in this case
956 // we only needed to inject an additional instruction rather than replace it.
962 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
963 MachineBasicBlock *BB) const {
964 switch (MI->getOpcode()) {
966 llvm_unreachable("Unexpected instr type to insert");
967 case Mips::ATOMIC_LOAD_ADD_I8:
968 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
969 case Mips::ATOMIC_LOAD_ADD_I16:
970 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
971 case Mips::ATOMIC_LOAD_ADD_I32:
972 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
973 case Mips::ATOMIC_LOAD_ADD_I64:
974 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
976 case Mips::ATOMIC_LOAD_AND_I8:
977 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
978 case Mips::ATOMIC_LOAD_AND_I16:
979 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
980 case Mips::ATOMIC_LOAD_AND_I32:
981 return emitAtomicBinary(MI, BB, 4, Mips::AND);
982 case Mips::ATOMIC_LOAD_AND_I64:
983 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
985 case Mips::ATOMIC_LOAD_OR_I8:
986 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
987 case Mips::ATOMIC_LOAD_OR_I16:
988 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
989 case Mips::ATOMIC_LOAD_OR_I32:
990 return emitAtomicBinary(MI, BB, 4, Mips::OR);
991 case Mips::ATOMIC_LOAD_OR_I64:
992 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
994 case Mips::ATOMIC_LOAD_XOR_I8:
995 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
996 case Mips::ATOMIC_LOAD_XOR_I16:
997 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
998 case Mips::ATOMIC_LOAD_XOR_I32:
999 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1000 case Mips::ATOMIC_LOAD_XOR_I64:
1001 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1003 case Mips::ATOMIC_LOAD_NAND_I8:
1004 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1005 case Mips::ATOMIC_LOAD_NAND_I16:
1006 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1007 case Mips::ATOMIC_LOAD_NAND_I32:
1008 return emitAtomicBinary(MI, BB, 4, 0, true);
1009 case Mips::ATOMIC_LOAD_NAND_I64:
1010 return emitAtomicBinary(MI, BB, 8, 0, true);
1012 case Mips::ATOMIC_LOAD_SUB_I8:
1013 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1014 case Mips::ATOMIC_LOAD_SUB_I16:
1015 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1016 case Mips::ATOMIC_LOAD_SUB_I32:
1017 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1018 case Mips::ATOMIC_LOAD_SUB_I64:
1019 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1021 case Mips::ATOMIC_SWAP_I8:
1022 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1023 case Mips::ATOMIC_SWAP_I16:
1024 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1025 case Mips::ATOMIC_SWAP_I32:
1026 return emitAtomicBinary(MI, BB, 4, 0);
1027 case Mips::ATOMIC_SWAP_I64:
1028 return emitAtomicBinary(MI, BB, 8, 0);
1030 case Mips::ATOMIC_CMP_SWAP_I8:
1031 return emitAtomicCmpSwapPartword(MI, BB, 1);
1032 case Mips::ATOMIC_CMP_SWAP_I16:
1033 return emitAtomicCmpSwapPartword(MI, BB, 2);
1034 case Mips::ATOMIC_CMP_SWAP_I32:
1035 return emitAtomicCmpSwap(MI, BB, 4);
1036 case Mips::ATOMIC_CMP_SWAP_I64:
1037 return emitAtomicCmpSwap(MI, BB, 8);
1038 case Mips::PseudoSDIV:
1039 case Mips::PseudoUDIV:
1044 return insertDivByZeroTrap(
1045 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
1046 case Mips::PseudoDSDIV:
1047 case Mips::PseudoDUDIV:
1052 return insertDivByZeroTrap(
1053 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
1055 return emitSEL_D(MI, BB);
1059 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1060 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1062 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1063 unsigned Size, unsigned BinOpcode,
1065 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1067 MachineFunction *MF = BB->getParent();
1068 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1069 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1070 const TargetInstrInfo *TII =
1071 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1072 DebugLoc DL = MI->getDebugLoc();
1073 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1080 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1081 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1088 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1089 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1092 ZERO = Mips::ZERO_64;
1096 unsigned OldVal = MI->getOperand(0).getReg();
1097 unsigned Ptr = MI->getOperand(1).getReg();
1098 unsigned Incr = MI->getOperand(2).getReg();
1100 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1101 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1102 unsigned Success = RegInfo.createVirtualRegister(RC);
1104 // insert new blocks after the current block
1105 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1106 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1107 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1108 MachineFunction::iterator It = BB;
1110 MF->insert(It, loopMBB);
1111 MF->insert(It, exitMBB);
1113 // Transfer the remainder of BB and its successor edges to exitMBB.
1114 exitMBB->splice(exitMBB->begin(), BB,
1115 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1116 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1120 // fallthrough --> loopMBB
1121 BB->addSuccessor(loopMBB);
1122 loopMBB->addSuccessor(loopMBB);
1123 loopMBB->addSuccessor(exitMBB);
1126 // ll oldval, 0(ptr)
1127 // <binop> storeval, oldval, incr
1128 // sc success, storeval, 0(ptr)
1129 // beq success, $0, loopMBB
1131 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1133 // and andres, oldval, incr
1134 // nor storeval, $0, andres
1135 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1136 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1137 } else if (BinOpcode) {
1138 // <binop> storeval, oldval, incr
1139 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1143 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1144 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1146 MI->eraseFromParent(); // The instruction is gone now.
1151 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1152 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1153 unsigned SrcReg) const {
1154 const TargetInstrInfo *TII =
1155 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1156 DebugLoc DL = MI->getDebugLoc();
1158 if (Subtarget.hasMips32r2() && Size == 1) {
1159 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1163 if (Subtarget.hasMips32r2() && Size == 2) {
1164 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1168 MachineFunction *MF = BB->getParent();
1169 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1170 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1171 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1174 int64_t ShiftImm = 32 - (Size * 8);
1176 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1177 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1182 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1183 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1185 assert((Size == 1 || Size == 2) &&
1186 "Unsupported size for EmitAtomicBinaryPartial.");
1188 MachineFunction *MF = BB->getParent();
1189 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1190 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1191 const TargetInstrInfo *TII =
1192 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1193 DebugLoc DL = MI->getDebugLoc();
1195 unsigned Dest = MI->getOperand(0).getReg();
1196 unsigned Ptr = MI->getOperand(1).getReg();
1197 unsigned Incr = MI->getOperand(2).getReg();
1199 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1200 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1201 unsigned Mask = RegInfo.createVirtualRegister(RC);
1202 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1203 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1204 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1205 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1206 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1207 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1208 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1209 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1210 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1211 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1212 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1213 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1214 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1215 unsigned Success = RegInfo.createVirtualRegister(RC);
1217 // insert new blocks after the current block
1218 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1219 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1220 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1221 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1222 MachineFunction::iterator It = BB;
1224 MF->insert(It, loopMBB);
1225 MF->insert(It, sinkMBB);
1226 MF->insert(It, exitMBB);
1228 // Transfer the remainder of BB and its successor edges to exitMBB.
1229 exitMBB->splice(exitMBB->begin(), BB,
1230 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1231 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1233 BB->addSuccessor(loopMBB);
1234 loopMBB->addSuccessor(loopMBB);
1235 loopMBB->addSuccessor(sinkMBB);
1236 sinkMBB->addSuccessor(exitMBB);
1239 // addiu masklsb2,$0,-4 # 0xfffffffc
1240 // and alignedaddr,ptr,masklsb2
1241 // andi ptrlsb2,ptr,3
1242 // sll shiftamt,ptrlsb2,3
1243 // ori maskupper,$0,255 # 0xff
1244 // sll mask,maskupper,shiftamt
1245 // nor mask2,$0,mask
1246 // sll incr2,incr,shiftamt
1248 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1249 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1250 .addReg(Mips::ZERO).addImm(-4);
1251 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1252 .addReg(Ptr).addReg(MaskLSB2);
1253 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1254 if (Subtarget.isLittle()) {
1255 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1257 unsigned Off = RegInfo.createVirtualRegister(RC);
1258 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1259 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1260 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1262 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1263 .addReg(Mips::ZERO).addImm(MaskImm);
1264 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1265 .addReg(MaskUpper).addReg(ShiftAmt);
1266 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1267 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1269 // atomic.load.binop
1271 // ll oldval,0(alignedaddr)
1272 // binop binopres,oldval,incr2
1273 // and newval,binopres,mask
1274 // and maskedoldval0,oldval,mask2
1275 // or storeval,maskedoldval0,newval
1276 // sc success,storeval,0(alignedaddr)
1277 // beq success,$0,loopMBB
1281 // ll oldval,0(alignedaddr)
1282 // and newval,incr2,mask
1283 // and maskedoldval0,oldval,mask2
1284 // or storeval,maskedoldval0,newval
1285 // sc success,storeval,0(alignedaddr)
1286 // beq success,$0,loopMBB
1289 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1291 // and andres, oldval, incr2
1292 // nor binopres, $0, andres
1293 // and newval, binopres, mask
1294 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1295 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1296 .addReg(Mips::ZERO).addReg(AndRes);
1297 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1298 } else if (BinOpcode) {
1299 // <binop> binopres, oldval, incr2
1300 // and newval, binopres, mask
1301 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1302 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1303 } else { // atomic.swap
1304 // and newval, incr2, mask
1305 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1308 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1309 .addReg(OldVal).addReg(Mask2);
1310 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1311 .addReg(MaskedOldVal0).addReg(NewVal);
1312 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1313 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1314 BuildMI(BB, DL, TII->get(Mips::BEQ))
1315 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1318 // and maskedoldval1,oldval,mask
1319 // srl srlres,maskedoldval1,shiftamt
1320 // sign_extend dest,srlres
1323 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1324 .addReg(OldVal).addReg(Mask);
1325 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1326 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1327 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1329 MI->eraseFromParent(); // The instruction is gone now.
1334 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1335 MachineBasicBlock *BB,
1336 unsigned Size) const {
1337 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1339 MachineFunction *MF = BB->getParent();
1340 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1341 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1342 const TargetInstrInfo *TII =
1343 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1344 DebugLoc DL = MI->getDebugLoc();
1345 unsigned LL, SC, ZERO, BNE, BEQ;
1348 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1349 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1356 ZERO = Mips::ZERO_64;
1361 unsigned Dest = MI->getOperand(0).getReg();
1362 unsigned Ptr = MI->getOperand(1).getReg();
1363 unsigned OldVal = MI->getOperand(2).getReg();
1364 unsigned NewVal = MI->getOperand(3).getReg();
1366 unsigned Success = RegInfo.createVirtualRegister(RC);
1368 // insert new blocks after the current block
1369 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1370 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1371 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1372 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1373 MachineFunction::iterator It = BB;
1375 MF->insert(It, loop1MBB);
1376 MF->insert(It, loop2MBB);
1377 MF->insert(It, exitMBB);
1379 // Transfer the remainder of BB and its successor edges to exitMBB.
1380 exitMBB->splice(exitMBB->begin(), BB,
1381 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1382 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1386 // fallthrough --> loop1MBB
1387 BB->addSuccessor(loop1MBB);
1388 loop1MBB->addSuccessor(exitMBB);
1389 loop1MBB->addSuccessor(loop2MBB);
1390 loop2MBB->addSuccessor(loop1MBB);
1391 loop2MBB->addSuccessor(exitMBB);
1395 // bne dest, oldval, exitMBB
1397 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1398 BuildMI(BB, DL, TII->get(BNE))
1399 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1402 // sc success, newval, 0(ptr)
1403 // beq success, $0, loop1MBB
1405 BuildMI(BB, DL, TII->get(SC), Success)
1406 .addReg(NewVal).addReg(Ptr).addImm(0);
1407 BuildMI(BB, DL, TII->get(BEQ))
1408 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1410 MI->eraseFromParent(); // The instruction is gone now.
1416 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1417 MachineBasicBlock *BB,
1418 unsigned Size) const {
1419 assert((Size == 1 || Size == 2) &&
1420 "Unsupported size for EmitAtomicCmpSwapPartial.");
1422 MachineFunction *MF = BB->getParent();
1423 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1424 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1425 const TargetInstrInfo *TII =
1426 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1427 DebugLoc DL = MI->getDebugLoc();
1429 unsigned Dest = MI->getOperand(0).getReg();
1430 unsigned Ptr = MI->getOperand(1).getReg();
1431 unsigned CmpVal = MI->getOperand(2).getReg();
1432 unsigned NewVal = MI->getOperand(3).getReg();
1434 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1435 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1436 unsigned Mask = RegInfo.createVirtualRegister(RC);
1437 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1438 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1439 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1440 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1441 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1442 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1443 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1444 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1445 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1446 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1447 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1448 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1449 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1450 unsigned Success = RegInfo.createVirtualRegister(RC);
1452 // insert new blocks after the current block
1453 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1454 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1455 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1456 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1457 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1458 MachineFunction::iterator It = BB;
1460 MF->insert(It, loop1MBB);
1461 MF->insert(It, loop2MBB);
1462 MF->insert(It, sinkMBB);
1463 MF->insert(It, exitMBB);
1465 // Transfer the remainder of BB and its successor edges to exitMBB.
1466 exitMBB->splice(exitMBB->begin(), BB,
1467 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1468 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1470 BB->addSuccessor(loop1MBB);
1471 loop1MBB->addSuccessor(sinkMBB);
1472 loop1MBB->addSuccessor(loop2MBB);
1473 loop2MBB->addSuccessor(loop1MBB);
1474 loop2MBB->addSuccessor(sinkMBB);
1475 sinkMBB->addSuccessor(exitMBB);
1477 // FIXME: computation of newval2 can be moved to loop2MBB.
1479 // addiu masklsb2,$0,-4 # 0xfffffffc
1480 // and alignedaddr,ptr,masklsb2
1481 // andi ptrlsb2,ptr,3
1482 // sll shiftamt,ptrlsb2,3
1483 // ori maskupper,$0,255 # 0xff
1484 // sll mask,maskupper,shiftamt
1485 // nor mask2,$0,mask
1486 // andi maskedcmpval,cmpval,255
1487 // sll shiftedcmpval,maskedcmpval,shiftamt
1488 // andi maskednewval,newval,255
1489 // sll shiftednewval,maskednewval,shiftamt
1490 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1491 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1492 .addReg(Mips::ZERO).addImm(-4);
1493 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1494 .addReg(Ptr).addReg(MaskLSB2);
1495 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1496 if (Subtarget.isLittle()) {
1497 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1499 unsigned Off = RegInfo.createVirtualRegister(RC);
1500 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1501 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1502 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1504 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1505 .addReg(Mips::ZERO).addImm(MaskImm);
1506 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1507 .addReg(MaskUpper).addReg(ShiftAmt);
1508 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1509 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1510 .addReg(CmpVal).addImm(MaskImm);
1511 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1512 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1513 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1514 .addReg(NewVal).addImm(MaskImm);
1515 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1516 .addReg(MaskedNewVal).addReg(ShiftAmt);
1519 // ll oldval,0(alginedaddr)
1520 // and maskedoldval0,oldval,mask
1521 // bne maskedoldval0,shiftedcmpval,sinkMBB
1523 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1524 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1525 .addReg(OldVal).addReg(Mask);
1526 BuildMI(BB, DL, TII->get(Mips::BNE))
1527 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1530 // and maskedoldval1,oldval,mask2
1531 // or storeval,maskedoldval1,shiftednewval
1532 // sc success,storeval,0(alignedaddr)
1533 // beq success,$0,loop1MBB
1535 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1536 .addReg(OldVal).addReg(Mask2);
1537 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1538 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1539 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1540 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1541 BuildMI(BB, DL, TII->get(Mips::BEQ))
1542 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1545 // srl srlres,maskedoldval0,shiftamt
1546 // sign_extend dest,srlres
1549 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1550 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1551 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1553 MI->eraseFromParent(); // The instruction is gone now.
1558 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1559 MachineBasicBlock *BB) const {
1560 MachineFunction *MF = BB->getParent();
1561 const TargetRegisterInfo *TRI =
1562 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1563 const TargetInstrInfo *TII =
1564 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1565 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1566 DebugLoc DL = MI->getDebugLoc();
1567 MachineBasicBlock::iterator II(MI);
1569 unsigned Fc = MI->getOperand(1).getReg();
1570 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1572 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1574 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1577 .addImm(Mips::sub_lo);
1579 // We don't erase the original instruction, we just replace the condition
1580 // register with the 64-bit super-register.
1581 MI->getOperand(1).setReg(Fc2);
1586 //===----------------------------------------------------------------------===//
1587 // Misc Lower Operation implementation
1588 //===----------------------------------------------------------------------===//
1589 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1590 SDValue Chain = Op.getOperand(0);
1591 SDValue Table = Op.getOperand(1);
1592 SDValue Index = Op.getOperand(2);
1594 EVT PTy = getPointerTy();
1595 unsigned EntrySize =
1596 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1598 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1599 DAG.getConstant(EntrySize, PTy));
1600 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1602 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1603 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1604 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1606 Chain = Addr.getValue(1);
1608 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1609 Subtarget.isABI_N64()) {
1610 // For PIC, the sequence is:
1611 // BRIND(load(Jumptable + index) + RelocBase)
1612 // RelocBase can be JumpTable, GOT or some sort of global base.
1613 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1614 getPICJumpTableRelocBase(Table, DAG));
1617 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1620 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1621 // The first operand is the chain, the second is the condition, the third is
1622 // the block to branch to if the condition is true.
1623 SDValue Chain = Op.getOperand(0);
1624 SDValue Dest = Op.getOperand(2);
1627 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1628 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1630 // Return if flag is not set by a floating point comparison.
1631 if (CondRes.getOpcode() != MipsISD::FPCmp)
1634 SDValue CCNode = CondRes.getOperand(2);
1636 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1637 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1638 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1639 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1640 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1641 FCC0, Dest, CondRes);
1644 SDValue MipsTargetLowering::
1645 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1647 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1648 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1650 // Return if flag is not set by a floating point comparison.
1651 if (Cond.getOpcode() != MipsISD::FPCmp)
1654 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1658 SDValue MipsTargetLowering::
1659 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1662 EVT Ty = Op.getOperand(0).getValueType();
1663 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1664 getSetCCResultType(*DAG.getContext(), Ty),
1665 Op.getOperand(0), Op.getOperand(1),
1668 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1672 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1673 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1674 SDValue Cond = createFPCmp(DAG, Op);
1676 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1677 "Floating point operand expected.");
1679 SDValue True = DAG.getConstant(1, MVT::i32);
1680 SDValue False = DAG.getConstant(0, MVT::i32);
1682 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1685 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1686 SelectionDAG &DAG) const {
1687 // FIXME there isn't actually debug info here
1689 EVT Ty = Op.getValueType();
1690 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1691 const GlobalValue *GV = N->getGlobal();
1693 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1694 !Subtarget.isABI_N64()) {
1695 const MipsTargetObjectFile &TLOF =
1696 (const MipsTargetObjectFile&)getObjFileLowering();
1698 // %gp_rel relocation
1699 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1700 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1702 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1703 DAG.getVTList(MVT::i32), GA);
1704 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1705 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1708 // %hi/%lo relocation
1709 return getAddrNonPIC(N, Ty, DAG);
1712 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1713 return getAddrLocal(N, Ty, DAG,
1714 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1717 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1718 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1719 MachinePointerInfo::getGOT());
1721 return getAddrGlobal(N, Ty, DAG,
1722 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1723 ? MipsII::MO_GOT_DISP
1725 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1728 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1729 SelectionDAG &DAG) const {
1730 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1731 EVT Ty = Op.getValueType();
1733 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1734 !Subtarget.isABI_N64())
1735 return getAddrNonPIC(N, Ty, DAG);
1737 return getAddrLocal(N, Ty, DAG,
1738 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1741 SDValue MipsTargetLowering::
1742 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1744 // If the relocation model is PIC, use the General Dynamic TLS Model or
1745 // Local Dynamic TLS model, otherwise use the Initial Exec or
1746 // Local Exec TLS Model.
1748 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1750 const GlobalValue *GV = GA->getGlobal();
1751 EVT PtrVT = getPointerTy();
1753 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1755 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1756 // General Dynamic and Local Dynamic TLS Model.
1757 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1760 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1761 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1762 getGlobalReg(DAG, PtrVT), TGA);
1763 unsigned PtrSize = PtrVT.getSizeInBits();
1764 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1766 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1770 Entry.Node = Argument;
1772 Args.push_back(Entry);
1774 TargetLowering::CallLoweringInfo CLI(DAG);
1775 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1776 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1777 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1779 SDValue Ret = CallResult.first;
1781 if (model != TLSModel::LocalDynamic)
1784 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1785 MipsII::MO_DTPREL_HI);
1786 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1787 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1788 MipsII::MO_DTPREL_LO);
1789 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1790 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1791 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1795 if (model == TLSModel::InitialExec) {
1796 // Initial Exec TLS Model
1797 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1798 MipsII::MO_GOTTPREL);
1799 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1801 Offset = DAG.getLoad(PtrVT, DL,
1802 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1803 false, false, false, 0);
1805 // Local Exec TLS Model
1806 assert(model == TLSModel::LocalExec);
1807 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1808 MipsII::MO_TPREL_HI);
1809 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1810 MipsII::MO_TPREL_LO);
1811 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1812 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1813 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1816 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1817 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1820 SDValue MipsTargetLowering::
1821 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1823 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1824 EVT Ty = Op.getValueType();
1826 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1827 !Subtarget.isABI_N64())
1828 return getAddrNonPIC(N, Ty, DAG);
1830 return getAddrLocal(N, Ty, DAG,
1831 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1834 SDValue MipsTargetLowering::
1835 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1837 // gp_rel relocation
1838 // FIXME: we should reference the constant pool using small data sections,
1839 // but the asm printer currently doesn't support this feature without
1840 // hacking it. This feature should come soon so we can uncomment the
1842 //if (IsInSmallSection(C->getType())) {
1843 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1844 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1845 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1846 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1847 EVT Ty = Op.getValueType();
1849 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1850 !Subtarget.isABI_N64())
1851 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());
3049 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
3051 // Analyze return values.
3052 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3055 SmallVector<SDValue, 4> RetOps(1, Chain);
3057 // Copy the result values into the output registers.
3058 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3059 SDValue Val = OutVals[i];
3060 CCValAssign &VA = RVLocs[i];
3061 assert(VA.isRegLoc() && "Can only return in registers!");
3062 bool UseUpperBits = false;
3064 switch (VA.getLocInfo()) {
3066 llvm_unreachable("Unknown loc info!");
3067 case CCValAssign::Full:
3069 case CCValAssign::BCvt:
3070 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3072 case CCValAssign::AExtUpper:
3073 UseUpperBits = true;
3075 case CCValAssign::AExt:
3076 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3078 case CCValAssign::ZExtUpper:
3079 UseUpperBits = true;
3081 case CCValAssign::ZExt:
3082 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3084 case CCValAssign::SExtUpper:
3085 UseUpperBits = true;
3087 case CCValAssign::SExt:
3088 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3093 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3094 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3096 ISD::SHL, DL, VA.getLocVT(), Val,
3097 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3100 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3102 // Guarantee that all emitted copies are stuck together with flags.
3103 Flag = Chain.getValue(1);
3104 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3107 // The mips ABIs for returning structs by value requires that we copy
3108 // the sret argument into $v0 for the return. We saved the argument into
3109 // a virtual register in the entry block, so now we copy the value out
3111 if (MF.getFunction()->hasStructRetAttr()) {
3112 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3113 unsigned Reg = MipsFI->getSRetReturnReg();
3116 llvm_unreachable("sret virtual register not created in the entry block");
3117 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3118 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3120 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3121 Flag = Chain.getValue(1);
3122 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3125 RetOps[0] = Chain; // Update chain.
3127 // Add the flag if we have it.
3129 RetOps.push_back(Flag);
3131 // Return on Mips is always a "jr $ra"
3132 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3135 //===----------------------------------------------------------------------===//
3136 // Mips Inline Assembly Support
3137 //===----------------------------------------------------------------------===//
3139 /// getConstraintType - Given a constraint letter, return the type of
3140 /// constraint it is for this target.
3141 MipsTargetLowering::ConstraintType MipsTargetLowering::
3142 getConstraintType(const std::string &Constraint) const
3144 // Mips specific constraints
3145 // GCC config/mips/constraints.md
3147 // 'd' : An address register. Equivalent to r
3148 // unless generating MIPS16 code.
3149 // 'y' : Equivalent to r; retained for
3150 // backwards compatibility.
3151 // 'c' : A register suitable for use in an indirect
3152 // jump. This will always be $25 for -mabicalls.
3153 // 'l' : The lo register. 1 word storage.
3154 // 'x' : The hilo register pair. Double word storage.
3155 if (Constraint.size() == 1) {
3156 switch (Constraint[0]) {
3164 return C_RegisterClass;
3169 return TargetLowering::getConstraintType(Constraint);
3172 /// Examine constraint type and operand type and determine a weight value.
3173 /// This object must already have been set up with the operand type
3174 /// and the current alternative constraint selected.
3175 TargetLowering::ConstraintWeight
3176 MipsTargetLowering::getSingleConstraintMatchWeight(
3177 AsmOperandInfo &info, const char *constraint) const {
3178 ConstraintWeight weight = CW_Invalid;
3179 Value *CallOperandVal = info.CallOperandVal;
3180 // If we don't have a value, we can't do a match,
3181 // but allow it at the lowest weight.
3182 if (!CallOperandVal)
3184 Type *type = CallOperandVal->getType();
3185 // Look at the constraint type.
3186 switch (*constraint) {
3188 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3192 if (type->isIntegerTy())
3193 weight = CW_Register;
3195 case 'f': // FPU or MSA register
3196 if (Subtarget.hasMSA() && type->isVectorTy() &&
3197 cast<VectorType>(type)->getBitWidth() == 128)
3198 weight = CW_Register;
3199 else if (type->isFloatTy())
3200 weight = CW_Register;
3202 case 'c': // $25 for indirect jumps
3203 case 'l': // lo register
3204 case 'x': // hilo register pair
3205 if (type->isIntegerTy())
3206 weight = CW_SpecificReg;
3208 case 'I': // signed 16 bit immediate
3209 case 'J': // integer zero
3210 case 'K': // unsigned 16 bit immediate
3211 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3212 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3213 case 'O': // signed 15 bit immediate (+- 16383)
3214 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3215 if (isa<ConstantInt>(CallOperandVal))
3216 weight = CW_Constant;
3225 /// This is a helper function to parse a physical register string and split it
3226 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3227 /// that is returned indicates whether parsing was successful. The second flag
3228 /// is true if the numeric part exists.
3229 static std::pair<bool, bool>
3230 parsePhysicalReg(StringRef C, std::string &Prefix,
3231 unsigned long long &Reg) {
3232 if (C.front() != '{' || C.back() != '}')
3233 return std::make_pair(false, false);
3235 // Search for the first numeric character.
3236 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3237 I = std::find_if(B, E, std::ptr_fun(isdigit));
3239 Prefix.assign(B, I - B);
3241 // The second flag is set to false if no numeric characters were found.
3243 return std::make_pair(true, false);
3245 // Parse the numeric characters.
3246 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3250 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3251 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3252 const TargetRegisterInfo *TRI =
3253 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3254 const TargetRegisterClass *RC;
3256 unsigned long long Reg;
3258 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3261 return std::make_pair(0U, nullptr);
3263 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3264 // No numeric characters follow "hi" or "lo".
3266 return std::make_pair(0U, nullptr);
3268 RC = TRI->getRegClass(Prefix == "hi" ?
3269 Mips::HI32RegClassID : Mips::LO32RegClassID);
3270 return std::make_pair(*(RC->begin()), RC);
3271 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3272 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3274 // No numeric characters follow the name.
3276 return std::make_pair(0U, nullptr);
3278 Reg = StringSwitch<unsigned long long>(Prefix)
3279 .Case("$msair", Mips::MSAIR)
3280 .Case("$msacsr", Mips::MSACSR)
3281 .Case("$msaaccess", Mips::MSAAccess)
3282 .Case("$msasave", Mips::MSASave)
3283 .Case("$msamodify", Mips::MSAModify)
3284 .Case("$msarequest", Mips::MSARequest)
3285 .Case("$msamap", Mips::MSAMap)
3286 .Case("$msaunmap", Mips::MSAUnmap)
3290 return std::make_pair(0U, nullptr);
3292 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3293 return std::make_pair(Reg, RC);
3297 return std::make_pair(0U, nullptr);
3299 if (Prefix == "$f") { // Parse $f0-$f31.
3300 // If the size of FP registers is 64-bit or Reg is an even number, select
3301 // the 64-bit register class. Otherwise, select the 32-bit register class.
3302 if (VT == MVT::Other)
3303 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3305 RC = getRegClassFor(VT);
3307 if (RC == &Mips::AFGR64RegClass) {
3308 assert(Reg % 2 == 0);
3311 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3312 RC = TRI->getRegClass(Mips::FCCRegClassID);
3313 else if (Prefix == "$w") { // Parse $w0-$w31.
3314 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3315 } else { // Parse $0-$31.
3316 assert(Prefix == "$");
3317 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3320 assert(Reg < RC->getNumRegs());
3321 return std::make_pair(*(RC->begin() + Reg), RC);
3324 /// Given a register class constraint, like 'r', if this corresponds directly
3325 /// to an LLVM register class, return a register of 0 and the register class
3327 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3328 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3330 if (Constraint.size() == 1) {
3331 switch (Constraint[0]) {
3332 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3333 case 'y': // Same as 'r'. Exists for compatibility.
3335 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3336 if (Subtarget.inMips16Mode())
3337 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3338 return std::make_pair(0U, &Mips::GPR32RegClass);
3340 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3341 return std::make_pair(0U, &Mips::GPR32RegClass);
3342 if (VT == MVT::i64 && Subtarget.isGP64bit())
3343 return std::make_pair(0U, &Mips::GPR64RegClass);
3344 // This will generate an error message
3345 return std::make_pair(0U, nullptr);
3346 case 'f': // FPU or MSA register
3347 if (VT == MVT::v16i8)
3348 return std::make_pair(0U, &Mips::MSA128BRegClass);
3349 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3350 return std::make_pair(0U, &Mips::MSA128HRegClass);
3351 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3352 return std::make_pair(0U, &Mips::MSA128WRegClass);
3353 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3354 return std::make_pair(0U, &Mips::MSA128DRegClass);
3355 else if (VT == MVT::f32)
3356 return std::make_pair(0U, &Mips::FGR32RegClass);
3357 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3358 if (Subtarget.isFP64bit())
3359 return std::make_pair(0U, &Mips::FGR64RegClass);
3360 return std::make_pair(0U, &Mips::AFGR64RegClass);
3363 case 'c': // register suitable for indirect jump
3365 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3366 assert(VT == MVT::i64 && "Unexpected type.");
3367 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3368 case 'l': // register suitable for indirect jump
3370 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3371 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3372 case 'x': // register suitable for indirect jump
3373 // Fixme: Not triggering the use of both hi and low
3374 // This will generate an error message
3375 return std::make_pair(0U, nullptr);
3379 std::pair<unsigned, const TargetRegisterClass *> R;
3380 R = parseRegForInlineAsmConstraint(Constraint, VT);
3385 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3388 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3389 /// vector. If it is invalid, don't add anything to Ops.
3390 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3391 std::string &Constraint,
3392 std::vector<SDValue>&Ops,
3393 SelectionDAG &DAG) const {
3396 // Only support length 1 constraints for now.
3397 if (Constraint.length() > 1) return;
3399 char ConstraintLetter = Constraint[0];
3400 switch (ConstraintLetter) {
3401 default: break; // This will fall through to the generic implementation
3402 case 'I': // Signed 16 bit constant
3403 // If this fails, the parent routine will give an error
3404 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3405 EVT Type = Op.getValueType();
3406 int64_t Val = C->getSExtValue();
3407 if (isInt<16>(Val)) {
3408 Result = DAG.getTargetConstant(Val, Type);
3413 case 'J': // integer zero
3414 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3415 EVT Type = Op.getValueType();
3416 int64_t Val = C->getZExtValue();
3418 Result = DAG.getTargetConstant(0, Type);
3423 case 'K': // unsigned 16 bit immediate
3424 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3425 EVT Type = Op.getValueType();
3426 uint64_t Val = (uint64_t)C->getZExtValue();
3427 if (isUInt<16>(Val)) {
3428 Result = DAG.getTargetConstant(Val, Type);
3433 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3434 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3435 EVT Type = Op.getValueType();
3436 int64_t Val = C->getSExtValue();
3437 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3438 Result = DAG.getTargetConstant(Val, Type);
3443 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3445 EVT Type = Op.getValueType();
3446 int64_t Val = C->getSExtValue();
3447 if ((Val >= -65535) && (Val <= -1)) {
3448 Result = DAG.getTargetConstant(Val, Type);
3453 case 'O': // signed 15 bit immediate
3454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3455 EVT Type = Op.getValueType();
3456 int64_t Val = C->getSExtValue();
3457 if ((isInt<15>(Val))) {
3458 Result = DAG.getTargetConstant(Val, Type);
3463 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3465 EVT Type = Op.getValueType();
3466 int64_t Val = C->getSExtValue();
3467 if ((Val <= 65535) && (Val >= 1)) {
3468 Result = DAG.getTargetConstant(Val, Type);
3475 if (Result.getNode()) {
3476 Ops.push_back(Result);
3480 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3483 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3485 // No global is ever allowed as a base.
3490 case 0: // "r+i" or just "i", depending on HasBaseReg.
3493 if (!AM.HasBaseReg) // allow "r+i".
3495 return false; // disallow "r+r" or "r+r+i".
3504 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3505 // The Mips target isn't yet aware of offsets.
3509 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3511 bool IsMemset, bool ZeroMemset,
3513 MachineFunction &MF) const {
3514 if (Subtarget.hasMips64())
3520 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3521 if (VT != MVT::f32 && VT != MVT::f64)
3523 if (Imm.isNegZero())
3525 return Imm.isZero();
3528 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3529 if (Subtarget.isABI_N64())
3530 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3532 return TargetLowering::getJumpTableEncoding();
3535 /// This function returns true if CallSym is a long double emulation routine.
3536 static bool isF128SoftLibCall(const char *CallSym) {
3537 const char *const LibCalls[] =
3538 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3539 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3540 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3541 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3542 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3543 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3544 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3545 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3548 const char *const *End = LibCalls + array_lengthof(LibCalls);
3550 // Check that LibCalls is sorted alphabetically.
3551 MipsTargetLowering::LTStr Comp;
3554 for (const char *const *I = LibCalls; I < End - 1; ++I)
3555 assert(Comp(*I, *(I + 1)));
3558 return std::binary_search(LibCalls, End, CallSym, Comp);
3561 /// This function returns true if Ty is fp128, {f128} or i128 which was
3562 /// originally a fp128.
3563 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3564 if (Ty->isFP128Ty())
3567 if (Ty->isStructTy() && Ty->getStructNumElements() == 1 &&
3568 Ty->getStructElementType(0)->isFP128Ty())
3571 const ExternalSymbolSDNode *ES =
3572 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3574 // If the Ty is i128 and the function being called is a long double emulation
3575 // routine, then the original type is f128.
3576 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3579 MipsTargetLowering::MipsCC::SpecialCallingConvType
3580 MipsTargetLowering::MipsCC::getSpecialCallingConv(const SDNode *Callee) const {
3581 MipsCC::SpecialCallingConvType SpecialCallingConv =
3582 MipsCC::NoSpecialCallingConv;
3583 if (Subtarget.inMips16HardFloat()) {
3584 if (const GlobalAddressSDNode *G =
3585 dyn_cast<const GlobalAddressSDNode>(Callee)) {
3586 llvm::StringRef Sym = G->getGlobal()->getName();
3587 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3588 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3589 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3593 return SpecialCallingConv;
3596 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC,
3597 const MipsSubtarget &Subtarget_,
3599 : CallConv(CC), Subtarget(Subtarget_) {
3600 // Pre-allocate reserved argument area.
3601 Info.AllocateStack(reservedArgArea(), 1);
3604 void MipsTargetLowering::MipsCC::analyzeCallOperands(
3605 const SmallVectorImpl<ISD::OutputArg> &Args, bool IsVarArg,
3606 bool IsSoftFloat, const SDNode *CallNode,
3607 std::vector<ArgListEntry> &FuncArgs, CCState &State) {
3608 MipsCC::SpecialCallingConvType SpecialCallingConv =
3609 getSpecialCallingConv(CallNode);
3610 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3611 "CallingConv::Fast shouldn't be used for vararg functions.");
3613 unsigned NumOpnds = Args.size();
3614 llvm::CCAssignFn *FixedFn = CC_Mips_FixedArg;
3615 if (CallConv != CallingConv::Fast &&
3616 SpecialCallingConv == Mips16RetHelperConv)
3617 FixedFn = CC_Mips16RetHelper;
3619 for (unsigned I = 0; I != NumOpnds; ++I) {
3620 MVT ArgVT = Args[I].VT;
3621 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3624 if (IsVarArg && !Args[I].IsFixed)
3625 R = CC_Mips_VarArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
3627 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
3631 dbgs() << "Call operand #" << I << " has unhandled type "
3632 << EVT(ArgVT).getEVTString();
3634 llvm_unreachable(nullptr);
3639 void MipsTargetLowering::MipsCC::analyzeFormalArguments(
3640 const SmallVectorImpl<ISD::InputArg> &Args, bool IsSoftFloat,
3642 unsigned NumArgs = Args.size();
3644 for (unsigned I = 0; I != NumArgs; ++I) {
3645 MVT ArgVT = Args[I].VT;
3646 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3648 if (!CC_Mips_FixedArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State))
3652 dbgs() << "Formal Arg #" << I << " has unhandled type "
3653 << EVT(ArgVT).getEVTString();
3655 llvm_unreachable(nullptr);
3659 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3660 return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
3663 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
3664 if (Subtarget.isABI_O32())
3665 return makeArrayRef(O32IntRegs);
3666 return makeArrayRef(Mips64IntRegs);
3669 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3670 const SDNode *CallNode,
3671 bool IsSoftFloat) const {
3672 if (IsSoftFloat || Subtarget.isABI_O32())
3675 // Check if the original type was fp128.
3676 if (originalTypeIsF128(OrigTy, CallNode)) {
3677 assert(VT == MVT::i64);
3684 void MipsTargetLowering::copyByValRegs(
3685 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3686 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3687 const Argument *FuncArg, const MipsCC &CC, unsigned FirstReg,
3688 unsigned LastReg, const CCValAssign &VA) const {
3689 MachineFunction &MF = DAG.getMachineFunction();
3690 MachineFrameInfo *MFI = MF.getFrameInfo();
3691 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3692 unsigned NumRegs = LastReg - FirstReg;
3693 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3694 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3699 (int)CC.reservedArgArea() -
3700 (int)((CC.intArgRegs().size() - FirstReg) * GPRSizeInBytes);
3702 FrameObjOffset = VA.getLocMemOffset();
3704 // Create frame object.
3705 EVT PtrTy = getPointerTy();
3706 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3707 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3708 InVals.push_back(FIN);
3713 // Copy arg registers.
3714 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3715 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3717 for (unsigned I = 0; I < NumRegs; ++I) {
3718 unsigned ArgReg = CC.intArgRegs()[FirstReg + I];
3719 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3720 unsigned Offset = I * GPRSizeInBytes;
3721 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3722 DAG.getConstant(Offset, PtrTy));
3723 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3724 StorePtr, MachinePointerInfo(FuncArg, Offset),
3726 OutChains.push_back(Store);
3730 // Copy byVal arg to registers and stack.
3731 void MipsTargetLowering::passByValArg(
3732 SDValue Chain, SDLoc DL,
3733 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3734 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3735 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, const MipsCC &CC,
3736 unsigned FirstReg, unsigned LastReg, const ISD::ArgFlagsTy &Flags,
3737 bool isLittle, const CCValAssign &VA) const {
3738 unsigned ByValSizeInBytes = Flags.getByValSize();
3739 unsigned OffsetInBytes = 0; // From beginning of struct
3740 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3741 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3742 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3743 unsigned NumRegs = LastReg - FirstReg;
3746 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3747 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3750 // Copy words to registers.
3751 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3752 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3753 DAG.getConstant(OffsetInBytes, PtrTy));
3754 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3755 MachinePointerInfo(), false, false, false,
3757 MemOpChains.push_back(LoadVal.getValue(1));
3758 unsigned ArgReg = ArgRegs[FirstReg + I];
3759 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3762 // Return if the struct has been fully copied.
3763 if (ByValSizeInBytes == OffsetInBytes)
3766 // Copy the remainder of the byval argument with sub-word loads and shifts.
3767 if (LeftoverBytes) {
3770 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3771 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3772 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3774 if (RemainingSizeInBytes < LoadSizeInBytes)
3778 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3779 DAG.getConstant(OffsetInBytes, PtrTy));
3780 SDValue LoadVal = DAG.getExtLoad(
3781 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3782 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3784 MemOpChains.push_back(LoadVal.getValue(1));
3786 // Shift the loaded value.
3790 Shamt = TotalBytesLoaded * 8;
3792 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3794 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3795 DAG.getConstant(Shamt, MVT::i32));
3798 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3802 OffsetInBytes += LoadSizeInBytes;
3803 TotalBytesLoaded += LoadSizeInBytes;
3804 Alignment = std::min(Alignment, LoadSizeInBytes);
3807 unsigned ArgReg = ArgRegs[FirstReg + I];
3808 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3813 // Copy remainder of byval arg to it with memcpy.
3814 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3815 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3816 DAG.getConstant(OffsetInBytes, PtrTy));
3817 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3818 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3819 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3820 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3821 MachinePointerInfo(), MachinePointerInfo());
3822 MemOpChains.push_back(Chain);
3825 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3826 const MipsCC &CC, SDValue Chain,
3827 SDLoc DL, SelectionDAG &DAG,
3828 CCState &State) const {
3829 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3830 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3831 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3832 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3833 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3834 MachineFunction &MF = DAG.getMachineFunction();
3835 MachineFrameInfo *MFI = MF.getFrameInfo();
3836 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3838 // Offset of the first variable argument from stack pointer.
3841 if (ArgRegs.size() == Idx)
3843 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3845 VaArgOffset = (int)CC.reservedArgArea() -
3846 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3848 // Record the frame index of the first variable argument
3849 // which is a value necessary to VASTART.
3850 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3851 MipsFI->setVarArgsFrameIndex(FI);
3853 // Copy the integer registers that have not been used for argument passing
3854 // to the argument register save area. For O32, the save area is allocated
3855 // in the caller's stack frame, while for N32/64, it is allocated in the
3856 // callee's stack frame.
3857 for (unsigned I = Idx; I < ArgRegs.size();
3858 ++I, VaArgOffset += RegSizeInBytes) {
3859 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3860 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3861 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3862 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3863 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3864 MachinePointerInfo(), false, false, 0);
3865 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3867 OutChains.push_back(Store);
3871 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3872 unsigned Align) const {
3873 MachineFunction &MF = State->getMachineFunction();
3874 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3876 assert(Size && "Byval argument's size shouldn't be 0.");
3878 Align = std::min(Align, TFL->getStackAlignment());
3880 unsigned FirstReg = 0;
3881 unsigned NumRegs = 0;
3883 if (State->getCallingConv() != CallingConv::Fast) {
3884 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3885 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3886 // FIXME: The O32 case actually describes no shadow registers.
3887 const MCPhysReg *ShadowRegs =
3888 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3890 // We used to check the size as well but we can't do that anymore since
3891 // CCState::HandleByVal() rounds up the size after calling this function.
3892 assert(!(Align % RegSizeInBytes) &&
3893 "Byval argument's alignment should be a multiple of"
3896 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3898 // If Align > RegSizeInBytes, the first arg register must be even.
3899 // FIXME: This condition happens to do the right thing but it's not the
3900 // right way to test it. We want to check that the stack frame offset
3901 // of the register is aligned.
3902 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3903 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3907 // Mark the registers allocated.
3908 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3909 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3910 Size -= RegSizeInBytes, ++I, ++NumRegs)
3911 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3914 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);