1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
44 #define DEBUG_TYPE "mips-lower"
46 STATISTIC(NumTailCalls, "Number of tail calls");
49 LargeGOT("mxgot", cl::Hidden,
50 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
53 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
54 cl::desc("MIPS: Don't trap on integer division by zero."),
57 static const MCPhysReg Mips64DPRegs[8] = {
58 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
59 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
62 // If I is a shifted mask, set the size (Size) and the first bit of the
63 // mask (Pos), and return true.
64 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
65 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
66 if (!isShiftedMask_64(I))
69 Size = countPopulation(I);
70 Pos = countTrailingZeros(I);
74 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
75 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
76 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
79 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
81 unsigned Flag) const {
82 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
85 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
87 unsigned Flag) const {
88 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
91 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
93 unsigned Flag) const {
94 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
97 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
99 unsigned Flag) const {
100 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
103 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
105 unsigned Flag) const {
106 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
107 N->getOffset(), Flag);
110 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
111 switch ((MipsISD::NodeType)Opcode) {
112 case MipsISD::FIRST_NUMBER: break;
113 case MipsISD::JmpLink: return "MipsISD::JmpLink";
114 case MipsISD::TailCall: return "MipsISD::TailCall";
115 case MipsISD::Hi: return "MipsISD::Hi";
116 case MipsISD::Lo: return "MipsISD::Lo";
117 case MipsISD::GPRel: return "MipsISD::GPRel";
118 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
119 case MipsISD::Ret: return "MipsISD::Ret";
120 case MipsISD::ERet: return "MipsISD::ERet";
121 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
122 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
123 case MipsISD::FPCmp: return "MipsISD::FPCmp";
124 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
125 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
126 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
127 case MipsISD::MFHI: return "MipsISD::MFHI";
128 case MipsISD::MFLO: return "MipsISD::MFLO";
129 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
130 case MipsISD::Mult: return "MipsISD::Mult";
131 case MipsISD::Multu: return "MipsISD::Multu";
132 case MipsISD::MAdd: return "MipsISD::MAdd";
133 case MipsISD::MAddu: return "MipsISD::MAddu";
134 case MipsISD::MSub: return "MipsISD::MSub";
135 case MipsISD::MSubu: return "MipsISD::MSubu";
136 case MipsISD::DivRem: return "MipsISD::DivRem";
137 case MipsISD::DivRemU: return "MipsISD::DivRemU";
138 case MipsISD::DivRem16: return "MipsISD::DivRem16";
139 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
140 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
141 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
142 case MipsISD::Wrapper: return "MipsISD::Wrapper";
143 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
144 case MipsISD::Sync: return "MipsISD::Sync";
145 case MipsISD::Ext: return "MipsISD::Ext";
146 case MipsISD::Ins: return "MipsISD::Ins";
147 case MipsISD::LWL: return "MipsISD::LWL";
148 case MipsISD::LWR: return "MipsISD::LWR";
149 case MipsISD::SWL: return "MipsISD::SWL";
150 case MipsISD::SWR: return "MipsISD::SWR";
151 case MipsISD::LDL: return "MipsISD::LDL";
152 case MipsISD::LDR: return "MipsISD::LDR";
153 case MipsISD::SDL: return "MipsISD::SDL";
154 case MipsISD::SDR: return "MipsISD::SDR";
155 case MipsISD::EXTP: return "MipsISD::EXTP";
156 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
157 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
158 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
159 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
160 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
161 case MipsISD::SHILO: return "MipsISD::SHILO";
162 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
163 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
164 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
165 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
166 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
167 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
168 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
169 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
170 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
171 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
172 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
173 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
174 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
175 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
176 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
177 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
178 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
179 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
180 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
181 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
182 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
183 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
184 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
185 case MipsISD::MULT: return "MipsISD::MULT";
186 case MipsISD::MULTU: return "MipsISD::MULTU";
187 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
188 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
189 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
190 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
191 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
192 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
193 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
194 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
195 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
196 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
197 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
198 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
199 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
200 case MipsISD::VCEQ: return "MipsISD::VCEQ";
201 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
202 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
203 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
204 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
205 case MipsISD::VSMAX: return "MipsISD::VSMAX";
206 case MipsISD::VSMIN: return "MipsISD::VSMIN";
207 case MipsISD::VUMAX: return "MipsISD::VUMAX";
208 case MipsISD::VUMIN: return "MipsISD::VUMIN";
209 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
210 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
211 case MipsISD::VNOR: return "MipsISD::VNOR";
212 case MipsISD::VSHF: return "MipsISD::VSHF";
213 case MipsISD::SHF: return "MipsISD::SHF";
214 case MipsISD::ILVEV: return "MipsISD::ILVEV";
215 case MipsISD::ILVOD: return "MipsISD::ILVOD";
216 case MipsISD::ILVL: return "MipsISD::ILVL";
217 case MipsISD::ILVR: return "MipsISD::ILVR";
218 case MipsISD::PCKEV: return "MipsISD::PCKEV";
219 case MipsISD::PCKOD: return "MipsISD::PCKOD";
220 case MipsISD::INSVE: return "MipsISD::INSVE";
225 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
226 const MipsSubtarget &STI)
227 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
228 // Mips does not have i1 type, so use i32 for
229 // setcc operations results (slt, sgt, ...).
230 setBooleanContents(ZeroOrOneBooleanContent);
231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
232 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
233 // does. Integer booleans still use 0 and 1.
234 if (Subtarget.hasMips32r6())
235 setBooleanContents(ZeroOrOneBooleanContent,
236 ZeroOrNegativeOneBooleanContent);
238 // Load extented operations for i1 types must be promoted
239 for (MVT VT : MVT::integer_valuetypes()) {
240 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
241 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
242 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
245 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
247 for (MVT VT : MVT::fp_valuetypes()) {
248 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
249 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
252 // Set LoadExtAction for f16 vectors to Expand
253 for (MVT VT : MVT::fp_vector_valuetypes()) {
254 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
256 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
259 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
260 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
262 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
264 // Used by legalize types to correctly generate the setcc result.
265 // Without this, every float setcc comes with a AND/OR with the result,
266 // we don't want this, since the fpcmp result goes to a flag register,
267 // which is used implicitly by brcond and select operations.
268 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
270 // Mips Custom Operations
271 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
272 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
273 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
274 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
275 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
276 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
277 setOperationAction(ISD::SELECT, MVT::f32, Custom);
278 setOperationAction(ISD::SELECT, MVT::f64, Custom);
279 setOperationAction(ISD::SELECT, MVT::i32, Custom);
280 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
281 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
282 setOperationAction(ISD::SETCC, MVT::f32, Custom);
283 setOperationAction(ISD::SETCC, MVT::f64, Custom);
284 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
286 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
287 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
289 if (Subtarget.isGP64bit()) {
290 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
291 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
292 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
293 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
294 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
295 setOperationAction(ISD::SELECT, MVT::i64, Custom);
296 setOperationAction(ISD::LOAD, MVT::i64, Custom);
297 setOperationAction(ISD::STORE, MVT::i64, Custom);
298 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
299 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
300 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
301 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
304 if (!Subtarget.isGP64bit()) {
305 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
306 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
307 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
310 setOperationAction(ISD::ADD, MVT::i32, Custom);
311 if (Subtarget.isGP64bit())
312 setOperationAction(ISD::ADD, MVT::i64, Custom);
314 setOperationAction(ISD::SDIV, MVT::i32, Expand);
315 setOperationAction(ISD::SREM, MVT::i32, Expand);
316 setOperationAction(ISD::UDIV, MVT::i32, Expand);
317 setOperationAction(ISD::UREM, MVT::i32, Expand);
318 setOperationAction(ISD::SDIV, MVT::i64, Expand);
319 setOperationAction(ISD::SREM, MVT::i64, Expand);
320 setOperationAction(ISD::UDIV, MVT::i64, Expand);
321 setOperationAction(ISD::UREM, MVT::i64, Expand);
323 // Operations not directly supported by Mips.
324 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
325 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
326 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
327 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
328 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
329 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
330 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
331 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
332 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
333 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
334 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
335 if (Subtarget.hasCnMips()) {
336 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
337 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
339 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
340 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
342 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
343 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
344 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
345 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
347 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
348 setOperationAction(ISD::ROTL, MVT::i32, Expand);
349 setOperationAction(ISD::ROTL, MVT::i64, Expand);
350 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
351 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
353 if (!Subtarget.hasMips32r2())
354 setOperationAction(ISD::ROTR, MVT::i32, Expand);
356 if (!Subtarget.hasMips64r2())
357 setOperationAction(ISD::ROTR, MVT::i64, Expand);
359 setOperationAction(ISD::FSIN, MVT::f32, Expand);
360 setOperationAction(ISD::FSIN, MVT::f64, Expand);
361 setOperationAction(ISD::FCOS, MVT::f32, Expand);
362 setOperationAction(ISD::FCOS, MVT::f64, Expand);
363 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
364 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
365 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
366 setOperationAction(ISD::FPOW, MVT::f32, Expand);
367 setOperationAction(ISD::FPOW, MVT::f64, Expand);
368 setOperationAction(ISD::FLOG, MVT::f32, Expand);
369 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
370 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
371 setOperationAction(ISD::FEXP, MVT::f32, Expand);
372 setOperationAction(ISD::FMA, MVT::f32, Expand);
373 setOperationAction(ISD::FMA, MVT::f64, Expand);
374 setOperationAction(ISD::FREM, MVT::f32, Expand);
375 setOperationAction(ISD::FREM, MVT::f64, Expand);
377 // Lower f16 conversion operations into library calls
378 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
380 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
381 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
383 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
385 setOperationAction(ISD::VASTART, MVT::Other, Custom);
386 setOperationAction(ISD::VAARG, MVT::Other, Custom);
387 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
388 setOperationAction(ISD::VAEND, MVT::Other, Expand);
390 // Use the default for now
391 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
392 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
394 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
395 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
396 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
397 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
399 setInsertFencesForAtomic(true);
401 if (!Subtarget.hasMips32r2()) {
402 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
403 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
406 // MIPS16 lacks MIPS32's clz and clo instructions.
407 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
408 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
409 if (!Subtarget.hasMips64())
410 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
412 if (!Subtarget.hasMips32r2())
413 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
414 if (!Subtarget.hasMips64r2())
415 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
417 if (Subtarget.isGP64bit()) {
418 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
419 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
420 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
421 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
424 setOperationAction(ISD::TRAP, MVT::Other, Legal);
426 setTargetDAGCombine(ISD::SDIVREM);
427 setTargetDAGCombine(ISD::UDIVREM);
428 setTargetDAGCombine(ISD::SELECT);
429 setTargetDAGCombine(ISD::AND);
430 setTargetDAGCombine(ISD::OR);
431 setTargetDAGCombine(ISD::ADD);
433 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
435 // The arguments on the stack are defined in terms of 4-byte slots on O32
436 // and 8-byte slots on N32/N64.
437 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
439 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
441 setExceptionPointerRegister(ABI.IsN64() ? Mips::A0_64 : Mips::A0);
442 setExceptionSelectorRegister(ABI.IsN64() ? Mips::A1_64 : Mips::A1);
444 MaxStoresPerMemcpy = 16;
446 isMicroMips = Subtarget.inMicroMipsMode();
449 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
450 const MipsSubtarget &STI) {
451 if (STI.inMips16Mode())
452 return llvm::createMips16TargetLowering(TM, STI);
454 return llvm::createMipsSETargetLowering(TM, STI);
457 // Create a fast isel object.
459 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
460 const TargetLibraryInfo *libInfo) const {
461 if (!funcInfo.MF->getTarget().Options.EnableFastISel)
462 return TargetLowering::createFastISel(funcInfo, libInfo);
463 return Mips::createFastISel(funcInfo, libInfo);
466 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
470 return VT.changeVectorElementTypeToInteger();
473 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
474 TargetLowering::DAGCombinerInfo &DCI,
475 const MipsSubtarget &Subtarget) {
476 if (DCI.isBeforeLegalizeOps())
479 EVT Ty = N->getValueType(0);
480 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
481 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
482 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
486 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
487 N->getOperand(0), N->getOperand(1));
488 SDValue InChain = DAG.getEntryNode();
489 SDValue InGlue = DivRem;
492 if (N->hasAnyUseOfValue(0)) {
493 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
495 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
496 InChain = CopyFromLo.getValue(1);
497 InGlue = CopyFromLo.getValue(2);
501 if (N->hasAnyUseOfValue(1)) {
502 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
504 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
510 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
512 default: llvm_unreachable("Unknown fp condition code!");
514 case ISD::SETOEQ: return Mips::FCOND_OEQ;
515 case ISD::SETUNE: return Mips::FCOND_UNE;
517 case ISD::SETOLT: return Mips::FCOND_OLT;
519 case ISD::SETOGT: return Mips::FCOND_OGT;
521 case ISD::SETOLE: return Mips::FCOND_OLE;
523 case ISD::SETOGE: return Mips::FCOND_OGE;
524 case ISD::SETULT: return Mips::FCOND_ULT;
525 case ISD::SETULE: return Mips::FCOND_ULE;
526 case ISD::SETUGT: return Mips::FCOND_UGT;
527 case ISD::SETUGE: return Mips::FCOND_UGE;
528 case ISD::SETUO: return Mips::FCOND_UN;
529 case ISD::SETO: return Mips::FCOND_OR;
531 case ISD::SETONE: return Mips::FCOND_ONE;
532 case ISD::SETUEQ: return Mips::FCOND_UEQ;
537 /// This function returns true if the floating point conditional branches and
538 /// conditional moves which use condition code CC should be inverted.
539 static bool invertFPCondCodeUser(Mips::CondCode CC) {
540 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
543 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
544 "Illegal Condition Code");
549 // Creates and returns an FPCmp node from a setcc node.
550 // Returns Op if setcc is not a floating point comparison.
551 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
552 // must be a SETCC node
553 if (Op.getOpcode() != ISD::SETCC)
556 SDValue LHS = Op.getOperand(0);
558 if (!LHS.getValueType().isFloatingPoint())
561 SDValue RHS = Op.getOperand(1);
564 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
565 // node if necessary.
566 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
568 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
569 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
572 // Creates and returns a CMovFPT/F node.
573 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
574 SDValue False, SDLoc DL) {
575 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
576 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
577 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
579 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
580 True.getValueType(), True, FCC0, False, Cond);
583 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
584 TargetLowering::DAGCombinerInfo &DCI,
585 const MipsSubtarget &Subtarget) {
586 if (DCI.isBeforeLegalizeOps())
589 SDValue SetCC = N->getOperand(0);
591 if ((SetCC.getOpcode() != ISD::SETCC) ||
592 !SetCC.getOperand(0).getValueType().isInteger())
595 SDValue False = N->getOperand(2);
596 EVT FalseTy = False.getValueType();
598 if (!FalseTy.isInteger())
601 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
603 // If the RHS (False) is 0, we swap the order of the operands
604 // of ISD::SELECT (obviously also inverting the condition) so that we can
605 // take advantage of conditional moves using the $0 register.
607 // return (a != 0) ? x : 0;
615 if (!FalseC->getZExtValue()) {
616 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
617 SDValue True = N->getOperand(1);
619 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
620 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
622 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
625 // If both operands are integer constants there's a possibility that we
626 // can do some interesting optimizations.
627 SDValue True = N->getOperand(1);
628 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
630 if (!TrueC || !True.getValueType().isInteger())
633 // We'll also ignore MVT::i64 operands as this optimizations proves
634 // to be ineffective because of the required sign extensions as the result
635 // of a SETCC operator is always MVT::i32 for non-vector types.
636 if (True.getValueType() == MVT::i64)
639 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
641 // 1) (a < x) ? y : y-1
643 // addiu $reg2, $reg1, y-1
645 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
647 // 2) (a < x) ? y-1 : y
649 // xor $reg1, $reg1, 1
650 // addiu $reg2, $reg1, y-1
652 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
653 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
654 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
655 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
658 // Couldn't optimize.
662 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
663 TargetLowering::DAGCombinerInfo &DCI,
664 const MipsSubtarget &Subtarget) {
665 if (DCI.isBeforeLegalizeOps())
668 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
670 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
671 if (!FalseC || FalseC->getZExtValue())
674 // Since RHS (False) is 0, we swap the order of the True/False operands
675 // (obviously also inverting the condition) so that we can
676 // take advantage of conditional moves using the $0 register.
678 // return (a != 0) ? x : 0;
681 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
684 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
685 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
686 ValueIfFalse, FCC, ValueIfTrue, Glue);
689 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
690 TargetLowering::DAGCombinerInfo &DCI,
691 const MipsSubtarget &Subtarget) {
692 // Pattern match EXT.
693 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
694 // => ext $dst, $src, size, pos
695 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
698 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
699 unsigned ShiftRightOpc = ShiftRight.getOpcode();
701 // Op's first operand must be a shift right.
702 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
705 // The second operand of the shift must be an immediate.
707 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
710 uint64_t Pos = CN->getZExtValue();
711 uint64_t SMPos, SMSize;
713 // Op's second operand must be a shifted mask.
714 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
715 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
718 // Return if the shifted mask does not start at bit 0 or the sum of its size
719 // and Pos exceeds the word's size.
720 EVT ValTy = N->getValueType(0);
721 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
725 return DAG.getNode(MipsISD::Ext, DL, ValTy,
726 ShiftRight.getOperand(0),
727 DAG.getConstant(Pos, DL, MVT::i32),
728 DAG.getConstant(SMSize, DL, MVT::i32));
731 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
732 TargetLowering::DAGCombinerInfo &DCI,
733 const MipsSubtarget &Subtarget) {
734 // Pattern match INS.
735 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
736 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
737 // => ins $dst, $src, size, pos, $src1
738 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
741 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
742 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
745 // See if Op's first operand matches (and $src1 , mask0).
746 if (And0.getOpcode() != ISD::AND)
749 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
750 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
753 // See if Op's second operand matches (and (shl $src, pos), mask1).
754 if (And1.getOpcode() != ISD::AND)
757 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
758 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
761 // The shift masks must have the same position and size.
762 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
765 SDValue Shl = And1.getOperand(0);
766 if (Shl.getOpcode() != ISD::SHL)
769 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
772 unsigned Shamt = CN->getZExtValue();
774 // Return if the shift amount and the first bit position of mask are not the
776 EVT ValTy = N->getValueType(0);
777 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
781 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
782 DAG.getConstant(SMPos0, DL, MVT::i32),
783 DAG.getConstant(SMSize0, DL, MVT::i32),
787 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
788 TargetLowering::DAGCombinerInfo &DCI,
789 const MipsSubtarget &Subtarget) {
790 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
792 if (DCI.isBeforeLegalizeOps())
795 SDValue Add = N->getOperand(1);
797 if (Add.getOpcode() != ISD::ADD)
800 SDValue Lo = Add.getOperand(1);
802 if ((Lo.getOpcode() != MipsISD::Lo) ||
803 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
806 EVT ValTy = N->getValueType(0);
809 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
811 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
814 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
816 SelectionDAG &DAG = DCI.DAG;
817 unsigned Opc = N->getOpcode();
823 return performDivRemCombine(N, DAG, DCI, Subtarget);
825 return performSELECTCombine(N, DAG, DCI, Subtarget);
826 case MipsISD::CMovFP_F:
827 case MipsISD::CMovFP_T:
828 return performCMovFPCombine(N, DAG, DCI, Subtarget);
830 return performANDCombine(N, DAG, DCI, Subtarget);
832 return performORCombine(N, DAG, DCI, Subtarget);
834 return performADDCombine(N, DAG, DCI, Subtarget);
841 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
842 SmallVectorImpl<SDValue> &Results,
843 SelectionDAG &DAG) const {
844 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
846 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
847 Results.push_back(Res.getValue(I));
851 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
852 SmallVectorImpl<SDValue> &Results,
853 SelectionDAG &DAG) const {
854 return LowerOperationWrapper(N, Results, DAG);
857 SDValue MipsTargetLowering::
858 LowerOperation(SDValue Op, SelectionDAG &DAG) const
860 switch (Op.getOpcode())
862 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
863 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
864 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
865 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
866 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
867 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
868 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
869 case ISD::SELECT: return lowerSELECT(Op, DAG);
870 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
871 case ISD::SETCC: return lowerSETCC(Op, DAG);
872 case ISD::VASTART: return lowerVASTART(Op, DAG);
873 case ISD::VAARG: return lowerVAARG(Op, DAG);
874 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
875 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
876 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
877 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
878 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
879 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
880 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
881 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
882 case ISD::LOAD: return lowerLOAD(Op, DAG);
883 case ISD::STORE: return lowerSTORE(Op, DAG);
884 case ISD::ADD: return lowerADD(Op, DAG);
885 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
890 //===----------------------------------------------------------------------===//
891 // Lower helper functions
892 //===----------------------------------------------------------------------===//
894 // addLiveIn - This helper function adds the specified physical register to the
895 // MachineFunction as a live in value. It also creates a corresponding
896 // virtual register for it.
898 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
900 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
901 MF.getRegInfo().addLiveIn(PReg, VReg);
905 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
906 MachineBasicBlock &MBB,
907 const TargetInstrInfo &TII,
912 // Insert instruction "teq $divisor_reg, $zero, 7".
913 MachineBasicBlock::iterator I(MI);
914 MachineInstrBuilder MIB;
915 MachineOperand &Divisor = MI->getOperand(2);
916 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
917 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
918 .addReg(Mips::ZERO).addImm(7);
920 // Use the 32-bit sub-register if this is a 64-bit division.
922 MIB->getOperand(0).setSubReg(Mips::sub_32);
924 // Clear Divisor's kill flag.
925 Divisor.setIsKill(false);
927 // We would normally delete the original instruction here but in this case
928 // we only needed to inject an additional instruction rather than replace it.
934 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
935 MachineBasicBlock *BB) const {
936 switch (MI->getOpcode()) {
938 llvm_unreachable("Unexpected instr type to insert");
939 case Mips::ATOMIC_LOAD_ADD_I8:
940 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
941 case Mips::ATOMIC_LOAD_ADD_I16:
942 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
943 case Mips::ATOMIC_LOAD_ADD_I32:
944 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
945 case Mips::ATOMIC_LOAD_ADD_I64:
946 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
948 case Mips::ATOMIC_LOAD_AND_I8:
949 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
950 case Mips::ATOMIC_LOAD_AND_I16:
951 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
952 case Mips::ATOMIC_LOAD_AND_I32:
953 return emitAtomicBinary(MI, BB, 4, Mips::AND);
954 case Mips::ATOMIC_LOAD_AND_I64:
955 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
957 case Mips::ATOMIC_LOAD_OR_I8:
958 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
959 case Mips::ATOMIC_LOAD_OR_I16:
960 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
961 case Mips::ATOMIC_LOAD_OR_I32:
962 return emitAtomicBinary(MI, BB, 4, Mips::OR);
963 case Mips::ATOMIC_LOAD_OR_I64:
964 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
966 case Mips::ATOMIC_LOAD_XOR_I8:
967 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
968 case Mips::ATOMIC_LOAD_XOR_I16:
969 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
970 case Mips::ATOMIC_LOAD_XOR_I32:
971 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
972 case Mips::ATOMIC_LOAD_XOR_I64:
973 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
975 case Mips::ATOMIC_LOAD_NAND_I8:
976 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
977 case Mips::ATOMIC_LOAD_NAND_I16:
978 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
979 case Mips::ATOMIC_LOAD_NAND_I32:
980 return emitAtomicBinary(MI, BB, 4, 0, true);
981 case Mips::ATOMIC_LOAD_NAND_I64:
982 return emitAtomicBinary(MI, BB, 8, 0, true);
984 case Mips::ATOMIC_LOAD_SUB_I8:
985 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
986 case Mips::ATOMIC_LOAD_SUB_I16:
987 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
988 case Mips::ATOMIC_LOAD_SUB_I32:
989 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
990 case Mips::ATOMIC_LOAD_SUB_I64:
991 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
993 case Mips::ATOMIC_SWAP_I8:
994 return emitAtomicBinaryPartword(MI, BB, 1, 0);
995 case Mips::ATOMIC_SWAP_I16:
996 return emitAtomicBinaryPartword(MI, BB, 2, 0);
997 case Mips::ATOMIC_SWAP_I32:
998 return emitAtomicBinary(MI, BB, 4, 0);
999 case Mips::ATOMIC_SWAP_I64:
1000 return emitAtomicBinary(MI, BB, 8, 0);
1002 case Mips::ATOMIC_CMP_SWAP_I8:
1003 return emitAtomicCmpSwapPartword(MI, BB, 1);
1004 case Mips::ATOMIC_CMP_SWAP_I16:
1005 return emitAtomicCmpSwapPartword(MI, BB, 2);
1006 case Mips::ATOMIC_CMP_SWAP_I32:
1007 return emitAtomicCmpSwap(MI, BB, 4);
1008 case Mips::ATOMIC_CMP_SWAP_I64:
1009 return emitAtomicCmpSwap(MI, BB, 8);
1010 case Mips::PseudoSDIV:
1011 case Mips::PseudoUDIV:
1016 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
1017 case Mips::PseudoDSDIV:
1018 case Mips::PseudoDUDIV:
1023 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
1025 return emitSEL_D(MI, BB);
1027 case Mips::PseudoSELECT_I:
1028 case Mips::PseudoSELECT_I64:
1029 case Mips::PseudoSELECT_S:
1030 case Mips::PseudoSELECT_D32:
1031 case Mips::PseudoSELECT_D64:
1032 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1033 case Mips::PseudoSELECTFP_F_I:
1034 case Mips::PseudoSELECTFP_F_I64:
1035 case Mips::PseudoSELECTFP_F_S:
1036 case Mips::PseudoSELECTFP_F_D32:
1037 case Mips::PseudoSELECTFP_F_D64:
1038 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1039 case Mips::PseudoSELECTFP_T_I:
1040 case Mips::PseudoSELECTFP_T_I64:
1041 case Mips::PseudoSELECTFP_T_S:
1042 case Mips::PseudoSELECTFP_T_D32:
1043 case Mips::PseudoSELECTFP_T_D64:
1044 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1048 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1049 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1051 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1052 unsigned Size, unsigned BinOpcode,
1054 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1056 MachineFunction *MF = BB->getParent();
1057 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1058 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1059 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1060 DebugLoc DL = MI->getDebugLoc();
1061 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1068 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1069 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1076 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1077 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1080 ZERO = Mips::ZERO_64;
1084 unsigned OldVal = MI->getOperand(0).getReg();
1085 unsigned Ptr = MI->getOperand(1).getReg();
1086 unsigned Incr = MI->getOperand(2).getReg();
1088 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1089 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1090 unsigned Success = RegInfo.createVirtualRegister(RC);
1092 // insert new blocks after the current block
1093 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1094 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1095 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1096 MachineFunction::iterator It = ++BB->getIterator();
1097 MF->insert(It, loopMBB);
1098 MF->insert(It, exitMBB);
1100 // Transfer the remainder of BB and its successor edges to exitMBB.
1101 exitMBB->splice(exitMBB->begin(), BB,
1102 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1103 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1107 // fallthrough --> loopMBB
1108 BB->addSuccessor(loopMBB);
1109 loopMBB->addSuccessor(loopMBB);
1110 loopMBB->addSuccessor(exitMBB);
1113 // ll oldval, 0(ptr)
1114 // <binop> storeval, oldval, incr
1115 // sc success, storeval, 0(ptr)
1116 // beq success, $0, loopMBB
1118 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1120 // and andres, oldval, incr
1121 // nor storeval, $0, andres
1122 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1123 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1124 } else if (BinOpcode) {
1125 // <binop> storeval, oldval, incr
1126 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1130 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1131 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1133 MI->eraseFromParent(); // The instruction is gone now.
1138 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1139 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1140 unsigned SrcReg) const {
1141 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1142 DebugLoc DL = MI->getDebugLoc();
1144 if (Subtarget.hasMips32r2() && Size == 1) {
1145 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1149 if (Subtarget.hasMips32r2() && Size == 2) {
1150 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1154 MachineFunction *MF = BB->getParent();
1155 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1156 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1157 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1160 int64_t ShiftImm = 32 - (Size * 8);
1162 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1163 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1168 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1169 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1171 assert((Size == 1 || Size == 2) &&
1172 "Unsupported size for EmitAtomicBinaryPartial.");
1174 MachineFunction *MF = BB->getParent();
1175 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1176 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1177 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1178 DebugLoc DL = MI->getDebugLoc();
1180 unsigned Dest = MI->getOperand(0).getReg();
1181 unsigned Ptr = MI->getOperand(1).getReg();
1182 unsigned Incr = MI->getOperand(2).getReg();
1184 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1185 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1186 unsigned Mask = RegInfo.createVirtualRegister(RC);
1187 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1188 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1189 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1190 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1191 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1192 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1193 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1194 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1195 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1196 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1197 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1198 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1199 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1200 unsigned Success = RegInfo.createVirtualRegister(RC);
1202 // insert new blocks after the current block
1203 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1204 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1205 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1206 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1207 MachineFunction::iterator It = ++BB->getIterator();
1208 MF->insert(It, loopMBB);
1209 MF->insert(It, sinkMBB);
1210 MF->insert(It, exitMBB);
1212 // Transfer the remainder of BB and its successor edges to exitMBB.
1213 exitMBB->splice(exitMBB->begin(), BB,
1214 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1215 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1217 BB->addSuccessor(loopMBB);
1218 loopMBB->addSuccessor(loopMBB);
1219 loopMBB->addSuccessor(sinkMBB);
1220 sinkMBB->addSuccessor(exitMBB);
1223 // addiu masklsb2,$0,-4 # 0xfffffffc
1224 // and alignedaddr,ptr,masklsb2
1225 // andi ptrlsb2,ptr,3
1226 // sll shiftamt,ptrlsb2,3
1227 // ori maskupper,$0,255 # 0xff
1228 // sll mask,maskupper,shiftamt
1229 // nor mask2,$0,mask
1230 // sll incr2,incr,shiftamt
1232 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1233 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1234 .addReg(Mips::ZERO).addImm(-4);
1235 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1236 .addReg(Ptr).addReg(MaskLSB2);
1237 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1238 if (Subtarget.isLittle()) {
1239 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1241 unsigned Off = RegInfo.createVirtualRegister(RC);
1242 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1243 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1244 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1246 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1247 .addReg(Mips::ZERO).addImm(MaskImm);
1248 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1249 .addReg(MaskUpper).addReg(ShiftAmt);
1250 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1251 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1253 // atomic.load.binop
1255 // ll oldval,0(alignedaddr)
1256 // binop binopres,oldval,incr2
1257 // and newval,binopres,mask
1258 // and maskedoldval0,oldval,mask2
1259 // or storeval,maskedoldval0,newval
1260 // sc success,storeval,0(alignedaddr)
1261 // beq success,$0,loopMBB
1265 // ll oldval,0(alignedaddr)
1266 // and newval,incr2,mask
1267 // and maskedoldval0,oldval,mask2
1268 // or storeval,maskedoldval0,newval
1269 // sc success,storeval,0(alignedaddr)
1270 // beq success,$0,loopMBB
1273 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1274 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1276 // and andres, oldval, incr2
1277 // nor binopres, $0, andres
1278 // and newval, binopres, mask
1279 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1280 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1281 .addReg(Mips::ZERO).addReg(AndRes);
1282 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1283 } else if (BinOpcode) {
1284 // <binop> binopres, oldval, incr2
1285 // and newval, binopres, mask
1286 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1287 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1288 } else { // atomic.swap
1289 // and newval, incr2, mask
1290 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1293 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1294 .addReg(OldVal).addReg(Mask2);
1295 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1296 .addReg(MaskedOldVal0).addReg(NewVal);
1297 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1298 BuildMI(BB, DL, TII->get(SC), Success)
1299 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1300 BuildMI(BB, DL, TII->get(Mips::BEQ))
1301 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1304 // and maskedoldval1,oldval,mask
1305 // srl srlres,maskedoldval1,shiftamt
1306 // sign_extend dest,srlres
1309 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1310 .addReg(OldVal).addReg(Mask);
1311 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1312 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1313 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1315 MI->eraseFromParent(); // The instruction is gone now.
1320 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1321 MachineBasicBlock *BB,
1322 unsigned Size) const {
1323 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1325 MachineFunction *MF = BB->getParent();
1326 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1327 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1328 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1329 DebugLoc DL = MI->getDebugLoc();
1330 unsigned LL, SC, ZERO, BNE, BEQ;
1337 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1338 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1344 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1345 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1346 ZERO = Mips::ZERO_64;
1351 unsigned Dest = MI->getOperand(0).getReg();
1352 unsigned Ptr = MI->getOperand(1).getReg();
1353 unsigned OldVal = MI->getOperand(2).getReg();
1354 unsigned NewVal = MI->getOperand(3).getReg();
1356 unsigned Success = RegInfo.createVirtualRegister(RC);
1358 // insert new blocks after the current block
1359 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1360 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1361 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1362 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1363 MachineFunction::iterator It = ++BB->getIterator();
1364 MF->insert(It, loop1MBB);
1365 MF->insert(It, loop2MBB);
1366 MF->insert(It, exitMBB);
1368 // Transfer the remainder of BB and its successor edges to exitMBB.
1369 exitMBB->splice(exitMBB->begin(), BB,
1370 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1371 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1375 // fallthrough --> loop1MBB
1376 BB->addSuccessor(loop1MBB);
1377 loop1MBB->addSuccessor(exitMBB);
1378 loop1MBB->addSuccessor(loop2MBB);
1379 loop2MBB->addSuccessor(loop1MBB);
1380 loop2MBB->addSuccessor(exitMBB);
1384 // bne dest, oldval, exitMBB
1386 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1387 BuildMI(BB, DL, TII->get(BNE))
1388 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1391 // sc success, newval, 0(ptr)
1392 // beq success, $0, loop1MBB
1394 BuildMI(BB, DL, TII->get(SC), Success)
1395 .addReg(NewVal).addReg(Ptr).addImm(0);
1396 BuildMI(BB, DL, TII->get(BEQ))
1397 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1399 MI->eraseFromParent(); // The instruction is gone now.
1405 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1406 MachineBasicBlock *BB,
1407 unsigned Size) const {
1408 assert((Size == 1 || Size == 2) &&
1409 "Unsupported size for EmitAtomicCmpSwapPartial.");
1411 MachineFunction *MF = BB->getParent();
1412 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1413 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1414 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1415 DebugLoc DL = MI->getDebugLoc();
1417 unsigned Dest = MI->getOperand(0).getReg();
1418 unsigned Ptr = MI->getOperand(1).getReg();
1419 unsigned CmpVal = MI->getOperand(2).getReg();
1420 unsigned NewVal = MI->getOperand(3).getReg();
1422 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1423 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1424 unsigned Mask = RegInfo.createVirtualRegister(RC);
1425 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1426 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1427 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1428 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1429 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1430 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1431 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1432 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1433 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1434 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1435 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1436 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1437 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1438 unsigned Success = RegInfo.createVirtualRegister(RC);
1440 // insert new blocks after the current block
1441 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1442 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1443 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1444 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1445 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1446 MachineFunction::iterator It = ++BB->getIterator();
1447 MF->insert(It, loop1MBB);
1448 MF->insert(It, loop2MBB);
1449 MF->insert(It, sinkMBB);
1450 MF->insert(It, exitMBB);
1452 // Transfer the remainder of BB and its successor edges to exitMBB.
1453 exitMBB->splice(exitMBB->begin(), BB,
1454 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1455 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1457 BB->addSuccessor(loop1MBB);
1458 loop1MBB->addSuccessor(sinkMBB);
1459 loop1MBB->addSuccessor(loop2MBB);
1460 loop2MBB->addSuccessor(loop1MBB);
1461 loop2MBB->addSuccessor(sinkMBB);
1462 sinkMBB->addSuccessor(exitMBB);
1464 // FIXME: computation of newval2 can be moved to loop2MBB.
1466 // addiu masklsb2,$0,-4 # 0xfffffffc
1467 // and alignedaddr,ptr,masklsb2
1468 // andi ptrlsb2,ptr,3
1469 // sll shiftamt,ptrlsb2,3
1470 // ori maskupper,$0,255 # 0xff
1471 // sll mask,maskupper,shiftamt
1472 // nor mask2,$0,mask
1473 // andi maskedcmpval,cmpval,255
1474 // sll shiftedcmpval,maskedcmpval,shiftamt
1475 // andi maskednewval,newval,255
1476 // sll shiftednewval,maskednewval,shiftamt
1477 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1478 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1479 .addReg(Mips::ZERO).addImm(-4);
1480 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1481 .addReg(Ptr).addReg(MaskLSB2);
1482 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1483 if (Subtarget.isLittle()) {
1484 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1486 unsigned Off = RegInfo.createVirtualRegister(RC);
1487 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1488 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1489 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1491 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1492 .addReg(Mips::ZERO).addImm(MaskImm);
1493 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1494 .addReg(MaskUpper).addReg(ShiftAmt);
1495 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1496 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1497 .addReg(CmpVal).addImm(MaskImm);
1498 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1499 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1500 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1501 .addReg(NewVal).addImm(MaskImm);
1502 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1503 .addReg(MaskedNewVal).addReg(ShiftAmt);
1506 // ll oldval,0(alginedaddr)
1507 // and maskedoldval0,oldval,mask
1508 // bne maskedoldval0,shiftedcmpval,sinkMBB
1510 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1511 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1512 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1513 .addReg(OldVal).addReg(Mask);
1514 BuildMI(BB, DL, TII->get(Mips::BNE))
1515 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1518 // and maskedoldval1,oldval,mask2
1519 // or storeval,maskedoldval1,shiftednewval
1520 // sc success,storeval,0(alignedaddr)
1521 // beq success,$0,loop1MBB
1523 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1524 .addReg(OldVal).addReg(Mask2);
1525 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1526 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1527 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1528 BuildMI(BB, DL, TII->get(SC), Success)
1529 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1530 BuildMI(BB, DL, TII->get(Mips::BEQ))
1531 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1534 // srl srlres,maskedoldval0,shiftamt
1535 // sign_extend dest,srlres
1538 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1539 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1540 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1542 MI->eraseFromParent(); // The instruction is gone now.
1547 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1548 MachineBasicBlock *BB) const {
1549 MachineFunction *MF = BB->getParent();
1550 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1551 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1552 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1553 DebugLoc DL = MI->getDebugLoc();
1554 MachineBasicBlock::iterator II(MI);
1556 unsigned Fc = MI->getOperand(1).getReg();
1557 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1559 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1561 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1564 .addImm(Mips::sub_lo);
1566 // We don't erase the original instruction, we just replace the condition
1567 // register with the 64-bit super-register.
1568 MI->getOperand(1).setReg(Fc2);
1573 //===----------------------------------------------------------------------===//
1574 // Misc Lower Operation implementation
1575 //===----------------------------------------------------------------------===//
1576 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1577 SDValue Chain = Op.getOperand(0);
1578 SDValue Table = Op.getOperand(1);
1579 SDValue Index = Op.getOperand(2);
1581 auto &TD = DAG.getDataLayout();
1582 EVT PTy = getPointerTy(TD);
1583 unsigned EntrySize =
1584 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
1586 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1587 DAG.getConstant(EntrySize, DL, PTy));
1588 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1590 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1592 DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1593 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
1594 MemVT, false, false, false, 0);
1595 Chain = Addr.getValue(1);
1597 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1598 // For PIC, the sequence is:
1599 // BRIND(load(Jumptable + index) + RelocBase)
1600 // RelocBase can be JumpTable, GOT or some sort of global base.
1601 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1602 getPICJumpTableRelocBase(Table, DAG));
1605 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1608 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1609 // The first operand is the chain, the second is the condition, the third is
1610 // the block to branch to if the condition is true.
1611 SDValue Chain = Op.getOperand(0);
1612 SDValue Dest = Op.getOperand(2);
1615 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1616 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1618 // Return if flag is not set by a floating point comparison.
1619 if (CondRes.getOpcode() != MipsISD::FPCmp)
1622 SDValue CCNode = CondRes.getOperand(2);
1624 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1625 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1626 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1627 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1628 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1629 FCC0, Dest, CondRes);
1632 SDValue MipsTargetLowering::
1633 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1635 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1636 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1638 // Return if flag is not set by a floating point comparison.
1639 if (Cond.getOpcode() != MipsISD::FPCmp)
1642 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1646 SDValue MipsTargetLowering::
1647 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1650 EVT Ty = Op.getOperand(0).getValueType();
1652 DAG.getNode(ISD::SETCC, DL, getSetCCResultType(DAG.getDataLayout(),
1653 *DAG.getContext(), Ty),
1654 Op.getOperand(0), Op.getOperand(1), Op.getOperand(4));
1656 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1660 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1661 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1662 SDValue Cond = createFPCmp(DAG, Op);
1664 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1665 "Floating point operand expected.");
1668 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1669 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1671 return createCMovFP(DAG, Cond, True, False, DL);
1674 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1675 SelectionDAG &DAG) const {
1676 EVT Ty = Op.getValueType();
1677 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1678 const GlobalValue *GV = N->getGlobal();
1680 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1681 const MipsTargetObjectFile *TLOF =
1682 static_cast<const MipsTargetObjectFile *>(
1683 getTargetMachine().getObjFileLowering());
1684 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1685 // %gp_rel relocation
1686 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1688 // %hi/%lo relocation
1689 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1692 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1693 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1696 return getAddrGlobalLargeGOT(
1697 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
1699 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1701 return getAddrGlobal(
1702 N, SDLoc(N), Ty, DAG,
1703 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1704 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1707 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1708 SelectionDAG &DAG) const {
1709 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1710 EVT Ty = Op.getValueType();
1712 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1713 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1715 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1718 SDValue MipsTargetLowering::
1719 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1721 // If the relocation model is PIC, use the General Dynamic TLS Model or
1722 // Local Dynamic TLS model, otherwise use the Initial Exec or
1723 // Local Exec TLS Model.
1725 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1726 if (DAG.getTarget().Options.EmulatedTLS)
1727 return LowerToTLSEmulatedModel(GA, DAG);
1730 const GlobalValue *GV = GA->getGlobal();
1731 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1733 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1735 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1736 // General Dynamic and Local Dynamic TLS Model.
1737 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1740 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1741 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1742 getGlobalReg(DAG, PtrVT), TGA);
1743 unsigned PtrSize = PtrVT.getSizeInBits();
1744 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1746 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1750 Entry.Node = Argument;
1752 Args.push_back(Entry);
1754 TargetLowering::CallLoweringInfo CLI(DAG);
1755 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1756 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1757 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1759 SDValue Ret = CallResult.first;
1761 if (model != TLSModel::LocalDynamic)
1764 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1765 MipsII::MO_DTPREL_HI);
1766 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1767 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1768 MipsII::MO_DTPREL_LO);
1769 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1770 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1771 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1775 if (model == TLSModel::InitialExec) {
1776 // Initial Exec TLS Model
1777 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1778 MipsII::MO_GOTTPREL);
1779 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1781 Offset = DAG.getLoad(PtrVT, DL,
1782 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1783 false, false, false, 0);
1785 // Local Exec TLS Model
1786 assert(model == TLSModel::LocalExec);
1787 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1788 MipsII::MO_TPREL_HI);
1789 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1790 MipsII::MO_TPREL_LO);
1791 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1792 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1793 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1796 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1797 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1800 SDValue MipsTargetLowering::
1801 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1803 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1804 EVT Ty = Op.getValueType();
1806 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1807 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1809 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1812 SDValue MipsTargetLowering::
1813 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1815 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1816 EVT Ty = Op.getValueType();
1818 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1819 const MipsTargetObjectFile *TLOF =
1820 static_cast<const MipsTargetObjectFile *>(
1821 getTargetMachine().getObjFileLowering());
1823 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
1824 getTargetMachine()))
1825 // %gp_rel relocation
1826 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1828 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1831 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1834 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1835 MachineFunction &MF = DAG.getMachineFunction();
1836 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1839 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1840 getPointerTy(MF.getDataLayout()));
1842 // vastart just stores the address of the VarArgsFrameIndex slot into the
1843 // memory location argument.
1844 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1845 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1846 MachinePointerInfo(SV), false, false, 0);
1849 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1850 SDNode *Node = Op.getNode();
1851 EVT VT = Node->getValueType(0);
1852 SDValue Chain = Node->getOperand(0);
1853 SDValue VAListPtr = Node->getOperand(1);
1854 unsigned Align = Node->getConstantOperandVal(3);
1855 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1857 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1859 SDValue VAListLoad =
1860 DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, VAListPtr,
1861 MachinePointerInfo(SV), false, false, false, 0);
1862 SDValue VAList = VAListLoad;
1864 // Re-align the pointer if necessary.
1865 // It should only ever be necessary for 64-bit types on O32 since the minimum
1866 // argument alignment is the same as the maximum type alignment for N32/N64.
1868 // FIXME: We currently align too often. The code generator doesn't notice
1869 // when the pointer is still aligned from the last va_arg (or pair of
1870 // va_args for the i64 on O32 case).
1871 if (Align > getMinStackArgumentAlignment()) {
1872 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1874 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1875 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
1877 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1878 DAG.getConstant(-(int64_t)Align, DL,
1879 VAList.getValueType()));
1882 // Increment the pointer, VAList, to the next vaarg.
1883 auto &TD = DAG.getDataLayout();
1884 unsigned ArgSizeInBytes =
1885 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1886 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1887 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes,
1888 ArgSlotSizeInBytes),
1889 DL, VAList.getValueType()));
1890 // Store the incremented VAList to the legalized pointer
1891 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1892 MachinePointerInfo(SV), false, false, 0);
1894 // In big-endian mode we must adjust the pointer when the load size is smaller
1895 // than the argument slot size. We must also reduce the known alignment to
1896 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1897 // the correct half of the slot, and reduce the alignment from 8 (slot
1898 // alignment) down to 4 (type alignment).
1899 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1900 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1901 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1902 DAG.getIntPtrConstant(Adjustment, DL));
1904 // Load the actual argument out of the pointer VAList
1905 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1909 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1910 bool HasExtractInsert) {
1911 EVT TyX = Op.getOperand(0).getValueType();
1912 EVT TyY = Op.getOperand(1).getValueType();
1914 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1915 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
1918 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1920 SDValue X = (TyX == MVT::f32) ?
1921 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1922 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1924 SDValue Y = (TyY == MVT::f32) ?
1925 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1926 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1929 if (HasExtractInsert) {
1930 // ext E, Y, 31, 1 ; extract bit31 of Y
1931 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1932 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1933 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1936 // srl SrlX, SllX, 1
1938 // sll SllY, SrlX, 31
1939 // or Or, SrlX, SllY
1940 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1941 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1942 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1943 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1944 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1947 if (TyX == MVT::f32)
1948 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1950 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1952 DAG.getConstant(0, DL, MVT::i32));
1953 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1956 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1957 bool HasExtractInsert) {
1958 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1959 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1960 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1962 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1964 // Bitcast to integer nodes.
1965 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1966 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1968 if (HasExtractInsert) {
1969 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1970 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1971 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1972 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
1974 if (WidthX > WidthY)
1975 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1976 else if (WidthY > WidthX)
1977 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1979 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1980 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
1982 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1985 // (d)sll SllX, X, 1
1986 // (d)srl SrlX, SllX, 1
1987 // (d)srl SrlY, Y, width(Y)-1
1988 // (d)sll SllY, SrlX, width(Y)-1
1989 // or Or, SrlX, SllY
1990 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1991 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1992 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1993 DAG.getConstant(WidthY - 1, DL, MVT::i32));
1995 if (WidthX > WidthY)
1996 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1997 else if (WidthY > WidthX)
1998 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2000 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2001 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2002 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2003 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2007 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2008 if (Subtarget.isGP64bit())
2009 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2011 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2014 SDValue MipsTargetLowering::
2015 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2017 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2018 "Frame address can only be determined for current frame.");
2020 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2021 MFI->setFrameAddressIsTaken(true);
2022 EVT VT = Op.getValueType();
2024 SDValue FrameAddr = DAG.getCopyFromReg(
2025 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2029 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2030 SelectionDAG &DAG) const {
2031 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2035 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2036 "Return address can be determined only for current frame.");
2038 MachineFunction &MF = DAG.getMachineFunction();
2039 MachineFrameInfo *MFI = MF.getFrameInfo();
2040 MVT VT = Op.getSimpleValueType();
2041 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2042 MFI->setReturnAddressIsTaken(true);
2044 // Return RA, which contains the return address. Mark it an implicit live-in.
2045 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2046 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2049 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2050 // generated from __builtin_eh_return (offset, handler)
2051 // The effect of this is to adjust the stack pointer by "offset"
2052 // and then branch to "handler".
2053 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2055 MachineFunction &MF = DAG.getMachineFunction();
2056 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2058 MipsFI->setCallsEhReturn();
2059 SDValue Chain = Op.getOperand(0);
2060 SDValue Offset = Op.getOperand(1);
2061 SDValue Handler = Op.getOperand(2);
2063 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2065 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2066 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2067 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2068 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2069 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2070 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2071 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2072 DAG.getRegister(OffsetReg, Ty),
2073 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2077 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2078 SelectionDAG &DAG) const {
2079 // FIXME: Need pseudo-fence for 'singlethread' fences
2080 // FIXME: Set SType for weaker fences where supported/appropriate.
2083 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2084 DAG.getConstant(SType, DL, MVT::i32));
2087 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2088 SelectionDAG &DAG) const {
2090 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2092 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2093 SDValue Shamt = Op.getOperand(2);
2094 // if shamt < (VT.bits):
2095 // lo = (shl lo, shamt)
2096 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2099 // hi = (shl lo, shamt[4:0])
2100 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2101 DAG.getConstant(-1, DL, MVT::i32));
2102 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2103 DAG.getConstant(1, DL, VT));
2104 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2105 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2106 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2107 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2108 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2109 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2110 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2111 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2112 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2114 SDValue Ops[2] = {Lo, Hi};
2115 return DAG.getMergeValues(Ops, DL);
2118 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2121 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2122 SDValue Shamt = Op.getOperand(2);
2123 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2125 // if shamt < (VT.bits):
2126 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2128 // hi = (sra hi, shamt)
2130 // hi = (srl hi, shamt)
2133 // lo = (sra hi, shamt[4:0])
2134 // hi = (sra hi, 31)
2136 // lo = (srl hi, shamt[4:0])
2138 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2139 DAG.getConstant(-1, DL, MVT::i32));
2140 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2141 DAG.getConstant(1, DL, VT));
2142 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2143 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2144 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2145 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2147 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2148 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2149 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2150 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2151 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2152 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2153 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2155 SDValue Ops[2] = {Lo, Hi};
2156 return DAG.getMergeValues(Ops, DL);
2159 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2160 SDValue Chain, SDValue Src, unsigned Offset) {
2161 SDValue Ptr = LD->getBasePtr();
2162 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2163 EVT BasePtrVT = Ptr.getValueType();
2165 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2168 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2169 DAG.getConstant(Offset, DL, BasePtrVT));
2171 SDValue Ops[] = { Chain, Ptr, Src };
2172 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2173 LD->getMemOperand());
2176 // Expand an unaligned 32 or 64-bit integer load node.
2177 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2178 LoadSDNode *LD = cast<LoadSDNode>(Op);
2179 EVT MemVT = LD->getMemoryVT();
2181 if (Subtarget.systemSupportsUnalignedAccess())
2184 // Return if load is aligned or if MemVT is neither i32 nor i64.
2185 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2186 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2189 bool IsLittle = Subtarget.isLittle();
2190 EVT VT = Op.getValueType();
2191 ISD::LoadExtType ExtType = LD->getExtensionType();
2192 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2194 assert((VT == MVT::i32) || (VT == MVT::i64));
2197 // (set dst, (i64 (load baseptr)))
2199 // (set tmp, (ldl (add baseptr, 7), undef))
2200 // (set dst, (ldr baseptr, tmp))
2201 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2202 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2204 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2208 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2210 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2214 // (set dst, (i32 (load baseptr))) or
2215 // (set dst, (i64 (sextload baseptr))) or
2216 // (set dst, (i64 (extload baseptr)))
2218 // (set tmp, (lwl (add baseptr, 3), undef))
2219 // (set dst, (lwr baseptr, tmp))
2220 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2221 (ExtType == ISD::EXTLOAD))
2224 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2227 // (set dst, (i64 (zextload baseptr)))
2229 // (set tmp0, (lwl (add baseptr, 3), undef))
2230 // (set tmp1, (lwr baseptr, tmp0))
2231 // (set tmp2, (shl tmp1, 32))
2232 // (set dst, (srl tmp2, 32))
2234 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2235 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2236 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2237 SDValue Ops[] = { SRL, LWR.getValue(1) };
2238 return DAG.getMergeValues(Ops, DL);
2241 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2242 SDValue Chain, unsigned Offset) {
2243 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2244 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2246 SDVTList VTList = DAG.getVTList(MVT::Other);
2249 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2250 DAG.getConstant(Offset, DL, BasePtrVT));
2252 SDValue Ops[] = { Chain, Value, Ptr };
2253 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2254 SD->getMemOperand());
2257 // Expand an unaligned 32 or 64-bit integer store node.
2258 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2260 SDValue Value = SD->getValue(), Chain = SD->getChain();
2261 EVT VT = Value.getValueType();
2264 // (store val, baseptr) or
2265 // (truncstore val, baseptr)
2267 // (swl val, (add baseptr, 3))
2268 // (swr val, baseptr)
2269 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2270 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2272 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2275 assert(VT == MVT::i64);
2278 // (store val, baseptr)
2280 // (sdl val, (add baseptr, 7))
2281 // (sdr val, baseptr)
2282 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2283 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2286 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2287 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2288 SDValue Val = SD->getValue();
2290 if (Val.getOpcode() != ISD::FP_TO_SINT)
2293 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2294 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2297 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2298 SD->getPointerInfo(), SD->isVolatile(),
2299 SD->isNonTemporal(), SD->getAlignment());
2302 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2303 StoreSDNode *SD = cast<StoreSDNode>(Op);
2304 EVT MemVT = SD->getMemoryVT();
2306 // Lower unaligned integer stores.
2307 if (!Subtarget.systemSupportsUnalignedAccess() &&
2308 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2309 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2310 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2312 return lowerFP_TO_SINT_STORE(SD, DAG);
2315 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2316 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2317 || cast<ConstantSDNode>
2318 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2319 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2323 // (add (frameaddr 0), (frame_to_args_offset))
2324 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2325 // (add FrameObject, 0)
2326 // where FrameObject is a fixed StackObject with offset 0 which points to
2327 // the old stack pointer.
2328 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2329 EVT ValTy = Op->getValueType(0);
2330 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2331 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2333 return DAG.getNode(ISD::ADD, DL, ValTy, InArgsAddr,
2334 DAG.getConstant(0, DL, ValTy));
2337 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2338 SelectionDAG &DAG) const {
2339 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2340 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2342 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2345 //===----------------------------------------------------------------------===//
2346 // Calling Convention Implementation
2347 //===----------------------------------------------------------------------===//
2349 //===----------------------------------------------------------------------===//
2350 // TODO: Implement a generic logic using tblgen that can support this.
2351 // Mips O32 ABI rules:
2353 // i32 - Passed in A0, A1, A2, A3 and stack
2354 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2355 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2356 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2357 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2358 // not used, it must be shadowed. If only A3 is available, shadow it and
2361 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2362 //===----------------------------------------------------------------------===//
2364 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2365 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2366 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2367 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2368 State.getMachineFunction().getSubtarget());
2370 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2371 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2373 // Do not process byval args here.
2374 if (ArgFlags.isByVal())
2377 // Promote i8 and i16
2378 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2379 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2381 if (ArgFlags.isSExt())
2382 LocInfo = CCValAssign::SExtUpper;
2383 else if (ArgFlags.isZExt())
2384 LocInfo = CCValAssign::ZExtUpper;
2386 LocInfo = CCValAssign::AExtUpper;
2390 // Promote i8 and i16
2391 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2393 if (ArgFlags.isSExt())
2394 LocInfo = CCValAssign::SExt;
2395 else if (ArgFlags.isZExt())
2396 LocInfo = CCValAssign::ZExt;
2398 LocInfo = CCValAssign::AExt;
2403 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2404 // is true: function is vararg, argument is 3rd or higher, there is previous
2405 // argument which is not f32 or f64.
2406 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2407 State.getFirstUnallocated(F32Regs) != ValNo;
2408 unsigned OrigAlign = ArgFlags.getOrigAlign();
2409 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2411 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2412 Reg = State.AllocateReg(IntRegs);
2413 // If this is the first part of an i64 arg,
2414 // the allocated register must be either A0 or A2.
2415 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2416 Reg = State.AllocateReg(IntRegs);
2418 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2419 // Allocate int register and shadow next int register. If first
2420 // available register is Mips::A1 or Mips::A3, shadow it too.
2421 Reg = State.AllocateReg(IntRegs);
2422 if (Reg == Mips::A1 || Reg == Mips::A3)
2423 Reg = State.AllocateReg(IntRegs);
2424 State.AllocateReg(IntRegs);
2426 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2427 // we are guaranteed to find an available float register
2428 if (ValVT == MVT::f32) {
2429 Reg = State.AllocateReg(F32Regs);
2430 // Shadow int register
2431 State.AllocateReg(IntRegs);
2433 Reg = State.AllocateReg(F64Regs);
2434 // Shadow int registers
2435 unsigned Reg2 = State.AllocateReg(IntRegs);
2436 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2437 State.AllocateReg(IntRegs);
2438 State.AllocateReg(IntRegs);
2441 llvm_unreachable("Cannot handle this ValVT.");
2444 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2446 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2448 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2453 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2454 MVT LocVT, CCValAssign::LocInfo LocInfo,
2455 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2456 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2458 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2461 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2462 MVT LocVT, CCValAssign::LocInfo LocInfo,
2463 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2464 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2466 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2469 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2470 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2471 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2473 #include "MipsGenCallingConv.inc"
2475 //===----------------------------------------------------------------------===//
2476 // Call Calling Convention Implementation
2477 //===----------------------------------------------------------------------===//
2479 // Return next O32 integer argument register.
2480 static unsigned getNextIntArgReg(unsigned Reg) {
2481 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2482 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2486 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2487 SDValue Chain, SDValue Arg, SDLoc DL,
2488 bool IsTailCall, SelectionDAG &DAG) const {
2491 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2492 DAG.getIntPtrConstant(Offset, DL));
2493 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2497 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2498 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2499 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2500 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2501 /*isVolatile=*/ true, false, 0);
2504 void MipsTargetLowering::
2505 getOpndList(SmallVectorImpl<SDValue> &Ops,
2506 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2507 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2508 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2509 SDValue Chain) const {
2510 // Insert node "GP copy globalreg" before call to function.
2512 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2513 // in PIC mode) allow symbols to be resolved via lazy binding.
2514 // The lazy binding stub requires GP to point to the GOT.
2515 // Note that we don't need GP to point to the GOT for indirect calls
2516 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2517 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2518 // used for the function (that is, Mips linker doesn't generate lazy binding
2519 // stub for a function whose address is taken in the program).
2520 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2521 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2522 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2523 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2526 // Build a sequence of copy-to-reg nodes chained together with token
2527 // chain and flag operands which copy the outgoing args into registers.
2528 // The InFlag in necessary since all emitted instructions must be
2532 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2533 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2534 RegsToPass[i].second, InFlag);
2535 InFlag = Chain.getValue(1);
2538 // Add argument registers to the end of the list so that they are
2539 // known live into the call.
2540 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2541 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2542 RegsToPass[i].second.getValueType()));
2544 // Add a register mask operand representing the call-preserved registers.
2545 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2546 const uint32_t *Mask =
2547 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2548 assert(Mask && "Missing call preserved mask for calling convention");
2549 if (Subtarget.inMips16HardFloat()) {
2550 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2551 llvm::StringRef Sym = G->getGlobal()->getName();
2552 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2553 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2554 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2558 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2560 if (InFlag.getNode())
2561 Ops.push_back(InFlag);
2564 /// LowerCall - functions arguments are copied from virtual regs to
2565 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2567 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2568 SmallVectorImpl<SDValue> &InVals) const {
2569 SelectionDAG &DAG = CLI.DAG;
2571 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2572 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2573 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2574 SDValue Chain = CLI.Chain;
2575 SDValue Callee = CLI.Callee;
2576 bool &IsTailCall = CLI.IsTailCall;
2577 CallingConv::ID CallConv = CLI.CallConv;
2578 bool IsVarArg = CLI.IsVarArg;
2580 MachineFunction &MF = DAG.getMachineFunction();
2581 MachineFrameInfo *MFI = MF.getFrameInfo();
2582 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2583 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2584 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2586 // Analyze operands of the call, assigning locations to each operand.
2587 SmallVector<CCValAssign, 16> ArgLocs;
2589 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2590 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2592 // Allocate the reserved argument area. It seems strange to do this from the
2593 // caller side but removing it breaks the frame size calculation.
2594 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2596 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2598 // Get a count of how many bytes are to be pushed on the stack.
2599 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2601 // Check if it's really possible to do a tail call.
2603 IsTailCall = isEligibleForTailCallOptimization(
2604 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2606 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2607 report_fatal_error("failed to perform tail call elimination on a call "
2608 "site marked musttail");
2613 // Chain is the output chain of the last Load/Store or CopyToReg node.
2614 // ByValChain is the output chain of the last Memcpy node created for copying
2615 // byval arguments to the stack.
2616 unsigned StackAlignment = TFL->getStackAlignment();
2617 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2618 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2621 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2624 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
2625 getPointerTy(DAG.getDataLayout()));
2627 // With EABI is it possible to have 16 args on registers.
2628 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2629 SmallVector<SDValue, 8> MemOpChains;
2631 CCInfo.rewindByValRegsInfo();
2633 // Walk the register/memloc assignments, inserting copies/loads.
2634 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2635 SDValue Arg = OutVals[i];
2636 CCValAssign &VA = ArgLocs[i];
2637 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2638 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2639 bool UseUpperBits = false;
2642 if (Flags.isByVal()) {
2643 unsigned FirstByValReg, LastByValReg;
2644 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2645 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2647 assert(Flags.getByValSize() &&
2648 "ByVal args of size 0 should have been ignored by front-end.");
2649 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2650 assert(!IsTailCall &&
2651 "Do not tail-call optimize if there is a byval argument.");
2652 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2653 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2655 CCInfo.nextInRegsParam();
2659 // Promote the value if needed.
2660 switch (VA.getLocInfo()) {
2662 llvm_unreachable("Unknown loc info!");
2663 case CCValAssign::Full:
2664 if (VA.isRegLoc()) {
2665 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2666 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2667 (ValVT == MVT::i64 && LocVT == MVT::f64))
2668 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2669 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2670 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2671 Arg, DAG.getConstant(0, DL, MVT::i32));
2672 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2673 Arg, DAG.getConstant(1, DL, MVT::i32));
2674 if (!Subtarget.isLittle())
2676 unsigned LocRegLo = VA.getLocReg();
2677 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2678 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2679 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2684 case CCValAssign::BCvt:
2685 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2687 case CCValAssign::SExtUpper:
2688 UseUpperBits = true;
2690 case CCValAssign::SExt:
2691 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2693 case CCValAssign::ZExtUpper:
2694 UseUpperBits = true;
2696 case CCValAssign::ZExt:
2697 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2699 case CCValAssign::AExtUpper:
2700 UseUpperBits = true;
2702 case CCValAssign::AExt:
2703 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2708 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2709 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2711 ISD::SHL, DL, VA.getLocVT(), Arg,
2712 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2715 // Arguments that can be passed on register must be kept at
2716 // RegsToPass vector
2717 if (VA.isRegLoc()) {
2718 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2722 // Register can't get to this point...
2723 assert(VA.isMemLoc());
2725 // emit ISD::STORE whichs stores the
2726 // parameter value to a stack Location
2727 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2728 Chain, Arg, DL, IsTailCall, DAG));
2731 // Transform all store nodes into one single node because all store
2732 // nodes are independent of each other.
2733 if (!MemOpChains.empty())
2734 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2736 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2737 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2738 // node so that legalize doesn't hack it.
2739 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2741 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2743 EVT Ty = Callee.getValueType();
2745 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2747 const GlobalValue *Val = G->getGlobal();
2748 InternalLinkage = Val->hasInternalLinkage();
2750 if (InternalLinkage)
2751 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2752 else if (LargeGOT) {
2753 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2754 MipsII::MO_CALL_LO16, Chain,
2755 FuncInfo->callPtrInfo(Val));
2758 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2759 FuncInfo->callPtrInfo(Val));
2763 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
2764 getPointerTy(DAG.getDataLayout()), 0,
2765 MipsII::MO_NO_FLAG);
2766 GlobalOrExternal = true;
2768 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2769 const char *Sym = S->getSymbol();
2771 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2772 Callee = DAG.getTargetExternalSymbol(
2773 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
2774 else if (LargeGOT) {
2775 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2776 MipsII::MO_CALL_LO16, Chain,
2777 FuncInfo->callPtrInfo(Sym));
2779 } else { // N64 || PIC
2780 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2781 FuncInfo->callPtrInfo(Sym));
2785 GlobalOrExternal = true;
2788 SmallVector<SDValue, 8> Ops(1, Chain);
2789 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2791 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2792 IsCallReloc, CLI, Callee, Chain);
2795 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2797 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2798 SDValue InFlag = Chain.getValue(1);
2800 // Create the CALLSEQ_END node.
2801 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2802 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2803 InFlag = Chain.getValue(1);
2805 // Handle result values, copying them out of physregs into vregs that we
2807 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2811 /// LowerCallResult - Lower the result values of a call into the
2812 /// appropriate copies out of appropriate physical registers.
2813 SDValue MipsTargetLowering::LowerCallResult(
2814 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2815 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2816 SmallVectorImpl<SDValue> &InVals,
2817 TargetLowering::CallLoweringInfo &CLI) const {
2818 // Assign locations to each value returned by this call.
2819 SmallVector<CCValAssign, 16> RVLocs;
2820 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2822 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2824 // Copy all of the result registers out of their specified physreg.
2825 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2826 CCValAssign &VA = RVLocs[i];
2827 assert(VA.isRegLoc() && "Can only return in registers!");
2829 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2830 RVLocs[i].getLocVT(), InFlag);
2831 Chain = Val.getValue(1);
2832 InFlag = Val.getValue(2);
2834 if (VA.isUpperBitsInLoc()) {
2835 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2836 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2838 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2840 Shift, DL, VA.getLocVT(), Val,
2841 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2844 switch (VA.getLocInfo()) {
2846 llvm_unreachable("Unknown loc info!");
2847 case CCValAssign::Full:
2849 case CCValAssign::BCvt:
2850 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2852 case CCValAssign::AExt:
2853 case CCValAssign::AExtUpper:
2854 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2856 case CCValAssign::ZExt:
2857 case CCValAssign::ZExtUpper:
2858 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2859 DAG.getValueType(VA.getValVT()));
2860 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2862 case CCValAssign::SExt:
2863 case CCValAssign::SExtUpper:
2864 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2865 DAG.getValueType(VA.getValVT()));
2866 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2870 InVals.push_back(Val);
2876 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2877 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2878 MVT LocVT = VA.getLocVT();
2879 EVT ValVT = VA.getValVT();
2881 // Shift into the upper bits if necessary.
2882 switch (VA.getLocInfo()) {
2885 case CCValAssign::AExtUpper:
2886 case CCValAssign::SExtUpper:
2887 case CCValAssign::ZExtUpper: {
2888 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2889 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2891 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2893 Opcode, DL, VA.getLocVT(), Val,
2894 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2899 // If this is an value smaller than the argument slot size (32-bit for O32,
2900 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2901 // size. Extract the value and insert any appropriate assertions regarding
2902 // sign/zero extension.
2903 switch (VA.getLocInfo()) {
2905 llvm_unreachable("Unknown loc info!");
2906 case CCValAssign::Full:
2908 case CCValAssign::AExtUpper:
2909 case CCValAssign::AExt:
2910 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2912 case CCValAssign::SExtUpper:
2913 case CCValAssign::SExt:
2914 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2915 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2917 case CCValAssign::ZExtUpper:
2918 case CCValAssign::ZExt:
2919 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2920 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2922 case CCValAssign::BCvt:
2923 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2930 //===----------------------------------------------------------------------===//
2931 // Formal Arguments Calling Convention Implementation
2932 //===----------------------------------------------------------------------===//
2933 /// LowerFormalArguments - transform physical registers into virtual registers
2934 /// and generate load operations for arguments places on the stack.
2936 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2937 CallingConv::ID CallConv,
2939 const SmallVectorImpl<ISD::InputArg> &Ins,
2940 SDLoc DL, SelectionDAG &DAG,
2941 SmallVectorImpl<SDValue> &InVals)
2943 MachineFunction &MF = DAG.getMachineFunction();
2944 MachineFrameInfo *MFI = MF.getFrameInfo();
2945 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2947 MipsFI->setVarArgsFrameIndex(0);
2949 // Used with vargs to acumulate store chains.
2950 std::vector<SDValue> OutChains;
2952 // Assign locations to all of the incoming arguments.
2953 SmallVector<CCValAssign, 16> ArgLocs;
2954 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2956 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2957 const Function *Func = DAG.getMachineFunction().getFunction();
2958 Function::const_arg_iterator FuncArg = Func->arg_begin();
2960 if (Func->hasFnAttribute("interrupt") && !Func->arg_empty())
2962 "Functions with the interrupt attribute cannot have arguments!");
2964 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2965 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2966 CCInfo.getInRegsParamsCount() > 0);
2968 unsigned CurArgIdx = 0;
2969 CCInfo.rewindByValRegsInfo();
2971 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2972 CCValAssign &VA = ArgLocs[i];
2973 if (Ins[i].isOrigArg()) {
2974 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2975 CurArgIdx = Ins[i].getOrigArgIndex();
2977 EVT ValVT = VA.getValVT();
2978 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2979 bool IsRegLoc = VA.isRegLoc();
2981 if (Flags.isByVal()) {
2982 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2983 unsigned FirstByValReg, LastByValReg;
2984 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2985 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2987 assert(Flags.getByValSize() &&
2988 "ByVal args of size 0 should have been ignored by front-end.");
2989 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2990 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2991 FirstByValReg, LastByValReg, VA, CCInfo);
2992 CCInfo.nextInRegsParam();
2996 // Arguments stored on registers
2998 MVT RegVT = VA.getLocVT();
2999 unsigned ArgReg = VA.getLocReg();
3000 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3002 // Transform the arguments stored on
3003 // physical registers into virtual ones
3004 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3005 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3007 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3009 // Handle floating point arguments passed in integer registers and
3010 // long double arguments passed in floating point registers.
3011 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3012 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3013 (RegVT == MVT::f64 && ValVT == MVT::i64))
3014 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3015 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3016 ValVT == MVT::f64) {
3017 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3018 getNextIntArgReg(ArgReg), RC);
3019 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3020 if (!Subtarget.isLittle())
3021 std::swap(ArgValue, ArgValue2);
3022 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3023 ArgValue, ArgValue2);
3026 InVals.push_back(ArgValue);
3027 } else { // VA.isRegLoc()
3028 MVT LocVT = VA.getLocVT();
3031 // We ought to be able to use LocVT directly but O32 sets it to i32
3032 // when allocating floating point values to integer registers.
3033 // This shouldn't influence how we load the value into registers unless
3034 // we are targeting softfloat.
3035 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3036 LocVT = VA.getValVT();
3040 assert(VA.isMemLoc());
3042 // The stack pointer offset is relative to the caller stack frame.
3043 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
3044 VA.getLocMemOffset(), true);
3046 // Create load nodes to retrieve arguments from the stack
3047 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3048 SDValue ArgValue = DAG.getLoad(
3049 LocVT, DL, Chain, FIN,
3050 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3051 false, false, false, 0);
3052 OutChains.push_back(ArgValue.getValue(1));
3054 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3056 InVals.push_back(ArgValue);
3060 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3061 // The mips ABIs for returning structs by value requires that we copy
3062 // the sret argument into $v0 for the return. Save the argument into
3063 // a virtual register so that we can access it from the return points.
3064 if (Ins[i].Flags.isSRet()) {
3065 unsigned Reg = MipsFI->getSRetReturnReg();
3067 Reg = MF.getRegInfo().createVirtualRegister(
3068 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3069 MipsFI->setSRetReturnReg(Reg);
3071 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3072 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3078 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3080 // All stores are grouped in one node to allow the matching between
3081 // the size of Ins and InVals. This only happens when on varg functions
3082 if (!OutChains.empty()) {
3083 OutChains.push_back(Chain);
3084 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3090 //===----------------------------------------------------------------------===//
3091 // Return Value Calling Convention Implementation
3092 //===----------------------------------------------------------------------===//
3095 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3096 MachineFunction &MF, bool IsVarArg,
3097 const SmallVectorImpl<ISD::OutputArg> &Outs,
3098 LLVMContext &Context) const {
3099 SmallVector<CCValAssign, 16> RVLocs;
3100 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3101 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3105 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3106 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3107 if (Type == MVT::i32)
3114 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3115 SDLoc DL, SelectionDAG &DAG) const {
3117 MachineFunction &MF = DAG.getMachineFunction();
3118 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3122 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3126 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3128 const SmallVectorImpl<ISD::OutputArg> &Outs,
3129 const SmallVectorImpl<SDValue> &OutVals,
3130 SDLoc DL, SelectionDAG &DAG) const {
3131 // CCValAssign - represent the assignment of
3132 // the return value to a location
3133 SmallVector<CCValAssign, 16> RVLocs;
3134 MachineFunction &MF = DAG.getMachineFunction();
3136 // CCState - Info about the registers and stack slot.
3137 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3139 // Analyze return values.
3140 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3143 SmallVector<SDValue, 4> RetOps(1, Chain);
3145 // Copy the result values into the output registers.
3146 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3147 SDValue Val = OutVals[i];
3148 CCValAssign &VA = RVLocs[i];
3149 assert(VA.isRegLoc() && "Can only return in registers!");
3150 bool UseUpperBits = false;
3152 switch (VA.getLocInfo()) {
3154 llvm_unreachable("Unknown loc info!");
3155 case CCValAssign::Full:
3157 case CCValAssign::BCvt:
3158 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3160 case CCValAssign::AExtUpper:
3161 UseUpperBits = true;
3163 case CCValAssign::AExt:
3164 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3166 case CCValAssign::ZExtUpper:
3167 UseUpperBits = true;
3169 case CCValAssign::ZExt:
3170 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3172 case CCValAssign::SExtUpper:
3173 UseUpperBits = true;
3175 case CCValAssign::SExt:
3176 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3181 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3182 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3184 ISD::SHL, DL, VA.getLocVT(), Val,
3185 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3188 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3190 // Guarantee that all emitted copies are stuck together with flags.
3191 Flag = Chain.getValue(1);
3192 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3195 // The mips ABIs for returning structs by value requires that we copy
3196 // the sret argument into $v0 for the return. We saved the argument into
3197 // a virtual register in the entry block, so now we copy the value out
3199 if (MF.getFunction()->hasStructRetAttr()) {
3200 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3201 unsigned Reg = MipsFI->getSRetReturnReg();
3204 llvm_unreachable("sret virtual register not created in the entry block");
3206 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3207 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3209 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3210 Flag = Chain.getValue(1);
3211 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3214 RetOps[0] = Chain; // Update chain.
3216 // Add the flag if we have it.
3218 RetOps.push_back(Flag);
3220 // ISRs must use "eret".
3221 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
3222 return LowerInterruptReturn(RetOps, DL, DAG);
3224 // Standard return on Mips is a "jr $ra"
3225 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3228 //===----------------------------------------------------------------------===//
3229 // Mips Inline Assembly Support
3230 //===----------------------------------------------------------------------===//
3232 /// getConstraintType - Given a constraint letter, return the type of
3233 /// constraint it is for this target.
3234 MipsTargetLowering::ConstraintType
3235 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3236 // Mips specific constraints
3237 // GCC config/mips/constraints.md
3239 // 'd' : An address register. Equivalent to r
3240 // unless generating MIPS16 code.
3241 // 'y' : Equivalent to r; retained for
3242 // backwards compatibility.
3243 // 'c' : A register suitable for use in an indirect
3244 // jump. This will always be $25 for -mabicalls.
3245 // 'l' : The lo register. 1 word storage.
3246 // 'x' : The hilo register pair. Double word storage.
3247 if (Constraint.size() == 1) {
3248 switch (Constraint[0]) {
3256 return C_RegisterClass;
3262 if (Constraint == "ZC")
3265 return TargetLowering::getConstraintType(Constraint);
3268 /// Examine constraint type and operand type and determine a weight value.
3269 /// This object must already have been set up with the operand type
3270 /// and the current alternative constraint selected.
3271 TargetLowering::ConstraintWeight
3272 MipsTargetLowering::getSingleConstraintMatchWeight(
3273 AsmOperandInfo &info, const char *constraint) const {
3274 ConstraintWeight weight = CW_Invalid;
3275 Value *CallOperandVal = info.CallOperandVal;
3276 // If we don't have a value, we can't do a match,
3277 // but allow it at the lowest weight.
3278 if (!CallOperandVal)
3280 Type *type = CallOperandVal->getType();
3281 // Look at the constraint type.
3282 switch (*constraint) {
3284 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3288 if (type->isIntegerTy())
3289 weight = CW_Register;
3291 case 'f': // FPU or MSA register
3292 if (Subtarget.hasMSA() && type->isVectorTy() &&
3293 cast<VectorType>(type)->getBitWidth() == 128)
3294 weight = CW_Register;
3295 else if (type->isFloatTy())
3296 weight = CW_Register;
3298 case 'c': // $25 for indirect jumps
3299 case 'l': // lo register
3300 case 'x': // hilo register pair
3301 if (type->isIntegerTy())
3302 weight = CW_SpecificReg;
3304 case 'I': // signed 16 bit immediate
3305 case 'J': // integer zero
3306 case 'K': // unsigned 16 bit immediate
3307 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3308 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3309 case 'O': // signed 15 bit immediate (+- 16383)
3310 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3311 if (isa<ConstantInt>(CallOperandVal))
3312 weight = CW_Constant;
3321 /// This is a helper function to parse a physical register string and split it
3322 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3323 /// that is returned indicates whether parsing was successful. The second flag
3324 /// is true if the numeric part exists.
3325 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3326 unsigned long long &Reg) {
3327 if (C.front() != '{' || C.back() != '}')
3328 return std::make_pair(false, false);
3330 // Search for the first numeric character.
3331 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3332 I = std::find_if(B, E, std::ptr_fun(isdigit));
3334 Prefix = StringRef(B, I - B);
3336 // The second flag is set to false if no numeric characters were found.
3338 return std::make_pair(true, false);
3340 // Parse the numeric characters.
3341 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3345 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3346 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3347 const TargetRegisterInfo *TRI =
3348 Subtarget.getRegisterInfo();
3349 const TargetRegisterClass *RC;
3351 unsigned long long Reg;
3353 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3356 return std::make_pair(0U, nullptr);
3358 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3359 // No numeric characters follow "hi" or "lo".
3361 return std::make_pair(0U, nullptr);
3363 RC = TRI->getRegClass(Prefix == "hi" ?
3364 Mips::HI32RegClassID : Mips::LO32RegClassID);
3365 return std::make_pair(*(RC->begin()), RC);
3366 } else if (Prefix.startswith("$msa")) {
3367 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3369 // No numeric characters follow the name.
3371 return std::make_pair(0U, nullptr);
3373 Reg = StringSwitch<unsigned long long>(Prefix)
3374 .Case("$msair", Mips::MSAIR)
3375 .Case("$msacsr", Mips::MSACSR)
3376 .Case("$msaaccess", Mips::MSAAccess)
3377 .Case("$msasave", Mips::MSASave)
3378 .Case("$msamodify", Mips::MSAModify)
3379 .Case("$msarequest", Mips::MSARequest)
3380 .Case("$msamap", Mips::MSAMap)
3381 .Case("$msaunmap", Mips::MSAUnmap)
3385 return std::make_pair(0U, nullptr);
3387 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3388 return std::make_pair(Reg, RC);
3392 return std::make_pair(0U, nullptr);
3394 if (Prefix == "$f") { // Parse $f0-$f31.
3395 // If the size of FP registers is 64-bit or Reg is an even number, select
3396 // the 64-bit register class. Otherwise, select the 32-bit register class.
3397 if (VT == MVT::Other)
3398 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3400 RC = getRegClassFor(VT);
3402 if (RC == &Mips::AFGR64RegClass) {
3403 assert(Reg % 2 == 0);
3406 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3407 RC = TRI->getRegClass(Mips::FCCRegClassID);
3408 else if (Prefix == "$w") { // Parse $w0-$w31.
3409 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3410 } else { // Parse $0-$31.
3411 assert(Prefix == "$");
3412 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3415 assert(Reg < RC->getNumRegs());
3416 return std::make_pair(*(RC->begin() + Reg), RC);
3419 /// Given a register class constraint, like 'r', if this corresponds directly
3420 /// to an LLVM register class, return a register of 0 and the register class
3422 std::pair<unsigned, const TargetRegisterClass *>
3423 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3424 StringRef Constraint,
3426 if (Constraint.size() == 1) {
3427 switch (Constraint[0]) {
3428 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3429 case 'y': // Same as 'r'. Exists for compatibility.
3431 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3432 if (Subtarget.inMips16Mode())
3433 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3434 return std::make_pair(0U, &Mips::GPR32RegClass);
3436 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3437 return std::make_pair(0U, &Mips::GPR32RegClass);
3438 if (VT == MVT::i64 && Subtarget.isGP64bit())
3439 return std::make_pair(0U, &Mips::GPR64RegClass);
3440 // This will generate an error message
3441 return std::make_pair(0U, nullptr);
3442 case 'f': // FPU or MSA register
3443 if (VT == MVT::v16i8)
3444 return std::make_pair(0U, &Mips::MSA128BRegClass);
3445 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3446 return std::make_pair(0U, &Mips::MSA128HRegClass);
3447 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3448 return std::make_pair(0U, &Mips::MSA128WRegClass);
3449 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3450 return std::make_pair(0U, &Mips::MSA128DRegClass);
3451 else if (VT == MVT::f32)
3452 return std::make_pair(0U, &Mips::FGR32RegClass);
3453 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3454 if (Subtarget.isFP64bit())
3455 return std::make_pair(0U, &Mips::FGR64RegClass);
3456 return std::make_pair(0U, &Mips::AFGR64RegClass);
3459 case 'c': // register suitable for indirect jump
3461 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3462 assert(VT == MVT::i64 && "Unexpected type.");
3463 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3464 case 'l': // register suitable for indirect jump
3466 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3467 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3468 case 'x': // register suitable for indirect jump
3469 // Fixme: Not triggering the use of both hi and low
3470 // This will generate an error message
3471 return std::make_pair(0U, nullptr);
3475 std::pair<unsigned, const TargetRegisterClass *> R;
3476 R = parseRegForInlineAsmConstraint(Constraint, VT);
3481 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3484 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3485 /// vector. If it is invalid, don't add anything to Ops.
3486 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3487 std::string &Constraint,
3488 std::vector<SDValue>&Ops,
3489 SelectionDAG &DAG) const {
3493 // Only support length 1 constraints for now.
3494 if (Constraint.length() > 1) return;
3496 char ConstraintLetter = Constraint[0];
3497 switch (ConstraintLetter) {
3498 default: break; // This will fall through to the generic implementation
3499 case 'I': // Signed 16 bit constant
3500 // If this fails, the parent routine will give an error
3501 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3502 EVT Type = Op.getValueType();
3503 int64_t Val = C->getSExtValue();
3504 if (isInt<16>(Val)) {
3505 Result = DAG.getTargetConstant(Val, DL, Type);
3510 case 'J': // integer zero
3511 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3512 EVT Type = Op.getValueType();
3513 int64_t Val = C->getZExtValue();
3515 Result = DAG.getTargetConstant(0, DL, Type);
3520 case 'K': // unsigned 16 bit immediate
3521 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3522 EVT Type = Op.getValueType();
3523 uint64_t Val = (uint64_t)C->getZExtValue();
3524 if (isUInt<16>(Val)) {
3525 Result = DAG.getTargetConstant(Val, DL, Type);
3530 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3531 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3532 EVT Type = Op.getValueType();
3533 int64_t Val = C->getSExtValue();
3534 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3535 Result = DAG.getTargetConstant(Val, DL, Type);
3540 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3541 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3542 EVT Type = Op.getValueType();
3543 int64_t Val = C->getSExtValue();
3544 if ((Val >= -65535) && (Val <= -1)) {
3545 Result = DAG.getTargetConstant(Val, DL, Type);
3550 case 'O': // signed 15 bit immediate
3551 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3552 EVT Type = Op.getValueType();
3553 int64_t Val = C->getSExtValue();
3554 if ((isInt<15>(Val))) {
3555 Result = DAG.getTargetConstant(Val, DL, Type);
3560 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3561 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3562 EVT Type = Op.getValueType();
3563 int64_t Val = C->getSExtValue();
3564 if ((Val <= 65535) && (Val >= 1)) {
3565 Result = DAG.getTargetConstant(Val, DL, Type);
3572 if (Result.getNode()) {
3573 Ops.push_back(Result);
3577 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3580 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3581 const AddrMode &AM, Type *Ty,
3582 unsigned AS) const {
3583 // No global is ever allowed as a base.
3588 case 0: // "r+i" or just "i", depending on HasBaseReg.
3591 if (!AM.HasBaseReg) // allow "r+i".
3593 return false; // disallow "r+r" or "r+r+i".
3602 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3603 // The Mips target isn't yet aware of offsets.
3607 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3609 bool IsMemset, bool ZeroMemset,
3611 MachineFunction &MF) const {
3612 if (Subtarget.hasMips64())
3618 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3619 if (VT != MVT::f32 && VT != MVT::f64)
3621 if (Imm.isNegZero())
3623 return Imm.isZero();
3626 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3628 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3630 return TargetLowering::getJumpTableEncoding();
3633 bool MipsTargetLowering::useSoftFloat() const {
3634 return Subtarget.useSoftFloat();
3637 void MipsTargetLowering::copyByValRegs(
3638 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3639 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3640 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3641 const CCValAssign &VA, MipsCCState &State) const {
3642 MachineFunction &MF = DAG.getMachineFunction();
3643 MachineFrameInfo *MFI = MF.getFrameInfo();
3644 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3645 unsigned NumRegs = LastReg - FirstReg;
3646 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3647 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3649 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3653 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3654 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3656 FrameObjOffset = VA.getLocMemOffset();
3658 // Create frame object.
3659 EVT PtrTy = getPointerTy(DAG.getDataLayout());
3660 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3661 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3662 InVals.push_back(FIN);
3667 // Copy arg registers.
3668 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3669 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3671 for (unsigned I = 0; I < NumRegs; ++I) {
3672 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3673 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3674 unsigned Offset = I * GPRSizeInBytes;
3675 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3676 DAG.getConstant(Offset, DL, PtrTy));
3677 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3678 StorePtr, MachinePointerInfo(FuncArg, Offset),
3680 OutChains.push_back(Store);
3684 // Copy byVal arg to registers and stack.
3685 void MipsTargetLowering::passByValArg(
3686 SDValue Chain, SDLoc DL,
3687 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3688 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3689 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3690 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3691 const CCValAssign &VA) const {
3692 unsigned ByValSizeInBytes = Flags.getByValSize();
3693 unsigned OffsetInBytes = 0; // From beginning of struct
3694 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3695 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3696 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
3697 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3698 unsigned NumRegs = LastReg - FirstReg;
3701 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3702 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3705 // Copy words to registers.
3706 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3707 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3708 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3709 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3710 MachinePointerInfo(), false, false, false,
3712 MemOpChains.push_back(LoadVal.getValue(1));
3713 unsigned ArgReg = ArgRegs[FirstReg + I];
3714 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3717 // Return if the struct has been fully copied.
3718 if (ByValSizeInBytes == OffsetInBytes)
3721 // Copy the remainder of the byval argument with sub-word loads and shifts.
3722 if (LeftoverBytes) {
3725 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3726 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3727 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3729 if (RemainingSizeInBytes < LoadSizeInBytes)
3733 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3734 DAG.getConstant(OffsetInBytes, DL,
3736 SDValue LoadVal = DAG.getExtLoad(
3737 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3738 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3740 MemOpChains.push_back(LoadVal.getValue(1));
3742 // Shift the loaded value.
3746 Shamt = TotalBytesLoaded * 8;
3748 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3750 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3751 DAG.getConstant(Shamt, DL, MVT::i32));
3754 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3758 OffsetInBytes += LoadSizeInBytes;
3759 TotalBytesLoaded += LoadSizeInBytes;
3760 Alignment = std::min(Alignment, LoadSizeInBytes);
3763 unsigned ArgReg = ArgRegs[FirstReg + I];
3764 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3769 // Copy remainder of byval arg to it with memcpy.
3770 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3771 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3772 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3773 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3774 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3775 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3776 DAG.getConstant(MemCpySize, DL, PtrTy),
3777 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3778 /*isTailCall=*/false,
3779 MachinePointerInfo(), MachinePointerInfo());
3780 MemOpChains.push_back(Chain);
3783 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3784 SDValue Chain, SDLoc DL,
3786 CCState &State) const {
3787 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3788 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3789 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3790 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3791 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3792 MachineFunction &MF = DAG.getMachineFunction();
3793 MachineFrameInfo *MFI = MF.getFrameInfo();
3794 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3796 // Offset of the first variable argument from stack pointer.
3799 if (ArgRegs.size() == Idx)
3801 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3804 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3805 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3808 // Record the frame index of the first variable argument
3809 // which is a value necessary to VASTART.
3810 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3811 MipsFI->setVarArgsFrameIndex(FI);
3813 // Copy the integer registers that have not been used for argument passing
3814 // to the argument register save area. For O32, the save area is allocated
3815 // in the caller's stack frame, while for N32/64, it is allocated in the
3816 // callee's stack frame.
3817 for (unsigned I = Idx; I < ArgRegs.size();
3818 ++I, VaArgOffset += RegSizeInBytes) {
3819 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3820 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3821 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3822 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3823 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3824 MachinePointerInfo(), false, false, 0);
3825 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3827 OutChains.push_back(Store);
3831 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3832 unsigned Align) const {
3833 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3835 assert(Size && "Byval argument's size shouldn't be 0.");
3837 Align = std::min(Align, TFL->getStackAlignment());
3839 unsigned FirstReg = 0;
3840 unsigned NumRegs = 0;
3842 if (State->getCallingConv() != CallingConv::Fast) {
3843 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3844 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3845 // FIXME: The O32 case actually describes no shadow registers.
3846 const MCPhysReg *ShadowRegs =
3847 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3849 // We used to check the size as well but we can't do that anymore since
3850 // CCState::HandleByVal() rounds up the size after calling this function.
3851 assert(!(Align % RegSizeInBytes) &&
3852 "Byval argument's alignment should be a multiple of"
3855 FirstReg = State->getFirstUnallocated(IntArgRegs);
3857 // If Align > RegSizeInBytes, the first arg register must be even.
3858 // FIXME: This condition happens to do the right thing but it's not the
3859 // right way to test it. We want to check that the stack frame offset
3860 // of the register is aligned.
3861 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3862 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3866 // Mark the registers allocated.
3867 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3868 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3869 Size -= RegSizeInBytes, ++I, ++NumRegs)
3870 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3873 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3877 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3878 bool isFPCmp, unsigned Opc) const {
3879 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3880 "Subtarget already supports SELECT nodes with the use of"
3881 "conditional-move instructions.");
3883 const TargetInstrInfo *TII =
3884 Subtarget.getInstrInfo();
3885 DebugLoc DL = MI->getDebugLoc();
3887 // To "insert" a SELECT instruction, we actually have to insert the
3888 // diamond control-flow pattern. The incoming instruction knows the
3889 // destination vreg to set, the condition code register to branch on, the
3890 // true/false values to select between, and a branch opcode to use.
3891 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3892 MachineFunction::iterator It = ++BB->getIterator();
3898 // bNE r1, r0, copy1MBB
3899 // fallthrough --> copy0MBB
3900 MachineBasicBlock *thisMBB = BB;
3901 MachineFunction *F = BB->getParent();
3902 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3903 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3904 F->insert(It, copy0MBB);
3905 F->insert(It, sinkMBB);
3907 // Transfer the remainder of BB and its successor edges to sinkMBB.
3908 sinkMBB->splice(sinkMBB->begin(), BB,
3909 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3910 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3912 // Next, add the true and fallthrough blocks as its successors.
3913 BB->addSuccessor(copy0MBB);
3914 BB->addSuccessor(sinkMBB);
3917 // bc1[tf] cc, sinkMBB
3918 BuildMI(BB, DL, TII->get(Opc))
3919 .addReg(MI->getOperand(1).getReg())
3922 // bne rs, $0, sinkMBB
3923 BuildMI(BB, DL, TII->get(Opc))
3924 .addReg(MI->getOperand(1).getReg())
3930 // %FalseValue = ...
3931 // # fallthrough to sinkMBB
3934 // Update machine-CFG edges
3935 BB->addSuccessor(sinkMBB);
3938 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3942 BuildMI(*BB, BB->begin(), DL,
3943 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3944 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3945 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3947 MI->eraseFromParent(); // The pseudo instruction is gone now.
3952 // FIXME? Maybe this could be a TableGen attribute on some registers and
3953 // this table could be generated automatically from RegInfo.
3954 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
3955 SelectionDAG &DAG) const {
3956 // Named registers is expected to be fairly rare. For now, just support $28
3957 // since the linux kernel uses it.
3958 if (Subtarget.isGP64bit()) {
3959 unsigned Reg = StringSwitch<unsigned>(RegName)
3960 .Case("$28", Mips::GP_64)
3965 unsigned Reg = StringSwitch<unsigned>(RegName)
3966 .Case("$28", Mips::GP)
3971 report_fatal_error("Invalid register name global variable");