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;
1333 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1334 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1341 ZERO = Mips::ZERO_64;
1346 unsigned Dest = MI->getOperand(0).getReg();
1347 unsigned Ptr = MI->getOperand(1).getReg();
1348 unsigned OldVal = MI->getOperand(2).getReg();
1349 unsigned NewVal = MI->getOperand(3).getReg();
1351 unsigned Success = RegInfo.createVirtualRegister(RC);
1353 // insert new blocks after the current block
1354 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1355 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1356 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1357 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1358 MachineFunction::iterator It = ++BB->getIterator();
1359 MF->insert(It, loop1MBB);
1360 MF->insert(It, loop2MBB);
1361 MF->insert(It, exitMBB);
1363 // Transfer the remainder of BB and its successor edges to exitMBB.
1364 exitMBB->splice(exitMBB->begin(), BB,
1365 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1366 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1370 // fallthrough --> loop1MBB
1371 BB->addSuccessor(loop1MBB);
1372 loop1MBB->addSuccessor(exitMBB);
1373 loop1MBB->addSuccessor(loop2MBB);
1374 loop2MBB->addSuccessor(loop1MBB);
1375 loop2MBB->addSuccessor(exitMBB);
1379 // bne dest, oldval, exitMBB
1381 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1382 BuildMI(BB, DL, TII->get(BNE))
1383 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1386 // sc success, newval, 0(ptr)
1387 // beq success, $0, loop1MBB
1389 BuildMI(BB, DL, TII->get(SC), Success)
1390 .addReg(NewVal).addReg(Ptr).addImm(0);
1391 BuildMI(BB, DL, TII->get(BEQ))
1392 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1394 MI->eraseFromParent(); // The instruction is gone now.
1400 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1401 MachineBasicBlock *BB,
1402 unsigned Size) const {
1403 assert((Size == 1 || Size == 2) &&
1404 "Unsupported size for EmitAtomicCmpSwapPartial.");
1406 MachineFunction *MF = BB->getParent();
1407 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1408 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1409 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1410 DebugLoc DL = MI->getDebugLoc();
1412 unsigned Dest = MI->getOperand(0).getReg();
1413 unsigned Ptr = MI->getOperand(1).getReg();
1414 unsigned CmpVal = MI->getOperand(2).getReg();
1415 unsigned NewVal = MI->getOperand(3).getReg();
1417 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1418 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1419 unsigned Mask = RegInfo.createVirtualRegister(RC);
1420 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1421 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1422 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1423 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1424 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1425 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1426 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1427 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1428 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1429 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1430 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1431 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1432 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1433 unsigned Success = RegInfo.createVirtualRegister(RC);
1435 // insert new blocks after the current block
1436 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1437 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1438 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1439 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1440 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1441 MachineFunction::iterator It = ++BB->getIterator();
1442 MF->insert(It, loop1MBB);
1443 MF->insert(It, loop2MBB);
1444 MF->insert(It, sinkMBB);
1445 MF->insert(It, exitMBB);
1447 // Transfer the remainder of BB and its successor edges to exitMBB.
1448 exitMBB->splice(exitMBB->begin(), BB,
1449 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1450 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1452 BB->addSuccessor(loop1MBB);
1453 loop1MBB->addSuccessor(sinkMBB);
1454 loop1MBB->addSuccessor(loop2MBB);
1455 loop2MBB->addSuccessor(loop1MBB);
1456 loop2MBB->addSuccessor(sinkMBB);
1457 sinkMBB->addSuccessor(exitMBB);
1459 // FIXME: computation of newval2 can be moved to loop2MBB.
1461 // addiu masklsb2,$0,-4 # 0xfffffffc
1462 // and alignedaddr,ptr,masklsb2
1463 // andi ptrlsb2,ptr,3
1464 // sll shiftamt,ptrlsb2,3
1465 // ori maskupper,$0,255 # 0xff
1466 // sll mask,maskupper,shiftamt
1467 // nor mask2,$0,mask
1468 // andi maskedcmpval,cmpval,255
1469 // sll shiftedcmpval,maskedcmpval,shiftamt
1470 // andi maskednewval,newval,255
1471 // sll shiftednewval,maskednewval,shiftamt
1472 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1473 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1474 .addReg(Mips::ZERO).addImm(-4);
1475 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1476 .addReg(Ptr).addReg(MaskLSB2);
1477 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1478 if (Subtarget.isLittle()) {
1479 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1481 unsigned Off = RegInfo.createVirtualRegister(RC);
1482 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1483 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1484 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1486 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1487 .addReg(Mips::ZERO).addImm(MaskImm);
1488 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1489 .addReg(MaskUpper).addReg(ShiftAmt);
1490 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1491 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1492 .addReg(CmpVal).addImm(MaskImm);
1493 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1494 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1495 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1496 .addReg(NewVal).addImm(MaskImm);
1497 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1498 .addReg(MaskedNewVal).addReg(ShiftAmt);
1501 // ll oldval,0(alginedaddr)
1502 // and maskedoldval0,oldval,mask
1503 // bne maskedoldval0,shiftedcmpval,sinkMBB
1505 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1506 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1507 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1508 .addReg(OldVal).addReg(Mask);
1509 BuildMI(BB, DL, TII->get(Mips::BNE))
1510 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1513 // and maskedoldval1,oldval,mask2
1514 // or storeval,maskedoldval1,shiftednewval
1515 // sc success,storeval,0(alignedaddr)
1516 // beq success,$0,loop1MBB
1518 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1519 .addReg(OldVal).addReg(Mask2);
1520 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1521 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1522 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1523 BuildMI(BB, DL, TII->get(SC), Success)
1524 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1525 BuildMI(BB, DL, TII->get(Mips::BEQ))
1526 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1529 // srl srlres,maskedoldval0,shiftamt
1530 // sign_extend dest,srlres
1533 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1534 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1535 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1537 MI->eraseFromParent(); // The instruction is gone now.
1542 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1543 MachineBasicBlock *BB) const {
1544 MachineFunction *MF = BB->getParent();
1545 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1546 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1547 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1548 DebugLoc DL = MI->getDebugLoc();
1549 MachineBasicBlock::iterator II(MI);
1551 unsigned Fc = MI->getOperand(1).getReg();
1552 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1554 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1556 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1559 .addImm(Mips::sub_lo);
1561 // We don't erase the original instruction, we just replace the condition
1562 // register with the 64-bit super-register.
1563 MI->getOperand(1).setReg(Fc2);
1568 //===----------------------------------------------------------------------===//
1569 // Misc Lower Operation implementation
1570 //===----------------------------------------------------------------------===//
1571 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1572 SDValue Chain = Op.getOperand(0);
1573 SDValue Table = Op.getOperand(1);
1574 SDValue Index = Op.getOperand(2);
1576 auto &TD = DAG.getDataLayout();
1577 EVT PTy = getPointerTy(TD);
1578 unsigned EntrySize =
1579 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
1581 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1582 DAG.getConstant(EntrySize, DL, PTy));
1583 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1585 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1587 DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1588 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
1589 MemVT, false, false, false, 0);
1590 Chain = Addr.getValue(1);
1592 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1593 // For PIC, the sequence is:
1594 // BRIND(load(Jumptable + index) + RelocBase)
1595 // RelocBase can be JumpTable, GOT or some sort of global base.
1596 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1597 getPICJumpTableRelocBase(Table, DAG));
1600 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1603 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1604 // The first operand is the chain, the second is the condition, the third is
1605 // the block to branch to if the condition is true.
1606 SDValue Chain = Op.getOperand(0);
1607 SDValue Dest = Op.getOperand(2);
1610 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1611 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1613 // Return if flag is not set by a floating point comparison.
1614 if (CondRes.getOpcode() != MipsISD::FPCmp)
1617 SDValue CCNode = CondRes.getOperand(2);
1619 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1620 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1621 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1622 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1623 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1624 FCC0, Dest, CondRes);
1627 SDValue MipsTargetLowering::
1628 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1630 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1631 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1633 // Return if flag is not set by a floating point comparison.
1634 if (Cond.getOpcode() != MipsISD::FPCmp)
1637 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1641 SDValue MipsTargetLowering::
1642 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1645 EVT Ty = Op.getOperand(0).getValueType();
1647 DAG.getNode(ISD::SETCC, DL, getSetCCResultType(DAG.getDataLayout(),
1648 *DAG.getContext(), Ty),
1649 Op.getOperand(0), Op.getOperand(1), Op.getOperand(4));
1651 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1655 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1656 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1657 SDValue Cond = createFPCmp(DAG, Op);
1659 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1660 "Floating point operand expected.");
1663 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1664 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1666 return createCMovFP(DAG, Cond, True, False, DL);
1669 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1670 SelectionDAG &DAG) const {
1671 EVT Ty = Op.getValueType();
1672 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1673 const GlobalValue *GV = N->getGlobal();
1675 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1676 const MipsTargetObjectFile *TLOF =
1677 static_cast<const MipsTargetObjectFile *>(
1678 getTargetMachine().getObjFileLowering());
1679 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1680 // %gp_rel relocation
1681 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1683 // %hi/%lo relocation
1684 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1687 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1688 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1691 return getAddrGlobalLargeGOT(
1692 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
1694 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1696 return getAddrGlobal(
1697 N, SDLoc(N), Ty, DAG,
1698 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1699 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1702 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1703 SelectionDAG &DAG) const {
1704 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1705 EVT Ty = Op.getValueType();
1707 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1708 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1710 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1713 SDValue MipsTargetLowering::
1714 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1716 // If the relocation model is PIC, use the General Dynamic TLS Model or
1717 // Local Dynamic TLS model, otherwise use the Initial Exec or
1718 // Local Exec TLS Model.
1720 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1721 if (DAG.getTarget().Options.EmulatedTLS)
1722 return LowerToTLSEmulatedModel(GA, DAG);
1725 const GlobalValue *GV = GA->getGlobal();
1726 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1728 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1730 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1731 // General Dynamic and Local Dynamic TLS Model.
1732 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1735 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1736 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1737 getGlobalReg(DAG, PtrVT), TGA);
1738 unsigned PtrSize = PtrVT.getSizeInBits();
1739 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1741 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1745 Entry.Node = Argument;
1747 Args.push_back(Entry);
1749 TargetLowering::CallLoweringInfo CLI(DAG);
1750 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1751 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1752 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1754 SDValue Ret = CallResult.first;
1756 if (model != TLSModel::LocalDynamic)
1759 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1760 MipsII::MO_DTPREL_HI);
1761 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1762 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1763 MipsII::MO_DTPREL_LO);
1764 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1765 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1766 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1770 if (model == TLSModel::InitialExec) {
1771 // Initial Exec TLS Model
1772 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1773 MipsII::MO_GOTTPREL);
1774 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1776 Offset = DAG.getLoad(PtrVT, DL,
1777 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1778 false, false, false, 0);
1780 // Local Exec TLS Model
1781 assert(model == TLSModel::LocalExec);
1782 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1783 MipsII::MO_TPREL_HI);
1784 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1785 MipsII::MO_TPREL_LO);
1786 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1787 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1788 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1791 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1792 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1795 SDValue MipsTargetLowering::
1796 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1798 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1799 EVT Ty = Op.getValueType();
1801 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1802 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1804 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1807 SDValue MipsTargetLowering::
1808 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1810 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1811 EVT Ty = Op.getValueType();
1813 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1814 const MipsTargetObjectFile *TLOF =
1815 static_cast<const MipsTargetObjectFile *>(
1816 getTargetMachine().getObjFileLowering());
1818 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
1819 getTargetMachine()))
1820 // %gp_rel relocation
1821 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1823 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1826 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1829 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1830 MachineFunction &MF = DAG.getMachineFunction();
1831 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1834 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1835 getPointerTy(MF.getDataLayout()));
1837 // vastart just stores the address of the VarArgsFrameIndex slot into the
1838 // memory location argument.
1839 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1840 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1841 MachinePointerInfo(SV), false, false, 0);
1844 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1845 SDNode *Node = Op.getNode();
1846 EVT VT = Node->getValueType(0);
1847 SDValue Chain = Node->getOperand(0);
1848 SDValue VAListPtr = Node->getOperand(1);
1849 unsigned Align = Node->getConstantOperandVal(3);
1850 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1852 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1854 SDValue VAListLoad =
1855 DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, VAListPtr,
1856 MachinePointerInfo(SV), false, false, false, 0);
1857 SDValue VAList = VAListLoad;
1859 // Re-align the pointer if necessary.
1860 // It should only ever be necessary for 64-bit types on O32 since the minimum
1861 // argument alignment is the same as the maximum type alignment for N32/N64.
1863 // FIXME: We currently align too often. The code generator doesn't notice
1864 // when the pointer is still aligned from the last va_arg (or pair of
1865 // va_args for the i64 on O32 case).
1866 if (Align > getMinStackArgumentAlignment()) {
1867 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1869 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1870 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
1872 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1873 DAG.getConstant(-(int64_t)Align, DL,
1874 VAList.getValueType()));
1877 // Increment the pointer, VAList, to the next vaarg.
1878 auto &TD = DAG.getDataLayout();
1879 unsigned ArgSizeInBytes =
1880 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1881 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1882 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes,
1883 ArgSlotSizeInBytes),
1884 DL, VAList.getValueType()));
1885 // Store the incremented VAList to the legalized pointer
1886 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1887 MachinePointerInfo(SV), false, false, 0);
1889 // In big-endian mode we must adjust the pointer when the load size is smaller
1890 // than the argument slot size. We must also reduce the known alignment to
1891 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1892 // the correct half of the slot, and reduce the alignment from 8 (slot
1893 // alignment) down to 4 (type alignment).
1894 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1895 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1896 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1897 DAG.getIntPtrConstant(Adjustment, DL));
1899 // Load the actual argument out of the pointer VAList
1900 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1904 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1905 bool HasExtractInsert) {
1906 EVT TyX = Op.getOperand(0).getValueType();
1907 EVT TyY = Op.getOperand(1).getValueType();
1909 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1910 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
1913 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1915 SDValue X = (TyX == MVT::f32) ?
1916 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1917 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1919 SDValue Y = (TyY == MVT::f32) ?
1920 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1921 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1924 if (HasExtractInsert) {
1925 // ext E, Y, 31, 1 ; extract bit31 of Y
1926 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1927 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1928 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1931 // srl SrlX, SllX, 1
1933 // sll SllY, SrlX, 31
1934 // or Or, SrlX, SllY
1935 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1936 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1937 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1938 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1939 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1942 if (TyX == MVT::f32)
1943 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1945 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1947 DAG.getConstant(0, DL, MVT::i32));
1948 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1951 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1952 bool HasExtractInsert) {
1953 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1954 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1955 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1957 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1959 // Bitcast to integer nodes.
1960 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1961 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1963 if (HasExtractInsert) {
1964 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1965 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1966 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1967 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
1969 if (WidthX > WidthY)
1970 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1971 else if (WidthY > WidthX)
1972 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1974 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1975 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
1977 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1980 // (d)sll SllX, X, 1
1981 // (d)srl SrlX, SllX, 1
1982 // (d)srl SrlY, Y, width(Y)-1
1983 // (d)sll SllY, SrlX, width(Y)-1
1984 // or Or, SrlX, SllY
1985 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1986 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1987 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1988 DAG.getConstant(WidthY - 1, DL, MVT::i32));
1990 if (WidthX > WidthY)
1991 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1992 else if (WidthY > WidthX)
1993 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1995 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1996 DAG.getConstant(WidthX - 1, DL, MVT::i32));
1997 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1998 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2002 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2003 if (Subtarget.isGP64bit())
2004 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2006 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2009 SDValue MipsTargetLowering::
2010 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2012 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2013 "Frame address can only be determined for current frame.");
2015 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2016 MFI->setFrameAddressIsTaken(true);
2017 EVT VT = Op.getValueType();
2019 SDValue FrameAddr = DAG.getCopyFromReg(
2020 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2024 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2025 SelectionDAG &DAG) const {
2026 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2030 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2031 "Return address can be determined only for current frame.");
2033 MachineFunction &MF = DAG.getMachineFunction();
2034 MachineFrameInfo *MFI = MF.getFrameInfo();
2035 MVT VT = Op.getSimpleValueType();
2036 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2037 MFI->setReturnAddressIsTaken(true);
2039 // Return RA, which contains the return address. Mark it an implicit live-in.
2040 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2041 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2044 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2045 // generated from __builtin_eh_return (offset, handler)
2046 // The effect of this is to adjust the stack pointer by "offset"
2047 // and then branch to "handler".
2048 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2050 MachineFunction &MF = DAG.getMachineFunction();
2051 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2053 MipsFI->setCallsEhReturn();
2054 SDValue Chain = Op.getOperand(0);
2055 SDValue Offset = Op.getOperand(1);
2056 SDValue Handler = Op.getOperand(2);
2058 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2060 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2061 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2062 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2063 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2064 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2065 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2066 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2067 DAG.getRegister(OffsetReg, Ty),
2068 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2072 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2073 SelectionDAG &DAG) const {
2074 // FIXME: Need pseudo-fence for 'singlethread' fences
2075 // FIXME: Set SType for weaker fences where supported/appropriate.
2078 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2079 DAG.getConstant(SType, DL, MVT::i32));
2082 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2083 SelectionDAG &DAG) const {
2085 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2087 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2088 SDValue Shamt = Op.getOperand(2);
2089 // if shamt < (VT.bits):
2090 // lo = (shl lo, shamt)
2091 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2094 // hi = (shl lo, shamt[4:0])
2095 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2096 DAG.getConstant(-1, DL, MVT::i32));
2097 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2098 DAG.getConstant(1, DL, VT));
2099 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2100 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2101 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2102 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2103 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2104 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2105 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2106 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2107 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2109 SDValue Ops[2] = {Lo, Hi};
2110 return DAG.getMergeValues(Ops, DL);
2113 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2116 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2117 SDValue Shamt = Op.getOperand(2);
2118 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2120 // if shamt < (VT.bits):
2121 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2123 // hi = (sra hi, shamt)
2125 // hi = (srl hi, shamt)
2128 // lo = (sra hi, shamt[4:0])
2129 // hi = (sra hi, 31)
2131 // lo = (srl hi, shamt[4:0])
2133 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2134 DAG.getConstant(-1, DL, MVT::i32));
2135 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2136 DAG.getConstant(1, DL, VT));
2137 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2138 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2139 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2140 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2142 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2143 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2144 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2145 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2146 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2147 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2148 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2150 SDValue Ops[2] = {Lo, Hi};
2151 return DAG.getMergeValues(Ops, DL);
2154 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2155 SDValue Chain, SDValue Src, unsigned Offset) {
2156 SDValue Ptr = LD->getBasePtr();
2157 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2158 EVT BasePtrVT = Ptr.getValueType();
2160 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2163 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2164 DAG.getConstant(Offset, DL, BasePtrVT));
2166 SDValue Ops[] = { Chain, Ptr, Src };
2167 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2168 LD->getMemOperand());
2171 // Expand an unaligned 32 or 64-bit integer load node.
2172 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2173 LoadSDNode *LD = cast<LoadSDNode>(Op);
2174 EVT MemVT = LD->getMemoryVT();
2176 if (Subtarget.systemSupportsUnalignedAccess())
2179 // Return if load is aligned or if MemVT is neither i32 nor i64.
2180 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2181 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2184 bool IsLittle = Subtarget.isLittle();
2185 EVT VT = Op.getValueType();
2186 ISD::LoadExtType ExtType = LD->getExtensionType();
2187 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2189 assert((VT == MVT::i32) || (VT == MVT::i64));
2192 // (set dst, (i64 (load baseptr)))
2194 // (set tmp, (ldl (add baseptr, 7), undef))
2195 // (set dst, (ldr baseptr, tmp))
2196 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2197 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2199 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2203 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2205 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2209 // (set dst, (i32 (load baseptr))) or
2210 // (set dst, (i64 (sextload baseptr))) or
2211 // (set dst, (i64 (extload baseptr)))
2213 // (set tmp, (lwl (add baseptr, 3), undef))
2214 // (set dst, (lwr baseptr, tmp))
2215 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2216 (ExtType == ISD::EXTLOAD))
2219 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2222 // (set dst, (i64 (zextload baseptr)))
2224 // (set tmp0, (lwl (add baseptr, 3), undef))
2225 // (set tmp1, (lwr baseptr, tmp0))
2226 // (set tmp2, (shl tmp1, 32))
2227 // (set dst, (srl tmp2, 32))
2229 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2230 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2231 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2232 SDValue Ops[] = { SRL, LWR.getValue(1) };
2233 return DAG.getMergeValues(Ops, DL);
2236 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2237 SDValue Chain, unsigned Offset) {
2238 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2239 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2241 SDVTList VTList = DAG.getVTList(MVT::Other);
2244 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2245 DAG.getConstant(Offset, DL, BasePtrVT));
2247 SDValue Ops[] = { Chain, Value, Ptr };
2248 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2249 SD->getMemOperand());
2252 // Expand an unaligned 32 or 64-bit integer store node.
2253 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2255 SDValue Value = SD->getValue(), Chain = SD->getChain();
2256 EVT VT = Value.getValueType();
2259 // (store val, baseptr) or
2260 // (truncstore val, baseptr)
2262 // (swl val, (add baseptr, 3))
2263 // (swr val, baseptr)
2264 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2265 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2267 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2270 assert(VT == MVT::i64);
2273 // (store val, baseptr)
2275 // (sdl val, (add baseptr, 7))
2276 // (sdr val, baseptr)
2277 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2278 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2281 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2282 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2283 SDValue Val = SD->getValue();
2285 if (Val.getOpcode() != ISD::FP_TO_SINT)
2288 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2289 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2292 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2293 SD->getPointerInfo(), SD->isVolatile(),
2294 SD->isNonTemporal(), SD->getAlignment());
2297 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2298 StoreSDNode *SD = cast<StoreSDNode>(Op);
2299 EVT MemVT = SD->getMemoryVT();
2301 // Lower unaligned integer stores.
2302 if (!Subtarget.systemSupportsUnalignedAccess() &&
2303 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2304 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2305 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2307 return lowerFP_TO_SINT_STORE(SD, DAG);
2310 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2311 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2312 || cast<ConstantSDNode>
2313 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2314 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2318 // (add (frameaddr 0), (frame_to_args_offset))
2319 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2320 // (add FrameObject, 0)
2321 // where FrameObject is a fixed StackObject with offset 0 which points to
2322 // the old stack pointer.
2323 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2324 EVT ValTy = Op->getValueType(0);
2325 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2326 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2328 return DAG.getNode(ISD::ADD, DL, ValTy, InArgsAddr,
2329 DAG.getConstant(0, DL, ValTy));
2332 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2333 SelectionDAG &DAG) const {
2334 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2335 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2337 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2340 //===----------------------------------------------------------------------===//
2341 // Calling Convention Implementation
2342 //===----------------------------------------------------------------------===//
2344 //===----------------------------------------------------------------------===//
2345 // TODO: Implement a generic logic using tblgen that can support this.
2346 // Mips O32 ABI rules:
2348 // i32 - Passed in A0, A1, A2, A3 and stack
2349 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2350 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2351 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2352 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2353 // not used, it must be shadowed. If only A3 is available, shadow it and
2356 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2357 //===----------------------------------------------------------------------===//
2359 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2360 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2361 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2362 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2363 State.getMachineFunction().getSubtarget());
2365 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2366 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2368 // Do not process byval args here.
2369 if (ArgFlags.isByVal())
2372 // Promote i8 and i16
2373 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2374 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2376 if (ArgFlags.isSExt())
2377 LocInfo = CCValAssign::SExtUpper;
2378 else if (ArgFlags.isZExt())
2379 LocInfo = CCValAssign::ZExtUpper;
2381 LocInfo = CCValAssign::AExtUpper;
2385 // Promote i8 and i16
2386 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2388 if (ArgFlags.isSExt())
2389 LocInfo = CCValAssign::SExt;
2390 else if (ArgFlags.isZExt())
2391 LocInfo = CCValAssign::ZExt;
2393 LocInfo = CCValAssign::AExt;
2398 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2399 // is true: function is vararg, argument is 3rd or higher, there is previous
2400 // argument which is not f32 or f64.
2401 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2402 State.getFirstUnallocated(F32Regs) != ValNo;
2403 unsigned OrigAlign = ArgFlags.getOrigAlign();
2404 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2406 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2407 Reg = State.AllocateReg(IntRegs);
2408 // If this is the first part of an i64 arg,
2409 // the allocated register must be either A0 or A2.
2410 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2411 Reg = State.AllocateReg(IntRegs);
2413 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2414 // Allocate int register and shadow next int register. If first
2415 // available register is Mips::A1 or Mips::A3, shadow it too.
2416 Reg = State.AllocateReg(IntRegs);
2417 if (Reg == Mips::A1 || Reg == Mips::A3)
2418 Reg = State.AllocateReg(IntRegs);
2419 State.AllocateReg(IntRegs);
2421 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2422 // we are guaranteed to find an available float register
2423 if (ValVT == MVT::f32) {
2424 Reg = State.AllocateReg(F32Regs);
2425 // Shadow int register
2426 State.AllocateReg(IntRegs);
2428 Reg = State.AllocateReg(F64Regs);
2429 // Shadow int registers
2430 unsigned Reg2 = State.AllocateReg(IntRegs);
2431 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2432 State.AllocateReg(IntRegs);
2433 State.AllocateReg(IntRegs);
2436 llvm_unreachable("Cannot handle this ValVT.");
2439 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2441 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2443 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2448 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2449 MVT LocVT, CCValAssign::LocInfo LocInfo,
2450 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2451 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2453 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2456 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2457 MVT LocVT, CCValAssign::LocInfo LocInfo,
2458 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2459 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2461 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2464 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2465 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2466 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2468 #include "MipsGenCallingConv.inc"
2470 //===----------------------------------------------------------------------===//
2471 // Call Calling Convention Implementation
2472 //===----------------------------------------------------------------------===//
2474 // Return next O32 integer argument register.
2475 static unsigned getNextIntArgReg(unsigned Reg) {
2476 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2477 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2481 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2482 SDValue Chain, SDValue Arg, SDLoc DL,
2483 bool IsTailCall, SelectionDAG &DAG) const {
2486 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2487 DAG.getIntPtrConstant(Offset, DL));
2488 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2492 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2493 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2494 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2495 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2496 /*isVolatile=*/ true, false, 0);
2499 void MipsTargetLowering::
2500 getOpndList(SmallVectorImpl<SDValue> &Ops,
2501 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2502 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2503 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2504 SDValue Chain) const {
2505 // Insert node "GP copy globalreg" before call to function.
2507 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2508 // in PIC mode) allow symbols to be resolved via lazy binding.
2509 // The lazy binding stub requires GP to point to the GOT.
2510 // Note that we don't need GP to point to the GOT for indirect calls
2511 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2512 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2513 // used for the function (that is, Mips linker doesn't generate lazy binding
2514 // stub for a function whose address is taken in the program).
2515 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2516 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2517 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2518 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2521 // Build a sequence of copy-to-reg nodes chained together with token
2522 // chain and flag operands which copy the outgoing args into registers.
2523 // The InFlag in necessary since all emitted instructions must be
2527 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2528 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2529 RegsToPass[i].second, InFlag);
2530 InFlag = Chain.getValue(1);
2533 // Add argument registers to the end of the list so that they are
2534 // known live into the call.
2535 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2536 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2537 RegsToPass[i].second.getValueType()));
2539 // Add a register mask operand representing the call-preserved registers.
2540 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2541 const uint32_t *Mask =
2542 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2543 assert(Mask && "Missing call preserved mask for calling convention");
2544 if (Subtarget.inMips16HardFloat()) {
2545 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2546 llvm::StringRef Sym = G->getGlobal()->getName();
2547 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2548 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2549 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2553 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2555 if (InFlag.getNode())
2556 Ops.push_back(InFlag);
2559 /// LowerCall - functions arguments are copied from virtual regs to
2560 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2562 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2563 SmallVectorImpl<SDValue> &InVals) const {
2564 SelectionDAG &DAG = CLI.DAG;
2566 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2567 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2568 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2569 SDValue Chain = CLI.Chain;
2570 SDValue Callee = CLI.Callee;
2571 bool &IsTailCall = CLI.IsTailCall;
2572 CallingConv::ID CallConv = CLI.CallConv;
2573 bool IsVarArg = CLI.IsVarArg;
2575 MachineFunction &MF = DAG.getMachineFunction();
2576 MachineFrameInfo *MFI = MF.getFrameInfo();
2577 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2578 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2579 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2581 // Analyze operands of the call, assigning locations to each operand.
2582 SmallVector<CCValAssign, 16> ArgLocs;
2584 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2585 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2587 // Allocate the reserved argument area. It seems strange to do this from the
2588 // caller side but removing it breaks the frame size calculation.
2589 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2591 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2593 // Get a count of how many bytes are to be pushed on the stack.
2594 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2596 // Check if it's really possible to do a tail call.
2598 IsTailCall = isEligibleForTailCallOptimization(
2599 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2601 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2602 report_fatal_error("failed to perform tail call elimination on a call "
2603 "site marked musttail");
2608 // Chain is the output chain of the last Load/Store or CopyToReg node.
2609 // ByValChain is the output chain of the last Memcpy node created for copying
2610 // byval arguments to the stack.
2611 unsigned StackAlignment = TFL->getStackAlignment();
2612 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2613 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2616 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2619 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
2620 getPointerTy(DAG.getDataLayout()));
2622 // With EABI is it possible to have 16 args on registers.
2623 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2624 SmallVector<SDValue, 8> MemOpChains;
2626 CCInfo.rewindByValRegsInfo();
2628 // Walk the register/memloc assignments, inserting copies/loads.
2629 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2630 SDValue Arg = OutVals[i];
2631 CCValAssign &VA = ArgLocs[i];
2632 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2633 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2634 bool UseUpperBits = false;
2637 if (Flags.isByVal()) {
2638 unsigned FirstByValReg, LastByValReg;
2639 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2640 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2642 assert(Flags.getByValSize() &&
2643 "ByVal args of size 0 should have been ignored by front-end.");
2644 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2645 assert(!IsTailCall &&
2646 "Do not tail-call optimize if there is a byval argument.");
2647 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2648 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2650 CCInfo.nextInRegsParam();
2654 // Promote the value if needed.
2655 switch (VA.getLocInfo()) {
2657 llvm_unreachable("Unknown loc info!");
2658 case CCValAssign::Full:
2659 if (VA.isRegLoc()) {
2660 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2661 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2662 (ValVT == MVT::i64 && LocVT == MVT::f64))
2663 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2664 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2665 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2666 Arg, DAG.getConstant(0, DL, MVT::i32));
2667 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2668 Arg, DAG.getConstant(1, DL, MVT::i32));
2669 if (!Subtarget.isLittle())
2671 unsigned LocRegLo = VA.getLocReg();
2672 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2673 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2674 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2679 case CCValAssign::BCvt:
2680 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2682 case CCValAssign::SExtUpper:
2683 UseUpperBits = true;
2685 case CCValAssign::SExt:
2686 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2688 case CCValAssign::ZExtUpper:
2689 UseUpperBits = true;
2691 case CCValAssign::ZExt:
2692 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2694 case CCValAssign::AExtUpper:
2695 UseUpperBits = true;
2697 case CCValAssign::AExt:
2698 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2703 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2704 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2706 ISD::SHL, DL, VA.getLocVT(), Arg,
2707 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2710 // Arguments that can be passed on register must be kept at
2711 // RegsToPass vector
2712 if (VA.isRegLoc()) {
2713 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2717 // Register can't get to this point...
2718 assert(VA.isMemLoc());
2720 // emit ISD::STORE whichs stores the
2721 // parameter value to a stack Location
2722 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2723 Chain, Arg, DL, IsTailCall, DAG));
2726 // Transform all store nodes into one single node because all store
2727 // nodes are independent of each other.
2728 if (!MemOpChains.empty())
2729 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2731 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2732 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2733 // node so that legalize doesn't hack it.
2734 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2736 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2738 EVT Ty = Callee.getValueType();
2740 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2742 const GlobalValue *Val = G->getGlobal();
2743 InternalLinkage = Val->hasInternalLinkage();
2745 if (InternalLinkage)
2746 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2747 else if (LargeGOT) {
2748 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2749 MipsII::MO_CALL_LO16, Chain,
2750 FuncInfo->callPtrInfo(Val));
2753 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2754 FuncInfo->callPtrInfo(Val));
2758 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
2759 getPointerTy(DAG.getDataLayout()), 0,
2760 MipsII::MO_NO_FLAG);
2761 GlobalOrExternal = true;
2763 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2764 const char *Sym = S->getSymbol();
2766 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2767 Callee = DAG.getTargetExternalSymbol(
2768 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
2769 else if (LargeGOT) {
2770 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2771 MipsII::MO_CALL_LO16, Chain,
2772 FuncInfo->callPtrInfo(Sym));
2774 } else { // N64 || PIC
2775 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2776 FuncInfo->callPtrInfo(Sym));
2780 GlobalOrExternal = true;
2783 SmallVector<SDValue, 8> Ops(1, Chain);
2784 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2786 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2787 IsCallReloc, CLI, Callee, Chain);
2790 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2792 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2793 SDValue InFlag = Chain.getValue(1);
2795 // Create the CALLSEQ_END node.
2796 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2797 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2798 InFlag = Chain.getValue(1);
2800 // Handle result values, copying them out of physregs into vregs that we
2802 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2806 /// LowerCallResult - Lower the result values of a call into the
2807 /// appropriate copies out of appropriate physical registers.
2808 SDValue MipsTargetLowering::LowerCallResult(
2809 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2810 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2811 SmallVectorImpl<SDValue> &InVals,
2812 TargetLowering::CallLoweringInfo &CLI) const {
2813 // Assign locations to each value returned by this call.
2814 SmallVector<CCValAssign, 16> RVLocs;
2815 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2817 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2819 // Copy all of the result registers out of their specified physreg.
2820 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2821 CCValAssign &VA = RVLocs[i];
2822 assert(VA.isRegLoc() && "Can only return in registers!");
2824 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2825 RVLocs[i].getLocVT(), InFlag);
2826 Chain = Val.getValue(1);
2827 InFlag = Val.getValue(2);
2829 if (VA.isUpperBitsInLoc()) {
2830 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2831 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2833 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2835 Shift, DL, VA.getLocVT(), Val,
2836 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2839 switch (VA.getLocInfo()) {
2841 llvm_unreachable("Unknown loc info!");
2842 case CCValAssign::Full:
2844 case CCValAssign::BCvt:
2845 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2847 case CCValAssign::AExt:
2848 case CCValAssign::AExtUpper:
2849 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2851 case CCValAssign::ZExt:
2852 case CCValAssign::ZExtUpper:
2853 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2854 DAG.getValueType(VA.getValVT()));
2855 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2857 case CCValAssign::SExt:
2858 case CCValAssign::SExtUpper:
2859 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2860 DAG.getValueType(VA.getValVT()));
2861 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2865 InVals.push_back(Val);
2871 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2872 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2873 MVT LocVT = VA.getLocVT();
2874 EVT ValVT = VA.getValVT();
2876 // Shift into the upper bits if necessary.
2877 switch (VA.getLocInfo()) {
2880 case CCValAssign::AExtUpper:
2881 case CCValAssign::SExtUpper:
2882 case CCValAssign::ZExtUpper: {
2883 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2884 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2886 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2888 Opcode, DL, VA.getLocVT(), Val,
2889 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2894 // If this is an value smaller than the argument slot size (32-bit for O32,
2895 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2896 // size. Extract the value and insert any appropriate assertions regarding
2897 // sign/zero extension.
2898 switch (VA.getLocInfo()) {
2900 llvm_unreachable("Unknown loc info!");
2901 case CCValAssign::Full:
2903 case CCValAssign::AExtUpper:
2904 case CCValAssign::AExt:
2905 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2907 case CCValAssign::SExtUpper:
2908 case CCValAssign::SExt:
2909 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2910 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2912 case CCValAssign::ZExtUpper:
2913 case CCValAssign::ZExt:
2914 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2915 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2917 case CCValAssign::BCvt:
2918 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2925 //===----------------------------------------------------------------------===//
2926 // Formal Arguments Calling Convention Implementation
2927 //===----------------------------------------------------------------------===//
2928 /// LowerFormalArguments - transform physical registers into virtual registers
2929 /// and generate load operations for arguments places on the stack.
2931 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2932 CallingConv::ID CallConv,
2934 const SmallVectorImpl<ISD::InputArg> &Ins,
2935 SDLoc DL, SelectionDAG &DAG,
2936 SmallVectorImpl<SDValue> &InVals)
2938 MachineFunction &MF = DAG.getMachineFunction();
2939 MachineFrameInfo *MFI = MF.getFrameInfo();
2940 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2942 MipsFI->setVarArgsFrameIndex(0);
2944 // Used with vargs to acumulate store chains.
2945 std::vector<SDValue> OutChains;
2947 // Assign locations to all of the incoming arguments.
2948 SmallVector<CCValAssign, 16> ArgLocs;
2949 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2951 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2952 const Function *Func = DAG.getMachineFunction().getFunction();
2953 Function::const_arg_iterator FuncArg = Func->arg_begin();
2955 if (Func->hasFnAttribute("interrupt"))
2956 assert(Func->arg_empty() &&
2957 "Functions with the interrupt attribute cannot have arguments!");
2959 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2960 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2961 CCInfo.getInRegsParamsCount() > 0);
2963 unsigned CurArgIdx = 0;
2964 CCInfo.rewindByValRegsInfo();
2966 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2967 CCValAssign &VA = ArgLocs[i];
2968 if (Ins[i].isOrigArg()) {
2969 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2970 CurArgIdx = Ins[i].getOrigArgIndex();
2972 EVT ValVT = VA.getValVT();
2973 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2974 bool IsRegLoc = VA.isRegLoc();
2976 if (Flags.isByVal()) {
2977 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2978 unsigned FirstByValReg, LastByValReg;
2979 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2980 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2982 assert(Flags.getByValSize() &&
2983 "ByVal args of size 0 should have been ignored by front-end.");
2984 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2985 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2986 FirstByValReg, LastByValReg, VA, CCInfo);
2987 CCInfo.nextInRegsParam();
2991 // Arguments stored on registers
2993 MVT RegVT = VA.getLocVT();
2994 unsigned ArgReg = VA.getLocReg();
2995 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2997 // Transform the arguments stored on
2998 // physical registers into virtual ones
2999 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3000 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3002 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3004 // Handle floating point arguments passed in integer registers and
3005 // long double arguments passed in floating point registers.
3006 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3007 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3008 (RegVT == MVT::f64 && ValVT == MVT::i64))
3009 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3010 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3011 ValVT == MVT::f64) {
3012 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3013 getNextIntArgReg(ArgReg), RC);
3014 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3015 if (!Subtarget.isLittle())
3016 std::swap(ArgValue, ArgValue2);
3017 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3018 ArgValue, ArgValue2);
3021 InVals.push_back(ArgValue);
3022 } else { // VA.isRegLoc()
3023 MVT LocVT = VA.getLocVT();
3026 // We ought to be able to use LocVT directly but O32 sets it to i32
3027 // when allocating floating point values to integer registers.
3028 // This shouldn't influence how we load the value into registers unless
3029 // we are targeting softfloat.
3030 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3031 LocVT = VA.getValVT();
3035 assert(VA.isMemLoc());
3037 // The stack pointer offset is relative to the caller stack frame.
3038 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
3039 VA.getLocMemOffset(), true);
3041 // Create load nodes to retrieve arguments from the stack
3042 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3043 SDValue ArgValue = DAG.getLoad(
3044 LocVT, DL, Chain, FIN,
3045 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3046 false, false, false, 0);
3047 OutChains.push_back(ArgValue.getValue(1));
3049 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3051 InVals.push_back(ArgValue);
3055 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3056 // The mips ABIs for returning structs by value requires that we copy
3057 // the sret argument into $v0 for the return. Save the argument into
3058 // a virtual register so that we can access it from the return points.
3059 if (Ins[i].Flags.isSRet()) {
3060 unsigned Reg = MipsFI->getSRetReturnReg();
3062 Reg = MF.getRegInfo().createVirtualRegister(
3063 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3064 MipsFI->setSRetReturnReg(Reg);
3066 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3067 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3073 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3075 // All stores are grouped in one node to allow the matching between
3076 // the size of Ins and InVals. This only happens when on varg functions
3077 if (!OutChains.empty()) {
3078 OutChains.push_back(Chain);
3079 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3085 //===----------------------------------------------------------------------===//
3086 // Return Value Calling Convention Implementation
3087 //===----------------------------------------------------------------------===//
3090 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3091 MachineFunction &MF, bool IsVarArg,
3092 const SmallVectorImpl<ISD::OutputArg> &Outs,
3093 LLVMContext &Context) const {
3094 SmallVector<CCValAssign, 16> RVLocs;
3095 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3096 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3100 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3101 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3102 if (Type == MVT::i32)
3109 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3110 SDLoc DL, SelectionDAG &DAG) const {
3112 MachineFunction &MF = DAG.getMachineFunction();
3113 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3117 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3121 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3123 const SmallVectorImpl<ISD::OutputArg> &Outs,
3124 const SmallVectorImpl<SDValue> &OutVals,
3125 SDLoc DL, SelectionDAG &DAG) const {
3126 // CCValAssign - represent the assignment of
3127 // the return value to a location
3128 SmallVector<CCValAssign, 16> RVLocs;
3129 MachineFunction &MF = DAG.getMachineFunction();
3131 // CCState - Info about the registers and stack slot.
3132 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3134 // Analyze return values.
3135 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3138 SmallVector<SDValue, 4> RetOps(1, Chain);
3140 // Copy the result values into the output registers.
3141 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3142 SDValue Val = OutVals[i];
3143 CCValAssign &VA = RVLocs[i];
3144 assert(VA.isRegLoc() && "Can only return in registers!");
3145 bool UseUpperBits = false;
3147 switch (VA.getLocInfo()) {
3149 llvm_unreachable("Unknown loc info!");
3150 case CCValAssign::Full:
3152 case CCValAssign::BCvt:
3153 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3155 case CCValAssign::AExtUpper:
3156 UseUpperBits = true;
3158 case CCValAssign::AExt:
3159 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3161 case CCValAssign::ZExtUpper:
3162 UseUpperBits = true;
3164 case CCValAssign::ZExt:
3165 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3167 case CCValAssign::SExtUpper:
3168 UseUpperBits = true;
3170 case CCValAssign::SExt:
3171 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3176 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3177 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3179 ISD::SHL, DL, VA.getLocVT(), Val,
3180 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3183 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3185 // Guarantee that all emitted copies are stuck together with flags.
3186 Flag = Chain.getValue(1);
3187 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3190 // The mips ABIs for returning structs by value requires that we copy
3191 // the sret argument into $v0 for the return. We saved the argument into
3192 // a virtual register in the entry block, so now we copy the value out
3194 if (MF.getFunction()->hasStructRetAttr()) {
3195 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3196 unsigned Reg = MipsFI->getSRetReturnReg();
3199 llvm_unreachable("sret virtual register not created in the entry block");
3201 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3202 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3204 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3205 Flag = Chain.getValue(1);
3206 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3209 RetOps[0] = Chain; // Update chain.
3211 // Add the flag if we have it.
3213 RetOps.push_back(Flag);
3215 // ISRs must use "eret".
3216 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
3217 return LowerInterruptReturn(RetOps, DL, DAG);
3219 // Standard return on Mips is a "jr $ra"
3220 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3223 //===----------------------------------------------------------------------===//
3224 // Mips Inline Assembly Support
3225 //===----------------------------------------------------------------------===//
3227 /// getConstraintType - Given a constraint letter, return the type of
3228 /// constraint it is for this target.
3229 MipsTargetLowering::ConstraintType
3230 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3231 // Mips specific constraints
3232 // GCC config/mips/constraints.md
3234 // 'd' : An address register. Equivalent to r
3235 // unless generating MIPS16 code.
3236 // 'y' : Equivalent to r; retained for
3237 // backwards compatibility.
3238 // 'c' : A register suitable for use in an indirect
3239 // jump. This will always be $25 for -mabicalls.
3240 // 'l' : The lo register. 1 word storage.
3241 // 'x' : The hilo register pair. Double word storage.
3242 if (Constraint.size() == 1) {
3243 switch (Constraint[0]) {
3251 return C_RegisterClass;
3257 if (Constraint == "ZC")
3260 return TargetLowering::getConstraintType(Constraint);
3263 /// Examine constraint type and operand type and determine a weight value.
3264 /// This object must already have been set up with the operand type
3265 /// and the current alternative constraint selected.
3266 TargetLowering::ConstraintWeight
3267 MipsTargetLowering::getSingleConstraintMatchWeight(
3268 AsmOperandInfo &info, const char *constraint) const {
3269 ConstraintWeight weight = CW_Invalid;
3270 Value *CallOperandVal = info.CallOperandVal;
3271 // If we don't have a value, we can't do a match,
3272 // but allow it at the lowest weight.
3273 if (!CallOperandVal)
3275 Type *type = CallOperandVal->getType();
3276 // Look at the constraint type.
3277 switch (*constraint) {
3279 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3283 if (type->isIntegerTy())
3284 weight = CW_Register;
3286 case 'f': // FPU or MSA register
3287 if (Subtarget.hasMSA() && type->isVectorTy() &&
3288 cast<VectorType>(type)->getBitWidth() == 128)
3289 weight = CW_Register;
3290 else if (type->isFloatTy())
3291 weight = CW_Register;
3293 case 'c': // $25 for indirect jumps
3294 case 'l': // lo register
3295 case 'x': // hilo register pair
3296 if (type->isIntegerTy())
3297 weight = CW_SpecificReg;
3299 case 'I': // signed 16 bit immediate
3300 case 'J': // integer zero
3301 case 'K': // unsigned 16 bit immediate
3302 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3303 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3304 case 'O': // signed 15 bit immediate (+- 16383)
3305 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3306 if (isa<ConstantInt>(CallOperandVal))
3307 weight = CW_Constant;
3316 /// This is a helper function to parse a physical register string and split it
3317 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3318 /// that is returned indicates whether parsing was successful. The second flag
3319 /// is true if the numeric part exists.
3320 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3321 unsigned long long &Reg) {
3322 if (C.front() != '{' || C.back() != '}')
3323 return std::make_pair(false, false);
3325 // Search for the first numeric character.
3326 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3327 I = std::find_if(B, E, std::ptr_fun(isdigit));
3329 Prefix = StringRef(B, I - B);
3331 // The second flag is set to false if no numeric characters were found.
3333 return std::make_pair(true, false);
3335 // Parse the numeric characters.
3336 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3340 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3341 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3342 const TargetRegisterInfo *TRI =
3343 Subtarget.getRegisterInfo();
3344 const TargetRegisterClass *RC;
3346 unsigned long long Reg;
3348 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3351 return std::make_pair(0U, nullptr);
3353 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3354 // No numeric characters follow "hi" or "lo".
3356 return std::make_pair(0U, nullptr);
3358 RC = TRI->getRegClass(Prefix == "hi" ?
3359 Mips::HI32RegClassID : Mips::LO32RegClassID);
3360 return std::make_pair(*(RC->begin()), RC);
3361 } else if (Prefix.startswith("$msa")) {
3362 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3364 // No numeric characters follow the name.
3366 return std::make_pair(0U, nullptr);
3368 Reg = StringSwitch<unsigned long long>(Prefix)
3369 .Case("$msair", Mips::MSAIR)
3370 .Case("$msacsr", Mips::MSACSR)
3371 .Case("$msaaccess", Mips::MSAAccess)
3372 .Case("$msasave", Mips::MSASave)
3373 .Case("$msamodify", Mips::MSAModify)
3374 .Case("$msarequest", Mips::MSARequest)
3375 .Case("$msamap", Mips::MSAMap)
3376 .Case("$msaunmap", Mips::MSAUnmap)
3380 return std::make_pair(0U, nullptr);
3382 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3383 return std::make_pair(Reg, RC);
3387 return std::make_pair(0U, nullptr);
3389 if (Prefix == "$f") { // Parse $f0-$f31.
3390 // If the size of FP registers is 64-bit or Reg is an even number, select
3391 // the 64-bit register class. Otherwise, select the 32-bit register class.
3392 if (VT == MVT::Other)
3393 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3395 RC = getRegClassFor(VT);
3397 if (RC == &Mips::AFGR64RegClass) {
3398 assert(Reg % 2 == 0);
3401 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3402 RC = TRI->getRegClass(Mips::FCCRegClassID);
3403 else if (Prefix == "$w") { // Parse $w0-$w31.
3404 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3405 } else { // Parse $0-$31.
3406 assert(Prefix == "$");
3407 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3410 assert(Reg < RC->getNumRegs());
3411 return std::make_pair(*(RC->begin() + Reg), RC);
3414 /// Given a register class constraint, like 'r', if this corresponds directly
3415 /// to an LLVM register class, return a register of 0 and the register class
3417 std::pair<unsigned, const TargetRegisterClass *>
3418 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3419 StringRef Constraint,
3421 if (Constraint.size() == 1) {
3422 switch (Constraint[0]) {
3423 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3424 case 'y': // Same as 'r'. Exists for compatibility.
3426 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3427 if (Subtarget.inMips16Mode())
3428 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3429 return std::make_pair(0U, &Mips::GPR32RegClass);
3431 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3432 return std::make_pair(0U, &Mips::GPR32RegClass);
3433 if (VT == MVT::i64 && Subtarget.isGP64bit())
3434 return std::make_pair(0U, &Mips::GPR64RegClass);
3435 // This will generate an error message
3436 return std::make_pair(0U, nullptr);
3437 case 'f': // FPU or MSA register
3438 if (VT == MVT::v16i8)
3439 return std::make_pair(0U, &Mips::MSA128BRegClass);
3440 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3441 return std::make_pair(0U, &Mips::MSA128HRegClass);
3442 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3443 return std::make_pair(0U, &Mips::MSA128WRegClass);
3444 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3445 return std::make_pair(0U, &Mips::MSA128DRegClass);
3446 else if (VT == MVT::f32)
3447 return std::make_pair(0U, &Mips::FGR32RegClass);
3448 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3449 if (Subtarget.isFP64bit())
3450 return std::make_pair(0U, &Mips::FGR64RegClass);
3451 return std::make_pair(0U, &Mips::AFGR64RegClass);
3454 case 'c': // register suitable for indirect jump
3456 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3457 assert(VT == MVT::i64 && "Unexpected type.");
3458 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3459 case 'l': // register suitable for indirect jump
3461 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3462 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3463 case 'x': // register suitable for indirect jump
3464 // Fixme: Not triggering the use of both hi and low
3465 // This will generate an error message
3466 return std::make_pair(0U, nullptr);
3470 std::pair<unsigned, const TargetRegisterClass *> R;
3471 R = parseRegForInlineAsmConstraint(Constraint, VT);
3476 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3479 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3480 /// vector. If it is invalid, don't add anything to Ops.
3481 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3482 std::string &Constraint,
3483 std::vector<SDValue>&Ops,
3484 SelectionDAG &DAG) const {
3488 // Only support length 1 constraints for now.
3489 if (Constraint.length() > 1) return;
3491 char ConstraintLetter = Constraint[0];
3492 switch (ConstraintLetter) {
3493 default: break; // This will fall through to the generic implementation
3494 case 'I': // Signed 16 bit constant
3495 // If this fails, the parent routine will give an error
3496 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3497 EVT Type = Op.getValueType();
3498 int64_t Val = C->getSExtValue();
3499 if (isInt<16>(Val)) {
3500 Result = DAG.getTargetConstant(Val, DL, Type);
3505 case 'J': // integer zero
3506 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3507 EVT Type = Op.getValueType();
3508 int64_t Val = C->getZExtValue();
3510 Result = DAG.getTargetConstant(0, DL, Type);
3515 case 'K': // unsigned 16 bit immediate
3516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3517 EVT Type = Op.getValueType();
3518 uint64_t Val = (uint64_t)C->getZExtValue();
3519 if (isUInt<16>(Val)) {
3520 Result = DAG.getTargetConstant(Val, DL, Type);
3525 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3526 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3527 EVT Type = Op.getValueType();
3528 int64_t Val = C->getSExtValue();
3529 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3530 Result = DAG.getTargetConstant(Val, DL, Type);
3535 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3536 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3537 EVT Type = Op.getValueType();
3538 int64_t Val = C->getSExtValue();
3539 if ((Val >= -65535) && (Val <= -1)) {
3540 Result = DAG.getTargetConstant(Val, DL, Type);
3545 case 'O': // signed 15 bit immediate
3546 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3547 EVT Type = Op.getValueType();
3548 int64_t Val = C->getSExtValue();
3549 if ((isInt<15>(Val))) {
3550 Result = DAG.getTargetConstant(Val, DL, Type);
3555 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3556 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3557 EVT Type = Op.getValueType();
3558 int64_t Val = C->getSExtValue();
3559 if ((Val <= 65535) && (Val >= 1)) {
3560 Result = DAG.getTargetConstant(Val, DL, Type);
3567 if (Result.getNode()) {
3568 Ops.push_back(Result);
3572 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3575 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3576 const AddrMode &AM, Type *Ty,
3577 unsigned AS) const {
3578 // No global is ever allowed as a base.
3583 case 0: // "r+i" or just "i", depending on HasBaseReg.
3586 if (!AM.HasBaseReg) // allow "r+i".
3588 return false; // disallow "r+r" or "r+r+i".
3597 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3598 // The Mips target isn't yet aware of offsets.
3602 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3604 bool IsMemset, bool ZeroMemset,
3606 MachineFunction &MF) const {
3607 if (Subtarget.hasMips64())
3613 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3614 if (VT != MVT::f32 && VT != MVT::f64)
3616 if (Imm.isNegZero())
3618 return Imm.isZero();
3621 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3623 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3625 return TargetLowering::getJumpTableEncoding();
3628 bool MipsTargetLowering::useSoftFloat() const {
3629 return Subtarget.useSoftFloat();
3632 void MipsTargetLowering::copyByValRegs(
3633 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3634 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3635 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3636 const CCValAssign &VA, MipsCCState &State) const {
3637 MachineFunction &MF = DAG.getMachineFunction();
3638 MachineFrameInfo *MFI = MF.getFrameInfo();
3639 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3640 unsigned NumRegs = LastReg - FirstReg;
3641 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3642 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3644 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3648 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3649 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3651 FrameObjOffset = VA.getLocMemOffset();
3653 // Create frame object.
3654 EVT PtrTy = getPointerTy(DAG.getDataLayout());
3655 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3656 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3657 InVals.push_back(FIN);
3662 // Copy arg registers.
3663 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3664 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3666 for (unsigned I = 0; I < NumRegs; ++I) {
3667 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3668 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3669 unsigned Offset = I * GPRSizeInBytes;
3670 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3671 DAG.getConstant(Offset, DL, PtrTy));
3672 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3673 StorePtr, MachinePointerInfo(FuncArg, Offset),
3675 OutChains.push_back(Store);
3679 // Copy byVal arg to registers and stack.
3680 void MipsTargetLowering::passByValArg(
3681 SDValue Chain, SDLoc DL,
3682 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3683 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3684 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3685 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3686 const CCValAssign &VA) const {
3687 unsigned ByValSizeInBytes = Flags.getByValSize();
3688 unsigned OffsetInBytes = 0; // From beginning of struct
3689 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3690 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3691 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
3692 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3693 unsigned NumRegs = LastReg - FirstReg;
3696 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3697 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3700 // Copy words to registers.
3701 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3702 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3703 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3704 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3705 MachinePointerInfo(), false, false, false,
3707 MemOpChains.push_back(LoadVal.getValue(1));
3708 unsigned ArgReg = ArgRegs[FirstReg + I];
3709 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3712 // Return if the struct has been fully copied.
3713 if (ByValSizeInBytes == OffsetInBytes)
3716 // Copy the remainder of the byval argument with sub-word loads and shifts.
3717 if (LeftoverBytes) {
3720 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3721 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3722 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3724 if (RemainingSizeInBytes < LoadSizeInBytes)
3728 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3729 DAG.getConstant(OffsetInBytes, DL,
3731 SDValue LoadVal = DAG.getExtLoad(
3732 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3733 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3735 MemOpChains.push_back(LoadVal.getValue(1));
3737 // Shift the loaded value.
3741 Shamt = TotalBytesLoaded * 8;
3743 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3745 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3746 DAG.getConstant(Shamt, DL, MVT::i32));
3749 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3753 OffsetInBytes += LoadSizeInBytes;
3754 TotalBytesLoaded += LoadSizeInBytes;
3755 Alignment = std::min(Alignment, LoadSizeInBytes);
3758 unsigned ArgReg = ArgRegs[FirstReg + I];
3759 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3764 // Copy remainder of byval arg to it with memcpy.
3765 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3766 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3767 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3768 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3769 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3770 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3771 DAG.getConstant(MemCpySize, DL, PtrTy),
3772 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3773 /*isTailCall=*/false,
3774 MachinePointerInfo(), MachinePointerInfo());
3775 MemOpChains.push_back(Chain);
3778 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3779 SDValue Chain, SDLoc DL,
3781 CCState &State) const {
3782 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3783 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3784 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3785 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3786 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3787 MachineFunction &MF = DAG.getMachineFunction();
3788 MachineFrameInfo *MFI = MF.getFrameInfo();
3789 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3791 // Offset of the first variable argument from stack pointer.
3794 if (ArgRegs.size() == Idx)
3796 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3799 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3800 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3803 // Record the frame index of the first variable argument
3804 // which is a value necessary to VASTART.
3805 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3806 MipsFI->setVarArgsFrameIndex(FI);
3808 // Copy the integer registers that have not been used for argument passing
3809 // to the argument register save area. For O32, the save area is allocated
3810 // in the caller's stack frame, while for N32/64, it is allocated in the
3811 // callee's stack frame.
3812 for (unsigned I = Idx; I < ArgRegs.size();
3813 ++I, VaArgOffset += RegSizeInBytes) {
3814 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3815 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3816 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3817 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3818 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3819 MachinePointerInfo(), false, false, 0);
3820 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3822 OutChains.push_back(Store);
3826 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3827 unsigned Align) const {
3828 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3830 assert(Size && "Byval argument's size shouldn't be 0.");
3832 Align = std::min(Align, TFL->getStackAlignment());
3834 unsigned FirstReg = 0;
3835 unsigned NumRegs = 0;
3837 if (State->getCallingConv() != CallingConv::Fast) {
3838 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3839 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3840 // FIXME: The O32 case actually describes no shadow registers.
3841 const MCPhysReg *ShadowRegs =
3842 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3844 // We used to check the size as well but we can't do that anymore since
3845 // CCState::HandleByVal() rounds up the size after calling this function.
3846 assert(!(Align % RegSizeInBytes) &&
3847 "Byval argument's alignment should be a multiple of"
3850 FirstReg = State->getFirstUnallocated(IntArgRegs);
3852 // If Align > RegSizeInBytes, the first arg register must be even.
3853 // FIXME: This condition happens to do the right thing but it's not the
3854 // right way to test it. We want to check that the stack frame offset
3855 // of the register is aligned.
3856 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3857 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3861 // Mark the registers allocated.
3862 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3863 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3864 Size -= RegSizeInBytes, ++I, ++NumRegs)
3865 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3868 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3872 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3873 bool isFPCmp, unsigned Opc) const {
3874 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3875 "Subtarget already supports SELECT nodes with the use of"
3876 "conditional-move instructions.");
3878 const TargetInstrInfo *TII =
3879 Subtarget.getInstrInfo();
3880 DebugLoc DL = MI->getDebugLoc();
3882 // To "insert" a SELECT instruction, we actually have to insert the
3883 // diamond control-flow pattern. The incoming instruction knows the
3884 // destination vreg to set, the condition code register to branch on, the
3885 // true/false values to select between, and a branch opcode to use.
3886 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3887 MachineFunction::iterator It = ++BB->getIterator();
3893 // bNE r1, r0, copy1MBB
3894 // fallthrough --> copy0MBB
3895 MachineBasicBlock *thisMBB = BB;
3896 MachineFunction *F = BB->getParent();
3897 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3898 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3899 F->insert(It, copy0MBB);
3900 F->insert(It, sinkMBB);
3902 // Transfer the remainder of BB and its successor edges to sinkMBB.
3903 sinkMBB->splice(sinkMBB->begin(), BB,
3904 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3905 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3907 // Next, add the true and fallthrough blocks as its successors.
3908 BB->addSuccessor(copy0MBB);
3909 BB->addSuccessor(sinkMBB);
3912 // bc1[tf] cc, sinkMBB
3913 BuildMI(BB, DL, TII->get(Opc))
3914 .addReg(MI->getOperand(1).getReg())
3917 // bne rs, $0, sinkMBB
3918 BuildMI(BB, DL, TII->get(Opc))
3919 .addReg(MI->getOperand(1).getReg())
3925 // %FalseValue = ...
3926 // # fallthrough to sinkMBB
3929 // Update machine-CFG edges
3930 BB->addSuccessor(sinkMBB);
3933 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3937 BuildMI(*BB, BB->begin(), DL,
3938 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3939 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3940 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3942 MI->eraseFromParent(); // The pseudo instruction is gone now.
3947 // FIXME? Maybe this could be a TableGen attribute on some registers and
3948 // this table could be generated automatically from RegInfo.
3949 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
3950 SelectionDAG &DAG) const {
3951 // Named registers is expected to be fairly rare. For now, just support $28
3952 // since the linux kernel uses it.
3953 if (Subtarget.isGP64bit()) {
3954 unsigned Reg = StringSwitch<unsigned>(RegName)
3955 .Case("$28", Mips::GP_64)
3960 unsigned Reg = StringSwitch<unsigned>(RegName)
3961 .Case("$28", Mips::GP)
3966 report_fatal_error("Invalid register name global variable");