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/SelectionDAGISel.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
43 #define DEBUG_TYPE "mips-lower"
45 STATISTIC(NumTailCalls, "Number of tail calls");
48 LargeGOT("mxgot", cl::Hidden,
49 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
52 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
53 cl::desc("MIPS: Don't trap on integer division by zero."),
57 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
58 cl::desc("Allow mips-fast-isel to be used"),
61 static const MCPhysReg Mips64DPRegs[8] = {
62 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
73 Size = countPopulation(I);
74 Pos = countTrailingZeros(I);
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
83 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
85 unsigned Flag) const {
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
89 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
91 unsigned Flag) const {
92 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
95 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
97 unsigned Flag) const {
98 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
103 unsigned Flag) const {
104 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
107 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
109 unsigned Flag) const {
110 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111 N->getOffset(), Flag);
114 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
115 switch ((MipsISD::NodeType)Opcode) {
116 case MipsISD::FIRST_NUMBER: break;
117 case MipsISD::JmpLink: return "MipsISD::JmpLink";
118 case MipsISD::TailCall: return "MipsISD::TailCall";
119 case MipsISD::Hi: return "MipsISD::Hi";
120 case MipsISD::Lo: return "MipsISD::Lo";
121 case MipsISD::GPRel: return "MipsISD::GPRel";
122 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
123 case MipsISD::Ret: return "MipsISD::Ret";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
147 case MipsISD::Sync: return "MipsISD::Sync";
148 case MipsISD::Ext: return "MipsISD::Ext";
149 case MipsISD::Ins: return "MipsISD::Ins";
150 case MipsISD::LWL: return "MipsISD::LWL";
151 case MipsISD::LWR: return "MipsISD::LWR";
152 case MipsISD::SWL: return "MipsISD::SWL";
153 case MipsISD::SWR: return "MipsISD::SWR";
154 case MipsISD::LDL: return "MipsISD::LDL";
155 case MipsISD::LDR: return "MipsISD::LDR";
156 case MipsISD::SDL: return "MipsISD::SDL";
157 case MipsISD::SDR: return "MipsISD::SDR";
158 case MipsISD::EXTP: return "MipsISD::EXTP";
159 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
160 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
161 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
162 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
163 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
164 case MipsISD::SHILO: return "MipsISD::SHILO";
165 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
166 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
167 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
168 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
169 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
170 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
171 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
172 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
173 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
174 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
175 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
176 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
177 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
178 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
179 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
180 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
181 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
182 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
183 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
184 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
185 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
186 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
187 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
188 case MipsISD::MULT: return "MipsISD::MULT";
189 case MipsISD::MULTU: return "MipsISD::MULTU";
190 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
191 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
192 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
193 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
194 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
195 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
196 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
197 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
198 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
199 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
200 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
201 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
202 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
203 case MipsISD::VCEQ: return "MipsISD::VCEQ";
204 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
205 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
206 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
207 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
208 case MipsISD::VSMAX: return "MipsISD::VSMAX";
209 case MipsISD::VSMIN: return "MipsISD::VSMIN";
210 case MipsISD::VUMAX: return "MipsISD::VUMAX";
211 case MipsISD::VUMIN: return "MipsISD::VUMIN";
212 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
213 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
214 case MipsISD::VNOR: return "MipsISD::VNOR";
215 case MipsISD::VSHF: return "MipsISD::VSHF";
216 case MipsISD::SHF: return "MipsISD::SHF";
217 case MipsISD::ILVEV: return "MipsISD::ILVEV";
218 case MipsISD::ILVOD: return "MipsISD::ILVOD";
219 case MipsISD::ILVL: return "MipsISD::ILVL";
220 case MipsISD::ILVR: return "MipsISD::ILVR";
221 case MipsISD::PCKEV: return "MipsISD::PCKEV";
222 case MipsISD::PCKOD: return "MipsISD::PCKOD";
223 case MipsISD::INSVE: return "MipsISD::INSVE";
228 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
229 const MipsSubtarget &STI)
230 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
231 // Mips does not have i1 type, so use i32 for
232 // setcc operations results (slt, sgt, ...).
233 setBooleanContents(ZeroOrOneBooleanContent);
234 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
236 // does. Integer booleans still use 0 and 1.
237 if (Subtarget.hasMips32r6())
238 setBooleanContents(ZeroOrOneBooleanContent,
239 ZeroOrNegativeOneBooleanContent);
241 // Load extented operations for i1 types must be promoted
242 for (MVT VT : MVT::integer_valuetypes()) {
243 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
244 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
245 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
248 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
250 for (MVT VT : MVT::fp_valuetypes()) {
251 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
252 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
255 // Set LoadExtAction for f16 vectors to Expand
256 for (MVT VT : MVT::fp_vector_valuetypes()) {
257 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
259 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
262 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
263 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
265 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
267 // Used by legalize types to correctly generate the setcc result.
268 // Without this, every float setcc comes with a AND/OR with the result,
269 // we don't want this, since the fpcmp result goes to a flag register,
270 // which is used implicitly by brcond and select operations.
271 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
273 // Mips Custom Operations
274 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
275 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
276 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
277 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
278 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
279 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
280 setOperationAction(ISD::SELECT, MVT::f32, Custom);
281 setOperationAction(ISD::SELECT, MVT::f64, Custom);
282 setOperationAction(ISD::SELECT, MVT::i32, Custom);
283 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
284 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
285 setOperationAction(ISD::SETCC, MVT::f32, Custom);
286 setOperationAction(ISD::SETCC, MVT::f64, Custom);
287 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
288 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
289 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
290 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
292 if (Subtarget.isGP64bit()) {
293 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
294 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
295 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
296 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
297 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
298 setOperationAction(ISD::SELECT, MVT::i64, Custom);
299 setOperationAction(ISD::LOAD, MVT::i64, Custom);
300 setOperationAction(ISD::STORE, MVT::i64, Custom);
301 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
302 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
303 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
304 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
307 if (!Subtarget.isGP64bit()) {
308 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
309 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
310 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
313 setOperationAction(ISD::ADD, MVT::i32, Custom);
314 if (Subtarget.isGP64bit())
315 setOperationAction(ISD::ADD, MVT::i64, Custom);
317 setOperationAction(ISD::SDIV, MVT::i32, Expand);
318 setOperationAction(ISD::SREM, MVT::i32, Expand);
319 setOperationAction(ISD::UDIV, MVT::i32, Expand);
320 setOperationAction(ISD::UREM, MVT::i32, Expand);
321 setOperationAction(ISD::SDIV, MVT::i64, Expand);
322 setOperationAction(ISD::SREM, MVT::i64, Expand);
323 setOperationAction(ISD::UDIV, MVT::i64, Expand);
324 setOperationAction(ISD::UREM, MVT::i64, Expand);
326 // Operations not directly supported by Mips.
327 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
328 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
329 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
330 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
331 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
332 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
333 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
334 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
335 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
336 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
337 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
338 if (Subtarget.hasCnMips()) {
339 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
340 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
342 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
343 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
345 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
346 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
347 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
348 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
349 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
350 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
351 setOperationAction(ISD::ROTL, MVT::i32, Expand);
352 setOperationAction(ISD::ROTL, MVT::i64, Expand);
353 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
354 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
356 if (!Subtarget.hasMips32r2())
357 setOperationAction(ISD::ROTR, MVT::i32, Expand);
359 if (!Subtarget.hasMips64r2())
360 setOperationAction(ISD::ROTR, MVT::i64, Expand);
362 setOperationAction(ISD::FSIN, MVT::f32, Expand);
363 setOperationAction(ISD::FSIN, MVT::f64, Expand);
364 setOperationAction(ISD::FCOS, MVT::f32, Expand);
365 setOperationAction(ISD::FCOS, MVT::f64, Expand);
366 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
367 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
368 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
369 setOperationAction(ISD::FPOW, MVT::f32, Expand);
370 setOperationAction(ISD::FPOW, MVT::f64, Expand);
371 setOperationAction(ISD::FLOG, MVT::f32, Expand);
372 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
373 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
374 setOperationAction(ISD::FEXP, MVT::f32, Expand);
375 setOperationAction(ISD::FMA, MVT::f32, Expand);
376 setOperationAction(ISD::FMA, MVT::f64, Expand);
377 setOperationAction(ISD::FREM, MVT::f32, Expand);
378 setOperationAction(ISD::FREM, MVT::f64, Expand);
380 // Lower f16 conversion operations into library calls
381 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
382 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
383 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
384 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
386 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
388 setOperationAction(ISD::VASTART, MVT::Other, Custom);
389 setOperationAction(ISD::VAARG, MVT::Other, Custom);
390 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
391 setOperationAction(ISD::VAEND, MVT::Other, Expand);
393 // Use the default for now
394 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
395 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
397 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
398 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
399 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
400 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
402 setInsertFencesForAtomic(true);
404 if (!Subtarget.hasMips32r2()) {
405 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
409 // MIPS16 lacks MIPS32's clz and clo instructions.
410 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
411 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
412 if (!Subtarget.hasMips64())
413 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
415 if (!Subtarget.hasMips32r2())
416 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
417 if (!Subtarget.hasMips64r2())
418 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
420 if (Subtarget.isGP64bit()) {
421 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
422 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
423 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
424 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
427 setOperationAction(ISD::TRAP, MVT::Other, Legal);
429 setTargetDAGCombine(ISD::SDIVREM);
430 setTargetDAGCombine(ISD::UDIVREM);
431 setTargetDAGCombine(ISD::SELECT);
432 setTargetDAGCombine(ISD::AND);
433 setTargetDAGCombine(ISD::OR);
434 setTargetDAGCombine(ISD::ADD);
436 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
438 // The arguments on the stack are defined in terms of 4-byte slots on O32
439 // and 8-byte slots on N32/N64.
440 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
442 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
444 setExceptionPointerRegister(ABI.IsN64() ? Mips::A0_64 : Mips::A0);
445 setExceptionSelectorRegister(ABI.IsN64() ? Mips::A1_64 : Mips::A1);
447 MaxStoresPerMemcpy = 16;
449 isMicroMips = Subtarget.inMicroMipsMode();
452 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
453 const MipsSubtarget &STI) {
454 if (STI.inMips16Mode())
455 return llvm::createMips16TargetLowering(TM, STI);
457 return llvm::createMipsSETargetLowering(TM, STI);
460 // Create a fast isel object.
462 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
463 const TargetLibraryInfo *libInfo) const {
464 if (!EnableMipsFastISel)
465 return TargetLowering::createFastISel(funcInfo, libInfo);
466 return Mips::createFastISel(funcInfo, libInfo);
469 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
473 return VT.changeVectorElementTypeToInteger();
476 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
477 TargetLowering::DAGCombinerInfo &DCI,
478 const MipsSubtarget &Subtarget) {
479 if (DCI.isBeforeLegalizeOps())
482 EVT Ty = N->getValueType(0);
483 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
484 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
485 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
489 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
490 N->getOperand(0), N->getOperand(1));
491 SDValue InChain = DAG.getEntryNode();
492 SDValue InGlue = DivRem;
495 if (N->hasAnyUseOfValue(0)) {
496 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
498 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
499 InChain = CopyFromLo.getValue(1);
500 InGlue = CopyFromLo.getValue(2);
504 if (N->hasAnyUseOfValue(1)) {
505 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
507 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
513 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
515 default: llvm_unreachable("Unknown fp condition code!");
517 case ISD::SETOEQ: return Mips::FCOND_OEQ;
518 case ISD::SETUNE: return Mips::FCOND_UNE;
520 case ISD::SETOLT: return Mips::FCOND_OLT;
522 case ISD::SETOGT: return Mips::FCOND_OGT;
524 case ISD::SETOLE: return Mips::FCOND_OLE;
526 case ISD::SETOGE: return Mips::FCOND_OGE;
527 case ISD::SETULT: return Mips::FCOND_ULT;
528 case ISD::SETULE: return Mips::FCOND_ULE;
529 case ISD::SETUGT: return Mips::FCOND_UGT;
530 case ISD::SETUGE: return Mips::FCOND_UGE;
531 case ISD::SETUO: return Mips::FCOND_UN;
532 case ISD::SETO: return Mips::FCOND_OR;
534 case ISD::SETONE: return Mips::FCOND_ONE;
535 case ISD::SETUEQ: return Mips::FCOND_UEQ;
540 /// This function returns true if the floating point conditional branches and
541 /// conditional moves which use condition code CC should be inverted.
542 static bool invertFPCondCodeUser(Mips::CondCode CC) {
543 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
546 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
547 "Illegal Condition Code");
552 // Creates and returns an FPCmp node from a setcc node.
553 // Returns Op if setcc is not a floating point comparison.
554 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
555 // must be a SETCC node
556 if (Op.getOpcode() != ISD::SETCC)
559 SDValue LHS = Op.getOperand(0);
561 if (!LHS.getValueType().isFloatingPoint())
564 SDValue RHS = Op.getOperand(1);
567 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
568 // node if necessary.
569 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
571 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
572 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
575 // Creates and returns a CMovFPT/F node.
576 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
577 SDValue False, SDLoc DL) {
578 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
579 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
580 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
582 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
583 True.getValueType(), True, FCC0, False, Cond);
586 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
587 TargetLowering::DAGCombinerInfo &DCI,
588 const MipsSubtarget &Subtarget) {
589 if (DCI.isBeforeLegalizeOps())
592 SDValue SetCC = N->getOperand(0);
594 if ((SetCC.getOpcode() != ISD::SETCC) ||
595 !SetCC.getOperand(0).getValueType().isInteger())
598 SDValue False = N->getOperand(2);
599 EVT FalseTy = False.getValueType();
601 if (!FalseTy.isInteger())
604 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
606 // If the RHS (False) is 0, we swap the order of the operands
607 // of ISD::SELECT (obviously also inverting the condition) so that we can
608 // take advantage of conditional moves using the $0 register.
610 // return (a != 0) ? x : 0;
618 if (!FalseC->getZExtValue()) {
619 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
620 SDValue True = N->getOperand(1);
622 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
623 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
625 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
628 // If both operands are integer constants there's a possibility that we
629 // can do some interesting optimizations.
630 SDValue True = N->getOperand(1);
631 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
633 if (!TrueC || !True.getValueType().isInteger())
636 // We'll also ignore MVT::i64 operands as this optimizations proves
637 // to be ineffective because of the required sign extensions as the result
638 // of a SETCC operator is always MVT::i32 for non-vector types.
639 if (True.getValueType() == MVT::i64)
642 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
644 // 1) (a < x) ? y : y-1
646 // addiu $reg2, $reg1, y-1
648 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
650 // 2) (a < x) ? y-1 : y
652 // xor $reg1, $reg1, 1
653 // addiu $reg2, $reg1, y-1
655 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
656 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
657 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
658 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
661 // Couldn't optimize.
665 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
666 TargetLowering::DAGCombinerInfo &DCI,
667 const MipsSubtarget &Subtarget) {
668 if (DCI.isBeforeLegalizeOps())
671 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
673 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
674 if (!FalseC || FalseC->getZExtValue())
677 // Since RHS (False) is 0, we swap the order of the True/False operands
678 // (obviously also inverting the condition) so that we can
679 // take advantage of conditional moves using the $0 register.
681 // return (a != 0) ? x : 0;
684 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
687 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
688 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
689 ValueIfFalse, FCC, ValueIfTrue, Glue);
692 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
693 TargetLowering::DAGCombinerInfo &DCI,
694 const MipsSubtarget &Subtarget) {
695 // Pattern match EXT.
696 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
697 // => ext $dst, $src, size, pos
698 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
701 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
702 unsigned ShiftRightOpc = ShiftRight.getOpcode();
704 // Op's first operand must be a shift right.
705 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
708 // The second operand of the shift must be an immediate.
710 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
713 uint64_t Pos = CN->getZExtValue();
714 uint64_t SMPos, SMSize;
716 // Op's second operand must be a shifted mask.
717 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
718 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
721 // Return if the shifted mask does not start at bit 0 or the sum of its size
722 // and Pos exceeds the word's size.
723 EVT ValTy = N->getValueType(0);
724 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
728 return DAG.getNode(MipsISD::Ext, DL, ValTy,
729 ShiftRight.getOperand(0),
730 DAG.getConstant(Pos, DL, MVT::i32),
731 DAG.getConstant(SMSize, DL, MVT::i32));
734 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
735 TargetLowering::DAGCombinerInfo &DCI,
736 const MipsSubtarget &Subtarget) {
737 // Pattern match INS.
738 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
739 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
740 // => ins $dst, $src, size, pos, $src1
741 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
744 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
745 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
748 // See if Op's first operand matches (and $src1 , mask0).
749 if (And0.getOpcode() != ISD::AND)
752 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
753 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
756 // See if Op's second operand matches (and (shl $src, pos), mask1).
757 if (And1.getOpcode() != ISD::AND)
760 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
761 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
764 // The shift masks must have the same position and size.
765 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
768 SDValue Shl = And1.getOperand(0);
769 if (Shl.getOpcode() != ISD::SHL)
772 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
775 unsigned Shamt = CN->getZExtValue();
777 // Return if the shift amount and the first bit position of mask are not the
779 EVT ValTy = N->getValueType(0);
780 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
784 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
785 DAG.getConstant(SMPos0, DL, MVT::i32),
786 DAG.getConstant(SMSize0, DL, MVT::i32),
790 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
791 TargetLowering::DAGCombinerInfo &DCI,
792 const MipsSubtarget &Subtarget) {
793 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
795 if (DCI.isBeforeLegalizeOps())
798 SDValue Add = N->getOperand(1);
800 if (Add.getOpcode() != ISD::ADD)
803 SDValue Lo = Add.getOperand(1);
805 if ((Lo.getOpcode() != MipsISD::Lo) ||
806 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
809 EVT ValTy = N->getValueType(0);
812 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
814 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
817 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
819 SelectionDAG &DAG = DCI.DAG;
820 unsigned Opc = N->getOpcode();
826 return performDivRemCombine(N, DAG, DCI, Subtarget);
828 return performSELECTCombine(N, DAG, DCI, Subtarget);
829 case MipsISD::CMovFP_F:
830 case MipsISD::CMovFP_T:
831 return performCMovFPCombine(N, DAG, DCI, Subtarget);
833 return performANDCombine(N, DAG, DCI, Subtarget);
835 return performORCombine(N, DAG, DCI, Subtarget);
837 return performADDCombine(N, DAG, DCI, Subtarget);
844 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
845 SmallVectorImpl<SDValue> &Results,
846 SelectionDAG &DAG) const {
847 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
849 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
850 Results.push_back(Res.getValue(I));
854 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
855 SmallVectorImpl<SDValue> &Results,
856 SelectionDAG &DAG) const {
857 return LowerOperationWrapper(N, Results, DAG);
860 SDValue MipsTargetLowering::
861 LowerOperation(SDValue Op, SelectionDAG &DAG) const
863 switch (Op.getOpcode())
865 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
866 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
867 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
868 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
869 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
870 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
871 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
872 case ISD::SELECT: return lowerSELECT(Op, DAG);
873 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
874 case ISD::SETCC: return lowerSETCC(Op, DAG);
875 case ISD::VASTART: return lowerVASTART(Op, DAG);
876 case ISD::VAARG: return lowerVAARG(Op, DAG);
877 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
878 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
879 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
880 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
881 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
882 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
883 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
884 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
885 case ISD::LOAD: return lowerLOAD(Op, DAG);
886 case ISD::STORE: return lowerSTORE(Op, DAG);
887 case ISD::ADD: return lowerADD(Op, DAG);
888 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
893 //===----------------------------------------------------------------------===//
894 // Lower helper functions
895 //===----------------------------------------------------------------------===//
897 // addLiveIn - This helper function adds the specified physical register to the
898 // MachineFunction as a live in value. It also creates a corresponding
899 // virtual register for it.
901 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
903 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
904 MF.getRegInfo().addLiveIn(PReg, VReg);
908 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
909 MachineBasicBlock &MBB,
910 const TargetInstrInfo &TII,
915 // Insert instruction "teq $divisor_reg, $zero, 7".
916 MachineBasicBlock::iterator I(MI);
917 MachineInstrBuilder MIB;
918 MachineOperand &Divisor = MI->getOperand(2);
919 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
920 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
921 .addReg(Mips::ZERO).addImm(7);
923 // Use the 32-bit sub-register if this is a 64-bit division.
925 MIB->getOperand(0).setSubReg(Mips::sub_32);
927 // Clear Divisor's kill flag.
928 Divisor.setIsKill(false);
930 // We would normally delete the original instruction here but in this case
931 // we only needed to inject an additional instruction rather than replace it.
937 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
938 MachineBasicBlock *BB) const {
939 switch (MI->getOpcode()) {
941 llvm_unreachable("Unexpected instr type to insert");
942 case Mips::ATOMIC_LOAD_ADD_I8:
943 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
944 case Mips::ATOMIC_LOAD_ADD_I16:
945 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
946 case Mips::ATOMIC_LOAD_ADD_I32:
947 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
948 case Mips::ATOMIC_LOAD_ADD_I64:
949 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
951 case Mips::ATOMIC_LOAD_AND_I8:
952 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
953 case Mips::ATOMIC_LOAD_AND_I16:
954 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
955 case Mips::ATOMIC_LOAD_AND_I32:
956 return emitAtomicBinary(MI, BB, 4, Mips::AND);
957 case Mips::ATOMIC_LOAD_AND_I64:
958 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
960 case Mips::ATOMIC_LOAD_OR_I8:
961 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
962 case Mips::ATOMIC_LOAD_OR_I16:
963 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
964 case Mips::ATOMIC_LOAD_OR_I32:
965 return emitAtomicBinary(MI, BB, 4, Mips::OR);
966 case Mips::ATOMIC_LOAD_OR_I64:
967 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
969 case Mips::ATOMIC_LOAD_XOR_I8:
970 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
971 case Mips::ATOMIC_LOAD_XOR_I16:
972 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
973 case Mips::ATOMIC_LOAD_XOR_I32:
974 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
975 case Mips::ATOMIC_LOAD_XOR_I64:
976 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
978 case Mips::ATOMIC_LOAD_NAND_I8:
979 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
980 case Mips::ATOMIC_LOAD_NAND_I16:
981 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
982 case Mips::ATOMIC_LOAD_NAND_I32:
983 return emitAtomicBinary(MI, BB, 4, 0, true);
984 case Mips::ATOMIC_LOAD_NAND_I64:
985 return emitAtomicBinary(MI, BB, 8, 0, true);
987 case Mips::ATOMIC_LOAD_SUB_I8:
988 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
989 case Mips::ATOMIC_LOAD_SUB_I16:
990 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
991 case Mips::ATOMIC_LOAD_SUB_I32:
992 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
993 case Mips::ATOMIC_LOAD_SUB_I64:
994 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
996 case Mips::ATOMIC_SWAP_I8:
997 return emitAtomicBinaryPartword(MI, BB, 1, 0);
998 case Mips::ATOMIC_SWAP_I16:
999 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1000 case Mips::ATOMIC_SWAP_I32:
1001 return emitAtomicBinary(MI, BB, 4, 0);
1002 case Mips::ATOMIC_SWAP_I64:
1003 return emitAtomicBinary(MI, BB, 8, 0);
1005 case Mips::ATOMIC_CMP_SWAP_I8:
1006 return emitAtomicCmpSwapPartword(MI, BB, 1);
1007 case Mips::ATOMIC_CMP_SWAP_I16:
1008 return emitAtomicCmpSwapPartword(MI, BB, 2);
1009 case Mips::ATOMIC_CMP_SWAP_I32:
1010 return emitAtomicCmpSwap(MI, BB, 4);
1011 case Mips::ATOMIC_CMP_SWAP_I64:
1012 return emitAtomicCmpSwap(MI, BB, 8);
1013 case Mips::PseudoSDIV:
1014 case Mips::PseudoUDIV:
1019 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
1020 case Mips::PseudoDSDIV:
1021 case Mips::PseudoDUDIV:
1026 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
1028 return emitSEL_D(MI, BB);
1030 case Mips::PseudoSELECT_I:
1031 case Mips::PseudoSELECT_I64:
1032 case Mips::PseudoSELECT_S:
1033 case Mips::PseudoSELECT_D32:
1034 case Mips::PseudoSELECT_D64:
1035 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1036 case Mips::PseudoSELECTFP_F_I:
1037 case Mips::PseudoSELECTFP_F_I64:
1038 case Mips::PseudoSELECTFP_F_S:
1039 case Mips::PseudoSELECTFP_F_D32:
1040 case Mips::PseudoSELECTFP_F_D64:
1041 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1042 case Mips::PseudoSELECTFP_T_I:
1043 case Mips::PseudoSELECTFP_T_I64:
1044 case Mips::PseudoSELECTFP_T_S:
1045 case Mips::PseudoSELECTFP_T_D32:
1046 case Mips::PseudoSELECTFP_T_D64:
1047 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1051 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1052 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1054 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1055 unsigned Size, unsigned BinOpcode,
1057 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1059 MachineFunction *MF = BB->getParent();
1060 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1061 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1062 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1063 DebugLoc DL = MI->getDebugLoc();
1064 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1071 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1072 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1079 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1080 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1083 ZERO = Mips::ZERO_64;
1087 unsigned OldVal = MI->getOperand(0).getReg();
1088 unsigned Ptr = MI->getOperand(1).getReg();
1089 unsigned Incr = MI->getOperand(2).getReg();
1091 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1092 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1093 unsigned Success = RegInfo.createVirtualRegister(RC);
1095 // insert new blocks after the current block
1096 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1097 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1098 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1099 MachineFunction::iterator It = BB;
1101 MF->insert(It, loopMBB);
1102 MF->insert(It, exitMBB);
1104 // Transfer the remainder of BB and its successor edges to exitMBB.
1105 exitMBB->splice(exitMBB->begin(), BB,
1106 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1107 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1111 // fallthrough --> loopMBB
1112 BB->addSuccessor(loopMBB);
1113 loopMBB->addSuccessor(loopMBB);
1114 loopMBB->addSuccessor(exitMBB);
1117 // ll oldval, 0(ptr)
1118 // <binop> storeval, oldval, incr
1119 // sc success, storeval, 0(ptr)
1120 // beq success, $0, loopMBB
1122 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1124 // and andres, oldval, incr
1125 // nor storeval, $0, andres
1126 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1127 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1128 } else if (BinOpcode) {
1129 // <binop> storeval, oldval, incr
1130 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1134 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1135 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1137 MI->eraseFromParent(); // The instruction is gone now.
1142 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1143 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1144 unsigned SrcReg) const {
1145 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1146 DebugLoc DL = MI->getDebugLoc();
1148 if (Subtarget.hasMips32r2() && Size == 1) {
1149 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1153 if (Subtarget.hasMips32r2() && Size == 2) {
1154 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1158 MachineFunction *MF = BB->getParent();
1159 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1160 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1161 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1164 int64_t ShiftImm = 32 - (Size * 8);
1166 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1167 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1172 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1173 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1175 assert((Size == 1 || Size == 2) &&
1176 "Unsupported size for EmitAtomicBinaryPartial.");
1178 MachineFunction *MF = BB->getParent();
1179 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1180 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1181 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1182 DebugLoc DL = MI->getDebugLoc();
1184 unsigned Dest = MI->getOperand(0).getReg();
1185 unsigned Ptr = MI->getOperand(1).getReg();
1186 unsigned Incr = MI->getOperand(2).getReg();
1188 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1189 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1190 unsigned Mask = RegInfo.createVirtualRegister(RC);
1191 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1192 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1193 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1194 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1195 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1196 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1197 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1198 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1199 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1200 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1201 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1202 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1203 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1204 unsigned Success = RegInfo.createVirtualRegister(RC);
1206 // insert new blocks after the current block
1207 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1208 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1209 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1210 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1211 MachineFunction::iterator It = BB;
1213 MF->insert(It, loopMBB);
1214 MF->insert(It, sinkMBB);
1215 MF->insert(It, exitMBB);
1217 // Transfer the remainder of BB and its successor edges to exitMBB.
1218 exitMBB->splice(exitMBB->begin(), BB,
1219 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1220 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1222 BB->addSuccessor(loopMBB);
1223 loopMBB->addSuccessor(loopMBB);
1224 loopMBB->addSuccessor(sinkMBB);
1225 sinkMBB->addSuccessor(exitMBB);
1228 // addiu masklsb2,$0,-4 # 0xfffffffc
1229 // and alignedaddr,ptr,masklsb2
1230 // andi ptrlsb2,ptr,3
1231 // sll shiftamt,ptrlsb2,3
1232 // ori maskupper,$0,255 # 0xff
1233 // sll mask,maskupper,shiftamt
1234 // nor mask2,$0,mask
1235 // sll incr2,incr,shiftamt
1237 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1238 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1239 .addReg(Mips::ZERO).addImm(-4);
1240 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1241 .addReg(Ptr).addReg(MaskLSB2);
1242 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1243 if (Subtarget.isLittle()) {
1244 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1246 unsigned Off = RegInfo.createVirtualRegister(RC);
1247 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1248 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1249 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1251 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1252 .addReg(Mips::ZERO).addImm(MaskImm);
1253 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1254 .addReg(MaskUpper).addReg(ShiftAmt);
1255 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1256 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1258 // atomic.load.binop
1260 // ll oldval,0(alignedaddr)
1261 // binop binopres,oldval,incr2
1262 // and newval,binopres,mask
1263 // and maskedoldval0,oldval,mask2
1264 // or storeval,maskedoldval0,newval
1265 // sc success,storeval,0(alignedaddr)
1266 // beq success,$0,loopMBB
1270 // ll oldval,0(alignedaddr)
1271 // and newval,incr2,mask
1272 // and maskedoldval0,oldval,mask2
1273 // or storeval,maskedoldval0,newval
1274 // sc success,storeval,0(alignedaddr)
1275 // beq success,$0,loopMBB
1278 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1279 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1281 // and andres, oldval, incr2
1282 // nor binopres, $0, andres
1283 // and newval, binopres, mask
1284 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1285 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1286 .addReg(Mips::ZERO).addReg(AndRes);
1287 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1288 } else if (BinOpcode) {
1289 // <binop> binopres, oldval, incr2
1290 // and newval, binopres, mask
1291 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1292 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1293 } else { // atomic.swap
1294 // and newval, incr2, mask
1295 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1298 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1299 .addReg(OldVal).addReg(Mask2);
1300 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1301 .addReg(MaskedOldVal0).addReg(NewVal);
1302 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1303 BuildMI(BB, DL, TII->get(SC), Success)
1304 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1305 BuildMI(BB, DL, TII->get(Mips::BEQ))
1306 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1309 // and maskedoldval1,oldval,mask
1310 // srl srlres,maskedoldval1,shiftamt
1311 // sign_extend dest,srlres
1314 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1315 .addReg(OldVal).addReg(Mask);
1316 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1317 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1318 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1320 MI->eraseFromParent(); // The instruction is gone now.
1325 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1326 MachineBasicBlock *BB,
1327 unsigned Size) const {
1328 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1330 MachineFunction *MF = BB->getParent();
1331 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1332 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1333 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1334 DebugLoc DL = MI->getDebugLoc();
1335 unsigned LL, SC, ZERO, BNE, BEQ;
1338 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1339 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1346 ZERO = Mips::ZERO_64;
1351 unsigned Dest = MI->getOperand(0).getReg();
1352 unsigned Ptr = MI->getOperand(1).getReg();
1353 unsigned OldVal = MI->getOperand(2).getReg();
1354 unsigned NewVal = MI->getOperand(3).getReg();
1356 unsigned Success = RegInfo.createVirtualRegister(RC);
1358 // insert new blocks after the current block
1359 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1360 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1361 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1362 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1363 MachineFunction::iterator It = BB;
1365 MF->insert(It, loop1MBB);
1366 MF->insert(It, loop2MBB);
1367 MF->insert(It, exitMBB);
1369 // Transfer the remainder of BB and its successor edges to exitMBB.
1370 exitMBB->splice(exitMBB->begin(), BB,
1371 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1372 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1376 // fallthrough --> loop1MBB
1377 BB->addSuccessor(loop1MBB);
1378 loop1MBB->addSuccessor(exitMBB);
1379 loop1MBB->addSuccessor(loop2MBB);
1380 loop2MBB->addSuccessor(loop1MBB);
1381 loop2MBB->addSuccessor(exitMBB);
1385 // bne dest, oldval, exitMBB
1387 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1388 BuildMI(BB, DL, TII->get(BNE))
1389 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1392 // sc success, newval, 0(ptr)
1393 // beq success, $0, loop1MBB
1395 BuildMI(BB, DL, TII->get(SC), Success)
1396 .addReg(NewVal).addReg(Ptr).addImm(0);
1397 BuildMI(BB, DL, TII->get(BEQ))
1398 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1400 MI->eraseFromParent(); // The instruction is gone now.
1406 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1407 MachineBasicBlock *BB,
1408 unsigned Size) const {
1409 assert((Size == 1 || Size == 2) &&
1410 "Unsupported size for EmitAtomicCmpSwapPartial.");
1412 MachineFunction *MF = BB->getParent();
1413 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1414 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1415 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1416 DebugLoc DL = MI->getDebugLoc();
1418 unsigned Dest = MI->getOperand(0).getReg();
1419 unsigned Ptr = MI->getOperand(1).getReg();
1420 unsigned CmpVal = MI->getOperand(2).getReg();
1421 unsigned NewVal = MI->getOperand(3).getReg();
1423 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1424 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1425 unsigned Mask = RegInfo.createVirtualRegister(RC);
1426 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1427 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1428 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1429 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1430 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1431 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1432 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1433 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1434 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1435 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1436 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1437 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1438 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1439 unsigned Success = RegInfo.createVirtualRegister(RC);
1441 // insert new blocks after the current block
1442 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1443 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1444 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1445 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1446 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1447 MachineFunction::iterator It = BB;
1449 MF->insert(It, loop1MBB);
1450 MF->insert(It, loop2MBB);
1451 MF->insert(It, sinkMBB);
1452 MF->insert(It, exitMBB);
1454 // Transfer the remainder of BB and its successor edges to exitMBB.
1455 exitMBB->splice(exitMBB->begin(), BB,
1456 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1457 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1459 BB->addSuccessor(loop1MBB);
1460 loop1MBB->addSuccessor(sinkMBB);
1461 loop1MBB->addSuccessor(loop2MBB);
1462 loop2MBB->addSuccessor(loop1MBB);
1463 loop2MBB->addSuccessor(sinkMBB);
1464 sinkMBB->addSuccessor(exitMBB);
1466 // FIXME: computation of newval2 can be moved to loop2MBB.
1468 // addiu masklsb2,$0,-4 # 0xfffffffc
1469 // and alignedaddr,ptr,masklsb2
1470 // andi ptrlsb2,ptr,3
1471 // sll shiftamt,ptrlsb2,3
1472 // ori maskupper,$0,255 # 0xff
1473 // sll mask,maskupper,shiftamt
1474 // nor mask2,$0,mask
1475 // andi maskedcmpval,cmpval,255
1476 // sll shiftedcmpval,maskedcmpval,shiftamt
1477 // andi maskednewval,newval,255
1478 // sll shiftednewval,maskednewval,shiftamt
1479 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1480 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1481 .addReg(Mips::ZERO).addImm(-4);
1482 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1483 .addReg(Ptr).addReg(MaskLSB2);
1484 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1485 if (Subtarget.isLittle()) {
1486 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1488 unsigned Off = RegInfo.createVirtualRegister(RC);
1489 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1490 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1491 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1493 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1494 .addReg(Mips::ZERO).addImm(MaskImm);
1495 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1496 .addReg(MaskUpper).addReg(ShiftAmt);
1497 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1498 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1499 .addReg(CmpVal).addImm(MaskImm);
1500 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1501 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1502 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1503 .addReg(NewVal).addImm(MaskImm);
1504 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1505 .addReg(MaskedNewVal).addReg(ShiftAmt);
1508 // ll oldval,0(alginedaddr)
1509 // and maskedoldval0,oldval,mask
1510 // bne maskedoldval0,shiftedcmpval,sinkMBB
1512 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1513 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1514 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1515 .addReg(OldVal).addReg(Mask);
1516 BuildMI(BB, DL, TII->get(Mips::BNE))
1517 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1520 // and maskedoldval1,oldval,mask2
1521 // or storeval,maskedoldval1,shiftednewval
1522 // sc success,storeval,0(alignedaddr)
1523 // beq success,$0,loop1MBB
1525 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1526 .addReg(OldVal).addReg(Mask2);
1527 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1528 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1529 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1530 BuildMI(BB, DL, TII->get(SC), Success)
1531 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1532 BuildMI(BB, DL, TII->get(Mips::BEQ))
1533 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1536 // srl srlres,maskedoldval0,shiftamt
1537 // sign_extend dest,srlres
1540 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1541 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1542 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1544 MI->eraseFromParent(); // The instruction is gone now.
1549 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1550 MachineBasicBlock *BB) const {
1551 MachineFunction *MF = BB->getParent();
1552 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1553 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1554 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1555 DebugLoc DL = MI->getDebugLoc();
1556 MachineBasicBlock::iterator II(MI);
1558 unsigned Fc = MI->getOperand(1).getReg();
1559 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1561 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1563 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1566 .addImm(Mips::sub_lo);
1568 // We don't erase the original instruction, we just replace the condition
1569 // register with the 64-bit super-register.
1570 MI->getOperand(1).setReg(Fc2);
1575 //===----------------------------------------------------------------------===//
1576 // Misc Lower Operation implementation
1577 //===----------------------------------------------------------------------===//
1578 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1579 SDValue Chain = Op.getOperand(0);
1580 SDValue Table = Op.getOperand(1);
1581 SDValue Index = Op.getOperand(2);
1583 auto &TD = DAG.getDataLayout();
1584 EVT PTy = getPointerTy(TD);
1585 unsigned EntrySize =
1586 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
1588 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1589 DAG.getConstant(EntrySize, DL, PTy));
1590 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1592 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1593 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1594 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1596 Chain = Addr.getValue(1);
1598 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1599 // For PIC, the sequence is:
1600 // BRIND(load(Jumptable + index) + RelocBase)
1601 // RelocBase can be JumpTable, GOT or some sort of global base.
1602 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1603 getPICJumpTableRelocBase(Table, DAG));
1606 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1609 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1610 // The first operand is the chain, the second is the condition, the third is
1611 // the block to branch to if the condition is true.
1612 SDValue Chain = Op.getOperand(0);
1613 SDValue Dest = Op.getOperand(2);
1616 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1617 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1619 // Return if flag is not set by a floating point comparison.
1620 if (CondRes.getOpcode() != MipsISD::FPCmp)
1623 SDValue CCNode = CondRes.getOperand(2);
1625 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1626 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1627 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1628 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1629 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1630 FCC0, Dest, CondRes);
1633 SDValue MipsTargetLowering::
1634 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1636 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1637 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1639 // Return if flag is not set by a floating point comparison.
1640 if (Cond.getOpcode() != MipsISD::FPCmp)
1643 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1647 SDValue MipsTargetLowering::
1648 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1651 EVT Ty = Op.getOperand(0).getValueType();
1653 DAG.getNode(ISD::SETCC, DL, getSetCCResultType(DAG.getDataLayout(),
1654 *DAG.getContext(), Ty),
1655 Op.getOperand(0), Op.getOperand(1), Op.getOperand(4));
1657 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1661 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1662 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1663 SDValue Cond = createFPCmp(DAG, Op);
1665 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1666 "Floating point operand expected.");
1669 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1670 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1672 return createCMovFP(DAG, Cond, True, False, DL);
1675 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1676 SelectionDAG &DAG) const {
1677 EVT Ty = Op.getValueType();
1678 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1679 const GlobalValue *GV = N->getGlobal();
1681 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1682 const MipsTargetObjectFile *TLOF =
1683 static_cast<const MipsTargetObjectFile *>(
1684 getTargetMachine().getObjFileLowering());
1685 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1686 // %gp_rel relocation
1687 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1689 // %hi/%lo relocation
1690 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1693 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1694 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1697 return getAddrGlobalLargeGOT(N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16,
1698 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1699 MachinePointerInfo::getGOT());
1701 return getAddrGlobal(N, SDLoc(N), Ty, DAG,
1702 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP
1704 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1707 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1708 SelectionDAG &DAG) const {
1709 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1710 EVT Ty = Op.getValueType();
1712 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1713 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1715 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1718 SDValue MipsTargetLowering::
1719 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1721 // If the relocation model is PIC, use the General Dynamic TLS Model or
1722 // Local Dynamic TLS model, otherwise use the Initial Exec or
1723 // Local Exec TLS Model.
1725 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1726 if (DAG.getTarget().Options.EmulatedTLS)
1727 return LowerToTLSEmulatedModel(GA, DAG);
1730 const GlobalValue *GV = GA->getGlobal();
1731 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1733 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1735 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1736 // General Dynamic and Local Dynamic TLS Model.
1737 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1740 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1741 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1742 getGlobalReg(DAG, PtrVT), TGA);
1743 unsigned PtrSize = PtrVT.getSizeInBits();
1744 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1746 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1750 Entry.Node = Argument;
1752 Args.push_back(Entry);
1754 TargetLowering::CallLoweringInfo CLI(DAG);
1755 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1756 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1757 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1759 SDValue Ret = CallResult.first;
1761 if (model != TLSModel::LocalDynamic)
1764 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1765 MipsII::MO_DTPREL_HI);
1766 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1767 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1768 MipsII::MO_DTPREL_LO);
1769 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1770 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1771 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1775 if (model == TLSModel::InitialExec) {
1776 // Initial Exec TLS Model
1777 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1778 MipsII::MO_GOTTPREL);
1779 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1781 Offset = DAG.getLoad(PtrVT, DL,
1782 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1783 false, false, false, 0);
1785 // Local Exec TLS Model
1786 assert(model == TLSModel::LocalExec);
1787 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1788 MipsII::MO_TPREL_HI);
1789 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1790 MipsII::MO_TPREL_LO);
1791 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1792 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1793 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1796 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1797 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1800 SDValue MipsTargetLowering::
1801 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1803 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1804 EVT Ty = Op.getValueType();
1806 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1807 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1809 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1812 SDValue MipsTargetLowering::
1813 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1815 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1816 EVT Ty = Op.getValueType();
1818 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1819 const MipsTargetObjectFile *TLOF =
1820 static_cast<const MipsTargetObjectFile *>(
1821 getTargetMachine().getObjFileLowering());
1823 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
1824 getTargetMachine()))
1825 // %gp_rel relocation
1826 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1828 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1831 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1834 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1835 MachineFunction &MF = DAG.getMachineFunction();
1836 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1839 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1840 getPointerTy(MF.getDataLayout()));
1842 // vastart just stores the address of the VarArgsFrameIndex slot into the
1843 // memory location argument.
1844 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1845 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1846 MachinePointerInfo(SV), false, false, 0);
1849 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1850 SDNode *Node = Op.getNode();
1851 EVT VT = Node->getValueType(0);
1852 SDValue Chain = Node->getOperand(0);
1853 SDValue VAListPtr = Node->getOperand(1);
1854 unsigned Align = Node->getConstantOperandVal(3);
1855 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1857 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1859 SDValue VAListLoad =
1860 DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, VAListPtr,
1861 MachinePointerInfo(SV), false, false, false, 0);
1862 SDValue VAList = VAListLoad;
1864 // Re-align the pointer if necessary.
1865 // It should only ever be necessary for 64-bit types on O32 since the minimum
1866 // argument alignment is the same as the maximum type alignment for N32/N64.
1868 // FIXME: We currently align too often. The code generator doesn't notice
1869 // when the pointer is still aligned from the last va_arg (or pair of
1870 // va_args for the i64 on O32 case).
1871 if (Align > getMinStackArgumentAlignment()) {
1872 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1874 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1875 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
1877 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1878 DAG.getConstant(-(int64_t)Align, DL,
1879 VAList.getValueType()));
1882 // Increment the pointer, VAList, to the next vaarg.
1883 auto &TD = DAG.getDataLayout();
1884 unsigned ArgSizeInBytes =
1885 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1886 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1887 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes,
1888 ArgSlotSizeInBytes),
1889 DL, VAList.getValueType()));
1890 // Store the incremented VAList to the legalized pointer
1891 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1892 MachinePointerInfo(SV), false, false, 0);
1894 // In big-endian mode we must adjust the pointer when the load size is smaller
1895 // than the argument slot size. We must also reduce the known alignment to
1896 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1897 // the correct half of the slot, and reduce the alignment from 8 (slot
1898 // alignment) down to 4 (type alignment).
1899 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1900 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1901 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1902 DAG.getIntPtrConstant(Adjustment, DL));
1904 // Load the actual argument out of the pointer VAList
1905 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1909 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1910 bool HasExtractInsert) {
1911 EVT TyX = Op.getOperand(0).getValueType();
1912 EVT TyY = Op.getOperand(1).getValueType();
1914 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1915 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
1918 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1920 SDValue X = (TyX == MVT::f32) ?
1921 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1922 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1924 SDValue Y = (TyY == MVT::f32) ?
1925 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1926 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1929 if (HasExtractInsert) {
1930 // ext E, Y, 31, 1 ; extract bit31 of Y
1931 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1932 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1933 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1936 // srl SrlX, SllX, 1
1938 // sll SllY, SrlX, 31
1939 // or Or, SrlX, SllY
1940 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1941 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1942 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1943 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1944 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1947 if (TyX == MVT::f32)
1948 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1950 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1952 DAG.getConstant(0, DL, MVT::i32));
1953 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1956 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1957 bool HasExtractInsert) {
1958 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1959 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1960 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1962 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1964 // Bitcast to integer nodes.
1965 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1966 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1968 if (HasExtractInsert) {
1969 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1970 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1971 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1972 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
1974 if (WidthX > WidthY)
1975 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1976 else if (WidthY > WidthX)
1977 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1979 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1980 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
1982 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1985 // (d)sll SllX, X, 1
1986 // (d)srl SrlX, SllX, 1
1987 // (d)srl SrlY, Y, width(Y)-1
1988 // (d)sll SllY, SrlX, width(Y)-1
1989 // or Or, SrlX, SllY
1990 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1991 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1992 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1993 DAG.getConstant(WidthY - 1, DL, MVT::i32));
1995 if (WidthX > WidthY)
1996 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1997 else if (WidthY > WidthX)
1998 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2000 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2001 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2002 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2003 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2007 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2008 if (Subtarget.isGP64bit())
2009 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2011 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2014 SDValue MipsTargetLowering::
2015 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2017 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2018 "Frame address can only be determined for current frame.");
2020 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2021 MFI->setFrameAddressIsTaken(true);
2022 EVT VT = Op.getValueType();
2024 SDValue FrameAddr = DAG.getCopyFromReg(
2025 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2029 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2030 SelectionDAG &DAG) const {
2031 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2035 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2036 "Return address can be determined only for current frame.");
2038 MachineFunction &MF = DAG.getMachineFunction();
2039 MachineFrameInfo *MFI = MF.getFrameInfo();
2040 MVT VT = Op.getSimpleValueType();
2041 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2042 MFI->setReturnAddressIsTaken(true);
2044 // Return RA, which contains the return address. Mark it an implicit live-in.
2045 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2046 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2049 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2050 // generated from __builtin_eh_return (offset, handler)
2051 // The effect of this is to adjust the stack pointer by "offset"
2052 // and then branch to "handler".
2053 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2055 MachineFunction &MF = DAG.getMachineFunction();
2056 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2058 MipsFI->setCallsEhReturn();
2059 SDValue Chain = Op.getOperand(0);
2060 SDValue Offset = Op.getOperand(1);
2061 SDValue Handler = Op.getOperand(2);
2063 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2065 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2066 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2067 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2068 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2069 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2070 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2071 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2072 DAG.getRegister(OffsetReg, Ty),
2073 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2077 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2078 SelectionDAG &DAG) const {
2079 // FIXME: Need pseudo-fence for 'singlethread' fences
2080 // FIXME: Set SType for weaker fences where supported/appropriate.
2083 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2084 DAG.getConstant(SType, DL, MVT::i32));
2087 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2088 SelectionDAG &DAG) const {
2090 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2092 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2093 SDValue Shamt = Op.getOperand(2);
2094 // if shamt < (VT.bits):
2095 // lo = (shl lo, shamt)
2096 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2099 // hi = (shl lo, shamt[4:0])
2100 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2101 DAG.getConstant(-1, DL, MVT::i32));
2102 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2103 DAG.getConstant(1, DL, VT));
2104 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2105 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2106 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2107 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2108 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2109 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2110 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2111 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2112 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2114 SDValue Ops[2] = {Lo, Hi};
2115 return DAG.getMergeValues(Ops, DL);
2118 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2121 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2122 SDValue Shamt = Op.getOperand(2);
2123 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2125 // if shamt < (VT.bits):
2126 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2128 // hi = (sra hi, shamt)
2130 // hi = (srl hi, shamt)
2133 // lo = (sra hi, shamt[4:0])
2134 // hi = (sra hi, 31)
2136 // lo = (srl hi, shamt[4:0])
2138 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2139 DAG.getConstant(-1, DL, MVT::i32));
2140 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2141 DAG.getConstant(1, DL, VT));
2142 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2143 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2144 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2145 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2147 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2148 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2149 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2150 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2151 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2152 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2153 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2155 SDValue Ops[2] = {Lo, Hi};
2156 return DAG.getMergeValues(Ops, DL);
2159 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2160 SDValue Chain, SDValue Src, unsigned Offset) {
2161 SDValue Ptr = LD->getBasePtr();
2162 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2163 EVT BasePtrVT = Ptr.getValueType();
2165 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2168 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2169 DAG.getConstant(Offset, DL, BasePtrVT));
2171 SDValue Ops[] = { Chain, Ptr, Src };
2172 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2173 LD->getMemOperand());
2176 // Expand an unaligned 32 or 64-bit integer load node.
2177 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2178 LoadSDNode *LD = cast<LoadSDNode>(Op);
2179 EVT MemVT = LD->getMemoryVT();
2181 if (Subtarget.systemSupportsUnalignedAccess())
2184 // Return if load is aligned or if MemVT is neither i32 nor i64.
2185 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2186 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2189 bool IsLittle = Subtarget.isLittle();
2190 EVT VT = Op.getValueType();
2191 ISD::LoadExtType ExtType = LD->getExtensionType();
2192 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2194 assert((VT == MVT::i32) || (VT == MVT::i64));
2197 // (set dst, (i64 (load baseptr)))
2199 // (set tmp, (ldl (add baseptr, 7), undef))
2200 // (set dst, (ldr baseptr, tmp))
2201 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2202 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2204 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2208 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2210 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2214 // (set dst, (i32 (load baseptr))) or
2215 // (set dst, (i64 (sextload baseptr))) or
2216 // (set dst, (i64 (extload baseptr)))
2218 // (set tmp, (lwl (add baseptr, 3), undef))
2219 // (set dst, (lwr baseptr, tmp))
2220 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2221 (ExtType == ISD::EXTLOAD))
2224 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2227 // (set dst, (i64 (zextload baseptr)))
2229 // (set tmp0, (lwl (add baseptr, 3), undef))
2230 // (set tmp1, (lwr baseptr, tmp0))
2231 // (set tmp2, (shl tmp1, 32))
2232 // (set dst, (srl tmp2, 32))
2234 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2235 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2236 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2237 SDValue Ops[] = { SRL, LWR.getValue(1) };
2238 return DAG.getMergeValues(Ops, DL);
2241 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2242 SDValue Chain, unsigned Offset) {
2243 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2244 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2246 SDVTList VTList = DAG.getVTList(MVT::Other);
2249 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2250 DAG.getConstant(Offset, DL, BasePtrVT));
2252 SDValue Ops[] = { Chain, Value, Ptr };
2253 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2254 SD->getMemOperand());
2257 // Expand an unaligned 32 or 64-bit integer store node.
2258 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2260 SDValue Value = SD->getValue(), Chain = SD->getChain();
2261 EVT VT = Value.getValueType();
2264 // (store val, baseptr) or
2265 // (truncstore val, baseptr)
2267 // (swl val, (add baseptr, 3))
2268 // (swr val, baseptr)
2269 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2270 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2272 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2275 assert(VT == MVT::i64);
2278 // (store val, baseptr)
2280 // (sdl val, (add baseptr, 7))
2281 // (sdr val, baseptr)
2282 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2283 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2286 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2287 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2288 SDValue Val = SD->getValue();
2290 if (Val.getOpcode() != ISD::FP_TO_SINT)
2293 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2294 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2297 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2298 SD->getPointerInfo(), SD->isVolatile(),
2299 SD->isNonTemporal(), SD->getAlignment());
2302 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2303 StoreSDNode *SD = cast<StoreSDNode>(Op);
2304 EVT MemVT = SD->getMemoryVT();
2306 // Lower unaligned integer stores.
2307 if (!Subtarget.systemSupportsUnalignedAccess() &&
2308 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2309 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2310 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2312 return lowerFP_TO_SINT_STORE(SD, DAG);
2315 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2316 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2317 || cast<ConstantSDNode>
2318 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2319 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2323 // (add (frameaddr 0), (frame_to_args_offset))
2324 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2325 // (add FrameObject, 0)
2326 // where FrameObject is a fixed StackObject with offset 0 which points to
2327 // the old stack pointer.
2328 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2329 EVT ValTy = Op->getValueType(0);
2330 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2331 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2333 return DAG.getNode(ISD::ADD, DL, ValTy, InArgsAddr,
2334 DAG.getConstant(0, DL, ValTy));
2337 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2338 SelectionDAG &DAG) const {
2339 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2340 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2342 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2345 //===----------------------------------------------------------------------===//
2346 // Calling Convention Implementation
2347 //===----------------------------------------------------------------------===//
2349 //===----------------------------------------------------------------------===//
2350 // TODO: Implement a generic logic using tblgen that can support this.
2351 // Mips O32 ABI rules:
2353 // i32 - Passed in A0, A1, A2, A3 and stack
2354 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2355 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2356 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2357 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2358 // not used, it must be shadowed. If only A3 is available, shadow it and
2361 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2362 //===----------------------------------------------------------------------===//
2364 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2365 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2366 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2367 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2368 State.getMachineFunction().getSubtarget());
2370 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2371 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2373 // Do not process byval args here.
2374 if (ArgFlags.isByVal())
2377 // Promote i8 and i16
2378 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2379 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2381 if (ArgFlags.isSExt())
2382 LocInfo = CCValAssign::SExtUpper;
2383 else if (ArgFlags.isZExt())
2384 LocInfo = CCValAssign::ZExtUpper;
2386 LocInfo = CCValAssign::AExtUpper;
2390 // Promote i8 and i16
2391 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2393 if (ArgFlags.isSExt())
2394 LocInfo = CCValAssign::SExt;
2395 else if (ArgFlags.isZExt())
2396 LocInfo = CCValAssign::ZExt;
2398 LocInfo = CCValAssign::AExt;
2403 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2404 // is true: function is vararg, argument is 3rd or higher, there is previous
2405 // argument which is not f32 or f64.
2406 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2407 State.getFirstUnallocated(F32Regs) != ValNo;
2408 unsigned OrigAlign = ArgFlags.getOrigAlign();
2409 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2411 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2412 Reg = State.AllocateReg(IntRegs);
2413 // If this is the first part of an i64 arg,
2414 // the allocated register must be either A0 or A2.
2415 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2416 Reg = State.AllocateReg(IntRegs);
2418 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2419 // Allocate int register and shadow next int register. If first
2420 // available register is Mips::A1 or Mips::A3, shadow it too.
2421 Reg = State.AllocateReg(IntRegs);
2422 if (Reg == Mips::A1 || Reg == Mips::A3)
2423 Reg = State.AllocateReg(IntRegs);
2424 State.AllocateReg(IntRegs);
2426 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2427 // we are guaranteed to find an available float register
2428 if (ValVT == MVT::f32) {
2429 Reg = State.AllocateReg(F32Regs);
2430 // Shadow int register
2431 State.AllocateReg(IntRegs);
2433 Reg = State.AllocateReg(F64Regs);
2434 // Shadow int registers
2435 unsigned Reg2 = State.AllocateReg(IntRegs);
2436 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2437 State.AllocateReg(IntRegs);
2438 State.AllocateReg(IntRegs);
2441 llvm_unreachable("Cannot handle this ValVT.");
2444 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2446 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2448 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2453 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2454 MVT LocVT, CCValAssign::LocInfo LocInfo,
2455 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2456 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2458 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2461 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2462 MVT LocVT, CCValAssign::LocInfo LocInfo,
2463 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2464 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2466 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2469 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2470 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2471 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2473 #include "MipsGenCallingConv.inc"
2475 //===----------------------------------------------------------------------===//
2476 // Call Calling Convention Implementation
2477 //===----------------------------------------------------------------------===//
2479 // Return next O32 integer argument register.
2480 static unsigned getNextIntArgReg(unsigned Reg) {
2481 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2482 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2486 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2487 SDValue Chain, SDValue Arg, SDLoc DL,
2488 bool IsTailCall, SelectionDAG &DAG) const {
2491 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2492 DAG.getIntPtrConstant(Offset, DL));
2493 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2497 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2498 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2499 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2500 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2501 /*isVolatile=*/ true, false, 0);
2504 void MipsTargetLowering::
2505 getOpndList(SmallVectorImpl<SDValue> &Ops,
2506 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2507 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2508 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2509 SDValue Chain) const {
2510 // Insert node "GP copy globalreg" before call to function.
2512 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2513 // in PIC mode) allow symbols to be resolved via lazy binding.
2514 // The lazy binding stub requires GP to point to the GOT.
2515 // Note that we don't need GP to point to the GOT for indirect calls
2516 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2517 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2518 // used for the function (that is, Mips linker doesn't generate lazy binding
2519 // stub for a function whose address is taken in the program).
2520 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2521 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2522 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2523 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2526 // Build a sequence of copy-to-reg nodes chained together with token
2527 // chain and flag operands which copy the outgoing args into registers.
2528 // The InFlag in necessary since all emitted instructions must be
2532 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2533 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2534 RegsToPass[i].second, InFlag);
2535 InFlag = Chain.getValue(1);
2538 // Add argument registers to the end of the list so that they are
2539 // known live into the call.
2540 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2541 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2542 RegsToPass[i].second.getValueType()));
2544 // Add a register mask operand representing the call-preserved registers.
2545 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2546 const uint32_t *Mask =
2547 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2548 assert(Mask && "Missing call preserved mask for calling convention");
2549 if (Subtarget.inMips16HardFloat()) {
2550 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2551 llvm::StringRef Sym = G->getGlobal()->getName();
2552 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2553 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2554 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2558 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2560 if (InFlag.getNode())
2561 Ops.push_back(InFlag);
2564 /// LowerCall - functions arguments are copied from virtual regs to
2565 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2567 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2568 SmallVectorImpl<SDValue> &InVals) const {
2569 SelectionDAG &DAG = CLI.DAG;
2571 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2572 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2573 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2574 SDValue Chain = CLI.Chain;
2575 SDValue Callee = CLI.Callee;
2576 bool &IsTailCall = CLI.IsTailCall;
2577 CallingConv::ID CallConv = CLI.CallConv;
2578 bool IsVarArg = CLI.IsVarArg;
2580 MachineFunction &MF = DAG.getMachineFunction();
2581 MachineFrameInfo *MFI = MF.getFrameInfo();
2582 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2583 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2584 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2586 // Analyze operands of the call, assigning locations to each operand.
2587 SmallVector<CCValAssign, 16> ArgLocs;
2589 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2590 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2592 // Allocate the reserved argument area. It seems strange to do this from the
2593 // caller side but removing it breaks the frame size calculation.
2594 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2596 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2598 // Get a count of how many bytes are to be pushed on the stack.
2599 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2601 // Check if it's really possible to do a tail call.
2603 IsTailCall = isEligibleForTailCallOptimization(
2604 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2606 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2607 report_fatal_error("failed to perform tail call elimination on a call "
2608 "site marked musttail");
2613 // Chain is the output chain of the last Load/Store or CopyToReg node.
2614 // ByValChain is the output chain of the last Memcpy node created for copying
2615 // byval arguments to the stack.
2616 unsigned StackAlignment = TFL->getStackAlignment();
2617 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2618 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2621 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2624 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
2625 getPointerTy(DAG.getDataLayout()));
2627 // With EABI is it possible to have 16 args on registers.
2628 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2629 SmallVector<SDValue, 8> MemOpChains;
2631 CCInfo.rewindByValRegsInfo();
2633 // Walk the register/memloc assignments, inserting copies/loads.
2634 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2635 SDValue Arg = OutVals[i];
2636 CCValAssign &VA = ArgLocs[i];
2637 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2638 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2639 bool UseUpperBits = false;
2642 if (Flags.isByVal()) {
2643 unsigned FirstByValReg, LastByValReg;
2644 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2645 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2647 assert(Flags.getByValSize() &&
2648 "ByVal args of size 0 should have been ignored by front-end.");
2649 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2650 assert(!IsTailCall &&
2651 "Do not tail-call optimize if there is a byval argument.");
2652 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2653 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2655 CCInfo.nextInRegsParam();
2659 // Promote the value if needed.
2660 switch (VA.getLocInfo()) {
2662 llvm_unreachable("Unknown loc info!");
2663 case CCValAssign::Full:
2664 if (VA.isRegLoc()) {
2665 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2666 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2667 (ValVT == MVT::i64 && LocVT == MVT::f64))
2668 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2669 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2670 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2671 Arg, DAG.getConstant(0, DL, MVT::i32));
2672 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2673 Arg, DAG.getConstant(1, DL, MVT::i32));
2674 if (!Subtarget.isLittle())
2676 unsigned LocRegLo = VA.getLocReg();
2677 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2678 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2679 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2684 case CCValAssign::BCvt:
2685 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2687 case CCValAssign::SExtUpper:
2688 UseUpperBits = true;
2690 case CCValAssign::SExt:
2691 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2693 case CCValAssign::ZExtUpper:
2694 UseUpperBits = true;
2696 case CCValAssign::ZExt:
2697 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2699 case CCValAssign::AExtUpper:
2700 UseUpperBits = true;
2702 case CCValAssign::AExt:
2703 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2708 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2709 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2711 ISD::SHL, DL, VA.getLocVT(), Arg,
2712 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2715 // Arguments that can be passed on register must be kept at
2716 // RegsToPass vector
2717 if (VA.isRegLoc()) {
2718 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2722 // Register can't get to this point...
2723 assert(VA.isMemLoc());
2725 // emit ISD::STORE whichs stores the
2726 // parameter value to a stack Location
2727 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2728 Chain, Arg, DL, IsTailCall, DAG));
2731 // Transform all store nodes into one single node because all store
2732 // nodes are independent of each other.
2733 if (!MemOpChains.empty())
2734 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2736 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2737 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2738 // node so that legalize doesn't hack it.
2739 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2741 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2743 EVT Ty = Callee.getValueType();
2745 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2747 const GlobalValue *Val = G->getGlobal();
2748 InternalLinkage = Val->hasInternalLinkage();
2750 if (InternalLinkage)
2751 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2752 else if (LargeGOT) {
2753 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2754 MipsII::MO_CALL_LO16, Chain,
2755 FuncInfo->callPtrInfo(Val));
2758 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2759 FuncInfo->callPtrInfo(Val));
2763 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
2764 getPointerTy(DAG.getDataLayout()), 0,
2765 MipsII::MO_NO_FLAG);
2766 GlobalOrExternal = true;
2768 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2769 const char *Sym = S->getSymbol();
2771 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2772 Callee = DAG.getTargetExternalSymbol(
2773 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
2774 else if (LargeGOT) {
2775 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2776 MipsII::MO_CALL_LO16, Chain,
2777 FuncInfo->callPtrInfo(Sym));
2779 } else { // N64 || PIC
2780 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2781 FuncInfo->callPtrInfo(Sym));
2785 GlobalOrExternal = true;
2788 SmallVector<SDValue, 8> Ops(1, Chain);
2789 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2791 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2792 IsCallReloc, CLI, Callee, Chain);
2795 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2797 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2798 SDValue InFlag = Chain.getValue(1);
2800 // Create the CALLSEQ_END node.
2801 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2802 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2803 InFlag = Chain.getValue(1);
2805 // Handle result values, copying them out of physregs into vregs that we
2807 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2811 /// LowerCallResult - Lower the result values of a call into the
2812 /// appropriate copies out of appropriate physical registers.
2813 SDValue MipsTargetLowering::LowerCallResult(
2814 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2815 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2816 SmallVectorImpl<SDValue> &InVals,
2817 TargetLowering::CallLoweringInfo &CLI) const {
2818 // Assign locations to each value returned by this call.
2819 SmallVector<CCValAssign, 16> RVLocs;
2820 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2822 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2824 // Copy all of the result registers out of their specified physreg.
2825 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2826 CCValAssign &VA = RVLocs[i];
2827 assert(VA.isRegLoc() && "Can only return in registers!");
2829 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2830 RVLocs[i].getLocVT(), InFlag);
2831 Chain = Val.getValue(1);
2832 InFlag = Val.getValue(2);
2834 if (VA.isUpperBitsInLoc()) {
2835 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2836 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2838 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2840 Shift, DL, VA.getLocVT(), Val,
2841 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2844 switch (VA.getLocInfo()) {
2846 llvm_unreachable("Unknown loc info!");
2847 case CCValAssign::Full:
2849 case CCValAssign::BCvt:
2850 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2852 case CCValAssign::AExt:
2853 case CCValAssign::AExtUpper:
2854 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2856 case CCValAssign::ZExt:
2857 case CCValAssign::ZExtUpper:
2858 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2859 DAG.getValueType(VA.getValVT()));
2860 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2862 case CCValAssign::SExt:
2863 case CCValAssign::SExtUpper:
2864 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2865 DAG.getValueType(VA.getValVT()));
2866 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2870 InVals.push_back(Val);
2876 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2877 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2878 MVT LocVT = VA.getLocVT();
2879 EVT ValVT = VA.getValVT();
2881 // Shift into the upper bits if necessary.
2882 switch (VA.getLocInfo()) {
2885 case CCValAssign::AExtUpper:
2886 case CCValAssign::SExtUpper:
2887 case CCValAssign::ZExtUpper: {
2888 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2889 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2891 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2893 Opcode, DL, VA.getLocVT(), Val,
2894 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2899 // If this is an value smaller than the argument slot size (32-bit for O32,
2900 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2901 // size. Extract the value and insert any appropriate assertions regarding
2902 // sign/zero extension.
2903 switch (VA.getLocInfo()) {
2905 llvm_unreachable("Unknown loc info!");
2906 case CCValAssign::Full:
2908 case CCValAssign::AExtUpper:
2909 case CCValAssign::AExt:
2910 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2912 case CCValAssign::SExtUpper:
2913 case CCValAssign::SExt:
2914 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2915 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2917 case CCValAssign::ZExtUpper:
2918 case CCValAssign::ZExt:
2919 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2920 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2922 case CCValAssign::BCvt:
2923 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2930 //===----------------------------------------------------------------------===//
2931 // Formal Arguments Calling Convention Implementation
2932 //===----------------------------------------------------------------------===//
2933 /// LowerFormalArguments - transform physical registers into virtual registers
2934 /// and generate load operations for arguments places on the stack.
2936 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2937 CallingConv::ID CallConv,
2939 const SmallVectorImpl<ISD::InputArg> &Ins,
2940 SDLoc DL, SelectionDAG &DAG,
2941 SmallVectorImpl<SDValue> &InVals)
2943 MachineFunction &MF = DAG.getMachineFunction();
2944 MachineFrameInfo *MFI = MF.getFrameInfo();
2945 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2947 MipsFI->setVarArgsFrameIndex(0);
2949 // Used with vargs to acumulate store chains.
2950 std::vector<SDValue> OutChains;
2952 // Assign locations to all of the incoming arguments.
2953 SmallVector<CCValAssign, 16> ArgLocs;
2954 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2956 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2957 Function::const_arg_iterator FuncArg =
2958 DAG.getMachineFunction().getFunction()->arg_begin();
2960 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2961 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2962 CCInfo.getInRegsParamsCount() > 0);
2964 unsigned CurArgIdx = 0;
2965 CCInfo.rewindByValRegsInfo();
2967 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2968 CCValAssign &VA = ArgLocs[i];
2969 if (Ins[i].isOrigArg()) {
2970 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2971 CurArgIdx = Ins[i].getOrigArgIndex();
2973 EVT ValVT = VA.getValVT();
2974 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2975 bool IsRegLoc = VA.isRegLoc();
2977 if (Flags.isByVal()) {
2978 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2979 unsigned FirstByValReg, LastByValReg;
2980 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2981 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2983 assert(Flags.getByValSize() &&
2984 "ByVal args of size 0 should have been ignored by front-end.");
2985 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2986 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2987 FirstByValReg, LastByValReg, VA, CCInfo);
2988 CCInfo.nextInRegsParam();
2992 // Arguments stored on registers
2994 MVT RegVT = VA.getLocVT();
2995 unsigned ArgReg = VA.getLocReg();
2996 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2998 // Transform the arguments stored on
2999 // physical registers into virtual ones
3000 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3001 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3003 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3005 // Handle floating point arguments passed in integer registers and
3006 // long double arguments passed in floating point registers.
3007 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3008 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3009 (RegVT == MVT::f64 && ValVT == MVT::i64))
3010 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3011 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3012 ValVT == MVT::f64) {
3013 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3014 getNextIntArgReg(ArgReg), RC);
3015 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3016 if (!Subtarget.isLittle())
3017 std::swap(ArgValue, ArgValue2);
3018 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3019 ArgValue, ArgValue2);
3022 InVals.push_back(ArgValue);
3023 } else { // VA.isRegLoc()
3024 MVT LocVT = VA.getLocVT();
3027 // We ought to be able to use LocVT directly but O32 sets it to i32
3028 // when allocating floating point values to integer registers.
3029 // This shouldn't influence how we load the value into registers unless
3030 // we are targetting softfloat.
3031 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3032 LocVT = VA.getValVT();
3036 assert(VA.isMemLoc());
3038 // The stack pointer offset is relative to the caller stack frame.
3039 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
3040 VA.getLocMemOffset(), true);
3042 // Create load nodes to retrieve arguments from the stack
3043 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3044 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
3045 MachinePointerInfo::getFixedStack(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::LowerReturn(SDValue Chain,
3110 CallingConv::ID CallConv, bool IsVarArg,
3111 const SmallVectorImpl<ISD::OutputArg> &Outs,
3112 const SmallVectorImpl<SDValue> &OutVals,
3113 SDLoc DL, SelectionDAG &DAG) const {
3114 // CCValAssign - represent the assignment of
3115 // the return value to a location
3116 SmallVector<CCValAssign, 16> RVLocs;
3117 MachineFunction &MF = DAG.getMachineFunction();
3119 // CCState - Info about the registers and stack slot.
3120 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3122 // Analyze return values.
3123 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3126 SmallVector<SDValue, 4> RetOps(1, Chain);
3128 // Copy the result values into the output registers.
3129 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3130 SDValue Val = OutVals[i];
3131 CCValAssign &VA = RVLocs[i];
3132 assert(VA.isRegLoc() && "Can only return in registers!");
3133 bool UseUpperBits = false;
3135 switch (VA.getLocInfo()) {
3137 llvm_unreachable("Unknown loc info!");
3138 case CCValAssign::Full:
3140 case CCValAssign::BCvt:
3141 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3143 case CCValAssign::AExtUpper:
3144 UseUpperBits = true;
3146 case CCValAssign::AExt:
3147 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3149 case CCValAssign::ZExtUpper:
3150 UseUpperBits = true;
3152 case CCValAssign::ZExt:
3153 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3155 case CCValAssign::SExtUpper:
3156 UseUpperBits = true;
3158 case CCValAssign::SExt:
3159 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3164 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3165 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3167 ISD::SHL, DL, VA.getLocVT(), Val,
3168 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3171 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3173 // Guarantee that all emitted copies are stuck together with flags.
3174 Flag = Chain.getValue(1);
3175 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3178 // The mips ABIs for returning structs by value requires that we copy
3179 // the sret argument into $v0 for the return. We saved the argument into
3180 // a virtual register in the entry block, so now we copy the value out
3182 if (MF.getFunction()->hasStructRetAttr()) {
3183 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3184 unsigned Reg = MipsFI->getSRetReturnReg();
3187 llvm_unreachable("sret virtual register not created in the entry block");
3189 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3190 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3192 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3193 Flag = Chain.getValue(1);
3194 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3197 RetOps[0] = Chain; // Update chain.
3199 // Add the flag if we have it.
3201 RetOps.push_back(Flag);
3203 // Return on Mips is always a "jr $ra"
3204 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3207 //===----------------------------------------------------------------------===//
3208 // Mips Inline Assembly Support
3209 //===----------------------------------------------------------------------===//
3211 /// getConstraintType - Given a constraint letter, return the type of
3212 /// constraint it is for this target.
3213 MipsTargetLowering::ConstraintType
3214 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3215 // Mips specific constraints
3216 // GCC config/mips/constraints.md
3218 // 'd' : An address register. Equivalent to r
3219 // unless generating MIPS16 code.
3220 // 'y' : Equivalent to r; retained for
3221 // backwards compatibility.
3222 // 'c' : A register suitable for use in an indirect
3223 // jump. This will always be $25 for -mabicalls.
3224 // 'l' : The lo register. 1 word storage.
3225 // 'x' : The hilo register pair. Double word storage.
3226 if (Constraint.size() == 1) {
3227 switch (Constraint[0]) {
3235 return C_RegisterClass;
3241 if (Constraint == "ZC")
3244 return TargetLowering::getConstraintType(Constraint);
3247 /// Examine constraint type and operand type and determine a weight value.
3248 /// This object must already have been set up with the operand type
3249 /// and the current alternative constraint selected.
3250 TargetLowering::ConstraintWeight
3251 MipsTargetLowering::getSingleConstraintMatchWeight(
3252 AsmOperandInfo &info, const char *constraint) const {
3253 ConstraintWeight weight = CW_Invalid;
3254 Value *CallOperandVal = info.CallOperandVal;
3255 // If we don't have a value, we can't do a match,
3256 // but allow it at the lowest weight.
3257 if (!CallOperandVal)
3259 Type *type = CallOperandVal->getType();
3260 // Look at the constraint type.
3261 switch (*constraint) {
3263 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3267 if (type->isIntegerTy())
3268 weight = CW_Register;
3270 case 'f': // FPU or MSA register
3271 if (Subtarget.hasMSA() && type->isVectorTy() &&
3272 cast<VectorType>(type)->getBitWidth() == 128)
3273 weight = CW_Register;
3274 else if (type->isFloatTy())
3275 weight = CW_Register;
3277 case 'c': // $25 for indirect jumps
3278 case 'l': // lo register
3279 case 'x': // hilo register pair
3280 if (type->isIntegerTy())
3281 weight = CW_SpecificReg;
3283 case 'I': // signed 16 bit immediate
3284 case 'J': // integer zero
3285 case 'K': // unsigned 16 bit immediate
3286 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3287 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3288 case 'O': // signed 15 bit immediate (+- 16383)
3289 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3290 if (isa<ConstantInt>(CallOperandVal))
3291 weight = CW_Constant;
3300 /// This is a helper function to parse a physical register string and split it
3301 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3302 /// that is returned indicates whether parsing was successful. The second flag
3303 /// is true if the numeric part exists.
3304 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3305 unsigned long long &Reg) {
3306 if (C.front() != '{' || C.back() != '}')
3307 return std::make_pair(false, false);
3309 // Search for the first numeric character.
3310 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3311 I = std::find_if(B, E, std::ptr_fun(isdigit));
3313 Prefix = StringRef(B, I - B);
3315 // The second flag is set to false if no numeric characters were found.
3317 return std::make_pair(true, false);
3319 // Parse the numeric characters.
3320 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3324 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3325 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3326 const TargetRegisterInfo *TRI =
3327 Subtarget.getRegisterInfo();
3328 const TargetRegisterClass *RC;
3330 unsigned long long Reg;
3332 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3335 return std::make_pair(0U, nullptr);
3337 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3338 // No numeric characters follow "hi" or "lo".
3340 return std::make_pair(0U, nullptr);
3342 RC = TRI->getRegClass(Prefix == "hi" ?
3343 Mips::HI32RegClassID : Mips::LO32RegClassID);
3344 return std::make_pair(*(RC->begin()), RC);
3345 } else if (Prefix.startswith("$msa")) {
3346 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3348 // No numeric characters follow the name.
3350 return std::make_pair(0U, nullptr);
3352 Reg = StringSwitch<unsigned long long>(Prefix)
3353 .Case("$msair", Mips::MSAIR)
3354 .Case("$msacsr", Mips::MSACSR)
3355 .Case("$msaaccess", Mips::MSAAccess)
3356 .Case("$msasave", Mips::MSASave)
3357 .Case("$msamodify", Mips::MSAModify)
3358 .Case("$msarequest", Mips::MSARequest)
3359 .Case("$msamap", Mips::MSAMap)
3360 .Case("$msaunmap", Mips::MSAUnmap)
3364 return std::make_pair(0U, nullptr);
3366 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3367 return std::make_pair(Reg, RC);
3371 return std::make_pair(0U, nullptr);
3373 if (Prefix == "$f") { // Parse $f0-$f31.
3374 // If the size of FP registers is 64-bit or Reg is an even number, select
3375 // the 64-bit register class. Otherwise, select the 32-bit register class.
3376 if (VT == MVT::Other)
3377 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3379 RC = getRegClassFor(VT);
3381 if (RC == &Mips::AFGR64RegClass) {
3382 assert(Reg % 2 == 0);
3385 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3386 RC = TRI->getRegClass(Mips::FCCRegClassID);
3387 else if (Prefix == "$w") { // Parse $w0-$w31.
3388 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3389 } else { // Parse $0-$31.
3390 assert(Prefix == "$");
3391 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3394 assert(Reg < RC->getNumRegs());
3395 return std::make_pair(*(RC->begin() + Reg), RC);
3398 /// Given a register class constraint, like 'r', if this corresponds directly
3399 /// to an LLVM register class, return a register of 0 and the register class
3401 std::pair<unsigned, const TargetRegisterClass *>
3402 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3403 StringRef Constraint,
3405 if (Constraint.size() == 1) {
3406 switch (Constraint[0]) {
3407 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3408 case 'y': // Same as 'r'. Exists for compatibility.
3410 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3411 if (Subtarget.inMips16Mode())
3412 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3413 return std::make_pair(0U, &Mips::GPR32RegClass);
3415 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3416 return std::make_pair(0U, &Mips::GPR32RegClass);
3417 if (VT == MVT::i64 && Subtarget.isGP64bit())
3418 return std::make_pair(0U, &Mips::GPR64RegClass);
3419 // This will generate an error message
3420 return std::make_pair(0U, nullptr);
3421 case 'f': // FPU or MSA register
3422 if (VT == MVT::v16i8)
3423 return std::make_pair(0U, &Mips::MSA128BRegClass);
3424 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3425 return std::make_pair(0U, &Mips::MSA128HRegClass);
3426 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3427 return std::make_pair(0U, &Mips::MSA128WRegClass);
3428 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3429 return std::make_pair(0U, &Mips::MSA128DRegClass);
3430 else if (VT == MVT::f32)
3431 return std::make_pair(0U, &Mips::FGR32RegClass);
3432 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3433 if (Subtarget.isFP64bit())
3434 return std::make_pair(0U, &Mips::FGR64RegClass);
3435 return std::make_pair(0U, &Mips::AFGR64RegClass);
3438 case 'c': // register suitable for indirect jump
3440 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3441 assert(VT == MVT::i64 && "Unexpected type.");
3442 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3443 case 'l': // register suitable for indirect jump
3445 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3446 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3447 case 'x': // register suitable for indirect jump
3448 // Fixme: Not triggering the use of both hi and low
3449 // This will generate an error message
3450 return std::make_pair(0U, nullptr);
3454 std::pair<unsigned, const TargetRegisterClass *> R;
3455 R = parseRegForInlineAsmConstraint(Constraint, VT);
3460 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3463 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3464 /// vector. If it is invalid, don't add anything to Ops.
3465 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3466 std::string &Constraint,
3467 std::vector<SDValue>&Ops,
3468 SelectionDAG &DAG) const {
3472 // Only support length 1 constraints for now.
3473 if (Constraint.length() > 1) return;
3475 char ConstraintLetter = Constraint[0];
3476 switch (ConstraintLetter) {
3477 default: break; // This will fall through to the generic implementation
3478 case 'I': // Signed 16 bit constant
3479 // If this fails, the parent routine will give an error
3480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3481 EVT Type = Op.getValueType();
3482 int64_t Val = C->getSExtValue();
3483 if (isInt<16>(Val)) {
3484 Result = DAG.getTargetConstant(Val, DL, Type);
3489 case 'J': // integer zero
3490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3491 EVT Type = Op.getValueType();
3492 int64_t Val = C->getZExtValue();
3494 Result = DAG.getTargetConstant(0, DL, Type);
3499 case 'K': // unsigned 16 bit immediate
3500 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3501 EVT Type = Op.getValueType();
3502 uint64_t Val = (uint64_t)C->getZExtValue();
3503 if (isUInt<16>(Val)) {
3504 Result = DAG.getTargetConstant(Val, DL, Type);
3509 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3510 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3511 EVT Type = Op.getValueType();
3512 int64_t Val = C->getSExtValue();
3513 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3514 Result = DAG.getTargetConstant(Val, DL, Type);
3519 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3520 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3521 EVT Type = Op.getValueType();
3522 int64_t Val = C->getSExtValue();
3523 if ((Val >= -65535) && (Val <= -1)) {
3524 Result = DAG.getTargetConstant(Val, DL, Type);
3529 case 'O': // signed 15 bit immediate
3530 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3531 EVT Type = Op.getValueType();
3532 int64_t Val = C->getSExtValue();
3533 if ((isInt<15>(Val))) {
3534 Result = DAG.getTargetConstant(Val, DL, Type);
3539 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3540 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3541 EVT Type = Op.getValueType();
3542 int64_t Val = C->getSExtValue();
3543 if ((Val <= 65535) && (Val >= 1)) {
3544 Result = DAG.getTargetConstant(Val, DL, Type);
3551 if (Result.getNode()) {
3552 Ops.push_back(Result);
3556 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3559 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3560 const AddrMode &AM, Type *Ty,
3561 unsigned AS) const {
3562 // No global is ever allowed as a base.
3567 case 0: // "r+i" or just "i", depending on HasBaseReg.
3570 if (!AM.HasBaseReg) // allow "r+i".
3572 return false; // disallow "r+r" or "r+r+i".
3581 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3582 // The Mips target isn't yet aware of offsets.
3586 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3588 bool IsMemset, bool ZeroMemset,
3590 MachineFunction &MF) const {
3591 if (Subtarget.hasMips64())
3597 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3598 if (VT != MVT::f32 && VT != MVT::f64)
3600 if (Imm.isNegZero())
3602 return Imm.isZero();
3605 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3607 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3609 return TargetLowering::getJumpTableEncoding();
3612 bool MipsTargetLowering::useSoftFloat() const {
3613 return Subtarget.useSoftFloat();
3616 void MipsTargetLowering::copyByValRegs(
3617 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3618 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3619 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3620 const CCValAssign &VA, MipsCCState &State) const {
3621 MachineFunction &MF = DAG.getMachineFunction();
3622 MachineFrameInfo *MFI = MF.getFrameInfo();
3623 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3624 unsigned NumRegs = LastReg - FirstReg;
3625 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3626 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3628 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3632 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3633 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3635 FrameObjOffset = VA.getLocMemOffset();
3637 // Create frame object.
3638 EVT PtrTy = getPointerTy(DAG.getDataLayout());
3639 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3640 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3641 InVals.push_back(FIN);
3646 // Copy arg registers.
3647 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3648 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3650 for (unsigned I = 0; I < NumRegs; ++I) {
3651 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3652 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3653 unsigned Offset = I * GPRSizeInBytes;
3654 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3655 DAG.getConstant(Offset, DL, PtrTy));
3656 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3657 StorePtr, MachinePointerInfo(FuncArg, Offset),
3659 OutChains.push_back(Store);
3663 // Copy byVal arg to registers and stack.
3664 void MipsTargetLowering::passByValArg(
3665 SDValue Chain, SDLoc DL,
3666 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3667 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3668 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3669 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3670 const CCValAssign &VA) const {
3671 unsigned ByValSizeInBytes = Flags.getByValSize();
3672 unsigned OffsetInBytes = 0; // From beginning of struct
3673 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3674 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3675 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
3676 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3677 unsigned NumRegs = LastReg - FirstReg;
3680 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3681 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3684 // Copy words to registers.
3685 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3686 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3687 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3688 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3689 MachinePointerInfo(), false, false, false,
3691 MemOpChains.push_back(LoadVal.getValue(1));
3692 unsigned ArgReg = ArgRegs[FirstReg + I];
3693 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3696 // Return if the struct has been fully copied.
3697 if (ByValSizeInBytes == OffsetInBytes)
3700 // Copy the remainder of the byval argument with sub-word loads and shifts.
3701 if (LeftoverBytes) {
3704 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3705 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3706 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3708 if (RemainingSizeInBytes < LoadSizeInBytes)
3712 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3713 DAG.getConstant(OffsetInBytes, DL,
3715 SDValue LoadVal = DAG.getExtLoad(
3716 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3717 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3719 MemOpChains.push_back(LoadVal.getValue(1));
3721 // Shift the loaded value.
3725 Shamt = TotalBytesLoaded * 8;
3727 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3729 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3730 DAG.getConstant(Shamt, DL, MVT::i32));
3733 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3737 OffsetInBytes += LoadSizeInBytes;
3738 TotalBytesLoaded += LoadSizeInBytes;
3739 Alignment = std::min(Alignment, LoadSizeInBytes);
3742 unsigned ArgReg = ArgRegs[FirstReg + I];
3743 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3748 // Copy remainder of byval arg to it with memcpy.
3749 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3750 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3751 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3752 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3753 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3754 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3755 DAG.getConstant(MemCpySize, DL, PtrTy),
3756 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3757 /*isTailCall=*/false,
3758 MachinePointerInfo(), MachinePointerInfo());
3759 MemOpChains.push_back(Chain);
3762 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3763 SDValue Chain, SDLoc DL,
3765 CCState &State) const {
3766 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3767 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3768 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3769 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3770 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3771 MachineFunction &MF = DAG.getMachineFunction();
3772 MachineFrameInfo *MFI = MF.getFrameInfo();
3773 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3775 // Offset of the first variable argument from stack pointer.
3778 if (ArgRegs.size() == Idx)
3780 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3783 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3784 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3787 // Record the frame index of the first variable argument
3788 // which is a value necessary to VASTART.
3789 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3790 MipsFI->setVarArgsFrameIndex(FI);
3792 // Copy the integer registers that have not been used for argument passing
3793 // to the argument register save area. For O32, the save area is allocated
3794 // in the caller's stack frame, while for N32/64, it is allocated in the
3795 // callee's stack frame.
3796 for (unsigned I = Idx; I < ArgRegs.size();
3797 ++I, VaArgOffset += RegSizeInBytes) {
3798 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3799 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3800 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3801 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3802 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3803 MachinePointerInfo(), false, false, 0);
3804 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3806 OutChains.push_back(Store);
3810 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3811 unsigned Align) const {
3812 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3814 assert(Size && "Byval argument's size shouldn't be 0.");
3816 Align = std::min(Align, TFL->getStackAlignment());
3818 unsigned FirstReg = 0;
3819 unsigned NumRegs = 0;
3821 if (State->getCallingConv() != CallingConv::Fast) {
3822 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3823 const ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3824 // FIXME: The O32 case actually describes no shadow registers.
3825 const MCPhysReg *ShadowRegs =
3826 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3828 // We used to check the size as well but we can't do that anymore since
3829 // CCState::HandleByVal() rounds up the size after calling this function.
3830 assert(!(Align % RegSizeInBytes) &&
3831 "Byval argument's alignment should be a multiple of"
3834 FirstReg = State->getFirstUnallocated(IntArgRegs);
3836 // If Align > RegSizeInBytes, the first arg register must be even.
3837 // FIXME: This condition happens to do the right thing but it's not the
3838 // right way to test it. We want to check that the stack frame offset
3839 // of the register is aligned.
3840 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3841 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3845 // Mark the registers allocated.
3846 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3847 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3848 Size -= RegSizeInBytes, ++I, ++NumRegs)
3849 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3852 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3856 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3857 bool isFPCmp, unsigned Opc) const {
3858 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3859 "Subtarget already supports SELECT nodes with the use of"
3860 "conditional-move instructions.");
3862 const TargetInstrInfo *TII =
3863 Subtarget.getInstrInfo();
3864 DebugLoc DL = MI->getDebugLoc();
3866 // To "insert" a SELECT instruction, we actually have to insert the
3867 // diamond control-flow pattern. The incoming instruction knows the
3868 // destination vreg to set, the condition code register to branch on, the
3869 // true/false values to select between, and a branch opcode to use.
3870 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3871 MachineFunction::iterator It = BB;
3878 // bNE r1, r0, copy1MBB
3879 // fallthrough --> copy0MBB
3880 MachineBasicBlock *thisMBB = BB;
3881 MachineFunction *F = BB->getParent();
3882 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3883 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3884 F->insert(It, copy0MBB);
3885 F->insert(It, sinkMBB);
3887 // Transfer the remainder of BB and its successor edges to sinkMBB.
3888 sinkMBB->splice(sinkMBB->begin(), BB,
3889 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3890 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3892 // Next, add the true and fallthrough blocks as its successors.
3893 BB->addSuccessor(copy0MBB);
3894 BB->addSuccessor(sinkMBB);
3897 // bc1[tf] cc, sinkMBB
3898 BuildMI(BB, DL, TII->get(Opc))
3899 .addReg(MI->getOperand(1).getReg())
3902 // bne rs, $0, sinkMBB
3903 BuildMI(BB, DL, TII->get(Opc))
3904 .addReg(MI->getOperand(1).getReg())
3910 // %FalseValue = ...
3911 // # fallthrough to sinkMBB
3914 // Update machine-CFG edges
3915 BB->addSuccessor(sinkMBB);
3918 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3922 BuildMI(*BB, BB->begin(), DL,
3923 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3924 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3925 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3927 MI->eraseFromParent(); // The pseudo instruction is gone now.
3932 // FIXME? Maybe this could be a TableGen attribute on some registers and
3933 // this table could be generated automatically from RegInfo.
3934 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
3935 SelectionDAG &DAG) const {
3936 // Named registers is expected to be fairly rare. For now, just support $28
3937 // since the linux kernel uses it.
3938 if (Subtarget.isGP64bit()) {
3939 unsigned Reg = StringSwitch<unsigned>(RegName)
3940 .Case("$28", Mips::GP_64)
3945 unsigned Reg = StringSwitch<unsigned>(RegName)
3946 .Case("$28", Mips::GP)
3951 report_fatal_error("Invalid register name global variable");