1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsSubtarget.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsTargetObjectFile.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "mips-lower"
44 STATISTIC(NumTailCalls, "Number of tail calls");
47 LargeGOT("mxgot", cl::Hidden,
48 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
51 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
52 cl::desc("MIPS: Don't trap on integer division by zero."),
56 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
57 cl::desc("Allow mips-fast-isel to be used"),
60 static const MCPhysReg O32IntRegs[4] = {
61 Mips::A0, Mips::A1, Mips::A2, Mips::A3
64 static const MCPhysReg Mips64IntRegs[8] = {
65 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
66 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
69 static const MCPhysReg Mips64DPRegs[8] = {
70 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
71 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
74 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode);
77 class MipsCCState : public CCState {
79 /// Identify lowered values that originated from f128 arguments and record
80 /// this for use by RetCC_MipsN.
82 PreAnalyzeCallResultForF128(const SmallVectorImpl<ISD::InputArg> &Ins,
83 const TargetLowering::CallLoweringInfo &CLI) {
84 for (unsigned i = 0; i < Ins.size(); ++i)
85 OriginalArgWasF128.push_back(
86 originalTypeIsF128(CLI.RetTy, CLI.Callee.getNode()));
89 /// Identify lowered values that originated from f128 arguments and record
90 /// this for use by RetCC_MipsN.
91 void PreAnalyzeReturnForF128(const SmallVectorImpl<ISD::OutputArg> &Outs) {
92 const MachineFunction &MF = getMachineFunction();
93 for (unsigned i = 0; i < Outs.size(); ++i)
94 OriginalArgWasF128.push_back(
95 originalTypeIsF128(MF.getFunction()->getReturnType(), nullptr));
98 /// Records whether the value has been lowered from an f128.
99 SmallVector<bool, 4> OriginalArgWasF128;
102 MipsCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
103 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C)
104 : CCState(CC, isVarArg, MF, locs, C) {}
106 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
108 const TargetLowering::CallLoweringInfo &CLI) {
109 PreAnalyzeCallResultForF128(Ins, CLI);
110 CCState::AnalyzeCallResult(Ins, Fn);
111 OriginalArgWasF128.clear();
114 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
116 PreAnalyzeReturnForF128(Outs);
117 CCState::AnalyzeReturn(Outs, Fn);
118 OriginalArgWasF128.clear();
121 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
123 PreAnalyzeReturnForF128(ArgsFlags);
124 bool Return = CCState::CheckReturn(ArgsFlags, Fn);
125 OriginalArgWasF128.clear();
129 bool WasOriginalArgF128(unsigned ValNo) { return OriginalArgWasF128[ValNo]; }
133 // If I is a shifted mask, set the size (Size) and the first bit of the
134 // mask (Pos), and return true.
135 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
136 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
137 if (!isShiftedMask_64(I))
140 Size = CountPopulation_64(I);
141 Pos = countTrailingZeros(I);
145 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
146 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
147 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
150 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
152 unsigned Flag) const {
153 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
156 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
158 unsigned Flag) const {
159 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
162 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
164 unsigned Flag) const {
165 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
168 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
170 unsigned Flag) const {
171 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
174 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
176 unsigned Flag) const {
177 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
178 N->getOffset(), Flag);
181 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
183 case MipsISD::JmpLink: return "MipsISD::JmpLink";
184 case MipsISD::TailCall: return "MipsISD::TailCall";
185 case MipsISD::Hi: return "MipsISD::Hi";
186 case MipsISD::Lo: return "MipsISD::Lo";
187 case MipsISD::GPRel: return "MipsISD::GPRel";
188 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
189 case MipsISD::Ret: return "MipsISD::Ret";
190 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
191 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
192 case MipsISD::FPCmp: return "MipsISD::FPCmp";
193 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
194 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
195 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
196 case MipsISD::MFHI: return "MipsISD::MFHI";
197 case MipsISD::MFLO: return "MipsISD::MFLO";
198 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
199 case MipsISD::Mult: return "MipsISD::Mult";
200 case MipsISD::Multu: return "MipsISD::Multu";
201 case MipsISD::MAdd: return "MipsISD::MAdd";
202 case MipsISD::MAddu: return "MipsISD::MAddu";
203 case MipsISD::MSub: return "MipsISD::MSub";
204 case MipsISD::MSubu: return "MipsISD::MSubu";
205 case MipsISD::DivRem: return "MipsISD::DivRem";
206 case MipsISD::DivRemU: return "MipsISD::DivRemU";
207 case MipsISD::DivRem16: return "MipsISD::DivRem16";
208 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
209 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
210 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
211 case MipsISD::Wrapper: return "MipsISD::Wrapper";
212 case MipsISD::Sync: return "MipsISD::Sync";
213 case MipsISD::Ext: return "MipsISD::Ext";
214 case MipsISD::Ins: return "MipsISD::Ins";
215 case MipsISD::LWL: return "MipsISD::LWL";
216 case MipsISD::LWR: return "MipsISD::LWR";
217 case MipsISD::SWL: return "MipsISD::SWL";
218 case MipsISD::SWR: return "MipsISD::SWR";
219 case MipsISD::LDL: return "MipsISD::LDL";
220 case MipsISD::LDR: return "MipsISD::LDR";
221 case MipsISD::SDL: return "MipsISD::SDL";
222 case MipsISD::SDR: return "MipsISD::SDR";
223 case MipsISD::EXTP: return "MipsISD::EXTP";
224 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
225 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
226 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
227 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
228 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
229 case MipsISD::SHILO: return "MipsISD::SHILO";
230 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
231 case MipsISD::MULT: return "MipsISD::MULT";
232 case MipsISD::MULTU: return "MipsISD::MULTU";
233 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
234 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
235 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
236 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
237 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
238 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
239 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
240 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
241 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
242 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
243 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
244 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
245 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
246 case MipsISD::VCEQ: return "MipsISD::VCEQ";
247 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
248 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
249 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
250 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
251 case MipsISD::VSMAX: return "MipsISD::VSMAX";
252 case MipsISD::VSMIN: return "MipsISD::VSMIN";
253 case MipsISD::VUMAX: return "MipsISD::VUMAX";
254 case MipsISD::VUMIN: return "MipsISD::VUMIN";
255 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
256 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
257 case MipsISD::VNOR: return "MipsISD::VNOR";
258 case MipsISD::VSHF: return "MipsISD::VSHF";
259 case MipsISD::SHF: return "MipsISD::SHF";
260 case MipsISD::ILVEV: return "MipsISD::ILVEV";
261 case MipsISD::ILVOD: return "MipsISD::ILVOD";
262 case MipsISD::ILVL: return "MipsISD::ILVL";
263 case MipsISD::ILVR: return "MipsISD::ILVR";
264 case MipsISD::PCKEV: return "MipsISD::PCKEV";
265 case MipsISD::PCKOD: return "MipsISD::PCKOD";
266 case MipsISD::INSVE: return "MipsISD::INSVE";
267 default: return nullptr;
271 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
272 const MipsSubtarget &STI)
273 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
274 // Mips does not have i1 type, so use i32 for
275 // setcc operations results (slt, sgt, ...).
276 setBooleanContents(ZeroOrOneBooleanContent);
277 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
278 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
279 // does. Integer booleans still use 0 and 1.
280 if (Subtarget.hasMips32r6())
281 setBooleanContents(ZeroOrOneBooleanContent,
282 ZeroOrNegativeOneBooleanContent);
284 // Load extented operations for i1 types must be promoted
285 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
286 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
287 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
289 // MIPS doesn't have extending float->double load/store
290 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
291 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
293 // Used by legalize types to correctly generate the setcc result.
294 // Without this, every float setcc comes with a AND/OR with the result,
295 // we don't want this, since the fpcmp result goes to a flag register,
296 // which is used implicitly by brcond and select operations.
297 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
299 // Mips Custom Operations
300 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
301 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
302 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
303 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
304 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
305 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
306 setOperationAction(ISD::SELECT, MVT::f32, Custom);
307 setOperationAction(ISD::SELECT, MVT::f64, Custom);
308 setOperationAction(ISD::SELECT, MVT::i32, Custom);
309 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
310 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
311 setOperationAction(ISD::SETCC, MVT::f32, Custom);
312 setOperationAction(ISD::SETCC, MVT::f64, Custom);
313 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
314 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
315 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
316 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
318 if (Subtarget.isGP64bit()) {
319 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
320 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
321 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
322 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
323 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
324 setOperationAction(ISD::SELECT, MVT::i64, Custom);
325 setOperationAction(ISD::LOAD, MVT::i64, Custom);
326 setOperationAction(ISD::STORE, MVT::i64, Custom);
327 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
330 if (!Subtarget.isGP64bit()) {
331 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
332 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
333 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
336 setOperationAction(ISD::ADD, MVT::i32, Custom);
337 if (Subtarget.isGP64bit())
338 setOperationAction(ISD::ADD, MVT::i64, Custom);
340 setOperationAction(ISD::SDIV, MVT::i32, Expand);
341 setOperationAction(ISD::SREM, MVT::i32, Expand);
342 setOperationAction(ISD::UDIV, MVT::i32, Expand);
343 setOperationAction(ISD::UREM, MVT::i32, Expand);
344 setOperationAction(ISD::SDIV, MVT::i64, Expand);
345 setOperationAction(ISD::SREM, MVT::i64, Expand);
346 setOperationAction(ISD::UDIV, MVT::i64, Expand);
347 setOperationAction(ISD::UREM, MVT::i64, Expand);
349 // Operations not directly supported by Mips.
350 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
351 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
352 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
353 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
354 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
355 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
356 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
357 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
358 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
359 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
360 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
361 if (Subtarget.hasCnMips()) {
362 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
363 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
365 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
366 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
368 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
369 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
370 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
371 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
372 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
373 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
374 setOperationAction(ISD::ROTL, MVT::i32, Expand);
375 setOperationAction(ISD::ROTL, MVT::i64, Expand);
376 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
377 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
379 if (!Subtarget.hasMips32r2())
380 setOperationAction(ISD::ROTR, MVT::i32, Expand);
382 if (!Subtarget.hasMips64r2())
383 setOperationAction(ISD::ROTR, MVT::i64, Expand);
385 setOperationAction(ISD::FSIN, MVT::f32, Expand);
386 setOperationAction(ISD::FSIN, MVT::f64, Expand);
387 setOperationAction(ISD::FCOS, MVT::f32, Expand);
388 setOperationAction(ISD::FCOS, MVT::f64, Expand);
389 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
390 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
391 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
392 setOperationAction(ISD::FPOW, MVT::f32, Expand);
393 setOperationAction(ISD::FPOW, MVT::f64, Expand);
394 setOperationAction(ISD::FLOG, MVT::f32, Expand);
395 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
396 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
397 setOperationAction(ISD::FEXP, MVT::f32, Expand);
398 setOperationAction(ISD::FMA, MVT::f32, Expand);
399 setOperationAction(ISD::FMA, MVT::f64, Expand);
400 setOperationAction(ISD::FREM, MVT::f32, Expand);
401 setOperationAction(ISD::FREM, MVT::f64, Expand);
403 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
405 setOperationAction(ISD::VASTART, MVT::Other, Custom);
406 setOperationAction(ISD::VAARG, MVT::Other, Custom);
407 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
408 setOperationAction(ISD::VAEND, MVT::Other, Expand);
410 // Use the default for now
411 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
412 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
414 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
415 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
416 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
417 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
419 setInsertFencesForAtomic(true);
421 if (!Subtarget.hasMips32r2()) {
422 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
423 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
426 // MIPS16 lacks MIPS32's clz and clo instructions.
427 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
428 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
429 if (!Subtarget.hasMips64())
430 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
432 if (!Subtarget.hasMips32r2())
433 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
434 if (!Subtarget.hasMips64r2())
435 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
437 if (Subtarget.isGP64bit()) {
438 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
439 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
440 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
441 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
444 setOperationAction(ISD::TRAP, MVT::Other, Legal);
446 setTargetDAGCombine(ISD::SDIVREM);
447 setTargetDAGCombine(ISD::UDIVREM);
448 setTargetDAGCombine(ISD::SELECT);
449 setTargetDAGCombine(ISD::AND);
450 setTargetDAGCombine(ISD::OR);
451 setTargetDAGCombine(ISD::ADD);
453 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
455 // The arguments on the stack are defined in terms of 4-byte slots on O32
456 // and 8-byte slots on N32/N64.
457 setMinStackArgumentAlignment(
458 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
460 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
463 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
464 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
466 MaxStoresPerMemcpy = 16;
468 isMicroMips = Subtarget.inMicroMipsMode();
471 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
472 const MipsSubtarget &STI) {
473 if (STI.inMips16Mode())
474 return llvm::createMips16TargetLowering(TM, STI);
476 return llvm::createMipsSETargetLowering(TM, STI);
479 // Create a fast isel object.
481 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
482 const TargetLibraryInfo *libInfo) const {
483 if (!EnableMipsFastISel)
484 return TargetLowering::createFastISel(funcInfo, libInfo);
485 return Mips::createFastISel(funcInfo, libInfo);
488 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
491 return VT.changeVectorElementTypeToInteger();
494 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
495 TargetLowering::DAGCombinerInfo &DCI,
496 const MipsSubtarget &Subtarget) {
497 if (DCI.isBeforeLegalizeOps())
500 EVT Ty = N->getValueType(0);
501 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
502 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
503 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
507 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
508 N->getOperand(0), N->getOperand(1));
509 SDValue InChain = DAG.getEntryNode();
510 SDValue InGlue = DivRem;
513 if (N->hasAnyUseOfValue(0)) {
514 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
516 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
517 InChain = CopyFromLo.getValue(1);
518 InGlue = CopyFromLo.getValue(2);
522 if (N->hasAnyUseOfValue(1)) {
523 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
525 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
531 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
533 default: llvm_unreachable("Unknown fp condition code!");
535 case ISD::SETOEQ: return Mips::FCOND_OEQ;
536 case ISD::SETUNE: return Mips::FCOND_UNE;
538 case ISD::SETOLT: return Mips::FCOND_OLT;
540 case ISD::SETOGT: return Mips::FCOND_OGT;
542 case ISD::SETOLE: return Mips::FCOND_OLE;
544 case ISD::SETOGE: return Mips::FCOND_OGE;
545 case ISD::SETULT: return Mips::FCOND_ULT;
546 case ISD::SETULE: return Mips::FCOND_ULE;
547 case ISD::SETUGT: return Mips::FCOND_UGT;
548 case ISD::SETUGE: return Mips::FCOND_UGE;
549 case ISD::SETUO: return Mips::FCOND_UN;
550 case ISD::SETO: return Mips::FCOND_OR;
552 case ISD::SETONE: return Mips::FCOND_ONE;
553 case ISD::SETUEQ: return Mips::FCOND_UEQ;
558 /// This function returns true if the floating point conditional branches and
559 /// conditional moves which use condition code CC should be inverted.
560 static bool invertFPCondCodeUser(Mips::CondCode CC) {
561 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
564 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
565 "Illegal Condition Code");
570 // Creates and returns an FPCmp node from a setcc node.
571 // Returns Op if setcc is not a floating point comparison.
572 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
573 // must be a SETCC node
574 if (Op.getOpcode() != ISD::SETCC)
577 SDValue LHS = Op.getOperand(0);
579 if (!LHS.getValueType().isFloatingPoint())
582 SDValue RHS = Op.getOperand(1);
585 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
586 // node if necessary.
587 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
589 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
590 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
593 // Creates and returns a CMovFPT/F node.
594 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
595 SDValue False, SDLoc DL) {
596 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
597 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
598 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
600 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
601 True.getValueType(), True, FCC0, False, Cond);
604 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
605 TargetLowering::DAGCombinerInfo &DCI,
606 const MipsSubtarget &Subtarget) {
607 if (DCI.isBeforeLegalizeOps())
610 SDValue SetCC = N->getOperand(0);
612 if ((SetCC.getOpcode() != ISD::SETCC) ||
613 !SetCC.getOperand(0).getValueType().isInteger())
616 SDValue False = N->getOperand(2);
617 EVT FalseTy = False.getValueType();
619 if (!FalseTy.isInteger())
622 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
624 // If the RHS (False) is 0, we swap the order of the operands
625 // of ISD::SELECT (obviously also inverting the condition) so that we can
626 // take advantage of conditional moves using the $0 register.
628 // return (a != 0) ? x : 0;
636 if (!FalseC->getZExtValue()) {
637 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
638 SDValue True = N->getOperand(1);
640 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
641 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
643 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
646 // If both operands are integer constants there's a possibility that we
647 // can do some interesting optimizations.
648 SDValue True = N->getOperand(1);
649 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
651 if (!TrueC || !True.getValueType().isInteger())
654 // We'll also ignore MVT::i64 operands as this optimizations proves
655 // to be ineffective because of the required sign extensions as the result
656 // of a SETCC operator is always MVT::i32 for non-vector types.
657 if (True.getValueType() == MVT::i64)
660 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
662 // 1) (a < x) ? y : y-1
664 // addiu $reg2, $reg1, y-1
666 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
668 // 2) (a < x) ? y-1 : y
670 // xor $reg1, $reg1, 1
671 // addiu $reg2, $reg1, y-1
673 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
674 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
675 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
676 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
679 // Couldn't optimize.
683 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
684 TargetLowering::DAGCombinerInfo &DCI,
685 const MipsSubtarget &Subtarget) {
686 // Pattern match EXT.
687 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
688 // => ext $dst, $src, size, pos
689 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
692 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
693 unsigned ShiftRightOpc = ShiftRight.getOpcode();
695 // Op's first operand must be a shift right.
696 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
699 // The second operand of the shift must be an immediate.
701 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
704 uint64_t Pos = CN->getZExtValue();
705 uint64_t SMPos, SMSize;
707 // Op's second operand must be a shifted mask.
708 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
709 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
712 // Return if the shifted mask does not start at bit 0 or the sum of its size
713 // and Pos exceeds the word's size.
714 EVT ValTy = N->getValueType(0);
715 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
718 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
719 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
720 DAG.getConstant(SMSize, MVT::i32));
723 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
724 TargetLowering::DAGCombinerInfo &DCI,
725 const MipsSubtarget &Subtarget) {
726 // Pattern match INS.
727 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
728 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
729 // => ins $dst, $src, size, pos, $src1
730 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
733 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
734 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
737 // See if Op's first operand matches (and $src1 , mask0).
738 if (And0.getOpcode() != ISD::AND)
741 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
742 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
745 // See if Op's second operand matches (and (shl $src, pos), mask1).
746 if (And1.getOpcode() != ISD::AND)
749 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
750 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
753 // The shift masks must have the same position and size.
754 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
757 SDValue Shl = And1.getOperand(0);
758 if (Shl.getOpcode() != ISD::SHL)
761 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
764 unsigned Shamt = CN->getZExtValue();
766 // Return if the shift amount and the first bit position of mask are not the
768 EVT ValTy = N->getValueType(0);
769 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
772 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
773 DAG.getConstant(SMPos0, MVT::i32),
774 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
777 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
778 TargetLowering::DAGCombinerInfo &DCI,
779 const MipsSubtarget &Subtarget) {
780 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
782 if (DCI.isBeforeLegalizeOps())
785 SDValue Add = N->getOperand(1);
787 if (Add.getOpcode() != ISD::ADD)
790 SDValue Lo = Add.getOperand(1);
792 if ((Lo.getOpcode() != MipsISD::Lo) ||
793 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
796 EVT ValTy = N->getValueType(0);
799 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
801 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
804 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
806 SelectionDAG &DAG = DCI.DAG;
807 unsigned Opc = N->getOpcode();
813 return performDivRemCombine(N, DAG, DCI, Subtarget);
815 return performSELECTCombine(N, DAG, DCI, Subtarget);
817 return performANDCombine(N, DAG, DCI, Subtarget);
819 return performORCombine(N, DAG, DCI, Subtarget);
821 return performADDCombine(N, DAG, DCI, Subtarget);
828 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
829 SmallVectorImpl<SDValue> &Results,
830 SelectionDAG &DAG) const {
831 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
833 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
834 Results.push_back(Res.getValue(I));
838 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
839 SmallVectorImpl<SDValue> &Results,
840 SelectionDAG &DAG) const {
841 return LowerOperationWrapper(N, Results, DAG);
844 SDValue MipsTargetLowering::
845 LowerOperation(SDValue Op, SelectionDAG &DAG) const
847 switch (Op.getOpcode())
849 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
850 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
851 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
852 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
853 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
854 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
855 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
856 case ISD::SELECT: return lowerSELECT(Op, DAG);
857 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
858 case ISD::SETCC: return lowerSETCC(Op, DAG);
859 case ISD::VASTART: return lowerVASTART(Op, DAG);
860 case ISD::VAARG: return lowerVAARG(Op, DAG);
861 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
862 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
863 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
864 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
865 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
866 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
867 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
868 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
869 case ISD::LOAD: return lowerLOAD(Op, DAG);
870 case ISD::STORE: return lowerSTORE(Op, DAG);
871 case ISD::ADD: return lowerADD(Op, DAG);
872 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
877 //===----------------------------------------------------------------------===//
878 // Lower helper functions
879 //===----------------------------------------------------------------------===//
881 // addLiveIn - This helper function adds the specified physical register to the
882 // MachineFunction as a live in value. It also creates a corresponding
883 // virtual register for it.
885 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
887 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
888 MF.getRegInfo().addLiveIn(PReg, VReg);
892 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
893 MachineBasicBlock &MBB,
894 const TargetInstrInfo &TII,
899 // Insert instruction "teq $divisor_reg, $zero, 7".
900 MachineBasicBlock::iterator I(MI);
901 MachineInstrBuilder MIB;
902 MachineOperand &Divisor = MI->getOperand(2);
903 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
904 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
905 .addReg(Mips::ZERO).addImm(7);
907 // Use the 32-bit sub-register if this is a 64-bit division.
909 MIB->getOperand(0).setSubReg(Mips::sub_32);
911 // Clear Divisor's kill flag.
912 Divisor.setIsKill(false);
914 // We would normally delete the original instruction here but in this case
915 // we only needed to inject an additional instruction rather than replace it.
921 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
922 MachineBasicBlock *BB) const {
923 switch (MI->getOpcode()) {
925 llvm_unreachable("Unexpected instr type to insert");
926 case Mips::ATOMIC_LOAD_ADD_I8:
927 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
928 case Mips::ATOMIC_LOAD_ADD_I16:
929 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
930 case Mips::ATOMIC_LOAD_ADD_I32:
931 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
932 case Mips::ATOMIC_LOAD_ADD_I64:
933 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
935 case Mips::ATOMIC_LOAD_AND_I8:
936 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
937 case Mips::ATOMIC_LOAD_AND_I16:
938 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
939 case Mips::ATOMIC_LOAD_AND_I32:
940 return emitAtomicBinary(MI, BB, 4, Mips::AND);
941 case Mips::ATOMIC_LOAD_AND_I64:
942 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
944 case Mips::ATOMIC_LOAD_OR_I8:
945 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
946 case Mips::ATOMIC_LOAD_OR_I16:
947 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
948 case Mips::ATOMIC_LOAD_OR_I32:
949 return emitAtomicBinary(MI, BB, 4, Mips::OR);
950 case Mips::ATOMIC_LOAD_OR_I64:
951 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
953 case Mips::ATOMIC_LOAD_XOR_I8:
954 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
955 case Mips::ATOMIC_LOAD_XOR_I16:
956 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
957 case Mips::ATOMIC_LOAD_XOR_I32:
958 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
959 case Mips::ATOMIC_LOAD_XOR_I64:
960 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
962 case Mips::ATOMIC_LOAD_NAND_I8:
963 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
964 case Mips::ATOMIC_LOAD_NAND_I16:
965 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
966 case Mips::ATOMIC_LOAD_NAND_I32:
967 return emitAtomicBinary(MI, BB, 4, 0, true);
968 case Mips::ATOMIC_LOAD_NAND_I64:
969 return emitAtomicBinary(MI, BB, 8, 0, true);
971 case Mips::ATOMIC_LOAD_SUB_I8:
972 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
973 case Mips::ATOMIC_LOAD_SUB_I16:
974 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
975 case Mips::ATOMIC_LOAD_SUB_I32:
976 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
977 case Mips::ATOMIC_LOAD_SUB_I64:
978 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
980 case Mips::ATOMIC_SWAP_I8:
981 return emitAtomicBinaryPartword(MI, BB, 1, 0);
982 case Mips::ATOMIC_SWAP_I16:
983 return emitAtomicBinaryPartword(MI, BB, 2, 0);
984 case Mips::ATOMIC_SWAP_I32:
985 return emitAtomicBinary(MI, BB, 4, 0);
986 case Mips::ATOMIC_SWAP_I64:
987 return emitAtomicBinary(MI, BB, 8, 0);
989 case Mips::ATOMIC_CMP_SWAP_I8:
990 return emitAtomicCmpSwapPartword(MI, BB, 1);
991 case Mips::ATOMIC_CMP_SWAP_I16:
992 return emitAtomicCmpSwapPartword(MI, BB, 2);
993 case Mips::ATOMIC_CMP_SWAP_I32:
994 return emitAtomicCmpSwap(MI, BB, 4);
995 case Mips::ATOMIC_CMP_SWAP_I64:
996 return emitAtomicCmpSwap(MI, BB, 8);
997 case Mips::PseudoSDIV:
998 case Mips::PseudoUDIV:
1003 return insertDivByZeroTrap(
1004 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
1005 case Mips::PseudoDSDIV:
1006 case Mips::PseudoDUDIV:
1011 return insertDivByZeroTrap(
1012 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
1014 return emitSEL_D(MI, BB);
1018 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1019 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1021 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1022 unsigned Size, unsigned BinOpcode,
1024 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1026 MachineFunction *MF = BB->getParent();
1027 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1028 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1029 const TargetInstrInfo *TII =
1030 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1031 DebugLoc DL = MI->getDebugLoc();
1032 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1039 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1040 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1047 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1048 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1051 ZERO = Mips::ZERO_64;
1055 unsigned OldVal = MI->getOperand(0).getReg();
1056 unsigned Ptr = MI->getOperand(1).getReg();
1057 unsigned Incr = MI->getOperand(2).getReg();
1059 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1060 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1061 unsigned Success = RegInfo.createVirtualRegister(RC);
1063 // insert new blocks after the current block
1064 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1065 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1066 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1067 MachineFunction::iterator It = BB;
1069 MF->insert(It, loopMBB);
1070 MF->insert(It, exitMBB);
1072 // Transfer the remainder of BB and its successor edges to exitMBB.
1073 exitMBB->splice(exitMBB->begin(), BB,
1074 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1075 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1079 // fallthrough --> loopMBB
1080 BB->addSuccessor(loopMBB);
1081 loopMBB->addSuccessor(loopMBB);
1082 loopMBB->addSuccessor(exitMBB);
1085 // ll oldval, 0(ptr)
1086 // <binop> storeval, oldval, incr
1087 // sc success, storeval, 0(ptr)
1088 // beq success, $0, loopMBB
1090 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1092 // and andres, oldval, incr
1093 // nor storeval, $0, andres
1094 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1095 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1096 } else if (BinOpcode) {
1097 // <binop> storeval, oldval, incr
1098 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1102 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1103 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1105 MI->eraseFromParent(); // The instruction is gone now.
1110 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1111 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1112 unsigned SrcReg) const {
1113 const TargetInstrInfo *TII =
1114 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1115 DebugLoc DL = MI->getDebugLoc();
1117 if (Subtarget.hasMips32r2() && Size == 1) {
1118 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1122 if (Subtarget.hasMips32r2() && Size == 2) {
1123 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1127 MachineFunction *MF = BB->getParent();
1128 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1129 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1130 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1133 int64_t ShiftImm = 32 - (Size * 8);
1135 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1136 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1141 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1142 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1144 assert((Size == 1 || Size == 2) &&
1145 "Unsupported size for EmitAtomicBinaryPartial.");
1147 MachineFunction *MF = BB->getParent();
1148 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1149 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1150 const TargetInstrInfo *TII =
1151 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1152 DebugLoc DL = MI->getDebugLoc();
1154 unsigned Dest = MI->getOperand(0).getReg();
1155 unsigned Ptr = MI->getOperand(1).getReg();
1156 unsigned Incr = MI->getOperand(2).getReg();
1158 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1159 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1160 unsigned Mask = RegInfo.createVirtualRegister(RC);
1161 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1162 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1163 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1164 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1165 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1166 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1167 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1168 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1169 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1170 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1171 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1172 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1173 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1174 unsigned Success = RegInfo.createVirtualRegister(RC);
1176 // insert new blocks after the current block
1177 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1178 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1179 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1180 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1181 MachineFunction::iterator It = BB;
1183 MF->insert(It, loopMBB);
1184 MF->insert(It, sinkMBB);
1185 MF->insert(It, exitMBB);
1187 // Transfer the remainder of BB and its successor edges to exitMBB.
1188 exitMBB->splice(exitMBB->begin(), BB,
1189 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1190 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1192 BB->addSuccessor(loopMBB);
1193 loopMBB->addSuccessor(loopMBB);
1194 loopMBB->addSuccessor(sinkMBB);
1195 sinkMBB->addSuccessor(exitMBB);
1198 // addiu masklsb2,$0,-4 # 0xfffffffc
1199 // and alignedaddr,ptr,masklsb2
1200 // andi ptrlsb2,ptr,3
1201 // sll shiftamt,ptrlsb2,3
1202 // ori maskupper,$0,255 # 0xff
1203 // sll mask,maskupper,shiftamt
1204 // nor mask2,$0,mask
1205 // sll incr2,incr,shiftamt
1207 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1208 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1209 .addReg(Mips::ZERO).addImm(-4);
1210 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1211 .addReg(Ptr).addReg(MaskLSB2);
1212 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1213 if (Subtarget.isLittle()) {
1214 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1216 unsigned Off = RegInfo.createVirtualRegister(RC);
1217 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1218 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1219 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1221 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1222 .addReg(Mips::ZERO).addImm(MaskImm);
1223 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1224 .addReg(MaskUpper).addReg(ShiftAmt);
1225 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1226 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1228 // atomic.load.binop
1230 // ll oldval,0(alignedaddr)
1231 // binop binopres,oldval,incr2
1232 // and newval,binopres,mask
1233 // and maskedoldval0,oldval,mask2
1234 // or storeval,maskedoldval0,newval
1235 // sc success,storeval,0(alignedaddr)
1236 // beq success,$0,loopMBB
1240 // ll oldval,0(alignedaddr)
1241 // and newval,incr2,mask
1242 // and maskedoldval0,oldval,mask2
1243 // or storeval,maskedoldval0,newval
1244 // sc success,storeval,0(alignedaddr)
1245 // beq success,$0,loopMBB
1248 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1250 // and andres, oldval, incr2
1251 // nor binopres, $0, andres
1252 // and newval, binopres, mask
1253 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1254 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1255 .addReg(Mips::ZERO).addReg(AndRes);
1256 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1257 } else if (BinOpcode) {
1258 // <binop> binopres, oldval, incr2
1259 // and newval, binopres, mask
1260 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1261 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1262 } else { // atomic.swap
1263 // and newval, incr2, mask
1264 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1267 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1268 .addReg(OldVal).addReg(Mask2);
1269 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1270 .addReg(MaskedOldVal0).addReg(NewVal);
1271 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1272 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1273 BuildMI(BB, DL, TII->get(Mips::BEQ))
1274 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1277 // and maskedoldval1,oldval,mask
1278 // srl srlres,maskedoldval1,shiftamt
1279 // sign_extend dest,srlres
1282 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1283 .addReg(OldVal).addReg(Mask);
1284 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1285 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1286 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1288 MI->eraseFromParent(); // The instruction is gone now.
1293 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1294 MachineBasicBlock *BB,
1295 unsigned Size) const {
1296 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1298 MachineFunction *MF = BB->getParent();
1299 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1300 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1301 const TargetInstrInfo *TII =
1302 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1303 DebugLoc DL = MI->getDebugLoc();
1304 unsigned LL, SC, ZERO, BNE, BEQ;
1307 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1308 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1315 ZERO = Mips::ZERO_64;
1320 unsigned Dest = MI->getOperand(0).getReg();
1321 unsigned Ptr = MI->getOperand(1).getReg();
1322 unsigned OldVal = MI->getOperand(2).getReg();
1323 unsigned NewVal = MI->getOperand(3).getReg();
1325 unsigned Success = RegInfo.createVirtualRegister(RC);
1327 // insert new blocks after the current block
1328 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1329 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1330 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1331 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1332 MachineFunction::iterator It = BB;
1334 MF->insert(It, loop1MBB);
1335 MF->insert(It, loop2MBB);
1336 MF->insert(It, exitMBB);
1338 // Transfer the remainder of BB and its successor edges to exitMBB.
1339 exitMBB->splice(exitMBB->begin(), BB,
1340 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1341 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1345 // fallthrough --> loop1MBB
1346 BB->addSuccessor(loop1MBB);
1347 loop1MBB->addSuccessor(exitMBB);
1348 loop1MBB->addSuccessor(loop2MBB);
1349 loop2MBB->addSuccessor(loop1MBB);
1350 loop2MBB->addSuccessor(exitMBB);
1354 // bne dest, oldval, exitMBB
1356 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1357 BuildMI(BB, DL, TII->get(BNE))
1358 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1361 // sc success, newval, 0(ptr)
1362 // beq success, $0, loop1MBB
1364 BuildMI(BB, DL, TII->get(SC), Success)
1365 .addReg(NewVal).addReg(Ptr).addImm(0);
1366 BuildMI(BB, DL, TII->get(BEQ))
1367 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1369 MI->eraseFromParent(); // The instruction is gone now.
1375 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1376 MachineBasicBlock *BB,
1377 unsigned Size) const {
1378 assert((Size == 1 || Size == 2) &&
1379 "Unsupported size for EmitAtomicCmpSwapPartial.");
1381 MachineFunction *MF = BB->getParent();
1382 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1383 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1384 const TargetInstrInfo *TII =
1385 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1386 DebugLoc DL = MI->getDebugLoc();
1388 unsigned Dest = MI->getOperand(0).getReg();
1389 unsigned Ptr = MI->getOperand(1).getReg();
1390 unsigned CmpVal = MI->getOperand(2).getReg();
1391 unsigned NewVal = MI->getOperand(3).getReg();
1393 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1394 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1395 unsigned Mask = RegInfo.createVirtualRegister(RC);
1396 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1397 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1398 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1399 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1400 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1401 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1402 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1403 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1404 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1405 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1406 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1407 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1408 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1409 unsigned Success = RegInfo.createVirtualRegister(RC);
1411 // insert new blocks after the current block
1412 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1413 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1414 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1415 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1416 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1417 MachineFunction::iterator It = BB;
1419 MF->insert(It, loop1MBB);
1420 MF->insert(It, loop2MBB);
1421 MF->insert(It, sinkMBB);
1422 MF->insert(It, exitMBB);
1424 // Transfer the remainder of BB and its successor edges to exitMBB.
1425 exitMBB->splice(exitMBB->begin(), BB,
1426 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1427 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1429 BB->addSuccessor(loop1MBB);
1430 loop1MBB->addSuccessor(sinkMBB);
1431 loop1MBB->addSuccessor(loop2MBB);
1432 loop2MBB->addSuccessor(loop1MBB);
1433 loop2MBB->addSuccessor(sinkMBB);
1434 sinkMBB->addSuccessor(exitMBB);
1436 // FIXME: computation of newval2 can be moved to loop2MBB.
1438 // addiu masklsb2,$0,-4 # 0xfffffffc
1439 // and alignedaddr,ptr,masklsb2
1440 // andi ptrlsb2,ptr,3
1441 // sll shiftamt,ptrlsb2,3
1442 // ori maskupper,$0,255 # 0xff
1443 // sll mask,maskupper,shiftamt
1444 // nor mask2,$0,mask
1445 // andi maskedcmpval,cmpval,255
1446 // sll shiftedcmpval,maskedcmpval,shiftamt
1447 // andi maskednewval,newval,255
1448 // sll shiftednewval,maskednewval,shiftamt
1449 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1450 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1451 .addReg(Mips::ZERO).addImm(-4);
1452 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1453 .addReg(Ptr).addReg(MaskLSB2);
1454 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1455 if (Subtarget.isLittle()) {
1456 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1458 unsigned Off = RegInfo.createVirtualRegister(RC);
1459 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1460 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1461 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1463 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1464 .addReg(Mips::ZERO).addImm(MaskImm);
1465 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1466 .addReg(MaskUpper).addReg(ShiftAmt);
1467 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1468 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1469 .addReg(CmpVal).addImm(MaskImm);
1470 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1471 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1472 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1473 .addReg(NewVal).addImm(MaskImm);
1474 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1475 .addReg(MaskedNewVal).addReg(ShiftAmt);
1478 // ll oldval,0(alginedaddr)
1479 // and maskedoldval0,oldval,mask
1480 // bne maskedoldval0,shiftedcmpval,sinkMBB
1482 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1483 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1484 .addReg(OldVal).addReg(Mask);
1485 BuildMI(BB, DL, TII->get(Mips::BNE))
1486 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1489 // and maskedoldval1,oldval,mask2
1490 // or storeval,maskedoldval1,shiftednewval
1491 // sc success,storeval,0(alignedaddr)
1492 // beq success,$0,loop1MBB
1494 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1495 .addReg(OldVal).addReg(Mask2);
1496 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1497 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1498 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1499 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1500 BuildMI(BB, DL, TII->get(Mips::BEQ))
1501 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1504 // srl srlres,maskedoldval0,shiftamt
1505 // sign_extend dest,srlres
1508 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1509 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1510 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1512 MI->eraseFromParent(); // The instruction is gone now.
1517 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1518 MachineBasicBlock *BB) const {
1519 MachineFunction *MF = BB->getParent();
1520 const TargetRegisterInfo *TRI =
1521 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1522 const TargetInstrInfo *TII =
1523 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1524 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1525 DebugLoc DL = MI->getDebugLoc();
1526 MachineBasicBlock::iterator II(MI);
1528 unsigned Fc = MI->getOperand(1).getReg();
1529 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1531 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1533 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1536 .addImm(Mips::sub_lo);
1538 // We don't erase the original instruction, we just replace the condition
1539 // register with the 64-bit super-register.
1540 MI->getOperand(1).setReg(Fc2);
1545 //===----------------------------------------------------------------------===//
1546 // Misc Lower Operation implementation
1547 //===----------------------------------------------------------------------===//
1548 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1549 SDValue Chain = Op.getOperand(0);
1550 SDValue Table = Op.getOperand(1);
1551 SDValue Index = Op.getOperand(2);
1553 EVT PTy = getPointerTy();
1554 unsigned EntrySize =
1555 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1557 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1558 DAG.getConstant(EntrySize, PTy));
1559 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1561 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1562 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1563 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1565 Chain = Addr.getValue(1);
1567 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1568 Subtarget.isABI_N64()) {
1569 // For PIC, the sequence is:
1570 // BRIND(load(Jumptable + index) + RelocBase)
1571 // RelocBase can be JumpTable, GOT or some sort of global base.
1572 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1573 getPICJumpTableRelocBase(Table, DAG));
1576 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1579 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1580 // The first operand is the chain, the second is the condition, the third is
1581 // the block to branch to if the condition is true.
1582 SDValue Chain = Op.getOperand(0);
1583 SDValue Dest = Op.getOperand(2);
1586 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1587 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1589 // Return if flag is not set by a floating point comparison.
1590 if (CondRes.getOpcode() != MipsISD::FPCmp)
1593 SDValue CCNode = CondRes.getOperand(2);
1595 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1596 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1597 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1598 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1599 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1600 FCC0, Dest, CondRes);
1603 SDValue MipsTargetLowering::
1604 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1606 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1607 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1609 // Return if flag is not set by a floating point comparison.
1610 if (Cond.getOpcode() != MipsISD::FPCmp)
1613 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1617 SDValue MipsTargetLowering::
1618 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1621 EVT Ty = Op.getOperand(0).getValueType();
1622 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1623 getSetCCResultType(*DAG.getContext(), Ty),
1624 Op.getOperand(0), Op.getOperand(1),
1627 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1631 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1632 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1633 SDValue Cond = createFPCmp(DAG, Op);
1635 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1636 "Floating point operand expected.");
1638 SDValue True = DAG.getConstant(1, MVT::i32);
1639 SDValue False = DAG.getConstant(0, MVT::i32);
1641 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1644 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1645 SelectionDAG &DAG) const {
1646 // FIXME there isn't actually debug info here
1648 EVT Ty = Op.getValueType();
1649 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1650 const GlobalValue *GV = N->getGlobal();
1652 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1653 !Subtarget.isABI_N64()) {
1654 const MipsTargetObjectFile &TLOF =
1655 (const MipsTargetObjectFile&)getObjFileLowering();
1657 // %gp_rel relocation
1658 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1659 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1661 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1662 DAG.getVTList(MVT::i32), GA);
1663 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1664 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1667 // %hi/%lo relocation
1668 return getAddrNonPIC(N, Ty, DAG);
1671 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1672 return getAddrLocal(N, Ty, DAG,
1673 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1676 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1677 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1678 MachinePointerInfo::getGOT());
1680 return getAddrGlobal(N, Ty, DAG,
1681 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1682 ? MipsII::MO_GOT_DISP
1684 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1687 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1688 SelectionDAG &DAG) const {
1689 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1690 EVT Ty = Op.getValueType();
1692 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1693 !Subtarget.isABI_N64())
1694 return getAddrNonPIC(N, Ty, DAG);
1696 return getAddrLocal(N, Ty, DAG,
1697 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1700 SDValue MipsTargetLowering::
1701 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1703 // If the relocation model is PIC, use the General Dynamic TLS Model or
1704 // Local Dynamic TLS model, otherwise use the Initial Exec or
1705 // Local Exec TLS Model.
1707 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1709 const GlobalValue *GV = GA->getGlobal();
1710 EVT PtrVT = getPointerTy();
1712 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1714 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1715 // General Dynamic and Local Dynamic TLS Model.
1716 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1719 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1720 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1721 getGlobalReg(DAG, PtrVT), TGA);
1722 unsigned PtrSize = PtrVT.getSizeInBits();
1723 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1725 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1729 Entry.Node = Argument;
1731 Args.push_back(Entry);
1733 TargetLowering::CallLoweringInfo CLI(DAG);
1734 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1735 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1736 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1738 SDValue Ret = CallResult.first;
1740 if (model != TLSModel::LocalDynamic)
1743 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1744 MipsII::MO_DTPREL_HI);
1745 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1746 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1747 MipsII::MO_DTPREL_LO);
1748 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1749 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1750 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1754 if (model == TLSModel::InitialExec) {
1755 // Initial Exec TLS Model
1756 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1757 MipsII::MO_GOTTPREL);
1758 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1760 Offset = DAG.getLoad(PtrVT, DL,
1761 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1762 false, false, false, 0);
1764 // Local Exec TLS Model
1765 assert(model == TLSModel::LocalExec);
1766 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1767 MipsII::MO_TPREL_HI);
1768 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1769 MipsII::MO_TPREL_LO);
1770 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1771 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1772 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1775 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1776 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1779 SDValue MipsTargetLowering::
1780 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1782 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1783 EVT Ty = Op.getValueType();
1785 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1786 !Subtarget.isABI_N64())
1787 return getAddrNonPIC(N, Ty, DAG);
1789 return getAddrLocal(N, Ty, DAG,
1790 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1793 SDValue MipsTargetLowering::
1794 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1796 // gp_rel relocation
1797 // FIXME: we should reference the constant pool using small data sections,
1798 // but the asm printer currently doesn't support this feature without
1799 // hacking it. This feature should come soon so we can uncomment the
1801 //if (IsInSmallSection(C->getType())) {
1802 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1803 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1804 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1805 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1806 EVT Ty = Op.getValueType();
1808 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1809 !Subtarget.isABI_N64())
1810 return getAddrNonPIC(N, Ty, DAG);
1812 return getAddrLocal(N, Ty, DAG,
1813 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1816 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1817 MachineFunction &MF = DAG.getMachineFunction();
1818 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1821 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1824 // vastart just stores the address of the VarArgsFrameIndex slot into the
1825 // memory location argument.
1826 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1827 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1828 MachinePointerInfo(SV), false, false, 0);
1831 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1832 SDNode *Node = Op.getNode();
1833 EVT VT = Node->getValueType(0);
1834 SDValue Chain = Node->getOperand(0);
1835 SDValue VAListPtr = Node->getOperand(1);
1836 unsigned Align = Node->getConstantOperandVal(3);
1837 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1839 unsigned ArgSlotSizeInBytes =
1840 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1842 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1843 MachinePointerInfo(SV), false, false, false,
1845 SDValue VAList = VAListLoad;
1847 // Re-align the pointer if necessary.
1848 // It should only ever be necessary for 64-bit types on O32 since the minimum
1849 // argument alignment is the same as the maximum type alignment for N32/N64.
1851 // FIXME: We currently align too often. The code generator doesn't notice
1852 // when the pointer is still aligned from the last va_arg (or pair of
1853 // va_args for the i64 on O32 case).
1854 if (Align > getMinStackArgumentAlignment()) {
1855 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1857 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1858 DAG.getConstant(Align - 1,
1859 VAList.getValueType()));
1861 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1862 DAG.getConstant(-(int64_t)Align,
1863 VAList.getValueType()));
1866 // Increment the pointer, VAList, to the next vaarg.
1867 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1868 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1869 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1870 VAList.getValueType()));
1871 // Store the incremented VAList to the legalized pointer
1872 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1873 MachinePointerInfo(SV), false, false, 0);
1875 // In big-endian mode we must adjust the pointer when the load size is smaller
1876 // than the argument slot size. We must also reduce the known alignment to
1877 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1878 // the correct half of the slot, and reduce the alignment from 8 (slot
1879 // alignment) down to 4 (type alignment).
1880 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1881 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1882 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1883 DAG.getIntPtrConstant(Adjustment));
1885 // Load the actual argument out of the pointer VAList
1886 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1890 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1891 bool HasExtractInsert) {
1892 EVT TyX = Op.getOperand(0).getValueType();
1893 EVT TyY = Op.getOperand(1).getValueType();
1894 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1895 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1899 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1901 SDValue X = (TyX == MVT::f32) ?
1902 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1903 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1905 SDValue Y = (TyY == MVT::f32) ?
1906 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1907 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1910 if (HasExtractInsert) {
1911 // ext E, Y, 31, 1 ; extract bit31 of Y
1912 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1913 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1914 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1917 // srl SrlX, SllX, 1
1919 // sll SllY, SrlX, 31
1920 // or Or, SrlX, SllY
1921 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1922 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1923 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1924 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1925 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1928 if (TyX == MVT::f32)
1929 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1931 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1932 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1933 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1936 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1937 bool HasExtractInsert) {
1938 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1939 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1940 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1941 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1944 // Bitcast to integer nodes.
1945 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1946 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1948 if (HasExtractInsert) {
1949 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1950 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1951 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1952 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1954 if (WidthX > WidthY)
1955 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1956 else if (WidthY > WidthX)
1957 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1959 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1960 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1961 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1964 // (d)sll SllX, X, 1
1965 // (d)srl SrlX, SllX, 1
1966 // (d)srl SrlY, Y, width(Y)-1
1967 // (d)sll SllY, SrlX, width(Y)-1
1968 // or Or, SrlX, SllY
1969 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1970 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1971 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1972 DAG.getConstant(WidthY - 1, MVT::i32));
1974 if (WidthX > WidthY)
1975 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1976 else if (WidthY > WidthX)
1977 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1979 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1980 DAG.getConstant(WidthX - 1, MVT::i32));
1981 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1982 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1986 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1987 if (Subtarget.isGP64bit())
1988 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1990 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1993 SDValue MipsTargetLowering::
1994 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1996 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1997 "Frame address can only be determined for current frame.");
1999 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2000 MFI->setFrameAddressIsTaken(true);
2001 EVT VT = Op.getValueType();
2004 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
2005 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
2009 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2010 SelectionDAG &DAG) const {
2011 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2015 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2016 "Return address can be determined only for current frame.");
2018 MachineFunction &MF = DAG.getMachineFunction();
2019 MachineFrameInfo *MFI = MF.getFrameInfo();
2020 MVT VT = Op.getSimpleValueType();
2021 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
2022 MFI->setReturnAddressIsTaken(true);
2024 // Return RA, which contains the return address. Mark it an implicit live-in.
2025 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2026 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2029 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2030 // generated from __builtin_eh_return (offset, handler)
2031 // The effect of this is to adjust the stack pointer by "offset"
2032 // and then branch to "handler".
2033 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2035 MachineFunction &MF = DAG.getMachineFunction();
2036 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2038 MipsFI->setCallsEhReturn();
2039 SDValue Chain = Op.getOperand(0);
2040 SDValue Offset = Op.getOperand(1);
2041 SDValue Handler = Op.getOperand(2);
2043 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2045 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2046 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2047 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
2048 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2049 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2050 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2051 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2052 DAG.getRegister(OffsetReg, Ty),
2053 DAG.getRegister(AddrReg, getPointerTy()),
2057 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2058 SelectionDAG &DAG) const {
2059 // FIXME: Need pseudo-fence for 'singlethread' fences
2060 // FIXME: Set SType for weaker fences where supported/appropriate.
2063 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2064 DAG.getConstant(SType, MVT::i32));
2067 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2068 SelectionDAG &DAG) const {
2070 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2071 SDValue Shamt = Op.getOperand(2);
2074 // lo = (shl lo, shamt)
2075 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2078 // hi = (shl lo, shamt[4:0])
2079 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2080 DAG.getConstant(-1, MVT::i32));
2081 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2082 DAG.getConstant(1, MVT::i32));
2083 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2085 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2086 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2087 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2088 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2089 DAG.getConstant(0x20, MVT::i32));
2090 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2091 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2092 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2094 SDValue Ops[2] = {Lo, Hi};
2095 return DAG.getMergeValues(Ops, DL);
2098 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2101 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2102 SDValue Shamt = Op.getOperand(2);
2105 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2107 // hi = (sra hi, shamt)
2109 // hi = (srl hi, shamt)
2112 // lo = (sra hi, shamt[4:0])
2113 // hi = (sra hi, 31)
2115 // lo = (srl hi, shamt[4:0])
2117 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2118 DAG.getConstant(-1, MVT::i32));
2119 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2120 DAG.getConstant(1, MVT::i32));
2121 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2122 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2123 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2124 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2126 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2127 DAG.getConstant(0x20, MVT::i32));
2128 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2129 DAG.getConstant(31, MVT::i32));
2130 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2131 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2132 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2135 SDValue Ops[2] = {Lo, Hi};
2136 return DAG.getMergeValues(Ops, DL);
2139 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2140 SDValue Chain, SDValue Src, unsigned Offset) {
2141 SDValue Ptr = LD->getBasePtr();
2142 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2143 EVT BasePtrVT = Ptr.getValueType();
2145 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2148 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2149 DAG.getConstant(Offset, BasePtrVT));
2151 SDValue Ops[] = { Chain, Ptr, Src };
2152 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2153 LD->getMemOperand());
2156 // Expand an unaligned 32 or 64-bit integer load node.
2157 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2158 LoadSDNode *LD = cast<LoadSDNode>(Op);
2159 EVT MemVT = LD->getMemoryVT();
2161 if (Subtarget.systemSupportsUnalignedAccess())
2164 // Return if load is aligned or if MemVT is neither i32 nor i64.
2165 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2166 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2169 bool IsLittle = Subtarget.isLittle();
2170 EVT VT = Op.getValueType();
2171 ISD::LoadExtType ExtType = LD->getExtensionType();
2172 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2174 assert((VT == MVT::i32) || (VT == MVT::i64));
2177 // (set dst, (i64 (load baseptr)))
2179 // (set tmp, (ldl (add baseptr, 7), undef))
2180 // (set dst, (ldr baseptr, tmp))
2181 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2182 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2184 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2188 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2190 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2194 // (set dst, (i32 (load baseptr))) or
2195 // (set dst, (i64 (sextload baseptr))) or
2196 // (set dst, (i64 (extload baseptr)))
2198 // (set tmp, (lwl (add baseptr, 3), undef))
2199 // (set dst, (lwr baseptr, tmp))
2200 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2201 (ExtType == ISD::EXTLOAD))
2204 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2207 // (set dst, (i64 (zextload baseptr)))
2209 // (set tmp0, (lwl (add baseptr, 3), undef))
2210 // (set tmp1, (lwr baseptr, tmp0))
2211 // (set tmp2, (shl tmp1, 32))
2212 // (set dst, (srl tmp2, 32))
2214 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2215 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2216 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2217 SDValue Ops[] = { SRL, LWR.getValue(1) };
2218 return DAG.getMergeValues(Ops, DL);
2221 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2222 SDValue Chain, unsigned Offset) {
2223 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2224 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2226 SDVTList VTList = DAG.getVTList(MVT::Other);
2229 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2230 DAG.getConstant(Offset, BasePtrVT));
2232 SDValue Ops[] = { Chain, Value, Ptr };
2233 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2234 SD->getMemOperand());
2237 // Expand an unaligned 32 or 64-bit integer store node.
2238 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2240 SDValue Value = SD->getValue(), Chain = SD->getChain();
2241 EVT VT = Value.getValueType();
2244 // (store val, baseptr) or
2245 // (truncstore val, baseptr)
2247 // (swl val, (add baseptr, 3))
2248 // (swr val, baseptr)
2249 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2250 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2252 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2255 assert(VT == MVT::i64);
2258 // (store val, baseptr)
2260 // (sdl val, (add baseptr, 7))
2261 // (sdr val, baseptr)
2262 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2263 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2266 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2267 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2268 SDValue Val = SD->getValue();
2270 if (Val.getOpcode() != ISD::FP_TO_SINT)
2273 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2274 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2277 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2278 SD->getPointerInfo(), SD->isVolatile(),
2279 SD->isNonTemporal(), SD->getAlignment());
2282 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2283 StoreSDNode *SD = cast<StoreSDNode>(Op);
2284 EVT MemVT = SD->getMemoryVT();
2286 // Lower unaligned integer stores.
2287 if (!Subtarget.systemSupportsUnalignedAccess() &&
2288 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2289 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2290 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2292 return lowerFP_TO_SINT_STORE(SD, DAG);
2295 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2296 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2297 || cast<ConstantSDNode>
2298 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2299 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2303 // (add (frameaddr 0), (frame_to_args_offset))
2304 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2305 // (add FrameObject, 0)
2306 // where FrameObject is a fixed StackObject with offset 0 which points to
2307 // the old stack pointer.
2308 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2309 EVT ValTy = Op->getValueType(0);
2310 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2311 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2312 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2313 DAG.getConstant(0, ValTy));
2316 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2317 SelectionDAG &DAG) const {
2318 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2319 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2321 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2324 //===----------------------------------------------------------------------===//
2325 // Calling Convention Implementation
2326 //===----------------------------------------------------------------------===//
2328 //===----------------------------------------------------------------------===//
2329 // TODO: Implement a generic logic using tblgen that can support this.
2330 // Mips O32 ABI rules:
2332 // i32 - Passed in A0, A1, A2, A3 and stack
2333 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2334 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2335 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2336 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2337 // not used, it must be shadowed. If only A3 is available, shadow it and
2340 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2341 //===----------------------------------------------------------------------===//
2343 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2344 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2345 CCState &State, const MCPhysReg *F64Regs) {
2347 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2349 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2350 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2352 // Do not process byval args here.
2353 if (ArgFlags.isByVal())
2356 // Promote i8 and i16
2357 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2359 if (ArgFlags.isSExt())
2360 LocInfo = CCValAssign::SExt;
2361 else if (ArgFlags.isZExt())
2362 LocInfo = CCValAssign::ZExt;
2364 LocInfo = CCValAssign::AExt;
2369 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2370 // is true: function is vararg, argument is 3rd or higher, there is previous
2371 // argument which is not f32 or f64.
2372 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2373 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2374 unsigned OrigAlign = ArgFlags.getOrigAlign();
2375 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2377 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2378 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2379 // If this is the first part of an i64 arg,
2380 // the allocated register must be either A0 or A2.
2381 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2382 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2384 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2385 // Allocate int register and shadow next int register. If first
2386 // available register is Mips::A1 or Mips::A3, shadow it too.
2387 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2388 if (Reg == Mips::A1 || Reg == Mips::A3)
2389 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2390 State.AllocateReg(IntRegs, IntRegsSize);
2392 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2393 // we are guaranteed to find an available float register
2394 if (ValVT == MVT::f32) {
2395 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2396 // Shadow int register
2397 State.AllocateReg(IntRegs, IntRegsSize);
2399 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2400 // Shadow int registers
2401 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2402 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2403 State.AllocateReg(IntRegs, IntRegsSize);
2404 State.AllocateReg(IntRegs, IntRegsSize);
2407 llvm_unreachable("Cannot handle this ValVT.");
2410 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2412 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2414 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2419 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2420 MVT LocVT, CCValAssign::LocInfo LocInfo,
2421 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2422 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2424 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2427 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2428 MVT LocVT, CCValAssign::LocInfo LocInfo,
2429 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2430 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2432 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2435 #include "MipsGenCallingConv.inc"
2437 //===----------------------------------------------------------------------===//
2438 // Call Calling Convention Implementation
2439 //===----------------------------------------------------------------------===//
2441 // Return next O32 integer argument register.
2442 static unsigned getNextIntArgReg(unsigned Reg) {
2443 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2444 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2448 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2449 SDValue Chain, SDValue Arg, SDLoc DL,
2450 bool IsTailCall, SelectionDAG &DAG) const {
2452 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2453 DAG.getIntPtrConstant(Offset));
2454 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2458 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2459 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2460 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2461 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2462 /*isVolatile=*/ true, false, 0);
2465 void MipsTargetLowering::
2466 getOpndList(SmallVectorImpl<SDValue> &Ops,
2467 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2468 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2469 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2470 SDValue Chain) const {
2471 // Insert node "GP copy globalreg" before call to function.
2473 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2474 // in PIC mode) allow symbols to be resolved via lazy binding.
2475 // The lazy binding stub requires GP to point to the GOT.
2476 // Note that we don't need GP to point to the GOT for indirect calls
2477 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2478 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2479 // used for the function (that is, Mips linker doesn't generate lazy binding
2480 // stub for a function whose address is taken in the program).
2481 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2482 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2483 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2484 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2487 // Build a sequence of copy-to-reg nodes chained together with token
2488 // chain and flag operands which copy the outgoing args into registers.
2489 // The InFlag in necessary since all emitted instructions must be
2493 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2494 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2495 RegsToPass[i].second, InFlag);
2496 InFlag = Chain.getValue(1);
2499 // Add argument registers to the end of the list so that they are
2500 // known live into the call.
2501 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2502 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2503 RegsToPass[i].second.getValueType()));
2505 // Add a register mask operand representing the call-preserved registers.
2506 const TargetRegisterInfo *TRI =
2507 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2508 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2509 assert(Mask && "Missing call preserved mask for calling convention");
2510 if (Subtarget.inMips16HardFloat()) {
2511 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2512 llvm::StringRef Sym = G->getGlobal()->getName();
2513 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2514 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2515 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2519 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2521 if (InFlag.getNode())
2522 Ops.push_back(InFlag);
2525 /// LowerCall - functions arguments are copied from virtual regs to
2526 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2528 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2529 SmallVectorImpl<SDValue> &InVals) const {
2530 SelectionDAG &DAG = CLI.DAG;
2532 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2533 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2534 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2535 SDValue Chain = CLI.Chain;
2536 SDValue Callee = CLI.Callee;
2537 bool &IsTailCall = CLI.IsTailCall;
2538 CallingConv::ID CallConv = CLI.CallConv;
2539 bool IsVarArg = CLI.IsVarArg;
2541 MachineFunction &MF = DAG.getMachineFunction();
2542 MachineFrameInfo *MFI = MF.getFrameInfo();
2543 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2544 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2545 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2547 // Analyze operands of the call, assigning locations to each operand.
2548 SmallVector<CCValAssign, 16> ArgLocs;
2549 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2551 MipsCC::SpecialCallingConvType SpecialCallingConv =
2552 getSpecialCallingConv(Callee);
2553 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo, SpecialCallingConv);
2555 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2556 Subtarget.abiUsesSoftFloat(),
2557 Callee.getNode(), CLI.getArgs());
2559 // Get a count of how many bytes are to be pushed on the stack.
2560 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2562 // Check if it's really possible to do a tail call.
2565 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2566 *MF.getInfo<MipsFunctionInfo>());
2568 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2569 report_fatal_error("failed to perform tail call elimination on a call "
2570 "site marked musttail");
2575 // Chain is the output chain of the last Load/Store or CopyToReg node.
2576 // ByValChain is the output chain of the last Memcpy node created for copying
2577 // byval arguments to the stack.
2578 unsigned StackAlignment = TFL->getStackAlignment();
2579 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2580 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2583 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2585 SDValue StackPtr = DAG.getCopyFromReg(
2586 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2589 // With EABI is it possible to have 16 args on registers.
2590 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2591 SmallVector<SDValue, 8> MemOpChains;
2592 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2594 // Walk the register/memloc assignments, inserting copies/loads.
2595 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2596 SDValue Arg = OutVals[i];
2597 CCValAssign &VA = ArgLocs[i];
2598 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2599 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2602 if (Flags.isByVal()) {
2603 assert(Flags.getByValSize() &&
2604 "ByVal args of size 0 should have been ignored by front-end.");
2605 assert(ByValArg != MipsCCInfo.byval_end());
2606 assert(!IsTailCall &&
2607 "Do not tail-call optimize if there is a byval argument.");
2608 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2609 MipsCCInfo, *ByValArg, Flags, Subtarget.isLittle());
2614 // Promote the value if needed.
2615 switch (VA.getLocInfo()) {
2616 default: llvm_unreachable("Unknown loc info!");
2617 case CCValAssign::Full:
2618 if (VA.isRegLoc()) {
2619 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2620 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2621 (ValVT == MVT::i64 && LocVT == MVT::f64))
2622 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2623 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2624 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2625 Arg, DAG.getConstant(0, MVT::i32));
2626 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2627 Arg, DAG.getConstant(1, MVT::i32));
2628 if (!Subtarget.isLittle())
2630 unsigned LocRegLo = VA.getLocReg();
2631 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2632 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2633 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2638 case CCValAssign::SExt:
2639 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2641 case CCValAssign::ZExt:
2642 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2644 case CCValAssign::AExt:
2645 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2649 // Arguments that can be passed on register must be kept at
2650 // RegsToPass vector
2651 if (VA.isRegLoc()) {
2652 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2656 // Register can't get to this point...
2657 assert(VA.isMemLoc());
2659 // emit ISD::STORE whichs stores the
2660 // parameter value to a stack Location
2661 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2662 Chain, Arg, DL, IsTailCall, DAG));
2665 // Transform all store nodes into one single node because all store
2666 // nodes are independent of each other.
2667 if (!MemOpChains.empty())
2668 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2670 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2671 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2672 // node so that legalize doesn't hack it.
2674 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2676 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2678 EVT Ty = Callee.getValueType();
2680 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2682 const GlobalValue *Val = G->getGlobal();
2683 InternalLinkage = Val->hasInternalLinkage();
2685 if (InternalLinkage)
2686 Callee = getAddrLocal(G, Ty, DAG,
2687 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2688 else if (LargeGOT) {
2689 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2690 MipsII::MO_CALL_LO16, Chain,
2691 FuncInfo->callPtrInfo(Val));
2694 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2695 FuncInfo->callPtrInfo(Val));
2699 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2700 MipsII::MO_NO_FLAG);
2701 GlobalOrExternal = true;
2703 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2704 const char *Sym = S->getSymbol();
2706 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2707 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2708 MipsII::MO_NO_FLAG);
2709 else if (LargeGOT) {
2710 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2711 MipsII::MO_CALL_LO16, Chain,
2712 FuncInfo->callPtrInfo(Sym));
2714 } else { // N64 || PIC
2715 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2716 FuncInfo->callPtrInfo(Sym));
2720 GlobalOrExternal = true;
2723 SmallVector<SDValue, 8> Ops(1, Chain);
2724 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2726 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2727 IsCallReloc, CLI, Callee, Chain);
2730 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2732 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2733 SDValue InFlag = Chain.getValue(1);
2735 // Create the CALLSEQ_END node.
2736 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2737 DAG.getIntPtrConstant(0, true), InFlag, DL);
2738 InFlag = Chain.getValue(1);
2740 // Handle result values, copying them out of physregs into vregs that we
2742 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2746 /// LowerCallResult - Lower the result values of a call into the
2747 /// appropriate copies out of appropriate physical registers.
2748 SDValue MipsTargetLowering::LowerCallResult(
2749 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2750 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2751 SmallVectorImpl<SDValue> &InVals,
2752 TargetLowering::CallLoweringInfo &CLI) const {
2753 // Assign locations to each value returned by this call.
2754 SmallVector<CCValAssign, 16> RVLocs;
2755 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2757 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2759 // Copy all of the result registers out of their specified physreg.
2760 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2761 CCValAssign &VA = RVLocs[i];
2762 assert(VA.isRegLoc() && "Can only return in registers!");
2764 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2765 RVLocs[i].getLocVT(), InFlag);
2766 Chain = Val.getValue(1);
2767 InFlag = Val.getValue(2);
2769 if (VA.isUpperBitsInLoc()) {
2770 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2771 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2773 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2775 Shift, DL, VA.getLocVT(), Val,
2776 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2779 switch (VA.getLocInfo()) {
2781 llvm_unreachable("Unknown loc info!");
2782 case CCValAssign::Full:
2784 case CCValAssign::BCvt:
2785 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2787 case CCValAssign::AExt:
2788 case CCValAssign::AExtUpper:
2789 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2791 case CCValAssign::ZExt:
2792 case CCValAssign::ZExtUpper:
2793 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2794 DAG.getValueType(VA.getValVT()));
2795 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2797 case CCValAssign::SExt:
2798 case CCValAssign::SExtUpper:
2799 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2800 DAG.getValueType(VA.getValVT()));
2801 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2805 InVals.push_back(Val);
2811 //===----------------------------------------------------------------------===//
2812 // Formal Arguments Calling Convention Implementation
2813 //===----------------------------------------------------------------------===//
2814 /// LowerFormalArguments - transform physical registers into virtual registers
2815 /// and generate load operations for arguments places on the stack.
2817 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2818 CallingConv::ID CallConv,
2820 const SmallVectorImpl<ISD::InputArg> &Ins,
2821 SDLoc DL, SelectionDAG &DAG,
2822 SmallVectorImpl<SDValue> &InVals)
2824 MachineFunction &MF = DAG.getMachineFunction();
2825 MachineFrameInfo *MFI = MF.getFrameInfo();
2826 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2828 MipsFI->setVarArgsFrameIndex(0);
2830 // Used with vargs to acumulate store chains.
2831 std::vector<SDValue> OutChains;
2833 // Assign locations to all of the incoming arguments.
2834 SmallVector<CCValAssign, 16> ArgLocs;
2835 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2837 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2838 Function::const_arg_iterator FuncArg =
2839 DAG.getMachineFunction().getFunction()->arg_begin();
2840 bool UseSoftFloat = Subtarget.abiUsesSoftFloat();
2842 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2843 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2844 MipsCCInfo.hasByValArg());
2846 unsigned CurArgIdx = 0;
2847 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2849 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2850 CCValAssign &VA = ArgLocs[i];
2851 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2852 CurArgIdx = Ins[i].OrigArgIndex;
2853 EVT ValVT = VA.getValVT();
2854 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2855 bool IsRegLoc = VA.isRegLoc();
2857 if (Flags.isByVal()) {
2858 assert(Flags.getByValSize() &&
2859 "ByVal args of size 0 should have been ignored by front-end.");
2860 assert(ByValArg != MipsCCInfo.byval_end());
2861 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2862 MipsCCInfo, *ByValArg);
2867 // Arguments stored on registers
2869 MVT RegVT = VA.getLocVT();
2870 unsigned ArgReg = VA.getLocReg();
2871 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2873 // Transform the arguments stored on
2874 // physical registers into virtual ones
2875 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2876 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2878 // If this is an 8 or 16-bit value, it has been passed promoted
2879 // to 32 bits. Insert an assert[sz]ext to capture this, then
2880 // truncate to the right size.
2881 if (VA.getLocInfo() != CCValAssign::Full) {
2882 unsigned Opcode = 0;
2883 if (VA.getLocInfo() == CCValAssign::SExt)
2884 Opcode = ISD::AssertSext;
2885 else if (VA.getLocInfo() == CCValAssign::ZExt)
2886 Opcode = ISD::AssertZext;
2888 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2889 DAG.getValueType(ValVT));
2890 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2893 // Handle floating point arguments passed in integer registers and
2894 // long double arguments passed in floating point registers.
2895 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2896 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2897 (RegVT == MVT::f64 && ValVT == MVT::i64))
2898 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2899 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2900 ValVT == MVT::f64) {
2901 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2902 getNextIntArgReg(ArgReg), RC);
2903 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2904 if (!Subtarget.isLittle())
2905 std::swap(ArgValue, ArgValue2);
2906 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2907 ArgValue, ArgValue2);
2910 InVals.push_back(ArgValue);
2911 } else { // VA.isRegLoc()
2914 assert(VA.isMemLoc());
2916 // The stack pointer offset is relative to the caller stack frame.
2917 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2918 VA.getLocMemOffset(), true);
2920 // Create load nodes to retrieve arguments from the stack
2921 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2922 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2923 MachinePointerInfo::getFixedStack(FI),
2924 false, false, false, 0);
2925 InVals.push_back(Load);
2926 OutChains.push_back(Load.getValue(1));
2930 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2931 // The mips ABIs for returning structs by value requires that we copy
2932 // the sret argument into $v0 for the return. Save the argument into
2933 // a virtual register so that we can access it from the return points.
2934 if (Ins[i].Flags.isSRet()) {
2935 unsigned Reg = MipsFI->getSRetReturnReg();
2937 Reg = MF.getRegInfo().createVirtualRegister(
2938 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2939 MipsFI->setSRetReturnReg(Reg);
2941 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2942 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2948 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2950 // All stores are grouped in one node to allow the matching between
2951 // the size of Ins and InVals. This only happens when on varg functions
2952 if (!OutChains.empty()) {
2953 OutChains.push_back(Chain);
2954 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2960 //===----------------------------------------------------------------------===//
2961 // Return Value Calling Convention Implementation
2962 //===----------------------------------------------------------------------===//
2965 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2966 MachineFunction &MF, bool IsVarArg,
2967 const SmallVectorImpl<ISD::OutputArg> &Outs,
2968 LLVMContext &Context) const {
2969 SmallVector<CCValAssign, 16> RVLocs;
2970 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2971 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2975 MipsTargetLowering::LowerReturn(SDValue Chain,
2976 CallingConv::ID CallConv, bool IsVarArg,
2977 const SmallVectorImpl<ISD::OutputArg> &Outs,
2978 const SmallVectorImpl<SDValue> &OutVals,
2979 SDLoc DL, SelectionDAG &DAG) const {
2980 // CCValAssign - represent the assignment of
2981 // the return value to a location
2982 SmallVector<CCValAssign, 16> RVLocs;
2983 MachineFunction &MF = DAG.getMachineFunction();
2985 // CCState - Info about the registers and stack slot.
2986 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
2987 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2989 // Analyze return values.
2990 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2993 SmallVector<SDValue, 4> RetOps(1, Chain);
2995 // Copy the result values into the output registers.
2996 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2997 SDValue Val = OutVals[i];
2998 CCValAssign &VA = RVLocs[i];
2999 assert(VA.isRegLoc() && "Can only return in registers!");
3000 bool UseUpperBits = false;
3002 switch (VA.getLocInfo()) {
3004 llvm_unreachable("Unknown loc info!");
3005 case CCValAssign::Full:
3007 case CCValAssign::BCvt:
3008 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3010 case CCValAssign::AExtUpper:
3011 UseUpperBits = true;
3013 case CCValAssign::AExt:
3014 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3016 case CCValAssign::ZExtUpper:
3017 UseUpperBits = true;
3019 case CCValAssign::ZExt:
3020 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3022 case CCValAssign::SExtUpper:
3023 UseUpperBits = true;
3025 case CCValAssign::SExt:
3026 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3031 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3032 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3034 ISD::SHL, DL, VA.getLocVT(), Val,
3035 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3038 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3040 // Guarantee that all emitted copies are stuck together with flags.
3041 Flag = Chain.getValue(1);
3042 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3045 // The mips ABIs for returning structs by value requires that we copy
3046 // the sret argument into $v0 for the return. We saved the argument into
3047 // a virtual register in the entry block, so now we copy the value out
3049 if (MF.getFunction()->hasStructRetAttr()) {
3050 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3051 unsigned Reg = MipsFI->getSRetReturnReg();
3054 llvm_unreachable("sret virtual register not created in the entry block");
3055 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3056 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3058 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3059 Flag = Chain.getValue(1);
3060 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3063 RetOps[0] = Chain; // Update chain.
3065 // Add the flag if we have it.
3067 RetOps.push_back(Flag);
3069 // Return on Mips is always a "jr $ra"
3070 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3073 //===----------------------------------------------------------------------===//
3074 // Mips Inline Assembly Support
3075 //===----------------------------------------------------------------------===//
3077 /// getConstraintType - Given a constraint letter, return the type of
3078 /// constraint it is for this target.
3079 MipsTargetLowering::ConstraintType MipsTargetLowering::
3080 getConstraintType(const std::string &Constraint) const
3082 // Mips specific constraints
3083 // GCC config/mips/constraints.md
3085 // 'd' : An address register. Equivalent to r
3086 // unless generating MIPS16 code.
3087 // 'y' : Equivalent to r; retained for
3088 // backwards compatibility.
3089 // 'c' : A register suitable for use in an indirect
3090 // jump. This will always be $25 for -mabicalls.
3091 // 'l' : The lo register. 1 word storage.
3092 // 'x' : The hilo register pair. Double word storage.
3093 if (Constraint.size() == 1) {
3094 switch (Constraint[0]) {
3102 return C_RegisterClass;
3107 return TargetLowering::getConstraintType(Constraint);
3110 /// Examine constraint type and operand type and determine a weight value.
3111 /// This object must already have been set up with the operand type
3112 /// and the current alternative constraint selected.
3113 TargetLowering::ConstraintWeight
3114 MipsTargetLowering::getSingleConstraintMatchWeight(
3115 AsmOperandInfo &info, const char *constraint) const {
3116 ConstraintWeight weight = CW_Invalid;
3117 Value *CallOperandVal = info.CallOperandVal;
3118 // If we don't have a value, we can't do a match,
3119 // but allow it at the lowest weight.
3120 if (!CallOperandVal)
3122 Type *type = CallOperandVal->getType();
3123 // Look at the constraint type.
3124 switch (*constraint) {
3126 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3130 if (type->isIntegerTy())
3131 weight = CW_Register;
3133 case 'f': // FPU or MSA register
3134 if (Subtarget.hasMSA() && type->isVectorTy() &&
3135 cast<VectorType>(type)->getBitWidth() == 128)
3136 weight = CW_Register;
3137 else if (type->isFloatTy())
3138 weight = CW_Register;
3140 case 'c': // $25 for indirect jumps
3141 case 'l': // lo register
3142 case 'x': // hilo register pair
3143 if (type->isIntegerTy())
3144 weight = CW_SpecificReg;
3146 case 'I': // signed 16 bit immediate
3147 case 'J': // integer zero
3148 case 'K': // unsigned 16 bit immediate
3149 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3150 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3151 case 'O': // signed 15 bit immediate (+- 16383)
3152 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3153 if (isa<ConstantInt>(CallOperandVal))
3154 weight = CW_Constant;
3163 /// This is a helper function to parse a physical register string and split it
3164 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3165 /// that is returned indicates whether parsing was successful. The second flag
3166 /// is true if the numeric part exists.
3167 static std::pair<bool, bool>
3168 parsePhysicalReg(StringRef C, std::string &Prefix,
3169 unsigned long long &Reg) {
3170 if (C.front() != '{' || C.back() != '}')
3171 return std::make_pair(false, false);
3173 // Search for the first numeric character.
3174 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3175 I = std::find_if(B, E, std::ptr_fun(isdigit));
3177 Prefix.assign(B, I - B);
3179 // The second flag is set to false if no numeric characters were found.
3181 return std::make_pair(true, false);
3183 // Parse the numeric characters.
3184 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3188 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3189 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3190 const TargetRegisterInfo *TRI =
3191 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3192 const TargetRegisterClass *RC;
3194 unsigned long long Reg;
3196 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3199 return std::make_pair(0U, nullptr);
3201 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3202 // No numeric characters follow "hi" or "lo".
3204 return std::make_pair(0U, nullptr);
3206 RC = TRI->getRegClass(Prefix == "hi" ?
3207 Mips::HI32RegClassID : Mips::LO32RegClassID);
3208 return std::make_pair(*(RC->begin()), RC);
3209 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3210 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3212 // No numeric characters follow the name.
3214 return std::make_pair(0U, nullptr);
3216 Reg = StringSwitch<unsigned long long>(Prefix)
3217 .Case("$msair", Mips::MSAIR)
3218 .Case("$msacsr", Mips::MSACSR)
3219 .Case("$msaaccess", Mips::MSAAccess)
3220 .Case("$msasave", Mips::MSASave)
3221 .Case("$msamodify", Mips::MSAModify)
3222 .Case("$msarequest", Mips::MSARequest)
3223 .Case("$msamap", Mips::MSAMap)
3224 .Case("$msaunmap", Mips::MSAUnmap)
3228 return std::make_pair(0U, nullptr);
3230 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3231 return std::make_pair(Reg, RC);
3235 return std::make_pair(0U, nullptr);
3237 if (Prefix == "$f") { // Parse $f0-$f31.
3238 // If the size of FP registers is 64-bit or Reg is an even number, select
3239 // the 64-bit register class. Otherwise, select the 32-bit register class.
3240 if (VT == MVT::Other)
3241 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3243 RC = getRegClassFor(VT);
3245 if (RC == &Mips::AFGR64RegClass) {
3246 assert(Reg % 2 == 0);
3249 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3250 RC = TRI->getRegClass(Mips::FCCRegClassID);
3251 else if (Prefix == "$w") { // Parse $w0-$w31.
3252 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3253 } else { // Parse $0-$31.
3254 assert(Prefix == "$");
3255 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3258 assert(Reg < RC->getNumRegs());
3259 return std::make_pair(*(RC->begin() + Reg), RC);
3262 /// Given a register class constraint, like 'r', if this corresponds directly
3263 /// to an LLVM register class, return a register of 0 and the register class
3265 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3266 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3268 if (Constraint.size() == 1) {
3269 switch (Constraint[0]) {
3270 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3271 case 'y': // Same as 'r'. Exists for compatibility.
3273 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3274 if (Subtarget.inMips16Mode())
3275 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3276 return std::make_pair(0U, &Mips::GPR32RegClass);
3278 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3279 return std::make_pair(0U, &Mips::GPR32RegClass);
3280 if (VT == MVT::i64 && Subtarget.isGP64bit())
3281 return std::make_pair(0U, &Mips::GPR64RegClass);
3282 // This will generate an error message
3283 return std::make_pair(0U, nullptr);
3284 case 'f': // FPU or MSA register
3285 if (VT == MVT::v16i8)
3286 return std::make_pair(0U, &Mips::MSA128BRegClass);
3287 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3288 return std::make_pair(0U, &Mips::MSA128HRegClass);
3289 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3290 return std::make_pair(0U, &Mips::MSA128WRegClass);
3291 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3292 return std::make_pair(0U, &Mips::MSA128DRegClass);
3293 else if (VT == MVT::f32)
3294 return std::make_pair(0U, &Mips::FGR32RegClass);
3295 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3296 if (Subtarget.isFP64bit())
3297 return std::make_pair(0U, &Mips::FGR64RegClass);
3298 return std::make_pair(0U, &Mips::AFGR64RegClass);
3301 case 'c': // register suitable for indirect jump
3303 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3304 assert(VT == MVT::i64 && "Unexpected type.");
3305 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3306 case 'l': // register suitable for indirect jump
3308 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3309 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3310 case 'x': // register suitable for indirect jump
3311 // Fixme: Not triggering the use of both hi and low
3312 // This will generate an error message
3313 return std::make_pair(0U, nullptr);
3317 std::pair<unsigned, const TargetRegisterClass *> R;
3318 R = parseRegForInlineAsmConstraint(Constraint, VT);
3323 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3326 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3327 /// vector. If it is invalid, don't add anything to Ops.
3328 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3329 std::string &Constraint,
3330 std::vector<SDValue>&Ops,
3331 SelectionDAG &DAG) const {
3334 // Only support length 1 constraints for now.
3335 if (Constraint.length() > 1) return;
3337 char ConstraintLetter = Constraint[0];
3338 switch (ConstraintLetter) {
3339 default: break; // This will fall through to the generic implementation
3340 case 'I': // Signed 16 bit constant
3341 // If this fails, the parent routine will give an error
3342 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3343 EVT Type = Op.getValueType();
3344 int64_t Val = C->getSExtValue();
3345 if (isInt<16>(Val)) {
3346 Result = DAG.getTargetConstant(Val, Type);
3351 case 'J': // integer zero
3352 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3353 EVT Type = Op.getValueType();
3354 int64_t Val = C->getZExtValue();
3356 Result = DAG.getTargetConstant(0, Type);
3361 case 'K': // unsigned 16 bit immediate
3362 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3363 EVT Type = Op.getValueType();
3364 uint64_t Val = (uint64_t)C->getZExtValue();
3365 if (isUInt<16>(Val)) {
3366 Result = DAG.getTargetConstant(Val, Type);
3371 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3372 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3373 EVT Type = Op.getValueType();
3374 int64_t Val = C->getSExtValue();
3375 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3376 Result = DAG.getTargetConstant(Val, Type);
3381 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3382 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3383 EVT Type = Op.getValueType();
3384 int64_t Val = C->getSExtValue();
3385 if ((Val >= -65535) && (Val <= -1)) {
3386 Result = DAG.getTargetConstant(Val, Type);
3391 case 'O': // signed 15 bit immediate
3392 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3393 EVT Type = Op.getValueType();
3394 int64_t Val = C->getSExtValue();
3395 if ((isInt<15>(Val))) {
3396 Result = DAG.getTargetConstant(Val, Type);
3401 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3402 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3403 EVT Type = Op.getValueType();
3404 int64_t Val = C->getSExtValue();
3405 if ((Val <= 65535) && (Val >= 1)) {
3406 Result = DAG.getTargetConstant(Val, Type);
3413 if (Result.getNode()) {
3414 Ops.push_back(Result);
3418 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3421 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3423 // No global is ever allowed as a base.
3428 case 0: // "r+i" or just "i", depending on HasBaseReg.
3431 if (!AM.HasBaseReg) // allow "r+i".
3433 return false; // disallow "r+r" or "r+r+i".
3442 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3443 // The Mips target isn't yet aware of offsets.
3447 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3449 bool IsMemset, bool ZeroMemset,
3451 MachineFunction &MF) const {
3452 if (Subtarget.hasMips64())
3458 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3459 if (VT != MVT::f32 && VT != MVT::f64)
3461 if (Imm.isNegZero())
3463 return Imm.isZero();
3466 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3467 if (Subtarget.isABI_N64())
3468 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3470 return TargetLowering::getJumpTableEncoding();
3473 /// This function returns true if CallSym is a long double emulation routine.
3474 static bool isF128SoftLibCall(const char *CallSym) {
3475 const char *const LibCalls[] =
3476 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3477 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3478 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3479 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3480 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3481 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3482 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3483 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3486 const char *const *End = LibCalls + array_lengthof(LibCalls);
3488 // Check that LibCalls is sorted alphabetically.
3489 MipsTargetLowering::LTStr Comp;
3492 for (const char *const *I = LibCalls; I < End - 1; ++I)
3493 assert(Comp(*I, *(I + 1)));
3496 return std::binary_search(LibCalls, End, CallSym, Comp);
3499 /// This function returns true if Ty is fp128 or i128 which was originally a
3501 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3502 if (Ty->isFP128Ty())
3505 const ExternalSymbolSDNode *ES =
3506 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3508 // If the Ty is i128 and the function being called is a long double emulation
3509 // routine, then the original type is f128.
3510 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3513 MipsTargetLowering::MipsCC::SpecialCallingConvType
3514 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3515 MipsCC::SpecialCallingConvType SpecialCallingConv =
3516 MipsCC::NoSpecialCallingConv;
3517 if (Subtarget.inMips16HardFloat()) {
3518 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3519 llvm::StringRef Sym = G->getGlobal()->getName();
3520 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3521 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3522 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3526 return SpecialCallingConv;
3529 MipsTargetLowering::MipsCC::MipsCC(
3530 CallingConv::ID CC, const MipsSubtarget &Subtarget_, CCState &Info,
3531 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3532 : CCInfo(Info), CallConv(CC), Subtarget(Subtarget_),
3533 SpecialCallingConv(SpecialCallingConv_) {
3534 // Pre-allocate reserved argument area.
3535 CCInfo.AllocateStack(reservedArgArea(), 1);
3539 void MipsTargetLowering::MipsCC::
3540 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3541 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3542 std::vector<ArgListEntry> &FuncArgs) {
3543 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3544 "CallingConv::Fast shouldn't be used for vararg functions.");
3546 unsigned NumOpnds = Args.size();
3547 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3549 for (unsigned I = 0; I != NumOpnds; ++I) {
3550 MVT ArgVT = Args[I].VT;
3551 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3554 if (ArgFlags.isByVal()) {
3555 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3559 if (IsVarArg && !Args[I].IsFixed)
3560 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3562 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3564 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3569 dbgs() << "Call operand #" << I << " has unhandled type "
3570 << EVT(ArgVT).getEVTString();
3572 llvm_unreachable(nullptr);
3577 void MipsTargetLowering::MipsCC::
3578 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3579 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3580 unsigned NumArgs = Args.size();
3581 llvm::CCAssignFn *FixedFn = fixedArgFn();
3582 unsigned CurArgIdx = 0;
3584 for (unsigned I = 0; I != NumArgs; ++I) {
3585 MVT ArgVT = Args[I].VT;
3586 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3587 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3588 CurArgIdx = Args[I].OrigArgIndex;
3590 if (ArgFlags.isByVal()) {
3591 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3595 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
3597 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3601 dbgs() << "Formal Arg #" << I << " has unhandled type "
3602 << EVT(ArgVT).getEVTString();
3604 llvm_unreachable(nullptr);
3608 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3610 CCValAssign::LocInfo LocInfo,
3611 ISD::ArgFlagsTy ArgFlags) {
3612 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3614 struct ByValArgInfo ByVal;
3615 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3616 unsigned ByValSize =
3617 RoundUpToAlignment(ArgFlags.getByValSize(), RegSizeInBytes);
3618 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSizeInBytes),
3619 RegSizeInBytes * 2);
3621 if (useRegsForByval())
3622 allocateRegs(ByVal, ByValSize, Align);
3624 // Allocate space on caller's stack.
3626 CCInfo.AllocateStack(ByValSize - RegSizeInBytes * ByVal.NumRegs, Align);
3627 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3629 ByValArgs.push_back(ByVal);
3632 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3633 return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
3636 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
3637 if (Subtarget.isABI_O32())
3638 return makeArrayRef(O32IntRegs);
3639 return makeArrayRef(Mips64IntRegs);
3642 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3643 if (CallConv == CallingConv::Fast)
3644 return CC_Mips_FastCC;
3646 if (SpecialCallingConv == Mips16RetHelperConv)
3647 return CC_Mips16RetHelper;
3648 return Subtarget.isABI_O32()
3649 ? (Subtarget.isFP64bit() ? CC_MipsO32_FP64 : CC_MipsO32_FP32)
3653 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3654 return Subtarget.isABI_O32()
3655 ? (Subtarget.isFP64bit() ? CC_MipsO32_FP64 : CC_MipsO32_FP32)
3659 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3660 return Subtarget.isABI_O32() ? O32IntRegs : Mips64DPRegs;
3663 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3666 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3667 const ArrayRef<MCPhysReg> IntArgRegs = intArgRegs();
3668 const MCPhysReg *ShadowRegs = shadowRegs();
3669 assert(!(ByValSize % RegSizeInBytes) && !(Align % RegSizeInBytes) &&
3670 "Byval argument's size and alignment should be a multiple of"
3674 CCInfo.getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3676 // If Align > RegSizeInBytes, the first arg register must be even.
3677 if ((Align > RegSizeInBytes) && (ByVal.FirstIdx % 2)) {
3678 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3682 // Mark the registers allocated.
3683 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < IntArgRegs.size());
3684 ByValSize -= RegSizeInBytes, ++I, ++ByVal.NumRegs)
3685 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3688 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3689 const SDNode *CallNode,
3690 bool IsSoftFloat) const {
3691 if (IsSoftFloat || Subtarget.isABI_O32())
3694 // Check if the original type was fp128.
3695 if (originalTypeIsF128(OrigTy, CallNode)) {
3696 assert(VT == MVT::i64);
3703 void MipsTargetLowering::
3704 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3705 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3706 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3707 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3708 MachineFunction &MF = DAG.getMachineFunction();
3709 MachineFrameInfo *MFI = MF.getFrameInfo();
3710 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3711 unsigned RegAreaSize = ByVal.NumRegs * GPRSizeInBytes;
3712 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3717 (int)CC.reservedArgArea() -
3718 (int)((CC.intArgRegs().size() - ByVal.FirstIdx) * GPRSizeInBytes);
3720 FrameObjOffset = ByVal.Address;
3722 // Create frame object.
3723 EVT PtrTy = getPointerTy();
3724 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3725 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3726 InVals.push_back(FIN);
3731 // Copy arg registers.
3732 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3733 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3735 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3736 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3737 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3738 unsigned Offset = I * GPRSizeInBytes;
3739 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3740 DAG.getConstant(Offset, PtrTy));
3741 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3742 StorePtr, MachinePointerInfo(FuncArg, Offset),
3744 OutChains.push_back(Store);
3748 // Copy byVal arg to registers and stack.
3749 void MipsTargetLowering::
3750 passByValArg(SDValue Chain, SDLoc DL,
3751 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3752 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3753 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3754 const MipsCC &CC, const ByValArgInfo &ByVal,
3755 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3756 unsigned ByValSizeInBytes = Flags.getByValSize();
3757 unsigned OffsetInBytes = 0; // From beginning of struct
3758 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3759 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3760 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3762 if (ByVal.NumRegs) {
3763 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3764 bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
3767 // Copy words to registers.
3768 for (; I < ByVal.NumRegs - LeftoverBytes;
3769 ++I, OffsetInBytes += RegSizeInBytes) {
3770 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3771 DAG.getConstant(OffsetInBytes, PtrTy));
3772 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3773 MachinePointerInfo(), false, false, false,
3775 MemOpChains.push_back(LoadVal.getValue(1));
3776 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3777 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3780 // Return if the struct has been fully copied.
3781 if (ByValSizeInBytes == OffsetInBytes)
3784 // Copy the remainder of the byval argument with sub-word loads and shifts.
3785 if (LeftoverBytes) {
3786 assert((ByValSizeInBytes > OffsetInBytes) &&
3787 (ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
3788 "Size of the remainder should be smaller than RegSizeInBytes.");
3791 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3792 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3793 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3795 if (RemainingSizeInBytes < LoadSizeInBytes)
3799 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3800 DAG.getConstant(OffsetInBytes, PtrTy));
3801 SDValue LoadVal = DAG.getExtLoad(
3802 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3803 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3805 MemOpChains.push_back(LoadVal.getValue(1));
3807 // Shift the loaded value.
3811 Shamt = TotalBytesLoaded * 8;
3813 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3815 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3816 DAG.getConstant(Shamt, MVT::i32));
3819 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3823 OffsetInBytes += LoadSizeInBytes;
3824 TotalBytesLoaded += LoadSizeInBytes;
3825 Alignment = std::min(Alignment, LoadSizeInBytes);
3828 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3829 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3834 // Copy remainder of byval arg to it with memcpy.
3835 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3836 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3837 DAG.getConstant(OffsetInBytes, PtrTy));
3838 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3839 DAG.getIntPtrConstant(ByVal.Address));
3840 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3841 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3842 MachinePointerInfo(), MachinePointerInfo());
3843 MemOpChains.push_back(Chain);
3846 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3847 const MipsCC &CC, SDValue Chain,
3848 SDLoc DL, SelectionDAG &DAG) const {
3849 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3850 const CCState &CCInfo = CC.getCCInfo();
3851 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3852 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3853 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3854 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3855 MachineFunction &MF = DAG.getMachineFunction();
3856 MachineFrameInfo *MFI = MF.getFrameInfo();
3857 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3859 // Offset of the first variable argument from stack pointer.
3862 if (ArgRegs.size() == Idx)
3864 RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSizeInBytes);
3866 VaArgOffset = (int)CC.reservedArgArea() -
3867 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3869 // Record the frame index of the first variable argument
3870 // which is a value necessary to VASTART.
3871 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3872 MipsFI->setVarArgsFrameIndex(FI);
3874 // Copy the integer registers that have not been used for argument passing
3875 // to the argument register save area. For O32, the save area is allocated
3876 // in the caller's stack frame, while for N32/64, it is allocated in the
3877 // callee's stack frame.
3878 for (unsigned I = Idx; I < ArgRegs.size();
3879 ++I, VaArgOffset += RegSizeInBytes) {
3880 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3881 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3882 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3883 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3884 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3885 MachinePointerInfo(), false, false, 0);
3886 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3888 OutChains.push_back(Store);