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 enum SpecialCallingConvType { Mips16RetHelperConv, NoSpecialCallingConv };
81 /// Determine the SpecialCallingConvType for the given callee
82 static SpecialCallingConvType
83 getSpecialCallingConvForCallee(const SDNode *Callee,
84 const MipsSubtarget &Subtarget) {
85 SpecialCallingConvType SpecialCallingConv = NoSpecialCallingConv;
86 if (Subtarget.inMips16HardFloat()) {
87 if (const GlobalAddressSDNode *G =
88 dyn_cast<const GlobalAddressSDNode>(Callee)) {
89 llvm::StringRef Sym = G->getGlobal()->getName();
90 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
91 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
92 SpecialCallingConv = Mips16RetHelperConv;
96 return SpecialCallingConv;
100 /// Identify lowered values that originated from f128 arguments and record
101 /// this for use by RetCC_MipsN.
103 PreAnalyzeCallResultForF128(const SmallVectorImpl<ISD::InputArg> &Ins,
104 const TargetLowering::CallLoweringInfo &CLI) {
105 for (unsigned i = 0; i < Ins.size(); ++i)
106 OriginalArgWasF128.push_back(
107 originalTypeIsF128(CLI.RetTy, CLI.Callee.getNode()));
110 /// Identify lowered values that originated from f128 arguments and record
111 /// this for use by RetCC_MipsN.
112 void PreAnalyzeReturnForF128(const SmallVectorImpl<ISD::OutputArg> &Outs) {
113 const MachineFunction &MF = getMachineFunction();
114 for (unsigned i = 0; i < Outs.size(); ++i)
115 OriginalArgWasF128.push_back(
116 originalTypeIsF128(MF.getFunction()->getReturnType(), nullptr));
119 /// Identify lowered values that originated from f128 arguments and record
121 void PreAnalyzeCallOperands(
122 const SmallVectorImpl<ISD::OutputArg> &Outs,
123 std::vector<TargetLowering::ArgListEntry> &FuncArgs,
124 const SDNode *CallNode) {
125 for (unsigned i = 0; i < Outs.size(); ++i) {
126 OriginalArgWasF128.push_back(
127 originalTypeIsF128(FuncArgs[Outs[i].OrigArgIndex].Ty, CallNode));
128 CallOperandIsFixed.push_back(Outs[i].IsFixed);
132 /// Identify lowered values that originated from f128 arguments and record
135 PreAnalyzeFormalArgumentsForF128(const SmallVectorImpl<ISD::InputArg> &Ins) {
136 const MachineFunction &MF = getMachineFunction();
137 for (unsigned i = 0; i < Ins.size(); ++i) {
138 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
140 // SRet arguments cannot originate from f128 or {f128} returns so we just
141 // push false. We have to handle this specially since SRet arguments
142 // aren't mapped to an original argument.
143 if (Ins[i].Flags.isSRet()) {
144 OriginalArgWasF128.push_back(false);
148 assert(Ins[i].OrigArgIndex < MF.getFunction()->arg_size());
149 std::advance(FuncArg, Ins[i].OrigArgIndex);
150 OriginalArgWasF128.push_back(
151 originalTypeIsF128(FuncArg->getType(), nullptr));
155 /// Records whether the value has been lowered from an f128.
156 SmallVector<bool, 4> OriginalArgWasF128;
158 /// Records whether the value was a fixed argument.
159 /// See ISD::OutputArg::IsFixed,
160 SmallVector<bool, 4> CallOperandIsFixed;
162 // Used to handle MIPS16-specific calling convention tweaks.
163 // FIXME: This should probably be a fully fledged calling convention.
164 SpecialCallingConvType SpecialCallingConv;
168 MipsCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
169 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C,
170 SpecialCallingConvType SpecialCC = NoSpecialCallingConv)
171 : CCState(CC, isVarArg, MF, locs, C), SpecialCallingConv(SpecialCC) {}
174 AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
176 std::vector<TargetLowering::ArgListEntry> &FuncArgs,
177 const SDNode *CallNode) {
178 PreAnalyzeCallOperands(Outs, FuncArgs, CallNode);
179 CCState::AnalyzeCallOperands(Outs, Fn);
180 OriginalArgWasF128.clear();
181 CallOperandIsFixed.clear();
184 // The AnalyzeCallOperands in the base class is not usable since we must
185 // provide a means of accessing ArgListEntry::IsFixed. Delete them from this
186 // class. This doesn't stop them being used via the base class though.
187 void AnalyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Outs,
188 CCAssignFn Fn) = delete;
189 void AnalyzeCallOperands(const SmallVectorImpl<MVT> &Outs,
190 SmallVectorImpl<ISD::ArgFlagsTy> &Flags,
191 CCAssignFn Fn) = delete;
193 void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
195 PreAnalyzeFormalArgumentsForF128(Ins);
196 CCState::AnalyzeFormalArguments(Ins, Fn);
197 OriginalArgWasF128.clear();
200 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
202 const TargetLowering::CallLoweringInfo &CLI) {
203 PreAnalyzeCallResultForF128(Ins, CLI);
204 CCState::AnalyzeCallResult(Ins, Fn);
205 OriginalArgWasF128.clear();
208 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
210 PreAnalyzeReturnForF128(Outs);
211 CCState::AnalyzeReturn(Outs, Fn);
212 OriginalArgWasF128.clear();
215 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
217 PreAnalyzeReturnForF128(ArgsFlags);
218 bool Return = CCState::CheckReturn(ArgsFlags, Fn);
219 OriginalArgWasF128.clear();
223 bool WasOriginalArgF128(unsigned ValNo) { return OriginalArgWasF128[ValNo]; }
224 bool IsCallOperandFixed(unsigned ValNo) { return CallOperandIsFixed[ValNo]; }
225 SpecialCallingConvType getSpecialCallingConv() { return SpecialCallingConv; }
229 // If I is a shifted mask, set the size (Size) and the first bit of the
230 // mask (Pos), and return true.
231 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
232 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
233 if (!isShiftedMask_64(I))
236 Size = CountPopulation_64(I);
237 Pos = countTrailingZeros(I);
241 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
242 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
243 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
246 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
248 unsigned Flag) const {
249 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
252 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
254 unsigned Flag) const {
255 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
258 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
260 unsigned Flag) const {
261 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
264 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
266 unsigned Flag) const {
267 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
270 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
272 unsigned Flag) const {
273 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
274 N->getOffset(), Flag);
277 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
279 case MipsISD::JmpLink: return "MipsISD::JmpLink";
280 case MipsISD::TailCall: return "MipsISD::TailCall";
281 case MipsISD::Hi: return "MipsISD::Hi";
282 case MipsISD::Lo: return "MipsISD::Lo";
283 case MipsISD::GPRel: return "MipsISD::GPRel";
284 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
285 case MipsISD::Ret: return "MipsISD::Ret";
286 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
287 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
288 case MipsISD::FPCmp: return "MipsISD::FPCmp";
289 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
290 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
291 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
292 case MipsISD::MFHI: return "MipsISD::MFHI";
293 case MipsISD::MFLO: return "MipsISD::MFLO";
294 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
295 case MipsISD::Mult: return "MipsISD::Mult";
296 case MipsISD::Multu: return "MipsISD::Multu";
297 case MipsISD::MAdd: return "MipsISD::MAdd";
298 case MipsISD::MAddu: return "MipsISD::MAddu";
299 case MipsISD::MSub: return "MipsISD::MSub";
300 case MipsISD::MSubu: return "MipsISD::MSubu";
301 case MipsISD::DivRem: return "MipsISD::DivRem";
302 case MipsISD::DivRemU: return "MipsISD::DivRemU";
303 case MipsISD::DivRem16: return "MipsISD::DivRem16";
304 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
305 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
306 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
307 case MipsISD::Wrapper: return "MipsISD::Wrapper";
308 case MipsISD::Sync: return "MipsISD::Sync";
309 case MipsISD::Ext: return "MipsISD::Ext";
310 case MipsISD::Ins: return "MipsISD::Ins";
311 case MipsISD::LWL: return "MipsISD::LWL";
312 case MipsISD::LWR: return "MipsISD::LWR";
313 case MipsISD::SWL: return "MipsISD::SWL";
314 case MipsISD::SWR: return "MipsISD::SWR";
315 case MipsISD::LDL: return "MipsISD::LDL";
316 case MipsISD::LDR: return "MipsISD::LDR";
317 case MipsISD::SDL: return "MipsISD::SDL";
318 case MipsISD::SDR: return "MipsISD::SDR";
319 case MipsISD::EXTP: return "MipsISD::EXTP";
320 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
321 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
322 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
323 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
324 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
325 case MipsISD::SHILO: return "MipsISD::SHILO";
326 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
327 case MipsISD::MULT: return "MipsISD::MULT";
328 case MipsISD::MULTU: return "MipsISD::MULTU";
329 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
330 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
331 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
332 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
333 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
334 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
335 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
336 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
337 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
338 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
339 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
340 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
341 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
342 case MipsISD::VCEQ: return "MipsISD::VCEQ";
343 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
344 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
345 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
346 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
347 case MipsISD::VSMAX: return "MipsISD::VSMAX";
348 case MipsISD::VSMIN: return "MipsISD::VSMIN";
349 case MipsISD::VUMAX: return "MipsISD::VUMAX";
350 case MipsISD::VUMIN: return "MipsISD::VUMIN";
351 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
352 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
353 case MipsISD::VNOR: return "MipsISD::VNOR";
354 case MipsISD::VSHF: return "MipsISD::VSHF";
355 case MipsISD::SHF: return "MipsISD::SHF";
356 case MipsISD::ILVEV: return "MipsISD::ILVEV";
357 case MipsISD::ILVOD: return "MipsISD::ILVOD";
358 case MipsISD::ILVL: return "MipsISD::ILVL";
359 case MipsISD::ILVR: return "MipsISD::ILVR";
360 case MipsISD::PCKEV: return "MipsISD::PCKEV";
361 case MipsISD::PCKOD: return "MipsISD::PCKOD";
362 case MipsISD::INSVE: return "MipsISD::INSVE";
363 default: return nullptr;
367 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
368 const MipsSubtarget &STI)
369 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
370 // Mips does not have i1 type, so use i32 for
371 // setcc operations results (slt, sgt, ...).
372 setBooleanContents(ZeroOrOneBooleanContent);
373 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
374 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
375 // does. Integer booleans still use 0 and 1.
376 if (Subtarget.hasMips32r6())
377 setBooleanContents(ZeroOrOneBooleanContent,
378 ZeroOrNegativeOneBooleanContent);
380 // Load extented operations for i1 types must be promoted
381 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
382 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
383 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
385 // MIPS doesn't have extending float->double load/store
386 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
387 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
389 // Used by legalize types to correctly generate the setcc result.
390 // Without this, every float setcc comes with a AND/OR with the result,
391 // we don't want this, since the fpcmp result goes to a flag register,
392 // which is used implicitly by brcond and select operations.
393 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
395 // Mips Custom Operations
396 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
397 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
398 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
399 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
400 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
401 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
402 setOperationAction(ISD::SELECT, MVT::f32, Custom);
403 setOperationAction(ISD::SELECT, MVT::f64, Custom);
404 setOperationAction(ISD::SELECT, MVT::i32, Custom);
405 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
406 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
407 setOperationAction(ISD::SETCC, MVT::f32, Custom);
408 setOperationAction(ISD::SETCC, MVT::f64, Custom);
409 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
410 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
411 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
412 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
414 if (Subtarget.isGP64bit()) {
415 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
416 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
417 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
418 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
419 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
420 setOperationAction(ISD::SELECT, MVT::i64, Custom);
421 setOperationAction(ISD::LOAD, MVT::i64, Custom);
422 setOperationAction(ISD::STORE, MVT::i64, Custom);
423 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
426 if (!Subtarget.isGP64bit()) {
427 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
428 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
429 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
432 setOperationAction(ISD::ADD, MVT::i32, Custom);
433 if (Subtarget.isGP64bit())
434 setOperationAction(ISD::ADD, MVT::i64, Custom);
436 setOperationAction(ISD::SDIV, MVT::i32, Expand);
437 setOperationAction(ISD::SREM, MVT::i32, Expand);
438 setOperationAction(ISD::UDIV, MVT::i32, Expand);
439 setOperationAction(ISD::UREM, MVT::i32, Expand);
440 setOperationAction(ISD::SDIV, MVT::i64, Expand);
441 setOperationAction(ISD::SREM, MVT::i64, Expand);
442 setOperationAction(ISD::UDIV, MVT::i64, Expand);
443 setOperationAction(ISD::UREM, MVT::i64, Expand);
445 // Operations not directly supported by Mips.
446 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
447 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
448 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
449 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
450 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
451 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
452 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
453 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
454 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
455 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
456 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
457 if (Subtarget.hasCnMips()) {
458 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
459 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
461 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
462 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
464 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
465 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
466 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
467 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
468 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
469 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
470 setOperationAction(ISD::ROTL, MVT::i32, Expand);
471 setOperationAction(ISD::ROTL, MVT::i64, Expand);
472 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
473 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
475 if (!Subtarget.hasMips32r2())
476 setOperationAction(ISD::ROTR, MVT::i32, Expand);
478 if (!Subtarget.hasMips64r2())
479 setOperationAction(ISD::ROTR, MVT::i64, Expand);
481 setOperationAction(ISD::FSIN, MVT::f32, Expand);
482 setOperationAction(ISD::FSIN, MVT::f64, Expand);
483 setOperationAction(ISD::FCOS, MVT::f32, Expand);
484 setOperationAction(ISD::FCOS, MVT::f64, Expand);
485 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
486 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
487 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
488 setOperationAction(ISD::FPOW, MVT::f32, Expand);
489 setOperationAction(ISD::FPOW, MVT::f64, Expand);
490 setOperationAction(ISD::FLOG, MVT::f32, Expand);
491 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
492 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
493 setOperationAction(ISD::FEXP, MVT::f32, Expand);
494 setOperationAction(ISD::FMA, MVT::f32, Expand);
495 setOperationAction(ISD::FMA, MVT::f64, Expand);
496 setOperationAction(ISD::FREM, MVT::f32, Expand);
497 setOperationAction(ISD::FREM, MVT::f64, Expand);
499 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
501 setOperationAction(ISD::VASTART, MVT::Other, Custom);
502 setOperationAction(ISD::VAARG, MVT::Other, Custom);
503 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
504 setOperationAction(ISD::VAEND, MVT::Other, Expand);
506 // Use the default for now
507 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
508 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
510 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
511 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
512 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
513 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
515 setInsertFencesForAtomic(true);
517 if (!Subtarget.hasMips32r2()) {
518 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
519 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
522 // MIPS16 lacks MIPS32's clz and clo instructions.
523 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
524 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
525 if (!Subtarget.hasMips64())
526 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
528 if (!Subtarget.hasMips32r2())
529 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
530 if (!Subtarget.hasMips64r2())
531 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
533 if (Subtarget.isGP64bit()) {
534 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
535 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
536 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
537 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
540 setOperationAction(ISD::TRAP, MVT::Other, Legal);
542 setTargetDAGCombine(ISD::SDIVREM);
543 setTargetDAGCombine(ISD::UDIVREM);
544 setTargetDAGCombine(ISD::SELECT);
545 setTargetDAGCombine(ISD::AND);
546 setTargetDAGCombine(ISD::OR);
547 setTargetDAGCombine(ISD::ADD);
549 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
551 // The arguments on the stack are defined in terms of 4-byte slots on O32
552 // and 8-byte slots on N32/N64.
553 setMinStackArgumentAlignment(
554 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
556 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
559 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
560 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
562 MaxStoresPerMemcpy = 16;
564 isMicroMips = Subtarget.inMicroMipsMode();
567 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
568 const MipsSubtarget &STI) {
569 if (STI.inMips16Mode())
570 return llvm::createMips16TargetLowering(TM, STI);
572 return llvm::createMipsSETargetLowering(TM, STI);
575 // Create a fast isel object.
577 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
578 const TargetLibraryInfo *libInfo) const {
579 if (!EnableMipsFastISel)
580 return TargetLowering::createFastISel(funcInfo, libInfo);
581 return Mips::createFastISel(funcInfo, libInfo);
584 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
587 return VT.changeVectorElementTypeToInteger();
590 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
591 TargetLowering::DAGCombinerInfo &DCI,
592 const MipsSubtarget &Subtarget) {
593 if (DCI.isBeforeLegalizeOps())
596 EVT Ty = N->getValueType(0);
597 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
598 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
599 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
603 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
604 N->getOperand(0), N->getOperand(1));
605 SDValue InChain = DAG.getEntryNode();
606 SDValue InGlue = DivRem;
609 if (N->hasAnyUseOfValue(0)) {
610 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
612 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
613 InChain = CopyFromLo.getValue(1);
614 InGlue = CopyFromLo.getValue(2);
618 if (N->hasAnyUseOfValue(1)) {
619 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
621 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
627 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
629 default: llvm_unreachable("Unknown fp condition code!");
631 case ISD::SETOEQ: return Mips::FCOND_OEQ;
632 case ISD::SETUNE: return Mips::FCOND_UNE;
634 case ISD::SETOLT: return Mips::FCOND_OLT;
636 case ISD::SETOGT: return Mips::FCOND_OGT;
638 case ISD::SETOLE: return Mips::FCOND_OLE;
640 case ISD::SETOGE: return Mips::FCOND_OGE;
641 case ISD::SETULT: return Mips::FCOND_ULT;
642 case ISD::SETULE: return Mips::FCOND_ULE;
643 case ISD::SETUGT: return Mips::FCOND_UGT;
644 case ISD::SETUGE: return Mips::FCOND_UGE;
645 case ISD::SETUO: return Mips::FCOND_UN;
646 case ISD::SETO: return Mips::FCOND_OR;
648 case ISD::SETONE: return Mips::FCOND_ONE;
649 case ISD::SETUEQ: return Mips::FCOND_UEQ;
654 /// This function returns true if the floating point conditional branches and
655 /// conditional moves which use condition code CC should be inverted.
656 static bool invertFPCondCodeUser(Mips::CondCode CC) {
657 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
660 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
661 "Illegal Condition Code");
666 // Creates and returns an FPCmp node from a setcc node.
667 // Returns Op if setcc is not a floating point comparison.
668 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
669 // must be a SETCC node
670 if (Op.getOpcode() != ISD::SETCC)
673 SDValue LHS = Op.getOperand(0);
675 if (!LHS.getValueType().isFloatingPoint())
678 SDValue RHS = Op.getOperand(1);
681 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
682 // node if necessary.
683 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
685 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
686 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
689 // Creates and returns a CMovFPT/F node.
690 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
691 SDValue False, SDLoc DL) {
692 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
693 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
694 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
696 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
697 True.getValueType(), True, FCC0, False, Cond);
700 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
701 TargetLowering::DAGCombinerInfo &DCI,
702 const MipsSubtarget &Subtarget) {
703 if (DCI.isBeforeLegalizeOps())
706 SDValue SetCC = N->getOperand(0);
708 if ((SetCC.getOpcode() != ISD::SETCC) ||
709 !SetCC.getOperand(0).getValueType().isInteger())
712 SDValue False = N->getOperand(2);
713 EVT FalseTy = False.getValueType();
715 if (!FalseTy.isInteger())
718 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
720 // If the RHS (False) is 0, we swap the order of the operands
721 // of ISD::SELECT (obviously also inverting the condition) so that we can
722 // take advantage of conditional moves using the $0 register.
724 // return (a != 0) ? x : 0;
732 if (!FalseC->getZExtValue()) {
733 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
734 SDValue True = N->getOperand(1);
736 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
737 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
739 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
742 // If both operands are integer constants there's a possibility that we
743 // can do some interesting optimizations.
744 SDValue True = N->getOperand(1);
745 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
747 if (!TrueC || !True.getValueType().isInteger())
750 // We'll also ignore MVT::i64 operands as this optimizations proves
751 // to be ineffective because of the required sign extensions as the result
752 // of a SETCC operator is always MVT::i32 for non-vector types.
753 if (True.getValueType() == MVT::i64)
756 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
758 // 1) (a < x) ? y : y-1
760 // addiu $reg2, $reg1, y-1
762 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
764 // 2) (a < x) ? y-1 : y
766 // xor $reg1, $reg1, 1
767 // addiu $reg2, $reg1, y-1
769 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
770 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
771 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
772 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
775 // Couldn't optimize.
779 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
780 TargetLowering::DAGCombinerInfo &DCI,
781 const MipsSubtarget &Subtarget) {
782 // Pattern match EXT.
783 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
784 // => ext $dst, $src, size, pos
785 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
788 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
789 unsigned ShiftRightOpc = ShiftRight.getOpcode();
791 // Op's first operand must be a shift right.
792 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
795 // The second operand of the shift must be an immediate.
797 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
800 uint64_t Pos = CN->getZExtValue();
801 uint64_t SMPos, SMSize;
803 // Op's second operand must be a shifted mask.
804 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
805 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
808 // Return if the shifted mask does not start at bit 0 or the sum of its size
809 // and Pos exceeds the word's size.
810 EVT ValTy = N->getValueType(0);
811 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
814 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
815 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
816 DAG.getConstant(SMSize, MVT::i32));
819 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
820 TargetLowering::DAGCombinerInfo &DCI,
821 const MipsSubtarget &Subtarget) {
822 // Pattern match INS.
823 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
824 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
825 // => ins $dst, $src, size, pos, $src1
826 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
829 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
830 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
833 // See if Op's first operand matches (and $src1 , mask0).
834 if (And0.getOpcode() != ISD::AND)
837 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
838 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
841 // See if Op's second operand matches (and (shl $src, pos), mask1).
842 if (And1.getOpcode() != ISD::AND)
845 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
846 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
849 // The shift masks must have the same position and size.
850 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
853 SDValue Shl = And1.getOperand(0);
854 if (Shl.getOpcode() != ISD::SHL)
857 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
860 unsigned Shamt = CN->getZExtValue();
862 // Return if the shift amount and the first bit position of mask are not the
864 EVT ValTy = N->getValueType(0);
865 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
868 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
869 DAG.getConstant(SMPos0, MVT::i32),
870 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
873 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
874 TargetLowering::DAGCombinerInfo &DCI,
875 const MipsSubtarget &Subtarget) {
876 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
878 if (DCI.isBeforeLegalizeOps())
881 SDValue Add = N->getOperand(1);
883 if (Add.getOpcode() != ISD::ADD)
886 SDValue Lo = Add.getOperand(1);
888 if ((Lo.getOpcode() != MipsISD::Lo) ||
889 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
892 EVT ValTy = N->getValueType(0);
895 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
897 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
900 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
902 SelectionDAG &DAG = DCI.DAG;
903 unsigned Opc = N->getOpcode();
909 return performDivRemCombine(N, DAG, DCI, Subtarget);
911 return performSELECTCombine(N, DAG, DCI, Subtarget);
913 return performANDCombine(N, DAG, DCI, Subtarget);
915 return performORCombine(N, DAG, DCI, Subtarget);
917 return performADDCombine(N, DAG, DCI, Subtarget);
924 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
925 SmallVectorImpl<SDValue> &Results,
926 SelectionDAG &DAG) const {
927 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
929 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
930 Results.push_back(Res.getValue(I));
934 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
935 SmallVectorImpl<SDValue> &Results,
936 SelectionDAG &DAG) const {
937 return LowerOperationWrapper(N, Results, DAG);
940 SDValue MipsTargetLowering::
941 LowerOperation(SDValue Op, SelectionDAG &DAG) const
943 switch (Op.getOpcode())
945 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
946 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
947 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
948 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
949 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
950 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
951 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
952 case ISD::SELECT: return lowerSELECT(Op, DAG);
953 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
954 case ISD::SETCC: return lowerSETCC(Op, DAG);
955 case ISD::VASTART: return lowerVASTART(Op, DAG);
956 case ISD::VAARG: return lowerVAARG(Op, DAG);
957 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
958 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
959 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
960 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
961 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
962 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
963 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
964 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
965 case ISD::LOAD: return lowerLOAD(Op, DAG);
966 case ISD::STORE: return lowerSTORE(Op, DAG);
967 case ISD::ADD: return lowerADD(Op, DAG);
968 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
973 //===----------------------------------------------------------------------===//
974 // Lower helper functions
975 //===----------------------------------------------------------------------===//
977 // addLiveIn - This helper function adds the specified physical register to the
978 // MachineFunction as a live in value. It also creates a corresponding
979 // virtual register for it.
981 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
983 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
984 MF.getRegInfo().addLiveIn(PReg, VReg);
988 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
989 MachineBasicBlock &MBB,
990 const TargetInstrInfo &TII,
995 // Insert instruction "teq $divisor_reg, $zero, 7".
996 MachineBasicBlock::iterator I(MI);
997 MachineInstrBuilder MIB;
998 MachineOperand &Divisor = MI->getOperand(2);
999 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
1000 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1001 .addReg(Mips::ZERO).addImm(7);
1003 // Use the 32-bit sub-register if this is a 64-bit division.
1005 MIB->getOperand(0).setSubReg(Mips::sub_32);
1007 // Clear Divisor's kill flag.
1008 Divisor.setIsKill(false);
1010 // We would normally delete the original instruction here but in this case
1011 // we only needed to inject an additional instruction rather than replace it.
1017 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1018 MachineBasicBlock *BB) const {
1019 switch (MI->getOpcode()) {
1021 llvm_unreachable("Unexpected instr type to insert");
1022 case Mips::ATOMIC_LOAD_ADD_I8:
1023 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1024 case Mips::ATOMIC_LOAD_ADD_I16:
1025 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1026 case Mips::ATOMIC_LOAD_ADD_I32:
1027 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
1028 case Mips::ATOMIC_LOAD_ADD_I64:
1029 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
1031 case Mips::ATOMIC_LOAD_AND_I8:
1032 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1033 case Mips::ATOMIC_LOAD_AND_I16:
1034 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1035 case Mips::ATOMIC_LOAD_AND_I32:
1036 return emitAtomicBinary(MI, BB, 4, Mips::AND);
1037 case Mips::ATOMIC_LOAD_AND_I64:
1038 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
1040 case Mips::ATOMIC_LOAD_OR_I8:
1041 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1042 case Mips::ATOMIC_LOAD_OR_I16:
1043 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1044 case Mips::ATOMIC_LOAD_OR_I32:
1045 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1046 case Mips::ATOMIC_LOAD_OR_I64:
1047 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1049 case Mips::ATOMIC_LOAD_XOR_I8:
1050 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1051 case Mips::ATOMIC_LOAD_XOR_I16:
1052 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1053 case Mips::ATOMIC_LOAD_XOR_I32:
1054 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1055 case Mips::ATOMIC_LOAD_XOR_I64:
1056 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1058 case Mips::ATOMIC_LOAD_NAND_I8:
1059 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1060 case Mips::ATOMIC_LOAD_NAND_I16:
1061 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1062 case Mips::ATOMIC_LOAD_NAND_I32:
1063 return emitAtomicBinary(MI, BB, 4, 0, true);
1064 case Mips::ATOMIC_LOAD_NAND_I64:
1065 return emitAtomicBinary(MI, BB, 8, 0, true);
1067 case Mips::ATOMIC_LOAD_SUB_I8:
1068 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1069 case Mips::ATOMIC_LOAD_SUB_I16:
1070 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1071 case Mips::ATOMIC_LOAD_SUB_I32:
1072 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1073 case Mips::ATOMIC_LOAD_SUB_I64:
1074 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1076 case Mips::ATOMIC_SWAP_I8:
1077 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1078 case Mips::ATOMIC_SWAP_I16:
1079 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1080 case Mips::ATOMIC_SWAP_I32:
1081 return emitAtomicBinary(MI, BB, 4, 0);
1082 case Mips::ATOMIC_SWAP_I64:
1083 return emitAtomicBinary(MI, BB, 8, 0);
1085 case Mips::ATOMIC_CMP_SWAP_I8:
1086 return emitAtomicCmpSwapPartword(MI, BB, 1);
1087 case Mips::ATOMIC_CMP_SWAP_I16:
1088 return emitAtomicCmpSwapPartword(MI, BB, 2);
1089 case Mips::ATOMIC_CMP_SWAP_I32:
1090 return emitAtomicCmpSwap(MI, BB, 4);
1091 case Mips::ATOMIC_CMP_SWAP_I64:
1092 return emitAtomicCmpSwap(MI, BB, 8);
1093 case Mips::PseudoSDIV:
1094 case Mips::PseudoUDIV:
1099 return insertDivByZeroTrap(
1100 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
1101 case Mips::PseudoDSDIV:
1102 case Mips::PseudoDUDIV:
1107 return insertDivByZeroTrap(
1108 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
1110 return emitSEL_D(MI, BB);
1114 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1115 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1117 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1118 unsigned Size, unsigned BinOpcode,
1120 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1122 MachineFunction *MF = BB->getParent();
1123 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1124 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1125 const TargetInstrInfo *TII =
1126 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1127 DebugLoc DL = MI->getDebugLoc();
1128 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1135 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1136 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1143 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1144 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1147 ZERO = Mips::ZERO_64;
1151 unsigned OldVal = MI->getOperand(0).getReg();
1152 unsigned Ptr = MI->getOperand(1).getReg();
1153 unsigned Incr = MI->getOperand(2).getReg();
1155 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1156 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1157 unsigned Success = RegInfo.createVirtualRegister(RC);
1159 // insert new blocks after the current block
1160 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1161 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1162 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1163 MachineFunction::iterator It = BB;
1165 MF->insert(It, loopMBB);
1166 MF->insert(It, exitMBB);
1168 // Transfer the remainder of BB and its successor edges to exitMBB.
1169 exitMBB->splice(exitMBB->begin(), BB,
1170 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1171 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1175 // fallthrough --> loopMBB
1176 BB->addSuccessor(loopMBB);
1177 loopMBB->addSuccessor(loopMBB);
1178 loopMBB->addSuccessor(exitMBB);
1181 // ll oldval, 0(ptr)
1182 // <binop> storeval, oldval, incr
1183 // sc success, storeval, 0(ptr)
1184 // beq success, $0, loopMBB
1186 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1188 // and andres, oldval, incr
1189 // nor storeval, $0, andres
1190 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1191 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1192 } else if (BinOpcode) {
1193 // <binop> storeval, oldval, incr
1194 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1198 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1199 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1201 MI->eraseFromParent(); // The instruction is gone now.
1206 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1207 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1208 unsigned SrcReg) const {
1209 const TargetInstrInfo *TII =
1210 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1211 DebugLoc DL = MI->getDebugLoc();
1213 if (Subtarget.hasMips32r2() && Size == 1) {
1214 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1218 if (Subtarget.hasMips32r2() && Size == 2) {
1219 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1223 MachineFunction *MF = BB->getParent();
1224 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1225 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1226 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1229 int64_t ShiftImm = 32 - (Size * 8);
1231 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1232 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1237 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1238 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1240 assert((Size == 1 || Size == 2) &&
1241 "Unsupported size for EmitAtomicBinaryPartial.");
1243 MachineFunction *MF = BB->getParent();
1244 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1245 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1246 const TargetInstrInfo *TII =
1247 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1248 DebugLoc DL = MI->getDebugLoc();
1250 unsigned Dest = MI->getOperand(0).getReg();
1251 unsigned Ptr = MI->getOperand(1).getReg();
1252 unsigned Incr = MI->getOperand(2).getReg();
1254 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1255 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1256 unsigned Mask = RegInfo.createVirtualRegister(RC);
1257 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1258 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1259 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1260 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1261 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1262 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1263 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1264 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1265 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1266 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1267 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1268 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1269 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1270 unsigned Success = RegInfo.createVirtualRegister(RC);
1272 // insert new blocks after the current block
1273 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1274 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1275 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1276 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1277 MachineFunction::iterator It = BB;
1279 MF->insert(It, loopMBB);
1280 MF->insert(It, sinkMBB);
1281 MF->insert(It, exitMBB);
1283 // Transfer the remainder of BB and its successor edges to exitMBB.
1284 exitMBB->splice(exitMBB->begin(), BB,
1285 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1286 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1288 BB->addSuccessor(loopMBB);
1289 loopMBB->addSuccessor(loopMBB);
1290 loopMBB->addSuccessor(sinkMBB);
1291 sinkMBB->addSuccessor(exitMBB);
1294 // addiu masklsb2,$0,-4 # 0xfffffffc
1295 // and alignedaddr,ptr,masklsb2
1296 // andi ptrlsb2,ptr,3
1297 // sll shiftamt,ptrlsb2,3
1298 // ori maskupper,$0,255 # 0xff
1299 // sll mask,maskupper,shiftamt
1300 // nor mask2,$0,mask
1301 // sll incr2,incr,shiftamt
1303 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1304 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1305 .addReg(Mips::ZERO).addImm(-4);
1306 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1307 .addReg(Ptr).addReg(MaskLSB2);
1308 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1309 if (Subtarget.isLittle()) {
1310 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1312 unsigned Off = RegInfo.createVirtualRegister(RC);
1313 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1314 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1315 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1317 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1318 .addReg(Mips::ZERO).addImm(MaskImm);
1319 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1320 .addReg(MaskUpper).addReg(ShiftAmt);
1321 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1322 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1324 // atomic.load.binop
1326 // ll oldval,0(alignedaddr)
1327 // binop binopres,oldval,incr2
1328 // and newval,binopres,mask
1329 // and maskedoldval0,oldval,mask2
1330 // or storeval,maskedoldval0,newval
1331 // sc success,storeval,0(alignedaddr)
1332 // beq success,$0,loopMBB
1336 // ll oldval,0(alignedaddr)
1337 // and newval,incr2,mask
1338 // and maskedoldval0,oldval,mask2
1339 // or storeval,maskedoldval0,newval
1340 // sc success,storeval,0(alignedaddr)
1341 // beq success,$0,loopMBB
1344 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1346 // and andres, oldval, incr2
1347 // nor binopres, $0, andres
1348 // and newval, binopres, mask
1349 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1350 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1351 .addReg(Mips::ZERO).addReg(AndRes);
1352 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1353 } else if (BinOpcode) {
1354 // <binop> binopres, oldval, incr2
1355 // and newval, binopres, mask
1356 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1357 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1358 } else { // atomic.swap
1359 // and newval, incr2, mask
1360 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1363 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1364 .addReg(OldVal).addReg(Mask2);
1365 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1366 .addReg(MaskedOldVal0).addReg(NewVal);
1367 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1368 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1369 BuildMI(BB, DL, TII->get(Mips::BEQ))
1370 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1373 // and maskedoldval1,oldval,mask
1374 // srl srlres,maskedoldval1,shiftamt
1375 // sign_extend dest,srlres
1378 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1379 .addReg(OldVal).addReg(Mask);
1380 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1381 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1382 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1384 MI->eraseFromParent(); // The instruction is gone now.
1389 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1390 MachineBasicBlock *BB,
1391 unsigned Size) const {
1392 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1394 MachineFunction *MF = BB->getParent();
1395 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1396 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1397 const TargetInstrInfo *TII =
1398 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1399 DebugLoc DL = MI->getDebugLoc();
1400 unsigned LL, SC, ZERO, BNE, BEQ;
1403 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1404 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1411 ZERO = Mips::ZERO_64;
1416 unsigned Dest = MI->getOperand(0).getReg();
1417 unsigned Ptr = MI->getOperand(1).getReg();
1418 unsigned OldVal = MI->getOperand(2).getReg();
1419 unsigned NewVal = MI->getOperand(3).getReg();
1421 unsigned Success = RegInfo.createVirtualRegister(RC);
1423 // insert new blocks after the current block
1424 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1425 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1426 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1427 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1428 MachineFunction::iterator It = BB;
1430 MF->insert(It, loop1MBB);
1431 MF->insert(It, loop2MBB);
1432 MF->insert(It, exitMBB);
1434 // Transfer the remainder of BB and its successor edges to exitMBB.
1435 exitMBB->splice(exitMBB->begin(), BB,
1436 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1437 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1441 // fallthrough --> loop1MBB
1442 BB->addSuccessor(loop1MBB);
1443 loop1MBB->addSuccessor(exitMBB);
1444 loop1MBB->addSuccessor(loop2MBB);
1445 loop2MBB->addSuccessor(loop1MBB);
1446 loop2MBB->addSuccessor(exitMBB);
1450 // bne dest, oldval, exitMBB
1452 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1453 BuildMI(BB, DL, TII->get(BNE))
1454 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1457 // sc success, newval, 0(ptr)
1458 // beq success, $0, loop1MBB
1460 BuildMI(BB, DL, TII->get(SC), Success)
1461 .addReg(NewVal).addReg(Ptr).addImm(0);
1462 BuildMI(BB, DL, TII->get(BEQ))
1463 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1465 MI->eraseFromParent(); // The instruction is gone now.
1471 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1472 MachineBasicBlock *BB,
1473 unsigned Size) const {
1474 assert((Size == 1 || Size == 2) &&
1475 "Unsupported size for EmitAtomicCmpSwapPartial.");
1477 MachineFunction *MF = BB->getParent();
1478 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1479 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1480 const TargetInstrInfo *TII =
1481 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1482 DebugLoc DL = MI->getDebugLoc();
1484 unsigned Dest = MI->getOperand(0).getReg();
1485 unsigned Ptr = MI->getOperand(1).getReg();
1486 unsigned CmpVal = MI->getOperand(2).getReg();
1487 unsigned NewVal = MI->getOperand(3).getReg();
1489 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1490 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1491 unsigned Mask = RegInfo.createVirtualRegister(RC);
1492 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1493 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1494 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1495 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1496 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1497 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1498 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1499 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1500 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1501 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1502 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1503 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1504 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1505 unsigned Success = RegInfo.createVirtualRegister(RC);
1507 // insert new blocks after the current block
1508 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1509 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1510 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1511 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1512 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1513 MachineFunction::iterator It = BB;
1515 MF->insert(It, loop1MBB);
1516 MF->insert(It, loop2MBB);
1517 MF->insert(It, sinkMBB);
1518 MF->insert(It, exitMBB);
1520 // Transfer the remainder of BB and its successor edges to exitMBB.
1521 exitMBB->splice(exitMBB->begin(), BB,
1522 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1523 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1525 BB->addSuccessor(loop1MBB);
1526 loop1MBB->addSuccessor(sinkMBB);
1527 loop1MBB->addSuccessor(loop2MBB);
1528 loop2MBB->addSuccessor(loop1MBB);
1529 loop2MBB->addSuccessor(sinkMBB);
1530 sinkMBB->addSuccessor(exitMBB);
1532 // FIXME: computation of newval2 can be moved to loop2MBB.
1534 // addiu masklsb2,$0,-4 # 0xfffffffc
1535 // and alignedaddr,ptr,masklsb2
1536 // andi ptrlsb2,ptr,3
1537 // sll shiftamt,ptrlsb2,3
1538 // ori maskupper,$0,255 # 0xff
1539 // sll mask,maskupper,shiftamt
1540 // nor mask2,$0,mask
1541 // andi maskedcmpval,cmpval,255
1542 // sll shiftedcmpval,maskedcmpval,shiftamt
1543 // andi maskednewval,newval,255
1544 // sll shiftednewval,maskednewval,shiftamt
1545 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1546 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1547 .addReg(Mips::ZERO).addImm(-4);
1548 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1549 .addReg(Ptr).addReg(MaskLSB2);
1550 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1551 if (Subtarget.isLittle()) {
1552 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1554 unsigned Off = RegInfo.createVirtualRegister(RC);
1555 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1556 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1557 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1559 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1560 .addReg(Mips::ZERO).addImm(MaskImm);
1561 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1562 .addReg(MaskUpper).addReg(ShiftAmt);
1563 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1564 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1565 .addReg(CmpVal).addImm(MaskImm);
1566 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1567 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1568 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1569 .addReg(NewVal).addImm(MaskImm);
1570 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1571 .addReg(MaskedNewVal).addReg(ShiftAmt);
1574 // ll oldval,0(alginedaddr)
1575 // and maskedoldval0,oldval,mask
1576 // bne maskedoldval0,shiftedcmpval,sinkMBB
1578 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1579 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1580 .addReg(OldVal).addReg(Mask);
1581 BuildMI(BB, DL, TII->get(Mips::BNE))
1582 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1585 // and maskedoldval1,oldval,mask2
1586 // or storeval,maskedoldval1,shiftednewval
1587 // sc success,storeval,0(alignedaddr)
1588 // beq success,$0,loop1MBB
1590 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1591 .addReg(OldVal).addReg(Mask2);
1592 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1593 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1594 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1595 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1596 BuildMI(BB, DL, TII->get(Mips::BEQ))
1597 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1600 // srl srlres,maskedoldval0,shiftamt
1601 // sign_extend dest,srlres
1604 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1605 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1606 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1608 MI->eraseFromParent(); // The instruction is gone now.
1613 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1614 MachineBasicBlock *BB) const {
1615 MachineFunction *MF = BB->getParent();
1616 const TargetRegisterInfo *TRI =
1617 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1618 const TargetInstrInfo *TII =
1619 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1620 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1621 DebugLoc DL = MI->getDebugLoc();
1622 MachineBasicBlock::iterator II(MI);
1624 unsigned Fc = MI->getOperand(1).getReg();
1625 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1627 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1629 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1632 .addImm(Mips::sub_lo);
1634 // We don't erase the original instruction, we just replace the condition
1635 // register with the 64-bit super-register.
1636 MI->getOperand(1).setReg(Fc2);
1641 //===----------------------------------------------------------------------===//
1642 // Misc Lower Operation implementation
1643 //===----------------------------------------------------------------------===//
1644 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1645 SDValue Chain = Op.getOperand(0);
1646 SDValue Table = Op.getOperand(1);
1647 SDValue Index = Op.getOperand(2);
1649 EVT PTy = getPointerTy();
1650 unsigned EntrySize =
1651 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1653 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1654 DAG.getConstant(EntrySize, PTy));
1655 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1657 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1658 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1659 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1661 Chain = Addr.getValue(1);
1663 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1664 Subtarget.isABI_N64()) {
1665 // For PIC, the sequence is:
1666 // BRIND(load(Jumptable + index) + RelocBase)
1667 // RelocBase can be JumpTable, GOT or some sort of global base.
1668 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1669 getPICJumpTableRelocBase(Table, DAG));
1672 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1675 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1676 // The first operand is the chain, the second is the condition, the third is
1677 // the block to branch to if the condition is true.
1678 SDValue Chain = Op.getOperand(0);
1679 SDValue Dest = Op.getOperand(2);
1682 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1683 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1685 // Return if flag is not set by a floating point comparison.
1686 if (CondRes.getOpcode() != MipsISD::FPCmp)
1689 SDValue CCNode = CondRes.getOperand(2);
1691 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1692 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1693 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1694 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1695 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1696 FCC0, Dest, CondRes);
1699 SDValue MipsTargetLowering::
1700 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1702 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1703 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1705 // Return if flag is not set by a floating point comparison.
1706 if (Cond.getOpcode() != MipsISD::FPCmp)
1709 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1713 SDValue MipsTargetLowering::
1714 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1717 EVT Ty = Op.getOperand(0).getValueType();
1718 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1719 getSetCCResultType(*DAG.getContext(), Ty),
1720 Op.getOperand(0), Op.getOperand(1),
1723 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1727 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1728 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1729 SDValue Cond = createFPCmp(DAG, Op);
1731 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1732 "Floating point operand expected.");
1734 SDValue True = DAG.getConstant(1, MVT::i32);
1735 SDValue False = DAG.getConstant(0, MVT::i32);
1737 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1740 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1741 SelectionDAG &DAG) const {
1742 EVT Ty = Op.getValueType();
1743 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1744 const GlobalValue *GV = N->getGlobal();
1746 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1747 !Subtarget.isABI_N64()) {
1748 const MipsTargetObjectFile &TLOF =
1749 (const MipsTargetObjectFile&)getObjFileLowering();
1751 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine()))
1752 // %gp_rel relocation
1753 return getAddrGPRel(N, Ty, DAG);
1755 // %hi/%lo relocation
1756 return getAddrNonPIC(N, Ty, DAG);
1759 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1760 return getAddrLocal(N, Ty, DAG,
1761 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1764 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1765 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1766 MachinePointerInfo::getGOT());
1768 return getAddrGlobal(N, Ty, DAG,
1769 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1770 ? MipsII::MO_GOT_DISP
1772 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1775 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1776 SelectionDAG &DAG) const {
1777 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1778 EVT Ty = Op.getValueType();
1780 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1781 !Subtarget.isABI_N64())
1782 return getAddrNonPIC(N, Ty, DAG);
1784 return getAddrLocal(N, Ty, DAG,
1785 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1788 SDValue MipsTargetLowering::
1789 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1791 // If the relocation model is PIC, use the General Dynamic TLS Model or
1792 // Local Dynamic TLS model, otherwise use the Initial Exec or
1793 // Local Exec TLS Model.
1795 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1797 const GlobalValue *GV = GA->getGlobal();
1798 EVT PtrVT = getPointerTy();
1800 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1802 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1803 // General Dynamic and Local Dynamic TLS Model.
1804 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1807 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1808 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1809 getGlobalReg(DAG, PtrVT), TGA);
1810 unsigned PtrSize = PtrVT.getSizeInBits();
1811 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1813 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1817 Entry.Node = Argument;
1819 Args.push_back(Entry);
1821 TargetLowering::CallLoweringInfo CLI(DAG);
1822 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1823 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1824 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1826 SDValue Ret = CallResult.first;
1828 if (model != TLSModel::LocalDynamic)
1831 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1832 MipsII::MO_DTPREL_HI);
1833 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1834 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1835 MipsII::MO_DTPREL_LO);
1836 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1837 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1838 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1842 if (model == TLSModel::InitialExec) {
1843 // Initial Exec TLS Model
1844 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1845 MipsII::MO_GOTTPREL);
1846 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1848 Offset = DAG.getLoad(PtrVT, DL,
1849 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1850 false, false, false, 0);
1852 // Local Exec TLS Model
1853 assert(model == TLSModel::LocalExec);
1854 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1855 MipsII::MO_TPREL_HI);
1856 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1857 MipsII::MO_TPREL_LO);
1858 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1859 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1860 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1863 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1864 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1867 SDValue MipsTargetLowering::
1868 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1870 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1871 EVT Ty = Op.getValueType();
1873 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1874 !Subtarget.isABI_N64())
1875 return getAddrNonPIC(N, Ty, DAG);
1877 return getAddrLocal(N, Ty, DAG,
1878 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1881 SDValue MipsTargetLowering::
1882 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1884 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1885 EVT Ty = Op.getValueType();
1887 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1888 !Subtarget.isABI_N64()) {
1889 const MipsTargetObjectFile &TLOF =
1890 (const MipsTargetObjectFile&)getObjFileLowering();
1892 if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1893 // %gp_rel relocation
1894 return getAddrGPRel(N, Ty, DAG);
1896 return getAddrNonPIC(N, Ty, DAG);
1899 return getAddrLocal(N, Ty, DAG,
1900 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1903 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1904 MachineFunction &MF = DAG.getMachineFunction();
1905 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1908 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1911 // vastart just stores the address of the VarArgsFrameIndex slot into the
1912 // memory location argument.
1913 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1914 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1915 MachinePointerInfo(SV), false, false, 0);
1918 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1919 SDNode *Node = Op.getNode();
1920 EVT VT = Node->getValueType(0);
1921 SDValue Chain = Node->getOperand(0);
1922 SDValue VAListPtr = Node->getOperand(1);
1923 unsigned Align = Node->getConstantOperandVal(3);
1924 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1926 unsigned ArgSlotSizeInBytes =
1927 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1929 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1930 MachinePointerInfo(SV), false, false, false,
1932 SDValue VAList = VAListLoad;
1934 // Re-align the pointer if necessary.
1935 // It should only ever be necessary for 64-bit types on O32 since the minimum
1936 // argument alignment is the same as the maximum type alignment for N32/N64.
1938 // FIXME: We currently align too often. The code generator doesn't notice
1939 // when the pointer is still aligned from the last va_arg (or pair of
1940 // va_args for the i64 on O32 case).
1941 if (Align > getMinStackArgumentAlignment()) {
1942 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1944 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1945 DAG.getConstant(Align - 1,
1946 VAList.getValueType()));
1948 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1949 DAG.getConstant(-(int64_t)Align,
1950 VAList.getValueType()));
1953 // Increment the pointer, VAList, to the next vaarg.
1954 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1955 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1956 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1957 VAList.getValueType()));
1958 // Store the incremented VAList to the legalized pointer
1959 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1960 MachinePointerInfo(SV), false, false, 0);
1962 // In big-endian mode we must adjust the pointer when the load size is smaller
1963 // than the argument slot size. We must also reduce the known alignment to
1964 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1965 // the correct half of the slot, and reduce the alignment from 8 (slot
1966 // alignment) down to 4 (type alignment).
1967 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1968 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1969 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1970 DAG.getIntPtrConstant(Adjustment));
1972 // Load the actual argument out of the pointer VAList
1973 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1977 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1978 bool HasExtractInsert) {
1979 EVT TyX = Op.getOperand(0).getValueType();
1980 EVT TyY = Op.getOperand(1).getValueType();
1981 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1982 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1986 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1988 SDValue X = (TyX == MVT::f32) ?
1989 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1990 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1992 SDValue Y = (TyY == MVT::f32) ?
1993 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1994 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1997 if (HasExtractInsert) {
1998 // ext E, Y, 31, 1 ; extract bit31 of Y
1999 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2000 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2001 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2004 // srl SrlX, SllX, 1
2006 // sll SllY, SrlX, 31
2007 // or Or, SrlX, SllY
2008 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2009 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2010 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2011 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2012 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2015 if (TyX == MVT::f32)
2016 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2018 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2019 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2020 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2023 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2024 bool HasExtractInsert) {
2025 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2026 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2027 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2028 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2031 // Bitcast to integer nodes.
2032 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2033 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2035 if (HasExtractInsert) {
2036 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2037 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2038 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2039 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2041 if (WidthX > WidthY)
2042 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2043 else if (WidthY > WidthX)
2044 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2046 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2047 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2048 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2051 // (d)sll SllX, X, 1
2052 // (d)srl SrlX, SllX, 1
2053 // (d)srl SrlY, Y, width(Y)-1
2054 // (d)sll SllY, SrlX, width(Y)-1
2055 // or Or, SrlX, SllY
2056 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2057 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2058 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2059 DAG.getConstant(WidthY - 1, MVT::i32));
2061 if (WidthX > WidthY)
2062 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2063 else if (WidthY > WidthX)
2064 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2066 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2067 DAG.getConstant(WidthX - 1, MVT::i32));
2068 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2069 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2073 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2074 if (Subtarget.isGP64bit())
2075 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2077 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2080 SDValue MipsTargetLowering::
2081 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2083 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2084 "Frame address can only be determined for current frame.");
2086 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2087 MFI->setFrameAddressIsTaken(true);
2088 EVT VT = Op.getValueType();
2091 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
2092 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
2096 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2097 SelectionDAG &DAG) const {
2098 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2102 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2103 "Return address can be determined only for current frame.");
2105 MachineFunction &MF = DAG.getMachineFunction();
2106 MachineFrameInfo *MFI = MF.getFrameInfo();
2107 MVT VT = Op.getSimpleValueType();
2108 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
2109 MFI->setReturnAddressIsTaken(true);
2111 // Return RA, which contains the return address. Mark it an implicit live-in.
2112 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2113 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2116 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2117 // generated from __builtin_eh_return (offset, handler)
2118 // The effect of this is to adjust the stack pointer by "offset"
2119 // and then branch to "handler".
2120 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2122 MachineFunction &MF = DAG.getMachineFunction();
2123 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2125 MipsFI->setCallsEhReturn();
2126 SDValue Chain = Op.getOperand(0);
2127 SDValue Offset = Op.getOperand(1);
2128 SDValue Handler = Op.getOperand(2);
2130 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2132 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2133 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2134 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
2135 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2136 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2137 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2138 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2139 DAG.getRegister(OffsetReg, Ty),
2140 DAG.getRegister(AddrReg, getPointerTy()),
2144 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2145 SelectionDAG &DAG) const {
2146 // FIXME: Need pseudo-fence for 'singlethread' fences
2147 // FIXME: Set SType for weaker fences where supported/appropriate.
2150 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2151 DAG.getConstant(SType, MVT::i32));
2154 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2155 SelectionDAG &DAG) const {
2157 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2158 SDValue Shamt = Op.getOperand(2);
2161 // lo = (shl lo, shamt)
2162 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2165 // hi = (shl lo, shamt[4:0])
2166 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2167 DAG.getConstant(-1, MVT::i32));
2168 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2169 DAG.getConstant(1, MVT::i32));
2170 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2172 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2173 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2174 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2175 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2176 DAG.getConstant(0x20, MVT::i32));
2177 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2178 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2179 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2181 SDValue Ops[2] = {Lo, Hi};
2182 return DAG.getMergeValues(Ops, DL);
2185 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2188 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2189 SDValue Shamt = Op.getOperand(2);
2192 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2194 // hi = (sra hi, shamt)
2196 // hi = (srl hi, shamt)
2199 // lo = (sra hi, shamt[4:0])
2200 // hi = (sra hi, 31)
2202 // lo = (srl hi, shamt[4:0])
2204 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2205 DAG.getConstant(-1, MVT::i32));
2206 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2207 DAG.getConstant(1, MVT::i32));
2208 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2209 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2210 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2211 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2213 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2214 DAG.getConstant(0x20, MVT::i32));
2215 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2216 DAG.getConstant(31, MVT::i32));
2217 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2218 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2219 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2222 SDValue Ops[2] = {Lo, Hi};
2223 return DAG.getMergeValues(Ops, DL);
2226 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2227 SDValue Chain, SDValue Src, unsigned Offset) {
2228 SDValue Ptr = LD->getBasePtr();
2229 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2230 EVT BasePtrVT = Ptr.getValueType();
2232 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2235 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2236 DAG.getConstant(Offset, BasePtrVT));
2238 SDValue Ops[] = { Chain, Ptr, Src };
2239 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2240 LD->getMemOperand());
2243 // Expand an unaligned 32 or 64-bit integer load node.
2244 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2245 LoadSDNode *LD = cast<LoadSDNode>(Op);
2246 EVT MemVT = LD->getMemoryVT();
2248 if (Subtarget.systemSupportsUnalignedAccess())
2251 // Return if load is aligned or if MemVT is neither i32 nor i64.
2252 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2253 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2256 bool IsLittle = Subtarget.isLittle();
2257 EVT VT = Op.getValueType();
2258 ISD::LoadExtType ExtType = LD->getExtensionType();
2259 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2261 assert((VT == MVT::i32) || (VT == MVT::i64));
2264 // (set dst, (i64 (load baseptr)))
2266 // (set tmp, (ldl (add baseptr, 7), undef))
2267 // (set dst, (ldr baseptr, tmp))
2268 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2269 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2271 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2275 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2277 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2281 // (set dst, (i32 (load baseptr))) or
2282 // (set dst, (i64 (sextload baseptr))) or
2283 // (set dst, (i64 (extload baseptr)))
2285 // (set tmp, (lwl (add baseptr, 3), undef))
2286 // (set dst, (lwr baseptr, tmp))
2287 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2288 (ExtType == ISD::EXTLOAD))
2291 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2294 // (set dst, (i64 (zextload baseptr)))
2296 // (set tmp0, (lwl (add baseptr, 3), undef))
2297 // (set tmp1, (lwr baseptr, tmp0))
2298 // (set tmp2, (shl tmp1, 32))
2299 // (set dst, (srl tmp2, 32))
2301 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2302 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2303 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2304 SDValue Ops[] = { SRL, LWR.getValue(1) };
2305 return DAG.getMergeValues(Ops, DL);
2308 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2309 SDValue Chain, unsigned Offset) {
2310 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2311 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2313 SDVTList VTList = DAG.getVTList(MVT::Other);
2316 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2317 DAG.getConstant(Offset, BasePtrVT));
2319 SDValue Ops[] = { Chain, Value, Ptr };
2320 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2321 SD->getMemOperand());
2324 // Expand an unaligned 32 or 64-bit integer store node.
2325 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2327 SDValue Value = SD->getValue(), Chain = SD->getChain();
2328 EVT VT = Value.getValueType();
2331 // (store val, baseptr) or
2332 // (truncstore val, baseptr)
2334 // (swl val, (add baseptr, 3))
2335 // (swr val, baseptr)
2336 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2337 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2339 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2342 assert(VT == MVT::i64);
2345 // (store val, baseptr)
2347 // (sdl val, (add baseptr, 7))
2348 // (sdr val, baseptr)
2349 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2350 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2353 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2354 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2355 SDValue Val = SD->getValue();
2357 if (Val.getOpcode() != ISD::FP_TO_SINT)
2360 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2361 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2364 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2365 SD->getPointerInfo(), SD->isVolatile(),
2366 SD->isNonTemporal(), SD->getAlignment());
2369 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2370 StoreSDNode *SD = cast<StoreSDNode>(Op);
2371 EVT MemVT = SD->getMemoryVT();
2373 // Lower unaligned integer stores.
2374 if (!Subtarget.systemSupportsUnalignedAccess() &&
2375 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2376 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2377 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2379 return lowerFP_TO_SINT_STORE(SD, DAG);
2382 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2383 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2384 || cast<ConstantSDNode>
2385 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2386 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2390 // (add (frameaddr 0), (frame_to_args_offset))
2391 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2392 // (add FrameObject, 0)
2393 // where FrameObject is a fixed StackObject with offset 0 which points to
2394 // the old stack pointer.
2395 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2396 EVT ValTy = Op->getValueType(0);
2397 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2398 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2399 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2400 DAG.getConstant(0, ValTy));
2403 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2404 SelectionDAG &DAG) const {
2405 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2406 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2408 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2411 //===----------------------------------------------------------------------===//
2412 // Calling Convention Implementation
2413 //===----------------------------------------------------------------------===//
2415 //===----------------------------------------------------------------------===//
2416 // TODO: Implement a generic logic using tblgen that can support this.
2417 // Mips O32 ABI rules:
2419 // i32 - Passed in A0, A1, A2, A3 and stack
2420 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2421 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2422 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2423 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2424 // not used, it must be shadowed. If only A3 is available, shadow it and
2427 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2428 //===----------------------------------------------------------------------===//
2430 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2431 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2432 CCState &State, const MCPhysReg *F64Regs) {
2434 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2436 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2437 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2439 // Do not process byval args here.
2440 if (ArgFlags.isByVal())
2443 // Promote i8 and i16
2444 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2446 if (ArgFlags.isSExt())
2447 LocInfo = CCValAssign::SExt;
2448 else if (ArgFlags.isZExt())
2449 LocInfo = CCValAssign::ZExt;
2451 LocInfo = CCValAssign::AExt;
2456 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2457 // is true: function is vararg, argument is 3rd or higher, there is previous
2458 // argument which is not f32 or f64.
2459 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2460 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2461 unsigned OrigAlign = ArgFlags.getOrigAlign();
2462 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2464 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2465 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2466 // If this is the first part of an i64 arg,
2467 // the allocated register must be either A0 or A2.
2468 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2469 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2471 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2472 // Allocate int register and shadow next int register. If first
2473 // available register is Mips::A1 or Mips::A3, shadow it too.
2474 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2475 if (Reg == Mips::A1 || Reg == Mips::A3)
2476 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2477 State.AllocateReg(IntRegs, IntRegsSize);
2479 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2480 // we are guaranteed to find an available float register
2481 if (ValVT == MVT::f32) {
2482 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2483 // Shadow int register
2484 State.AllocateReg(IntRegs, IntRegsSize);
2486 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2487 // Shadow int registers
2488 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2489 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2490 State.AllocateReg(IntRegs, IntRegsSize);
2491 State.AllocateReg(IntRegs, IntRegsSize);
2494 llvm_unreachable("Cannot handle this ValVT.");
2497 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2499 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2501 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2506 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2507 MVT LocVT, CCValAssign::LocInfo LocInfo,
2508 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2509 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2511 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2514 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2515 MVT LocVT, CCValAssign::LocInfo LocInfo,
2516 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2517 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2519 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2522 #include "MipsGenCallingConv.inc"
2524 //===----------------------------------------------------------------------===//
2525 // Call Calling Convention Implementation
2526 //===----------------------------------------------------------------------===//
2528 // Return next O32 integer argument register.
2529 static unsigned getNextIntArgReg(unsigned Reg) {
2530 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2531 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2535 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2536 SDValue Chain, SDValue Arg, SDLoc DL,
2537 bool IsTailCall, SelectionDAG &DAG) const {
2539 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2540 DAG.getIntPtrConstant(Offset));
2541 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2545 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2546 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2547 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2548 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2549 /*isVolatile=*/ true, false, 0);
2552 void MipsTargetLowering::
2553 getOpndList(SmallVectorImpl<SDValue> &Ops,
2554 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2555 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2556 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2557 SDValue Chain) const {
2558 // Insert node "GP copy globalreg" before call to function.
2560 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2561 // in PIC mode) allow symbols to be resolved via lazy binding.
2562 // The lazy binding stub requires GP to point to the GOT.
2563 // Note that we don't need GP to point to the GOT for indirect calls
2564 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2565 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2566 // used for the function (that is, Mips linker doesn't generate lazy binding
2567 // stub for a function whose address is taken in the program).
2568 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2569 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2570 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2571 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2574 // Build a sequence of copy-to-reg nodes chained together with token
2575 // chain and flag operands which copy the outgoing args into registers.
2576 // The InFlag in necessary since all emitted instructions must be
2580 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2581 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2582 RegsToPass[i].second, InFlag);
2583 InFlag = Chain.getValue(1);
2586 // Add argument registers to the end of the list so that they are
2587 // known live into the call.
2588 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2589 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2590 RegsToPass[i].second.getValueType()));
2592 // Add a register mask operand representing the call-preserved registers.
2593 const TargetRegisterInfo *TRI =
2594 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2595 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2596 assert(Mask && "Missing call preserved mask for calling convention");
2597 if (Subtarget.inMips16HardFloat()) {
2598 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2599 llvm::StringRef Sym = G->getGlobal()->getName();
2600 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2601 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2602 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2606 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2608 if (InFlag.getNode())
2609 Ops.push_back(InFlag);
2612 /// LowerCall - functions arguments are copied from virtual regs to
2613 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2615 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2616 SmallVectorImpl<SDValue> &InVals) const {
2617 SelectionDAG &DAG = CLI.DAG;
2619 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2620 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2621 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2622 SDValue Chain = CLI.Chain;
2623 SDValue Callee = CLI.Callee;
2624 bool &IsTailCall = CLI.IsTailCall;
2625 CallingConv::ID CallConv = CLI.CallConv;
2626 bool IsVarArg = CLI.IsVarArg;
2628 MachineFunction &MF = DAG.getMachineFunction();
2629 MachineFrameInfo *MFI = MF.getFrameInfo();
2630 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2631 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2632 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2634 // Analyze operands of the call, assigning locations to each operand.
2635 SmallVector<CCValAssign, 16> ArgLocs;
2637 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2638 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2639 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2641 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2643 // Get a count of how many bytes are to be pushed on the stack.
2644 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2646 // Check if it's really possible to do a tail call.
2648 IsTailCall = isEligibleForTailCallOptimization(
2649 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2651 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2652 report_fatal_error("failed to perform tail call elimination on a call "
2653 "site marked musttail");
2658 // Chain is the output chain of the last Load/Store or CopyToReg node.
2659 // ByValChain is the output chain of the last Memcpy node created for copying
2660 // byval arguments to the stack.
2661 unsigned StackAlignment = TFL->getStackAlignment();
2662 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2663 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2666 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2668 SDValue StackPtr = DAG.getCopyFromReg(
2669 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2672 // With EABI is it possible to have 16 args on registers.
2673 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2674 SmallVector<SDValue, 8> MemOpChains;
2676 CCInfo.rewindByValRegsInfo();
2678 // Walk the register/memloc assignments, inserting copies/loads.
2679 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2680 SDValue Arg = OutVals[i];
2681 CCValAssign &VA = ArgLocs[i];
2682 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2683 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2686 if (Flags.isByVal()) {
2687 unsigned FirstByValReg, LastByValReg;
2688 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2689 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2691 assert(Flags.getByValSize() &&
2692 "ByVal args of size 0 should have been ignored by front-end.");
2693 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2694 assert(!IsTailCall &&
2695 "Do not tail-call optimize if there is a byval argument.");
2696 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2697 MipsCCInfo, FirstByValReg, LastByValReg, Flags,
2698 Subtarget.isLittle(), VA);
2699 CCInfo.nextInRegsParam();
2703 // Promote the value if needed.
2704 switch (VA.getLocInfo()) {
2705 default: llvm_unreachable("Unknown loc info!");
2706 case CCValAssign::Full:
2707 if (VA.isRegLoc()) {
2708 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2709 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2710 (ValVT == MVT::i64 && LocVT == MVT::f64))
2711 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2712 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2713 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2714 Arg, DAG.getConstant(0, MVT::i32));
2715 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2716 Arg, DAG.getConstant(1, MVT::i32));
2717 if (!Subtarget.isLittle())
2719 unsigned LocRegLo = VA.getLocReg();
2720 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2721 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2722 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2727 case CCValAssign::BCvt:
2728 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2730 case CCValAssign::SExt:
2731 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2733 case CCValAssign::ZExt:
2734 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2736 case CCValAssign::AExt:
2737 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2741 // Arguments that can be passed on register must be kept at
2742 // RegsToPass vector
2743 if (VA.isRegLoc()) {
2744 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2748 // Register can't get to this point...
2749 assert(VA.isMemLoc());
2751 // emit ISD::STORE whichs stores the
2752 // parameter value to a stack Location
2753 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2754 Chain, Arg, DL, IsTailCall, DAG));
2757 // Transform all store nodes into one single node because all store
2758 // nodes are independent of each other.
2759 if (!MemOpChains.empty())
2760 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2762 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2763 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2764 // node so that legalize doesn't hack it.
2766 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2768 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2770 EVT Ty = Callee.getValueType();
2772 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2774 const GlobalValue *Val = G->getGlobal();
2775 InternalLinkage = Val->hasInternalLinkage();
2777 if (InternalLinkage)
2778 Callee = getAddrLocal(G, Ty, DAG,
2779 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2780 else if (LargeGOT) {
2781 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2782 MipsII::MO_CALL_LO16, Chain,
2783 FuncInfo->callPtrInfo(Val));
2786 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2787 FuncInfo->callPtrInfo(Val));
2791 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2792 MipsII::MO_NO_FLAG);
2793 GlobalOrExternal = true;
2795 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2796 const char *Sym = S->getSymbol();
2798 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2799 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2800 MipsII::MO_NO_FLAG);
2801 else if (LargeGOT) {
2802 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2803 MipsII::MO_CALL_LO16, Chain,
2804 FuncInfo->callPtrInfo(Sym));
2806 } else { // N64 || PIC
2807 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2808 FuncInfo->callPtrInfo(Sym));
2812 GlobalOrExternal = true;
2815 SmallVector<SDValue, 8> Ops(1, Chain);
2816 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2818 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2819 IsCallReloc, CLI, Callee, Chain);
2822 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2824 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2825 SDValue InFlag = Chain.getValue(1);
2827 // Create the CALLSEQ_END node.
2828 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2829 DAG.getIntPtrConstant(0, true), InFlag, DL);
2830 InFlag = Chain.getValue(1);
2832 // Handle result values, copying them out of physregs into vregs that we
2834 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2838 /// LowerCallResult - Lower the result values of a call into the
2839 /// appropriate copies out of appropriate physical registers.
2840 SDValue MipsTargetLowering::LowerCallResult(
2841 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2842 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2843 SmallVectorImpl<SDValue> &InVals,
2844 TargetLowering::CallLoweringInfo &CLI) const {
2845 // Assign locations to each value returned by this call.
2846 SmallVector<CCValAssign, 16> RVLocs;
2847 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2849 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2851 // Copy all of the result registers out of their specified physreg.
2852 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2853 CCValAssign &VA = RVLocs[i];
2854 assert(VA.isRegLoc() && "Can only return in registers!");
2856 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2857 RVLocs[i].getLocVT(), InFlag);
2858 Chain = Val.getValue(1);
2859 InFlag = Val.getValue(2);
2861 if (VA.isUpperBitsInLoc()) {
2862 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2863 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2865 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2867 Shift, DL, VA.getLocVT(), Val,
2868 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2871 switch (VA.getLocInfo()) {
2873 llvm_unreachable("Unknown loc info!");
2874 case CCValAssign::Full:
2876 case CCValAssign::BCvt:
2877 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2879 case CCValAssign::AExt:
2880 case CCValAssign::AExtUpper:
2881 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2883 case CCValAssign::ZExt:
2884 case CCValAssign::ZExtUpper:
2885 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2886 DAG.getValueType(VA.getValVT()));
2887 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2889 case CCValAssign::SExt:
2890 case CCValAssign::SExtUpper:
2891 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2892 DAG.getValueType(VA.getValVT()));
2893 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2897 InVals.push_back(Val);
2903 //===----------------------------------------------------------------------===//
2904 // Formal Arguments Calling Convention Implementation
2905 //===----------------------------------------------------------------------===//
2906 /// LowerFormalArguments - transform physical registers into virtual registers
2907 /// and generate load operations for arguments places on the stack.
2909 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2910 CallingConv::ID CallConv,
2912 const SmallVectorImpl<ISD::InputArg> &Ins,
2913 SDLoc DL, SelectionDAG &DAG,
2914 SmallVectorImpl<SDValue> &InVals)
2916 MachineFunction &MF = DAG.getMachineFunction();
2917 MachineFrameInfo *MFI = MF.getFrameInfo();
2918 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2920 MipsFI->setVarArgsFrameIndex(0);
2922 // Used with vargs to acumulate store chains.
2923 std::vector<SDValue> OutChains;
2925 // Assign locations to all of the incoming arguments.
2926 SmallVector<CCValAssign, 16> ArgLocs;
2927 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2929 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2930 Function::const_arg_iterator FuncArg =
2931 DAG.getMachineFunction().getFunction()->arg_begin();
2933 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2934 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2935 CCInfo.getInRegsParamsCount() > 0);
2937 unsigned CurArgIdx = 0;
2938 CCInfo.rewindByValRegsInfo();
2940 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2941 CCValAssign &VA = ArgLocs[i];
2942 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2943 CurArgIdx = Ins[i].OrigArgIndex;
2944 EVT ValVT = VA.getValVT();
2945 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2946 bool IsRegLoc = VA.isRegLoc();
2948 if (Flags.isByVal()) {
2949 unsigned FirstByValReg, LastByValReg;
2950 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2951 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2953 assert(Flags.getByValSize() &&
2954 "ByVal args of size 0 should have been ignored by front-end.");
2955 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2956 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2957 MipsCCInfo, FirstByValReg, LastByValReg, VA);
2958 CCInfo.nextInRegsParam();
2962 // Arguments stored on registers
2964 MVT RegVT = VA.getLocVT();
2965 unsigned ArgReg = VA.getLocReg();
2966 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2968 // Transform the arguments stored on
2969 // physical registers into virtual ones
2970 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2971 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2973 // If this is an 8 or 16-bit value, it has been passed promoted
2974 // to 32 bits. Insert an assert[sz]ext to capture this, then
2975 // truncate to the right size.
2976 switch (VA.getLocInfo()) {
2978 llvm_unreachable("Unknown loc info!");
2979 case CCValAssign::Full:
2981 case CCValAssign::SExt:
2982 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2983 DAG.getValueType(ValVT));
2984 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2986 case CCValAssign::ZExt:
2987 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2988 DAG.getValueType(ValVT));
2989 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2991 case CCValAssign::BCvt:
2992 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2996 // Handle floating point arguments passed in integer registers and
2997 // long double arguments passed in floating point registers.
2998 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2999 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3000 (RegVT == MVT::f64 && ValVT == MVT::i64))
3001 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3002 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
3003 ValVT == MVT::f64) {
3004 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3005 getNextIntArgReg(ArgReg), RC);
3006 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3007 if (!Subtarget.isLittle())
3008 std::swap(ArgValue, ArgValue2);
3009 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3010 ArgValue, ArgValue2);
3013 InVals.push_back(ArgValue);
3014 } else { // VA.isRegLoc()
3017 assert(VA.isMemLoc());
3019 // The stack pointer offset is relative to the caller stack frame.
3020 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3021 VA.getLocMemOffset(), true);
3023 // Create load nodes to retrieve arguments from the stack
3024 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3025 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
3026 MachinePointerInfo::getFixedStack(FI),
3027 false, false, false, 0);
3028 InVals.push_back(Load);
3029 OutChains.push_back(Load.getValue(1));
3033 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3034 // The mips ABIs for returning structs by value requires that we copy
3035 // the sret argument into $v0 for the return. Save the argument into
3036 // a virtual register so that we can access it from the return points.
3037 if (Ins[i].Flags.isSRet()) {
3038 unsigned Reg = MipsFI->getSRetReturnReg();
3040 Reg = MF.getRegInfo().createVirtualRegister(
3041 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
3042 MipsFI->setSRetReturnReg(Reg);
3044 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3045 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3051 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG, CCInfo);
3053 // All stores are grouped in one node to allow the matching between
3054 // the size of Ins and InVals. This only happens when on varg functions
3055 if (!OutChains.empty()) {
3056 OutChains.push_back(Chain);
3057 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3063 //===----------------------------------------------------------------------===//
3064 // Return Value Calling Convention Implementation
3065 //===----------------------------------------------------------------------===//
3068 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3069 MachineFunction &MF, bool IsVarArg,
3070 const SmallVectorImpl<ISD::OutputArg> &Outs,
3071 LLVMContext &Context) const {
3072 SmallVector<CCValAssign, 16> RVLocs;
3073 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3074 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3078 MipsTargetLowering::LowerReturn(SDValue Chain,
3079 CallingConv::ID CallConv, bool IsVarArg,
3080 const SmallVectorImpl<ISD::OutputArg> &Outs,
3081 const SmallVectorImpl<SDValue> &OutVals,
3082 SDLoc DL, SelectionDAG &DAG) const {
3083 // CCValAssign - represent the assignment of
3084 // the return value to a location
3085 SmallVector<CCValAssign, 16> RVLocs;
3086 MachineFunction &MF = DAG.getMachineFunction();
3088 // CCState - Info about the registers and stack slot.
3089 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3091 // Analyze return values.
3092 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3095 SmallVector<SDValue, 4> RetOps(1, Chain);
3097 // Copy the result values into the output registers.
3098 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3099 SDValue Val = OutVals[i];
3100 CCValAssign &VA = RVLocs[i];
3101 assert(VA.isRegLoc() && "Can only return in registers!");
3102 bool UseUpperBits = false;
3104 switch (VA.getLocInfo()) {
3106 llvm_unreachable("Unknown loc info!");
3107 case CCValAssign::Full:
3109 case CCValAssign::BCvt:
3110 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3112 case CCValAssign::AExtUpper:
3113 UseUpperBits = true;
3115 case CCValAssign::AExt:
3116 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3118 case CCValAssign::ZExtUpper:
3119 UseUpperBits = true;
3121 case CCValAssign::ZExt:
3122 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3124 case CCValAssign::SExtUpper:
3125 UseUpperBits = true;
3127 case CCValAssign::SExt:
3128 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3133 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3134 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3136 ISD::SHL, DL, VA.getLocVT(), Val,
3137 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3140 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3142 // Guarantee that all emitted copies are stuck together with flags.
3143 Flag = Chain.getValue(1);
3144 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3147 // The mips ABIs for returning structs by value requires that we copy
3148 // the sret argument into $v0 for the return. We saved the argument into
3149 // a virtual register in the entry block, so now we copy the value out
3151 if (MF.getFunction()->hasStructRetAttr()) {
3152 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3153 unsigned Reg = MipsFI->getSRetReturnReg();
3156 llvm_unreachable("sret virtual register not created in the entry block");
3157 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3158 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3160 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3161 Flag = Chain.getValue(1);
3162 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3165 RetOps[0] = Chain; // Update chain.
3167 // Add the flag if we have it.
3169 RetOps.push_back(Flag);
3171 // Return on Mips is always a "jr $ra"
3172 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3175 //===----------------------------------------------------------------------===//
3176 // Mips Inline Assembly Support
3177 //===----------------------------------------------------------------------===//
3179 /// getConstraintType - Given a constraint letter, return the type of
3180 /// constraint it is for this target.
3181 MipsTargetLowering::ConstraintType MipsTargetLowering::
3182 getConstraintType(const std::string &Constraint) const
3184 // Mips specific constraints
3185 // GCC config/mips/constraints.md
3187 // 'd' : An address register. Equivalent to r
3188 // unless generating MIPS16 code.
3189 // 'y' : Equivalent to r; retained for
3190 // backwards compatibility.
3191 // 'c' : A register suitable for use in an indirect
3192 // jump. This will always be $25 for -mabicalls.
3193 // 'l' : The lo register. 1 word storage.
3194 // 'x' : The hilo register pair. Double word storage.
3195 if (Constraint.size() == 1) {
3196 switch (Constraint[0]) {
3204 return C_RegisterClass;
3209 return TargetLowering::getConstraintType(Constraint);
3212 /// Examine constraint type and operand type and determine a weight value.
3213 /// This object must already have been set up with the operand type
3214 /// and the current alternative constraint selected.
3215 TargetLowering::ConstraintWeight
3216 MipsTargetLowering::getSingleConstraintMatchWeight(
3217 AsmOperandInfo &info, const char *constraint) const {
3218 ConstraintWeight weight = CW_Invalid;
3219 Value *CallOperandVal = info.CallOperandVal;
3220 // If we don't have a value, we can't do a match,
3221 // but allow it at the lowest weight.
3222 if (!CallOperandVal)
3224 Type *type = CallOperandVal->getType();
3225 // Look at the constraint type.
3226 switch (*constraint) {
3228 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3232 if (type->isIntegerTy())
3233 weight = CW_Register;
3235 case 'f': // FPU or MSA register
3236 if (Subtarget.hasMSA() && type->isVectorTy() &&
3237 cast<VectorType>(type)->getBitWidth() == 128)
3238 weight = CW_Register;
3239 else if (type->isFloatTy())
3240 weight = CW_Register;
3242 case 'c': // $25 for indirect jumps
3243 case 'l': // lo register
3244 case 'x': // hilo register pair
3245 if (type->isIntegerTy())
3246 weight = CW_SpecificReg;
3248 case 'I': // signed 16 bit immediate
3249 case 'J': // integer zero
3250 case 'K': // unsigned 16 bit immediate
3251 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3252 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3253 case 'O': // signed 15 bit immediate (+- 16383)
3254 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3255 if (isa<ConstantInt>(CallOperandVal))
3256 weight = CW_Constant;
3265 /// This is a helper function to parse a physical register string and split it
3266 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3267 /// that is returned indicates whether parsing was successful. The second flag
3268 /// is true if the numeric part exists.
3269 static std::pair<bool, bool>
3270 parsePhysicalReg(StringRef C, std::string &Prefix,
3271 unsigned long long &Reg) {
3272 if (C.front() != '{' || C.back() != '}')
3273 return std::make_pair(false, false);
3275 // Search for the first numeric character.
3276 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3277 I = std::find_if(B, E, std::ptr_fun(isdigit));
3279 Prefix.assign(B, I - B);
3281 // The second flag is set to false if no numeric characters were found.
3283 return std::make_pair(true, false);
3285 // Parse the numeric characters.
3286 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3290 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3291 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3292 const TargetRegisterInfo *TRI =
3293 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3294 const TargetRegisterClass *RC;
3296 unsigned long long Reg;
3298 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3301 return std::make_pair(0U, nullptr);
3303 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3304 // No numeric characters follow "hi" or "lo".
3306 return std::make_pair(0U, nullptr);
3308 RC = TRI->getRegClass(Prefix == "hi" ?
3309 Mips::HI32RegClassID : Mips::LO32RegClassID);
3310 return std::make_pair(*(RC->begin()), RC);
3311 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3312 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3314 // No numeric characters follow the name.
3316 return std::make_pair(0U, nullptr);
3318 Reg = StringSwitch<unsigned long long>(Prefix)
3319 .Case("$msair", Mips::MSAIR)
3320 .Case("$msacsr", Mips::MSACSR)
3321 .Case("$msaaccess", Mips::MSAAccess)
3322 .Case("$msasave", Mips::MSASave)
3323 .Case("$msamodify", Mips::MSAModify)
3324 .Case("$msarequest", Mips::MSARequest)
3325 .Case("$msamap", Mips::MSAMap)
3326 .Case("$msaunmap", Mips::MSAUnmap)
3330 return std::make_pair(0U, nullptr);
3332 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3333 return std::make_pair(Reg, RC);
3337 return std::make_pair(0U, nullptr);
3339 if (Prefix == "$f") { // Parse $f0-$f31.
3340 // If the size of FP registers is 64-bit or Reg is an even number, select
3341 // the 64-bit register class. Otherwise, select the 32-bit register class.
3342 if (VT == MVT::Other)
3343 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3345 RC = getRegClassFor(VT);
3347 if (RC == &Mips::AFGR64RegClass) {
3348 assert(Reg % 2 == 0);
3351 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3352 RC = TRI->getRegClass(Mips::FCCRegClassID);
3353 else if (Prefix == "$w") { // Parse $w0-$w31.
3354 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3355 } else { // Parse $0-$31.
3356 assert(Prefix == "$");
3357 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3360 assert(Reg < RC->getNumRegs());
3361 return std::make_pair(*(RC->begin() + Reg), RC);
3364 /// Given a register class constraint, like 'r', if this corresponds directly
3365 /// to an LLVM register class, return a register of 0 and the register class
3367 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3368 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3370 if (Constraint.size() == 1) {
3371 switch (Constraint[0]) {
3372 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3373 case 'y': // Same as 'r'. Exists for compatibility.
3375 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3376 if (Subtarget.inMips16Mode())
3377 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3378 return std::make_pair(0U, &Mips::GPR32RegClass);
3380 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3381 return std::make_pair(0U, &Mips::GPR32RegClass);
3382 if (VT == MVT::i64 && Subtarget.isGP64bit())
3383 return std::make_pair(0U, &Mips::GPR64RegClass);
3384 // This will generate an error message
3385 return std::make_pair(0U, nullptr);
3386 case 'f': // FPU or MSA register
3387 if (VT == MVT::v16i8)
3388 return std::make_pair(0U, &Mips::MSA128BRegClass);
3389 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3390 return std::make_pair(0U, &Mips::MSA128HRegClass);
3391 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3392 return std::make_pair(0U, &Mips::MSA128WRegClass);
3393 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3394 return std::make_pair(0U, &Mips::MSA128DRegClass);
3395 else if (VT == MVT::f32)
3396 return std::make_pair(0U, &Mips::FGR32RegClass);
3397 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3398 if (Subtarget.isFP64bit())
3399 return std::make_pair(0U, &Mips::FGR64RegClass);
3400 return std::make_pair(0U, &Mips::AFGR64RegClass);
3403 case 'c': // register suitable for indirect jump
3405 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3406 assert(VT == MVT::i64 && "Unexpected type.");
3407 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3408 case 'l': // register suitable for indirect jump
3410 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3411 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3412 case 'x': // register suitable for indirect jump
3413 // Fixme: Not triggering the use of both hi and low
3414 // This will generate an error message
3415 return std::make_pair(0U, nullptr);
3419 std::pair<unsigned, const TargetRegisterClass *> R;
3420 R = parseRegForInlineAsmConstraint(Constraint, VT);
3425 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3428 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3429 /// vector. If it is invalid, don't add anything to Ops.
3430 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3431 std::string &Constraint,
3432 std::vector<SDValue>&Ops,
3433 SelectionDAG &DAG) const {
3436 // Only support length 1 constraints for now.
3437 if (Constraint.length() > 1) return;
3439 char ConstraintLetter = Constraint[0];
3440 switch (ConstraintLetter) {
3441 default: break; // This will fall through to the generic implementation
3442 case 'I': // Signed 16 bit constant
3443 // If this fails, the parent routine will give an error
3444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3445 EVT Type = Op.getValueType();
3446 int64_t Val = C->getSExtValue();
3447 if (isInt<16>(Val)) {
3448 Result = DAG.getTargetConstant(Val, Type);
3453 case 'J': // integer zero
3454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3455 EVT Type = Op.getValueType();
3456 int64_t Val = C->getZExtValue();
3458 Result = DAG.getTargetConstant(0, Type);
3463 case 'K': // unsigned 16 bit immediate
3464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3465 EVT Type = Op.getValueType();
3466 uint64_t Val = (uint64_t)C->getZExtValue();
3467 if (isUInt<16>(Val)) {
3468 Result = DAG.getTargetConstant(Val, Type);
3473 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3474 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3475 EVT Type = Op.getValueType();
3476 int64_t Val = C->getSExtValue();
3477 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3478 Result = DAG.getTargetConstant(Val, Type);
3483 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3485 EVT Type = Op.getValueType();
3486 int64_t Val = C->getSExtValue();
3487 if ((Val >= -65535) && (Val <= -1)) {
3488 Result = DAG.getTargetConstant(Val, Type);
3493 case 'O': // signed 15 bit immediate
3494 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3495 EVT Type = Op.getValueType();
3496 int64_t Val = C->getSExtValue();
3497 if ((isInt<15>(Val))) {
3498 Result = DAG.getTargetConstant(Val, Type);
3503 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3504 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3505 EVT Type = Op.getValueType();
3506 int64_t Val = C->getSExtValue();
3507 if ((Val <= 65535) && (Val >= 1)) {
3508 Result = DAG.getTargetConstant(Val, Type);
3515 if (Result.getNode()) {
3516 Ops.push_back(Result);
3520 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3523 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3525 // No global is ever allowed as a base.
3530 case 0: // "r+i" or just "i", depending on HasBaseReg.
3533 if (!AM.HasBaseReg) // allow "r+i".
3535 return false; // disallow "r+r" or "r+r+i".
3544 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3545 // The Mips target isn't yet aware of offsets.
3549 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3551 bool IsMemset, bool ZeroMemset,
3553 MachineFunction &MF) const {
3554 if (Subtarget.hasMips64())
3560 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3561 if (VT != MVT::f32 && VT != MVT::f64)
3563 if (Imm.isNegZero())
3565 return Imm.isZero();
3568 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3569 if (Subtarget.isABI_N64())
3570 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3572 return TargetLowering::getJumpTableEncoding();
3575 /// This function returns true if CallSym is a long double emulation routine.
3576 static bool isF128SoftLibCall(const char *CallSym) {
3577 const char *const LibCalls[] =
3578 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3579 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3580 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3581 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3582 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3583 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3584 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3585 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3588 const char *const *End = LibCalls + array_lengthof(LibCalls);
3590 // Check that LibCalls is sorted alphabetically.
3591 MipsTargetLowering::LTStr Comp;
3594 for (const char *const *I = LibCalls; I < End - 1; ++I)
3595 assert(Comp(*I, *(I + 1)));
3598 return std::binary_search(LibCalls, End, CallSym, Comp);
3601 /// This function returns true if Ty is fp128, {f128} or i128 which was
3602 /// originally a fp128.
3603 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3604 if (Ty->isFP128Ty())
3607 if (Ty->isStructTy() && Ty->getStructNumElements() == 1 &&
3608 Ty->getStructElementType(0)->isFP128Ty())
3611 const ExternalSymbolSDNode *ES =
3612 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3614 // If the Ty is i128 and the function being called is a long double emulation
3615 // routine, then the original type is f128.
3616 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3619 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC,
3620 const MipsSubtarget &Subtarget_,
3622 : CallConv(CC), Subtarget(Subtarget_) {
3623 // Pre-allocate reserved argument area.
3624 Info.AllocateStack(reservedArgArea(), 1);
3627 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3628 return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
3631 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
3632 if (Subtarget.isABI_O32())
3633 return makeArrayRef(O32IntRegs);
3634 return makeArrayRef(Mips64IntRegs);
3637 void MipsTargetLowering::copyByValRegs(
3638 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3639 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3640 const Argument *FuncArg, const MipsCC &CC, unsigned FirstReg,
3641 unsigned LastReg, const CCValAssign &VA) const {
3642 MachineFunction &MF = DAG.getMachineFunction();
3643 MachineFrameInfo *MFI = MF.getFrameInfo();
3644 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3645 unsigned NumRegs = LastReg - FirstReg;
3646 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3647 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3652 (int)CC.reservedArgArea() -
3653 (int)((CC.intArgRegs().size() - FirstReg) * GPRSizeInBytes);
3655 FrameObjOffset = VA.getLocMemOffset();
3657 // Create frame object.
3658 EVT PtrTy = getPointerTy();
3659 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3660 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3661 InVals.push_back(FIN);
3666 // Copy arg registers.
3667 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3668 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3670 for (unsigned I = 0; I < NumRegs; ++I) {
3671 unsigned ArgReg = CC.intArgRegs()[FirstReg + I];
3672 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3673 unsigned Offset = I * GPRSizeInBytes;
3674 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3675 DAG.getConstant(Offset, PtrTy));
3676 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3677 StorePtr, MachinePointerInfo(FuncArg, Offset),
3679 OutChains.push_back(Store);
3683 // Copy byVal arg to registers and stack.
3684 void MipsTargetLowering::passByValArg(
3685 SDValue Chain, SDLoc DL,
3686 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3687 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3688 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, const MipsCC &CC,
3689 unsigned FirstReg, unsigned LastReg, const ISD::ArgFlagsTy &Flags,
3690 bool isLittle, const CCValAssign &VA) const {
3691 unsigned ByValSizeInBytes = Flags.getByValSize();
3692 unsigned OffsetInBytes = 0; // From beginning of struct
3693 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3694 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3695 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3696 unsigned NumRegs = LastReg - FirstReg;
3699 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3700 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3703 // Copy words to registers.
3704 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3705 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3706 DAG.getConstant(OffsetInBytes, PtrTy));
3707 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3708 MachinePointerInfo(), false, false, false,
3710 MemOpChains.push_back(LoadVal.getValue(1));
3711 unsigned ArgReg = ArgRegs[FirstReg + I];
3712 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3715 // Return if the struct has been fully copied.
3716 if (ByValSizeInBytes == OffsetInBytes)
3719 // Copy the remainder of the byval argument with sub-word loads and shifts.
3720 if (LeftoverBytes) {
3723 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3724 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3725 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3727 if (RemainingSizeInBytes < LoadSizeInBytes)
3731 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3732 DAG.getConstant(OffsetInBytes, PtrTy));
3733 SDValue LoadVal = DAG.getExtLoad(
3734 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3735 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3737 MemOpChains.push_back(LoadVal.getValue(1));
3739 // Shift the loaded value.
3743 Shamt = TotalBytesLoaded * 8;
3745 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3747 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3748 DAG.getConstant(Shamt, MVT::i32));
3751 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3755 OffsetInBytes += LoadSizeInBytes;
3756 TotalBytesLoaded += LoadSizeInBytes;
3757 Alignment = std::min(Alignment, LoadSizeInBytes);
3760 unsigned ArgReg = ArgRegs[FirstReg + I];
3761 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3766 // Copy remainder of byval arg to it with memcpy.
3767 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3768 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3769 DAG.getConstant(OffsetInBytes, PtrTy));
3770 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3771 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3772 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3773 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3774 MachinePointerInfo(), MachinePointerInfo());
3775 MemOpChains.push_back(Chain);
3778 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3779 const MipsCC &CC, SDValue Chain,
3780 SDLoc DL, SelectionDAG &DAG,
3781 CCState &State) const {
3782 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3783 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3784 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3785 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3786 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3787 MachineFunction &MF = DAG.getMachineFunction();
3788 MachineFrameInfo *MFI = MF.getFrameInfo();
3789 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3791 // Offset of the first variable argument from stack pointer.
3794 if (ArgRegs.size() == Idx)
3796 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3798 VaArgOffset = (int)CC.reservedArgArea() -
3799 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3801 // Record the frame index of the first variable argument
3802 // which is a value necessary to VASTART.
3803 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3804 MipsFI->setVarArgsFrameIndex(FI);
3806 // Copy the integer registers that have not been used for argument passing
3807 // to the argument register save area. For O32, the save area is allocated
3808 // in the caller's stack frame, while for N32/64, it is allocated in the
3809 // callee's stack frame.
3810 for (unsigned I = Idx; I < ArgRegs.size();
3811 ++I, VaArgOffset += RegSizeInBytes) {
3812 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3813 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3814 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3815 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3816 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3817 MachinePointerInfo(), false, false, 0);
3818 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3820 OutChains.push_back(Store);
3824 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3825 unsigned Align) const {
3826 MachineFunction &MF = State->getMachineFunction();
3827 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3829 assert(Size && "Byval argument's size shouldn't be 0.");
3831 Align = std::min(Align, TFL->getStackAlignment());
3833 unsigned FirstReg = 0;
3834 unsigned NumRegs = 0;
3836 if (State->getCallingConv() != CallingConv::Fast) {
3837 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3838 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3839 // FIXME: The O32 case actually describes no shadow registers.
3840 const MCPhysReg *ShadowRegs =
3841 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3843 // We used to check the size as well but we can't do that anymore since
3844 // CCState::HandleByVal() rounds up the size after calling this function.
3845 assert(!(Align % RegSizeInBytes) &&
3846 "Byval argument's alignment should be a multiple of"
3849 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3851 // If Align > RegSizeInBytes, the first arg register must be even.
3852 // FIXME: This condition happens to do the right thing but it's not the
3853 // right way to test it. We want to check that the stack frame offset
3854 // of the register is aligned.
3855 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3856 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3860 // Mark the registers allocated.
3861 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3862 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3863 Size -= RegSizeInBytes, ++I, ++NumRegs)
3864 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3867 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);