1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
44 #define DEBUG_TYPE "mips-lower"
46 STATISTIC(NumTailCalls, "Number of tail calls");
49 LargeGOT("mxgot", cl::Hidden,
50 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
53 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
54 cl::desc("MIPS: Don't trap on integer division by zero."),
57 static const MCPhysReg Mips64DPRegs[8] = {
58 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
59 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
62 // If I is a shifted mask, set the size (Size) and the first bit of the
63 // mask (Pos), and return true.
64 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
65 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
66 if (!isShiftedMask_64(I))
69 Size = countPopulation(I);
70 Pos = countTrailingZeros(I);
74 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
75 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
76 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
79 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
81 unsigned Flag) const {
82 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
85 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
87 unsigned Flag) const {
88 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
91 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
93 unsigned Flag) const {
94 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
97 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
99 unsigned Flag) const {
100 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
103 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
105 unsigned Flag) const {
106 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
107 N->getOffset(), Flag);
110 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
111 switch ((MipsISD::NodeType)Opcode) {
112 case MipsISD::FIRST_NUMBER: break;
113 case MipsISD::JmpLink: return "MipsISD::JmpLink";
114 case MipsISD::TailCall: return "MipsISD::TailCall";
115 case MipsISD::Hi: return "MipsISD::Hi";
116 case MipsISD::Lo: return "MipsISD::Lo";
117 case MipsISD::GPRel: return "MipsISD::GPRel";
118 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
119 case MipsISD::Ret: return "MipsISD::Ret";
120 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
121 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
122 case MipsISD::FPCmp: return "MipsISD::FPCmp";
123 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
124 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
125 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
126 case MipsISD::MFHI: return "MipsISD::MFHI";
127 case MipsISD::MFLO: return "MipsISD::MFLO";
128 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
129 case MipsISD::Mult: return "MipsISD::Mult";
130 case MipsISD::Multu: return "MipsISD::Multu";
131 case MipsISD::MAdd: return "MipsISD::MAdd";
132 case MipsISD::MAddu: return "MipsISD::MAddu";
133 case MipsISD::MSub: return "MipsISD::MSub";
134 case MipsISD::MSubu: return "MipsISD::MSubu";
135 case MipsISD::DivRem: return "MipsISD::DivRem";
136 case MipsISD::DivRemU: return "MipsISD::DivRemU";
137 case MipsISD::DivRem16: return "MipsISD::DivRem16";
138 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
139 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
140 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
141 case MipsISD::Wrapper: return "MipsISD::Wrapper";
142 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
143 case MipsISD::Sync: return "MipsISD::Sync";
144 case MipsISD::Ext: return "MipsISD::Ext";
145 case MipsISD::Ins: return "MipsISD::Ins";
146 case MipsISD::LWL: return "MipsISD::LWL";
147 case MipsISD::LWR: return "MipsISD::LWR";
148 case MipsISD::SWL: return "MipsISD::SWL";
149 case MipsISD::SWR: return "MipsISD::SWR";
150 case MipsISD::LDL: return "MipsISD::LDL";
151 case MipsISD::LDR: return "MipsISD::LDR";
152 case MipsISD::SDL: return "MipsISD::SDL";
153 case MipsISD::SDR: return "MipsISD::SDR";
154 case MipsISD::EXTP: return "MipsISD::EXTP";
155 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
156 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
157 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
158 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
159 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
160 case MipsISD::SHILO: return "MipsISD::SHILO";
161 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
162 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
163 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
164 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
165 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
166 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
167 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
168 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
169 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
170 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
171 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
172 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
173 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
174 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
175 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
176 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
177 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
178 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
179 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
180 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
181 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
182 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
183 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
184 case MipsISD::MULT: return "MipsISD::MULT";
185 case MipsISD::MULTU: return "MipsISD::MULTU";
186 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
187 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
188 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
189 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
190 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
191 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
192 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
193 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
194 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
195 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
196 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
197 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
198 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
199 case MipsISD::VCEQ: return "MipsISD::VCEQ";
200 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
201 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
202 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
203 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
204 case MipsISD::VSMAX: return "MipsISD::VSMAX";
205 case MipsISD::VSMIN: return "MipsISD::VSMIN";
206 case MipsISD::VUMAX: return "MipsISD::VUMAX";
207 case MipsISD::VUMIN: return "MipsISD::VUMIN";
208 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
209 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
210 case MipsISD::VNOR: return "MipsISD::VNOR";
211 case MipsISD::VSHF: return "MipsISD::VSHF";
212 case MipsISD::SHF: return "MipsISD::SHF";
213 case MipsISD::ILVEV: return "MipsISD::ILVEV";
214 case MipsISD::ILVOD: return "MipsISD::ILVOD";
215 case MipsISD::ILVL: return "MipsISD::ILVL";
216 case MipsISD::ILVR: return "MipsISD::ILVR";
217 case MipsISD::PCKEV: return "MipsISD::PCKEV";
218 case MipsISD::PCKOD: return "MipsISD::PCKOD";
219 case MipsISD::INSVE: return "MipsISD::INSVE";
224 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
225 const MipsSubtarget &STI)
226 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
227 // Mips does not have i1 type, so use i32 for
228 // setcc operations results (slt, sgt, ...).
229 setBooleanContents(ZeroOrOneBooleanContent);
230 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
232 // does. Integer booleans still use 0 and 1.
233 if (Subtarget.hasMips32r6())
234 setBooleanContents(ZeroOrOneBooleanContent,
235 ZeroOrNegativeOneBooleanContent);
237 // Load extented operations for i1 types must be promoted
238 for (MVT VT : MVT::integer_valuetypes()) {
239 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
240 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
241 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
244 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
246 for (MVT VT : MVT::fp_valuetypes()) {
247 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
248 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
251 // Set LoadExtAction for f16 vectors to Expand
252 for (MVT VT : MVT::fp_vector_valuetypes()) {
253 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
255 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
258 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
259 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
261 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
263 // Used by legalize types to correctly generate the setcc result.
264 // Without this, every float setcc comes with a AND/OR with the result,
265 // we don't want this, since the fpcmp result goes to a flag register,
266 // which is used implicitly by brcond and select operations.
267 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
269 // Mips Custom Operations
270 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
271 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
272 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
273 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
274 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
275 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
276 setOperationAction(ISD::SELECT, MVT::f32, Custom);
277 setOperationAction(ISD::SELECT, MVT::f64, Custom);
278 setOperationAction(ISD::SELECT, MVT::i32, Custom);
279 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
280 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
281 setOperationAction(ISD::SETCC, MVT::f32, Custom);
282 setOperationAction(ISD::SETCC, MVT::f64, Custom);
283 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
284 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
288 if (Subtarget.isGP64bit()) {
289 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
290 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
291 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
292 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
293 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
294 setOperationAction(ISD::SELECT, MVT::i64, Custom);
295 setOperationAction(ISD::LOAD, MVT::i64, Custom);
296 setOperationAction(ISD::STORE, MVT::i64, Custom);
297 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
298 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
299 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
300 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
303 if (!Subtarget.isGP64bit()) {
304 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
305 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
306 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
309 setOperationAction(ISD::ADD, MVT::i32, Custom);
310 if (Subtarget.isGP64bit())
311 setOperationAction(ISD::ADD, MVT::i64, Custom);
313 setOperationAction(ISD::SDIV, MVT::i32, Expand);
314 setOperationAction(ISD::SREM, MVT::i32, Expand);
315 setOperationAction(ISD::UDIV, MVT::i32, Expand);
316 setOperationAction(ISD::UREM, MVT::i32, Expand);
317 setOperationAction(ISD::SDIV, MVT::i64, Expand);
318 setOperationAction(ISD::SREM, MVT::i64, Expand);
319 setOperationAction(ISD::UDIV, MVT::i64, Expand);
320 setOperationAction(ISD::UREM, MVT::i64, Expand);
322 // Operations not directly supported by Mips.
323 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
324 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
325 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
326 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
327 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
328 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
329 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
330 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
331 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
332 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
333 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
334 if (Subtarget.hasCnMips()) {
335 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
336 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
338 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
339 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
341 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
342 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
344 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
347 setOperationAction(ISD::ROTL, MVT::i32, Expand);
348 setOperationAction(ISD::ROTL, MVT::i64, Expand);
349 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
350 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
352 if (!Subtarget.hasMips32r2())
353 setOperationAction(ISD::ROTR, MVT::i32, Expand);
355 if (!Subtarget.hasMips64r2())
356 setOperationAction(ISD::ROTR, MVT::i64, Expand);
358 setOperationAction(ISD::FSIN, MVT::f32, Expand);
359 setOperationAction(ISD::FSIN, MVT::f64, Expand);
360 setOperationAction(ISD::FCOS, MVT::f32, Expand);
361 setOperationAction(ISD::FCOS, MVT::f64, Expand);
362 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
363 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
364 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
365 setOperationAction(ISD::FPOW, MVT::f32, Expand);
366 setOperationAction(ISD::FPOW, MVT::f64, Expand);
367 setOperationAction(ISD::FLOG, MVT::f32, Expand);
368 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
369 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
370 setOperationAction(ISD::FEXP, MVT::f32, Expand);
371 setOperationAction(ISD::FMA, MVT::f32, Expand);
372 setOperationAction(ISD::FMA, MVT::f64, Expand);
373 setOperationAction(ISD::FREM, MVT::f32, Expand);
374 setOperationAction(ISD::FREM, MVT::f64, Expand);
376 // Lower f16 conversion operations into library calls
377 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
378 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
379 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
382 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
384 setOperationAction(ISD::VASTART, MVT::Other, Custom);
385 setOperationAction(ISD::VAARG, MVT::Other, Custom);
386 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
387 setOperationAction(ISD::VAEND, MVT::Other, Expand);
389 // Use the default for now
390 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
391 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
393 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
394 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
395 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
396 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
398 setInsertFencesForAtomic(true);
400 if (!Subtarget.hasMips32r2()) {
401 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
402 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
405 // MIPS16 lacks MIPS32's clz and clo instructions.
406 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
407 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
408 if (!Subtarget.hasMips64())
409 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
411 if (!Subtarget.hasMips32r2())
412 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
413 if (!Subtarget.hasMips64r2())
414 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
416 if (Subtarget.isGP64bit()) {
417 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
418 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
419 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
420 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
423 setOperationAction(ISD::TRAP, MVT::Other, Legal);
425 setTargetDAGCombine(ISD::SDIVREM);
426 setTargetDAGCombine(ISD::UDIVREM);
427 setTargetDAGCombine(ISD::SELECT);
428 setTargetDAGCombine(ISD::AND);
429 setTargetDAGCombine(ISD::OR);
430 setTargetDAGCombine(ISD::ADD);
432 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
434 // The arguments on the stack are defined in terms of 4-byte slots on O32
435 // and 8-byte slots on N32/N64.
436 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
438 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
440 setExceptionPointerRegister(ABI.IsN64() ? Mips::A0_64 : Mips::A0);
441 setExceptionSelectorRegister(ABI.IsN64() ? Mips::A1_64 : Mips::A1);
443 MaxStoresPerMemcpy = 16;
445 isMicroMips = Subtarget.inMicroMipsMode();
448 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
449 const MipsSubtarget &STI) {
450 if (STI.inMips16Mode())
451 return llvm::createMips16TargetLowering(TM, STI);
453 return llvm::createMipsSETargetLowering(TM, STI);
456 // Create a fast isel object.
458 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
459 const TargetLibraryInfo *libInfo) const {
460 if (!funcInfo.MF->getTarget().Options.EnableFastISel)
461 return TargetLowering::createFastISel(funcInfo, libInfo);
462 return Mips::createFastISel(funcInfo, libInfo);
465 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
469 return VT.changeVectorElementTypeToInteger();
472 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
473 TargetLowering::DAGCombinerInfo &DCI,
474 const MipsSubtarget &Subtarget) {
475 if (DCI.isBeforeLegalizeOps())
478 EVT Ty = N->getValueType(0);
479 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
480 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
481 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
485 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
486 N->getOperand(0), N->getOperand(1));
487 SDValue InChain = DAG.getEntryNode();
488 SDValue InGlue = DivRem;
491 if (N->hasAnyUseOfValue(0)) {
492 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
494 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
495 InChain = CopyFromLo.getValue(1);
496 InGlue = CopyFromLo.getValue(2);
500 if (N->hasAnyUseOfValue(1)) {
501 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
503 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
509 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
511 default: llvm_unreachable("Unknown fp condition code!");
513 case ISD::SETOEQ: return Mips::FCOND_OEQ;
514 case ISD::SETUNE: return Mips::FCOND_UNE;
516 case ISD::SETOLT: return Mips::FCOND_OLT;
518 case ISD::SETOGT: return Mips::FCOND_OGT;
520 case ISD::SETOLE: return Mips::FCOND_OLE;
522 case ISD::SETOGE: return Mips::FCOND_OGE;
523 case ISD::SETULT: return Mips::FCOND_ULT;
524 case ISD::SETULE: return Mips::FCOND_ULE;
525 case ISD::SETUGT: return Mips::FCOND_UGT;
526 case ISD::SETUGE: return Mips::FCOND_UGE;
527 case ISD::SETUO: return Mips::FCOND_UN;
528 case ISD::SETO: return Mips::FCOND_OR;
530 case ISD::SETONE: return Mips::FCOND_ONE;
531 case ISD::SETUEQ: return Mips::FCOND_UEQ;
536 /// This function returns true if the floating point conditional branches and
537 /// conditional moves which use condition code CC should be inverted.
538 static bool invertFPCondCodeUser(Mips::CondCode CC) {
539 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
542 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
543 "Illegal Condition Code");
548 // Creates and returns an FPCmp node from a setcc node.
549 // Returns Op if setcc is not a floating point comparison.
550 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
551 // must be a SETCC node
552 if (Op.getOpcode() != ISD::SETCC)
555 SDValue LHS = Op.getOperand(0);
557 if (!LHS.getValueType().isFloatingPoint())
560 SDValue RHS = Op.getOperand(1);
563 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
564 // node if necessary.
565 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
567 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
568 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
571 // Creates and returns a CMovFPT/F node.
572 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
573 SDValue False, SDLoc DL) {
574 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
575 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
576 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
578 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
579 True.getValueType(), True, FCC0, False, Cond);
582 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
583 TargetLowering::DAGCombinerInfo &DCI,
584 const MipsSubtarget &Subtarget) {
585 if (DCI.isBeforeLegalizeOps())
588 SDValue SetCC = N->getOperand(0);
590 if ((SetCC.getOpcode() != ISD::SETCC) ||
591 !SetCC.getOperand(0).getValueType().isInteger())
594 SDValue False = N->getOperand(2);
595 EVT FalseTy = False.getValueType();
597 if (!FalseTy.isInteger())
600 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
602 // If the RHS (False) is 0, we swap the order of the operands
603 // of ISD::SELECT (obviously also inverting the condition) so that we can
604 // take advantage of conditional moves using the $0 register.
606 // return (a != 0) ? x : 0;
614 if (!FalseC->getZExtValue()) {
615 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
616 SDValue True = N->getOperand(1);
618 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
619 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
621 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
624 // If both operands are integer constants there's a possibility that we
625 // can do some interesting optimizations.
626 SDValue True = N->getOperand(1);
627 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
629 if (!TrueC || !True.getValueType().isInteger())
632 // We'll also ignore MVT::i64 operands as this optimizations proves
633 // to be ineffective because of the required sign extensions as the result
634 // of a SETCC operator is always MVT::i32 for non-vector types.
635 if (True.getValueType() == MVT::i64)
638 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
640 // 1) (a < x) ? y : y-1
642 // addiu $reg2, $reg1, y-1
644 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
646 // 2) (a < x) ? y-1 : y
648 // xor $reg1, $reg1, 1
649 // addiu $reg2, $reg1, y-1
651 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
652 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
653 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
654 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
657 // Couldn't optimize.
661 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
662 TargetLowering::DAGCombinerInfo &DCI,
663 const MipsSubtarget &Subtarget) {
664 if (DCI.isBeforeLegalizeOps())
667 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
669 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
670 if (!FalseC || FalseC->getZExtValue())
673 // Since RHS (False) is 0, we swap the order of the True/False operands
674 // (obviously also inverting the condition) so that we can
675 // take advantage of conditional moves using the $0 register.
677 // return (a != 0) ? x : 0;
680 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
683 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
684 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
685 ValueIfFalse, FCC, ValueIfTrue, Glue);
688 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
689 TargetLowering::DAGCombinerInfo &DCI,
690 const MipsSubtarget &Subtarget) {
691 // Pattern match EXT.
692 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
693 // => ext $dst, $src, size, pos
694 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
697 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
698 unsigned ShiftRightOpc = ShiftRight.getOpcode();
700 // Op's first operand must be a shift right.
701 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
704 // The second operand of the shift must be an immediate.
706 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
709 uint64_t Pos = CN->getZExtValue();
710 uint64_t SMPos, SMSize;
712 // Op's second operand must be a shifted mask.
713 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
714 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
717 // Return if the shifted mask does not start at bit 0 or the sum of its size
718 // and Pos exceeds the word's size.
719 EVT ValTy = N->getValueType(0);
720 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
724 return DAG.getNode(MipsISD::Ext, DL, ValTy,
725 ShiftRight.getOperand(0),
726 DAG.getConstant(Pos, DL, MVT::i32),
727 DAG.getConstant(SMSize, DL, MVT::i32));
730 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
731 TargetLowering::DAGCombinerInfo &DCI,
732 const MipsSubtarget &Subtarget) {
733 // Pattern match INS.
734 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
735 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
736 // => ins $dst, $src, size, pos, $src1
737 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
740 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
741 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
744 // See if Op's first operand matches (and $src1 , mask0).
745 if (And0.getOpcode() != ISD::AND)
748 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
749 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
752 // See if Op's second operand matches (and (shl $src, pos), mask1).
753 if (And1.getOpcode() != ISD::AND)
756 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
757 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
760 // The shift masks must have the same position and size.
761 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
764 SDValue Shl = And1.getOperand(0);
765 if (Shl.getOpcode() != ISD::SHL)
768 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
771 unsigned Shamt = CN->getZExtValue();
773 // Return if the shift amount and the first bit position of mask are not the
775 EVT ValTy = N->getValueType(0);
776 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
780 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
781 DAG.getConstant(SMPos0, DL, MVT::i32),
782 DAG.getConstant(SMSize0, DL, MVT::i32),
786 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
787 TargetLowering::DAGCombinerInfo &DCI,
788 const MipsSubtarget &Subtarget) {
789 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
791 if (DCI.isBeforeLegalizeOps())
794 SDValue Add = N->getOperand(1);
796 if (Add.getOpcode() != ISD::ADD)
799 SDValue Lo = Add.getOperand(1);
801 if ((Lo.getOpcode() != MipsISD::Lo) ||
802 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
805 EVT ValTy = N->getValueType(0);
808 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
810 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
813 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
815 SelectionDAG &DAG = DCI.DAG;
816 unsigned Opc = N->getOpcode();
822 return performDivRemCombine(N, DAG, DCI, Subtarget);
824 return performSELECTCombine(N, DAG, DCI, Subtarget);
825 case MipsISD::CMovFP_F:
826 case MipsISD::CMovFP_T:
827 return performCMovFPCombine(N, DAG, DCI, Subtarget);
829 return performANDCombine(N, DAG, DCI, Subtarget);
831 return performORCombine(N, DAG, DCI, Subtarget);
833 return performADDCombine(N, DAG, DCI, Subtarget);
840 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
841 SmallVectorImpl<SDValue> &Results,
842 SelectionDAG &DAG) const {
843 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
845 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
846 Results.push_back(Res.getValue(I));
850 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
851 SmallVectorImpl<SDValue> &Results,
852 SelectionDAG &DAG) const {
853 return LowerOperationWrapper(N, Results, DAG);
856 SDValue MipsTargetLowering::
857 LowerOperation(SDValue Op, SelectionDAG &DAG) const
859 switch (Op.getOpcode())
861 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
862 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
863 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
864 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
865 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
866 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
867 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
868 case ISD::SELECT: return lowerSELECT(Op, DAG);
869 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
870 case ISD::SETCC: return lowerSETCC(Op, DAG);
871 case ISD::VASTART: return lowerVASTART(Op, DAG);
872 case ISD::VAARG: return lowerVAARG(Op, DAG);
873 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
874 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
875 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
876 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
877 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
878 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
879 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
880 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
881 case ISD::LOAD: return lowerLOAD(Op, DAG);
882 case ISD::STORE: return lowerSTORE(Op, DAG);
883 case ISD::ADD: return lowerADD(Op, DAG);
884 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
889 //===----------------------------------------------------------------------===//
890 // Lower helper functions
891 //===----------------------------------------------------------------------===//
893 // addLiveIn - This helper function adds the specified physical register to the
894 // MachineFunction as a live in value. It also creates a corresponding
895 // virtual register for it.
897 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
899 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
900 MF.getRegInfo().addLiveIn(PReg, VReg);
904 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
905 MachineBasicBlock &MBB,
906 const TargetInstrInfo &TII,
911 // Insert instruction "teq $divisor_reg, $zero, 7".
912 MachineBasicBlock::iterator I(MI);
913 MachineInstrBuilder MIB;
914 MachineOperand &Divisor = MI->getOperand(2);
915 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
916 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
917 .addReg(Mips::ZERO).addImm(7);
919 // Use the 32-bit sub-register if this is a 64-bit division.
921 MIB->getOperand(0).setSubReg(Mips::sub_32);
923 // Clear Divisor's kill flag.
924 Divisor.setIsKill(false);
926 // We would normally delete the original instruction here but in this case
927 // we only needed to inject an additional instruction rather than replace it.
933 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
934 MachineBasicBlock *BB) const {
935 switch (MI->getOpcode()) {
937 llvm_unreachable("Unexpected instr type to insert");
938 case Mips::ATOMIC_LOAD_ADD_I8:
939 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
940 case Mips::ATOMIC_LOAD_ADD_I16:
941 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
942 case Mips::ATOMIC_LOAD_ADD_I32:
943 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
944 case Mips::ATOMIC_LOAD_ADD_I64:
945 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
947 case Mips::ATOMIC_LOAD_AND_I8:
948 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
949 case Mips::ATOMIC_LOAD_AND_I16:
950 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
951 case Mips::ATOMIC_LOAD_AND_I32:
952 return emitAtomicBinary(MI, BB, 4, Mips::AND);
953 case Mips::ATOMIC_LOAD_AND_I64:
954 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
956 case Mips::ATOMIC_LOAD_OR_I8:
957 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
958 case Mips::ATOMIC_LOAD_OR_I16:
959 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
960 case Mips::ATOMIC_LOAD_OR_I32:
961 return emitAtomicBinary(MI, BB, 4, Mips::OR);
962 case Mips::ATOMIC_LOAD_OR_I64:
963 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
965 case Mips::ATOMIC_LOAD_XOR_I8:
966 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
967 case Mips::ATOMIC_LOAD_XOR_I16:
968 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
969 case Mips::ATOMIC_LOAD_XOR_I32:
970 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
971 case Mips::ATOMIC_LOAD_XOR_I64:
972 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
974 case Mips::ATOMIC_LOAD_NAND_I8:
975 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
976 case Mips::ATOMIC_LOAD_NAND_I16:
977 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
978 case Mips::ATOMIC_LOAD_NAND_I32:
979 return emitAtomicBinary(MI, BB, 4, 0, true);
980 case Mips::ATOMIC_LOAD_NAND_I64:
981 return emitAtomicBinary(MI, BB, 8, 0, true);
983 case Mips::ATOMIC_LOAD_SUB_I8:
984 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
985 case Mips::ATOMIC_LOAD_SUB_I16:
986 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
987 case Mips::ATOMIC_LOAD_SUB_I32:
988 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
989 case Mips::ATOMIC_LOAD_SUB_I64:
990 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
992 case Mips::ATOMIC_SWAP_I8:
993 return emitAtomicBinaryPartword(MI, BB, 1, 0);
994 case Mips::ATOMIC_SWAP_I16:
995 return emitAtomicBinaryPartword(MI, BB, 2, 0);
996 case Mips::ATOMIC_SWAP_I32:
997 return emitAtomicBinary(MI, BB, 4, 0);
998 case Mips::ATOMIC_SWAP_I64:
999 return emitAtomicBinary(MI, BB, 8, 0);
1001 case Mips::ATOMIC_CMP_SWAP_I8:
1002 return emitAtomicCmpSwapPartword(MI, BB, 1);
1003 case Mips::ATOMIC_CMP_SWAP_I16:
1004 return emitAtomicCmpSwapPartword(MI, BB, 2);
1005 case Mips::ATOMIC_CMP_SWAP_I32:
1006 return emitAtomicCmpSwap(MI, BB, 4);
1007 case Mips::ATOMIC_CMP_SWAP_I64:
1008 return emitAtomicCmpSwap(MI, BB, 8);
1009 case Mips::PseudoSDIV:
1010 case Mips::PseudoUDIV:
1015 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
1016 case Mips::PseudoDSDIV:
1017 case Mips::PseudoDUDIV:
1022 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
1024 return emitSEL_D(MI, BB);
1026 case Mips::PseudoSELECT_I:
1027 case Mips::PseudoSELECT_I64:
1028 case Mips::PseudoSELECT_S:
1029 case Mips::PseudoSELECT_D32:
1030 case Mips::PseudoSELECT_D64:
1031 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1032 case Mips::PseudoSELECTFP_F_I:
1033 case Mips::PseudoSELECTFP_F_I64:
1034 case Mips::PseudoSELECTFP_F_S:
1035 case Mips::PseudoSELECTFP_F_D32:
1036 case Mips::PseudoSELECTFP_F_D64:
1037 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1038 case Mips::PseudoSELECTFP_T_I:
1039 case Mips::PseudoSELECTFP_T_I64:
1040 case Mips::PseudoSELECTFP_T_S:
1041 case Mips::PseudoSELECTFP_T_D32:
1042 case Mips::PseudoSELECTFP_T_D64:
1043 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1047 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1048 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1050 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1051 unsigned Size, unsigned BinOpcode,
1053 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1055 MachineFunction *MF = BB->getParent();
1056 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1057 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1058 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1059 DebugLoc DL = MI->getDebugLoc();
1060 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1067 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1068 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1075 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1076 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1079 ZERO = Mips::ZERO_64;
1083 unsigned OldVal = MI->getOperand(0).getReg();
1084 unsigned Ptr = MI->getOperand(1).getReg();
1085 unsigned Incr = MI->getOperand(2).getReg();
1087 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1088 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1089 unsigned Success = RegInfo.createVirtualRegister(RC);
1091 // insert new blocks after the current block
1092 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1093 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1094 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1095 MachineFunction::iterator It = BB;
1097 MF->insert(It, loopMBB);
1098 MF->insert(It, exitMBB);
1100 // Transfer the remainder of BB and its successor edges to exitMBB.
1101 exitMBB->splice(exitMBB->begin(), BB,
1102 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1103 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1107 // fallthrough --> loopMBB
1108 BB->addSuccessor(loopMBB);
1109 loopMBB->addSuccessor(loopMBB);
1110 loopMBB->addSuccessor(exitMBB);
1113 // ll oldval, 0(ptr)
1114 // <binop> storeval, oldval, incr
1115 // sc success, storeval, 0(ptr)
1116 // beq success, $0, loopMBB
1118 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1120 // and andres, oldval, incr
1121 // nor storeval, $0, andres
1122 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1123 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1124 } else if (BinOpcode) {
1125 // <binop> storeval, oldval, incr
1126 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1130 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1131 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1133 MI->eraseFromParent(); // The instruction is gone now.
1138 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1139 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1140 unsigned SrcReg) const {
1141 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1142 DebugLoc DL = MI->getDebugLoc();
1144 if (Subtarget.hasMips32r2() && Size == 1) {
1145 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1149 if (Subtarget.hasMips32r2() && Size == 2) {
1150 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1154 MachineFunction *MF = BB->getParent();
1155 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1156 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1157 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1160 int64_t ShiftImm = 32 - (Size * 8);
1162 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1163 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1168 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1169 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1171 assert((Size == 1 || Size == 2) &&
1172 "Unsupported size for EmitAtomicBinaryPartial.");
1174 MachineFunction *MF = BB->getParent();
1175 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1176 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1177 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1178 DebugLoc DL = MI->getDebugLoc();
1180 unsigned Dest = MI->getOperand(0).getReg();
1181 unsigned Ptr = MI->getOperand(1).getReg();
1182 unsigned Incr = MI->getOperand(2).getReg();
1184 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1185 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1186 unsigned Mask = RegInfo.createVirtualRegister(RC);
1187 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1188 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1189 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1190 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1191 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1192 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1193 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1194 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1195 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1196 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1197 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1198 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1199 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1200 unsigned Success = RegInfo.createVirtualRegister(RC);
1202 // insert new blocks after the current block
1203 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1204 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1205 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1206 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1207 MachineFunction::iterator It = BB;
1209 MF->insert(It, loopMBB);
1210 MF->insert(It, sinkMBB);
1211 MF->insert(It, exitMBB);
1213 // Transfer the remainder of BB and its successor edges to exitMBB.
1214 exitMBB->splice(exitMBB->begin(), BB,
1215 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1216 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1218 BB->addSuccessor(loopMBB);
1219 loopMBB->addSuccessor(loopMBB);
1220 loopMBB->addSuccessor(sinkMBB);
1221 sinkMBB->addSuccessor(exitMBB);
1224 // addiu masklsb2,$0,-4 # 0xfffffffc
1225 // and alignedaddr,ptr,masklsb2
1226 // andi ptrlsb2,ptr,3
1227 // sll shiftamt,ptrlsb2,3
1228 // ori maskupper,$0,255 # 0xff
1229 // sll mask,maskupper,shiftamt
1230 // nor mask2,$0,mask
1231 // sll incr2,incr,shiftamt
1233 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1234 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1235 .addReg(Mips::ZERO).addImm(-4);
1236 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1237 .addReg(Ptr).addReg(MaskLSB2);
1238 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1239 if (Subtarget.isLittle()) {
1240 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1242 unsigned Off = RegInfo.createVirtualRegister(RC);
1243 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1244 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1245 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1247 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1248 .addReg(Mips::ZERO).addImm(MaskImm);
1249 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1250 .addReg(MaskUpper).addReg(ShiftAmt);
1251 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1252 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1254 // atomic.load.binop
1256 // ll oldval,0(alignedaddr)
1257 // binop binopres,oldval,incr2
1258 // and newval,binopres,mask
1259 // and maskedoldval0,oldval,mask2
1260 // or storeval,maskedoldval0,newval
1261 // sc success,storeval,0(alignedaddr)
1262 // beq success,$0,loopMBB
1266 // ll oldval,0(alignedaddr)
1267 // and newval,incr2,mask
1268 // and maskedoldval0,oldval,mask2
1269 // or storeval,maskedoldval0,newval
1270 // sc success,storeval,0(alignedaddr)
1271 // beq success,$0,loopMBB
1274 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1275 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1277 // and andres, oldval, incr2
1278 // nor binopres, $0, andres
1279 // and newval, binopres, mask
1280 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1281 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1282 .addReg(Mips::ZERO).addReg(AndRes);
1283 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1284 } else if (BinOpcode) {
1285 // <binop> binopres, oldval, incr2
1286 // and newval, binopres, mask
1287 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1288 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1289 } else { // atomic.swap
1290 // and newval, incr2, mask
1291 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1294 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1295 .addReg(OldVal).addReg(Mask2);
1296 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1297 .addReg(MaskedOldVal0).addReg(NewVal);
1298 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1299 BuildMI(BB, DL, TII->get(SC), Success)
1300 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1301 BuildMI(BB, DL, TII->get(Mips::BEQ))
1302 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1305 // and maskedoldval1,oldval,mask
1306 // srl srlres,maskedoldval1,shiftamt
1307 // sign_extend dest,srlres
1310 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1311 .addReg(OldVal).addReg(Mask);
1312 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1313 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1314 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1316 MI->eraseFromParent(); // The instruction is gone now.
1321 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1322 MachineBasicBlock *BB,
1323 unsigned Size) const {
1324 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1326 MachineFunction *MF = BB->getParent();
1327 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1328 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1329 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1330 DebugLoc DL = MI->getDebugLoc();
1331 unsigned LL, SC, ZERO, BNE, BEQ;
1334 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1335 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1342 ZERO = Mips::ZERO_64;
1347 unsigned Dest = MI->getOperand(0).getReg();
1348 unsigned Ptr = MI->getOperand(1).getReg();
1349 unsigned OldVal = MI->getOperand(2).getReg();
1350 unsigned NewVal = MI->getOperand(3).getReg();
1352 unsigned Success = RegInfo.createVirtualRegister(RC);
1354 // insert new blocks after the current block
1355 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1356 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1357 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1358 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1359 MachineFunction::iterator It = BB;
1361 MF->insert(It, loop1MBB);
1362 MF->insert(It, loop2MBB);
1363 MF->insert(It, exitMBB);
1365 // Transfer the remainder of BB and its successor edges to exitMBB.
1366 exitMBB->splice(exitMBB->begin(), BB,
1367 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1368 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1372 // fallthrough --> loop1MBB
1373 BB->addSuccessor(loop1MBB);
1374 loop1MBB->addSuccessor(exitMBB);
1375 loop1MBB->addSuccessor(loop2MBB);
1376 loop2MBB->addSuccessor(loop1MBB);
1377 loop2MBB->addSuccessor(exitMBB);
1381 // bne dest, oldval, exitMBB
1383 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1384 BuildMI(BB, DL, TII->get(BNE))
1385 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1388 // sc success, newval, 0(ptr)
1389 // beq success, $0, loop1MBB
1391 BuildMI(BB, DL, TII->get(SC), Success)
1392 .addReg(NewVal).addReg(Ptr).addImm(0);
1393 BuildMI(BB, DL, TII->get(BEQ))
1394 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1396 MI->eraseFromParent(); // The instruction is gone now.
1402 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1403 MachineBasicBlock *BB,
1404 unsigned Size) const {
1405 assert((Size == 1 || Size == 2) &&
1406 "Unsupported size for EmitAtomicCmpSwapPartial.");
1408 MachineFunction *MF = BB->getParent();
1409 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1410 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1411 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1412 DebugLoc DL = MI->getDebugLoc();
1414 unsigned Dest = MI->getOperand(0).getReg();
1415 unsigned Ptr = MI->getOperand(1).getReg();
1416 unsigned CmpVal = MI->getOperand(2).getReg();
1417 unsigned NewVal = MI->getOperand(3).getReg();
1419 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1420 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1421 unsigned Mask = RegInfo.createVirtualRegister(RC);
1422 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1423 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1424 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1425 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1426 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1427 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1428 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1429 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1430 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1431 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1432 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1433 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1434 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1435 unsigned Success = RegInfo.createVirtualRegister(RC);
1437 // insert new blocks after the current block
1438 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1439 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1440 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1441 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1442 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1443 MachineFunction::iterator It = BB;
1445 MF->insert(It, loop1MBB);
1446 MF->insert(It, loop2MBB);
1447 MF->insert(It, sinkMBB);
1448 MF->insert(It, exitMBB);
1450 // Transfer the remainder of BB and its successor edges to exitMBB.
1451 exitMBB->splice(exitMBB->begin(), BB,
1452 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1453 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1455 BB->addSuccessor(loop1MBB);
1456 loop1MBB->addSuccessor(sinkMBB);
1457 loop1MBB->addSuccessor(loop2MBB);
1458 loop2MBB->addSuccessor(loop1MBB);
1459 loop2MBB->addSuccessor(sinkMBB);
1460 sinkMBB->addSuccessor(exitMBB);
1462 // FIXME: computation of newval2 can be moved to loop2MBB.
1464 // addiu masklsb2,$0,-4 # 0xfffffffc
1465 // and alignedaddr,ptr,masklsb2
1466 // andi ptrlsb2,ptr,3
1467 // sll shiftamt,ptrlsb2,3
1468 // ori maskupper,$0,255 # 0xff
1469 // sll mask,maskupper,shiftamt
1470 // nor mask2,$0,mask
1471 // andi maskedcmpval,cmpval,255
1472 // sll shiftedcmpval,maskedcmpval,shiftamt
1473 // andi maskednewval,newval,255
1474 // sll shiftednewval,maskednewval,shiftamt
1475 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1476 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1477 .addReg(Mips::ZERO).addImm(-4);
1478 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1479 .addReg(Ptr).addReg(MaskLSB2);
1480 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1481 if (Subtarget.isLittle()) {
1482 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1484 unsigned Off = RegInfo.createVirtualRegister(RC);
1485 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1486 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1487 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1489 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1490 .addReg(Mips::ZERO).addImm(MaskImm);
1491 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1492 .addReg(MaskUpper).addReg(ShiftAmt);
1493 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1494 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1495 .addReg(CmpVal).addImm(MaskImm);
1496 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1497 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1498 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1499 .addReg(NewVal).addImm(MaskImm);
1500 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1501 .addReg(MaskedNewVal).addReg(ShiftAmt);
1504 // ll oldval,0(alginedaddr)
1505 // and maskedoldval0,oldval,mask
1506 // bne maskedoldval0,shiftedcmpval,sinkMBB
1508 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1509 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1510 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1511 .addReg(OldVal).addReg(Mask);
1512 BuildMI(BB, DL, TII->get(Mips::BNE))
1513 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1516 // and maskedoldval1,oldval,mask2
1517 // or storeval,maskedoldval1,shiftednewval
1518 // sc success,storeval,0(alignedaddr)
1519 // beq success,$0,loop1MBB
1521 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1522 .addReg(OldVal).addReg(Mask2);
1523 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1524 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1525 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1526 BuildMI(BB, DL, TII->get(SC), Success)
1527 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1528 BuildMI(BB, DL, TII->get(Mips::BEQ))
1529 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1532 // srl srlres,maskedoldval0,shiftamt
1533 // sign_extend dest,srlres
1536 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1537 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1538 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1540 MI->eraseFromParent(); // The instruction is gone now.
1545 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1546 MachineBasicBlock *BB) const {
1547 MachineFunction *MF = BB->getParent();
1548 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1549 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1550 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1551 DebugLoc DL = MI->getDebugLoc();
1552 MachineBasicBlock::iterator II(MI);
1554 unsigned Fc = MI->getOperand(1).getReg();
1555 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1557 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1559 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1562 .addImm(Mips::sub_lo);
1564 // We don't erase the original instruction, we just replace the condition
1565 // register with the 64-bit super-register.
1566 MI->getOperand(1).setReg(Fc2);
1571 //===----------------------------------------------------------------------===//
1572 // Misc Lower Operation implementation
1573 //===----------------------------------------------------------------------===//
1574 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1575 SDValue Chain = Op.getOperand(0);
1576 SDValue Table = Op.getOperand(1);
1577 SDValue Index = Op.getOperand(2);
1579 auto &TD = DAG.getDataLayout();
1580 EVT PTy = getPointerTy(TD);
1581 unsigned EntrySize =
1582 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
1584 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1585 DAG.getConstant(EntrySize, DL, PTy));
1586 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1588 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1589 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1590 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1592 Chain = Addr.getValue(1);
1594 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1595 // For PIC, the sequence is:
1596 // BRIND(load(Jumptable + index) + RelocBase)
1597 // RelocBase can be JumpTable, GOT or some sort of global base.
1598 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1599 getPICJumpTableRelocBase(Table, DAG));
1602 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1605 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1606 // The first operand is the chain, the second is the condition, the third is
1607 // the block to branch to if the condition is true.
1608 SDValue Chain = Op.getOperand(0);
1609 SDValue Dest = Op.getOperand(2);
1612 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1613 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1615 // Return if flag is not set by a floating point comparison.
1616 if (CondRes.getOpcode() != MipsISD::FPCmp)
1619 SDValue CCNode = CondRes.getOperand(2);
1621 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1622 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1623 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1624 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1625 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1626 FCC0, Dest, CondRes);
1629 SDValue MipsTargetLowering::
1630 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1632 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1633 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1635 // Return if flag is not set by a floating point comparison.
1636 if (Cond.getOpcode() != MipsISD::FPCmp)
1639 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1643 SDValue MipsTargetLowering::
1644 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1647 EVT Ty = Op.getOperand(0).getValueType();
1649 DAG.getNode(ISD::SETCC, DL, getSetCCResultType(DAG.getDataLayout(),
1650 *DAG.getContext(), Ty),
1651 Op.getOperand(0), Op.getOperand(1), Op.getOperand(4));
1653 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1657 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1658 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1659 SDValue Cond = createFPCmp(DAG, Op);
1661 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1662 "Floating point operand expected.");
1665 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1666 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1668 return createCMovFP(DAG, Cond, True, False, DL);
1671 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1672 SelectionDAG &DAG) const {
1673 EVT Ty = Op.getValueType();
1674 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1675 const GlobalValue *GV = N->getGlobal();
1677 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1678 const MipsTargetObjectFile *TLOF =
1679 static_cast<const MipsTargetObjectFile *>(
1680 getTargetMachine().getObjFileLowering());
1681 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1682 // %gp_rel relocation
1683 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1685 // %hi/%lo relocation
1686 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1689 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1690 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1693 return getAddrGlobalLargeGOT(N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16,
1694 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1695 MachinePointerInfo::getGOT());
1697 return getAddrGlobal(N, SDLoc(N), Ty, DAG,
1698 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP
1700 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1703 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1704 SelectionDAG &DAG) const {
1705 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1706 EVT Ty = Op.getValueType();
1708 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1709 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1711 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1714 SDValue MipsTargetLowering::
1715 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1717 // If the relocation model is PIC, use the General Dynamic TLS Model or
1718 // Local Dynamic TLS model, otherwise use the Initial Exec or
1719 // Local Exec TLS Model.
1721 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1722 if (DAG.getTarget().Options.EmulatedTLS)
1723 return LowerToTLSEmulatedModel(GA, DAG);
1726 const GlobalValue *GV = GA->getGlobal();
1727 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1729 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1731 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1732 // General Dynamic and Local Dynamic TLS Model.
1733 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1736 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1737 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1738 getGlobalReg(DAG, PtrVT), TGA);
1739 unsigned PtrSize = PtrVT.getSizeInBits();
1740 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1742 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1746 Entry.Node = Argument;
1748 Args.push_back(Entry);
1750 TargetLowering::CallLoweringInfo CLI(DAG);
1751 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1752 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1753 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1755 SDValue Ret = CallResult.first;
1757 if (model != TLSModel::LocalDynamic)
1760 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1761 MipsII::MO_DTPREL_HI);
1762 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1763 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1764 MipsII::MO_DTPREL_LO);
1765 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1766 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1767 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1771 if (model == TLSModel::InitialExec) {
1772 // Initial Exec TLS Model
1773 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1774 MipsII::MO_GOTTPREL);
1775 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1777 Offset = DAG.getLoad(PtrVT, DL,
1778 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1779 false, false, false, 0);
1781 // Local Exec TLS Model
1782 assert(model == TLSModel::LocalExec);
1783 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1784 MipsII::MO_TPREL_HI);
1785 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1786 MipsII::MO_TPREL_LO);
1787 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1788 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1789 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1792 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1793 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1796 SDValue MipsTargetLowering::
1797 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1799 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1800 EVT Ty = Op.getValueType();
1802 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1803 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1805 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1808 SDValue MipsTargetLowering::
1809 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1811 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1812 EVT Ty = Op.getValueType();
1814 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1815 const MipsTargetObjectFile *TLOF =
1816 static_cast<const MipsTargetObjectFile *>(
1817 getTargetMachine().getObjFileLowering());
1819 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
1820 getTargetMachine()))
1821 // %gp_rel relocation
1822 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1824 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1827 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1830 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1831 MachineFunction &MF = DAG.getMachineFunction();
1832 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1835 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1836 getPointerTy(MF.getDataLayout()));
1838 // vastart just stores the address of the VarArgsFrameIndex slot into the
1839 // memory location argument.
1840 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1841 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1842 MachinePointerInfo(SV), false, false, 0);
1845 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1846 SDNode *Node = Op.getNode();
1847 EVT VT = Node->getValueType(0);
1848 SDValue Chain = Node->getOperand(0);
1849 SDValue VAListPtr = Node->getOperand(1);
1850 unsigned Align = Node->getConstantOperandVal(3);
1851 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1853 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1855 SDValue VAListLoad =
1856 DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, VAListPtr,
1857 MachinePointerInfo(SV), false, false, false, 0);
1858 SDValue VAList = VAListLoad;
1860 // Re-align the pointer if necessary.
1861 // It should only ever be necessary for 64-bit types on O32 since the minimum
1862 // argument alignment is the same as the maximum type alignment for N32/N64.
1864 // FIXME: We currently align too often. The code generator doesn't notice
1865 // when the pointer is still aligned from the last va_arg (or pair of
1866 // va_args for the i64 on O32 case).
1867 if (Align > getMinStackArgumentAlignment()) {
1868 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1870 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1871 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
1873 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1874 DAG.getConstant(-(int64_t)Align, DL,
1875 VAList.getValueType()));
1878 // Increment the pointer, VAList, to the next vaarg.
1879 auto &TD = DAG.getDataLayout();
1880 unsigned ArgSizeInBytes =
1881 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1882 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1883 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes,
1884 ArgSlotSizeInBytes),
1885 DL, VAList.getValueType()));
1886 // Store the incremented VAList to the legalized pointer
1887 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1888 MachinePointerInfo(SV), false, false, 0);
1890 // In big-endian mode we must adjust the pointer when the load size is smaller
1891 // than the argument slot size. We must also reduce the known alignment to
1892 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1893 // the correct half of the slot, and reduce the alignment from 8 (slot
1894 // alignment) down to 4 (type alignment).
1895 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1896 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1897 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1898 DAG.getIntPtrConstant(Adjustment, DL));
1900 // Load the actual argument out of the pointer VAList
1901 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1905 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1906 bool HasExtractInsert) {
1907 EVT TyX = Op.getOperand(0).getValueType();
1908 EVT TyY = Op.getOperand(1).getValueType();
1910 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1911 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
1914 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1916 SDValue X = (TyX == MVT::f32) ?
1917 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1918 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1920 SDValue Y = (TyY == MVT::f32) ?
1921 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1922 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1925 if (HasExtractInsert) {
1926 // ext E, Y, 31, 1 ; extract bit31 of Y
1927 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1928 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1929 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1932 // srl SrlX, SllX, 1
1934 // sll SllY, SrlX, 31
1935 // or Or, SrlX, SllY
1936 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1937 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1938 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1939 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1940 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1943 if (TyX == MVT::f32)
1944 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1946 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1948 DAG.getConstant(0, DL, MVT::i32));
1949 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1952 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1953 bool HasExtractInsert) {
1954 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1955 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1956 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1958 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1960 // Bitcast to integer nodes.
1961 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1962 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1964 if (HasExtractInsert) {
1965 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1966 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1967 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1968 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
1970 if (WidthX > WidthY)
1971 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1972 else if (WidthY > WidthX)
1973 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1975 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1976 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
1978 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1981 // (d)sll SllX, X, 1
1982 // (d)srl SrlX, SllX, 1
1983 // (d)srl SrlY, Y, width(Y)-1
1984 // (d)sll SllY, SrlX, width(Y)-1
1985 // or Or, SrlX, SllY
1986 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1987 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1988 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1989 DAG.getConstant(WidthY - 1, DL, MVT::i32));
1991 if (WidthX > WidthY)
1992 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1993 else if (WidthY > WidthX)
1994 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1996 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1997 DAG.getConstant(WidthX - 1, DL, MVT::i32));
1998 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1999 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2003 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2004 if (Subtarget.isGP64bit())
2005 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2007 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2010 SDValue MipsTargetLowering::
2011 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2013 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2014 "Frame address can only be determined for current frame.");
2016 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2017 MFI->setFrameAddressIsTaken(true);
2018 EVT VT = Op.getValueType();
2020 SDValue FrameAddr = DAG.getCopyFromReg(
2021 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2025 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2026 SelectionDAG &DAG) const {
2027 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2031 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2032 "Return address can be determined only for current frame.");
2034 MachineFunction &MF = DAG.getMachineFunction();
2035 MachineFrameInfo *MFI = MF.getFrameInfo();
2036 MVT VT = Op.getSimpleValueType();
2037 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2038 MFI->setReturnAddressIsTaken(true);
2040 // Return RA, which contains the return address. Mark it an implicit live-in.
2041 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2042 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2045 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2046 // generated from __builtin_eh_return (offset, handler)
2047 // The effect of this is to adjust the stack pointer by "offset"
2048 // and then branch to "handler".
2049 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2051 MachineFunction &MF = DAG.getMachineFunction();
2052 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2054 MipsFI->setCallsEhReturn();
2055 SDValue Chain = Op.getOperand(0);
2056 SDValue Offset = Op.getOperand(1);
2057 SDValue Handler = Op.getOperand(2);
2059 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2061 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2062 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2063 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2064 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2065 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2066 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2067 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2068 DAG.getRegister(OffsetReg, Ty),
2069 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2073 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2074 SelectionDAG &DAG) const {
2075 // FIXME: Need pseudo-fence for 'singlethread' fences
2076 // FIXME: Set SType for weaker fences where supported/appropriate.
2079 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2080 DAG.getConstant(SType, DL, MVT::i32));
2083 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2084 SelectionDAG &DAG) const {
2086 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2088 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2089 SDValue Shamt = Op.getOperand(2);
2090 // if shamt < (VT.bits):
2091 // lo = (shl lo, shamt)
2092 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2095 // hi = (shl lo, shamt[4:0])
2096 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2097 DAG.getConstant(-1, DL, MVT::i32));
2098 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2099 DAG.getConstant(1, DL, VT));
2100 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2101 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2102 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2103 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2104 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2105 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2106 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2107 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2108 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2110 SDValue Ops[2] = {Lo, Hi};
2111 return DAG.getMergeValues(Ops, DL);
2114 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2117 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2118 SDValue Shamt = Op.getOperand(2);
2119 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2121 // if shamt < (VT.bits):
2122 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2124 // hi = (sra hi, shamt)
2126 // hi = (srl hi, shamt)
2129 // lo = (sra hi, shamt[4:0])
2130 // hi = (sra hi, 31)
2132 // lo = (srl hi, shamt[4:0])
2134 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2135 DAG.getConstant(-1, DL, MVT::i32));
2136 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2137 DAG.getConstant(1, DL, VT));
2138 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2139 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2140 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2141 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2143 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2144 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2145 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2146 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2147 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2148 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2149 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2151 SDValue Ops[2] = {Lo, Hi};
2152 return DAG.getMergeValues(Ops, DL);
2155 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2156 SDValue Chain, SDValue Src, unsigned Offset) {
2157 SDValue Ptr = LD->getBasePtr();
2158 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2159 EVT BasePtrVT = Ptr.getValueType();
2161 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2164 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2165 DAG.getConstant(Offset, DL, BasePtrVT));
2167 SDValue Ops[] = { Chain, Ptr, Src };
2168 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2169 LD->getMemOperand());
2172 // Expand an unaligned 32 or 64-bit integer load node.
2173 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2174 LoadSDNode *LD = cast<LoadSDNode>(Op);
2175 EVT MemVT = LD->getMemoryVT();
2177 if (Subtarget.systemSupportsUnalignedAccess())
2180 // Return if load is aligned or if MemVT is neither i32 nor i64.
2181 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2182 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2185 bool IsLittle = Subtarget.isLittle();
2186 EVT VT = Op.getValueType();
2187 ISD::LoadExtType ExtType = LD->getExtensionType();
2188 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2190 assert((VT == MVT::i32) || (VT == MVT::i64));
2193 // (set dst, (i64 (load baseptr)))
2195 // (set tmp, (ldl (add baseptr, 7), undef))
2196 // (set dst, (ldr baseptr, tmp))
2197 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2198 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2200 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2204 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2206 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2210 // (set dst, (i32 (load baseptr))) or
2211 // (set dst, (i64 (sextload baseptr))) or
2212 // (set dst, (i64 (extload baseptr)))
2214 // (set tmp, (lwl (add baseptr, 3), undef))
2215 // (set dst, (lwr baseptr, tmp))
2216 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2217 (ExtType == ISD::EXTLOAD))
2220 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2223 // (set dst, (i64 (zextload baseptr)))
2225 // (set tmp0, (lwl (add baseptr, 3), undef))
2226 // (set tmp1, (lwr baseptr, tmp0))
2227 // (set tmp2, (shl tmp1, 32))
2228 // (set dst, (srl tmp2, 32))
2230 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2231 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2232 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2233 SDValue Ops[] = { SRL, LWR.getValue(1) };
2234 return DAG.getMergeValues(Ops, DL);
2237 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2238 SDValue Chain, unsigned Offset) {
2239 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2240 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2242 SDVTList VTList = DAG.getVTList(MVT::Other);
2245 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2246 DAG.getConstant(Offset, DL, BasePtrVT));
2248 SDValue Ops[] = { Chain, Value, Ptr };
2249 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2250 SD->getMemOperand());
2253 // Expand an unaligned 32 or 64-bit integer store node.
2254 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2256 SDValue Value = SD->getValue(), Chain = SD->getChain();
2257 EVT VT = Value.getValueType();
2260 // (store val, baseptr) or
2261 // (truncstore val, baseptr)
2263 // (swl val, (add baseptr, 3))
2264 // (swr val, baseptr)
2265 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2266 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2268 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2271 assert(VT == MVT::i64);
2274 // (store val, baseptr)
2276 // (sdl val, (add baseptr, 7))
2277 // (sdr val, baseptr)
2278 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2279 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2282 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2283 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2284 SDValue Val = SD->getValue();
2286 if (Val.getOpcode() != ISD::FP_TO_SINT)
2289 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2290 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2293 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2294 SD->getPointerInfo(), SD->isVolatile(),
2295 SD->isNonTemporal(), SD->getAlignment());
2298 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2299 StoreSDNode *SD = cast<StoreSDNode>(Op);
2300 EVT MemVT = SD->getMemoryVT();
2302 // Lower unaligned integer stores.
2303 if (!Subtarget.systemSupportsUnalignedAccess() &&
2304 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2305 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2306 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2308 return lowerFP_TO_SINT_STORE(SD, DAG);
2311 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2312 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2313 || cast<ConstantSDNode>
2314 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2315 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2319 // (add (frameaddr 0), (frame_to_args_offset))
2320 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2321 // (add FrameObject, 0)
2322 // where FrameObject is a fixed StackObject with offset 0 which points to
2323 // the old stack pointer.
2324 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2325 EVT ValTy = Op->getValueType(0);
2326 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2327 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2329 return DAG.getNode(ISD::ADD, DL, ValTy, InArgsAddr,
2330 DAG.getConstant(0, DL, ValTy));
2333 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2334 SelectionDAG &DAG) const {
2335 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2336 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2338 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2341 //===----------------------------------------------------------------------===//
2342 // Calling Convention Implementation
2343 //===----------------------------------------------------------------------===//
2345 //===----------------------------------------------------------------------===//
2346 // TODO: Implement a generic logic using tblgen that can support this.
2347 // Mips O32 ABI rules:
2349 // i32 - Passed in A0, A1, A2, A3 and stack
2350 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2351 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2352 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2353 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2354 // not used, it must be shadowed. If only A3 is available, shadow it and
2357 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2358 //===----------------------------------------------------------------------===//
2360 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2361 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2362 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2363 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2364 State.getMachineFunction().getSubtarget());
2366 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2367 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2369 // Do not process byval args here.
2370 if (ArgFlags.isByVal())
2373 // Promote i8 and i16
2374 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2375 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2377 if (ArgFlags.isSExt())
2378 LocInfo = CCValAssign::SExtUpper;
2379 else if (ArgFlags.isZExt())
2380 LocInfo = CCValAssign::ZExtUpper;
2382 LocInfo = CCValAssign::AExtUpper;
2386 // Promote i8 and i16
2387 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2389 if (ArgFlags.isSExt())
2390 LocInfo = CCValAssign::SExt;
2391 else if (ArgFlags.isZExt())
2392 LocInfo = CCValAssign::ZExt;
2394 LocInfo = CCValAssign::AExt;
2399 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2400 // is true: function is vararg, argument is 3rd or higher, there is previous
2401 // argument which is not f32 or f64.
2402 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2403 State.getFirstUnallocated(F32Regs) != ValNo;
2404 unsigned OrigAlign = ArgFlags.getOrigAlign();
2405 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2407 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2408 Reg = State.AllocateReg(IntRegs);
2409 // If this is the first part of an i64 arg,
2410 // the allocated register must be either A0 or A2.
2411 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2412 Reg = State.AllocateReg(IntRegs);
2414 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2415 // Allocate int register and shadow next int register. If first
2416 // available register is Mips::A1 or Mips::A3, shadow it too.
2417 Reg = State.AllocateReg(IntRegs);
2418 if (Reg == Mips::A1 || Reg == Mips::A3)
2419 Reg = State.AllocateReg(IntRegs);
2420 State.AllocateReg(IntRegs);
2422 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2423 // we are guaranteed to find an available float register
2424 if (ValVT == MVT::f32) {
2425 Reg = State.AllocateReg(F32Regs);
2426 // Shadow int register
2427 State.AllocateReg(IntRegs);
2429 Reg = State.AllocateReg(F64Regs);
2430 // Shadow int registers
2431 unsigned Reg2 = State.AllocateReg(IntRegs);
2432 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2433 State.AllocateReg(IntRegs);
2434 State.AllocateReg(IntRegs);
2437 llvm_unreachable("Cannot handle this ValVT.");
2440 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2442 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2444 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2449 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2450 MVT LocVT, CCValAssign::LocInfo LocInfo,
2451 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2452 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2454 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2457 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2458 MVT LocVT, CCValAssign::LocInfo LocInfo,
2459 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2460 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2462 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2465 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2466 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2467 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2469 #include "MipsGenCallingConv.inc"
2471 //===----------------------------------------------------------------------===//
2472 // Call Calling Convention Implementation
2473 //===----------------------------------------------------------------------===//
2475 // Return next O32 integer argument register.
2476 static unsigned getNextIntArgReg(unsigned Reg) {
2477 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2478 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2482 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2483 SDValue Chain, SDValue Arg, SDLoc DL,
2484 bool IsTailCall, SelectionDAG &DAG) const {
2487 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2488 DAG.getIntPtrConstant(Offset, DL));
2489 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2493 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2494 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2495 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2496 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2497 /*isVolatile=*/ true, false, 0);
2500 void MipsTargetLowering::
2501 getOpndList(SmallVectorImpl<SDValue> &Ops,
2502 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2503 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2504 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2505 SDValue Chain) const {
2506 // Insert node "GP copy globalreg" before call to function.
2508 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2509 // in PIC mode) allow symbols to be resolved via lazy binding.
2510 // The lazy binding stub requires GP to point to the GOT.
2511 // Note that we don't need GP to point to the GOT for indirect calls
2512 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2513 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2514 // used for the function (that is, Mips linker doesn't generate lazy binding
2515 // stub for a function whose address is taken in the program).
2516 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2517 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2518 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2519 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2522 // Build a sequence of copy-to-reg nodes chained together with token
2523 // chain and flag operands which copy the outgoing args into registers.
2524 // The InFlag in necessary since all emitted instructions must be
2528 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2529 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2530 RegsToPass[i].second, InFlag);
2531 InFlag = Chain.getValue(1);
2534 // Add argument registers to the end of the list so that they are
2535 // known live into the call.
2536 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2537 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2538 RegsToPass[i].second.getValueType()));
2540 // Add a register mask operand representing the call-preserved registers.
2541 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2542 const uint32_t *Mask =
2543 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2544 assert(Mask && "Missing call preserved mask for calling convention");
2545 if (Subtarget.inMips16HardFloat()) {
2546 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2547 llvm::StringRef Sym = G->getGlobal()->getName();
2548 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2549 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2550 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2554 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2556 if (InFlag.getNode())
2557 Ops.push_back(InFlag);
2560 /// LowerCall - functions arguments are copied from virtual regs to
2561 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2563 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2564 SmallVectorImpl<SDValue> &InVals) const {
2565 SelectionDAG &DAG = CLI.DAG;
2567 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2568 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2569 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2570 SDValue Chain = CLI.Chain;
2571 SDValue Callee = CLI.Callee;
2572 bool &IsTailCall = CLI.IsTailCall;
2573 CallingConv::ID CallConv = CLI.CallConv;
2574 bool IsVarArg = CLI.IsVarArg;
2576 MachineFunction &MF = DAG.getMachineFunction();
2577 MachineFrameInfo *MFI = MF.getFrameInfo();
2578 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2579 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2580 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2582 // Analyze operands of the call, assigning locations to each operand.
2583 SmallVector<CCValAssign, 16> ArgLocs;
2585 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2586 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2588 // Allocate the reserved argument area. It seems strange to do this from the
2589 // caller side but removing it breaks the frame size calculation.
2590 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2592 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2594 // Get a count of how many bytes are to be pushed on the stack.
2595 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2597 // Check if it's really possible to do a tail call.
2599 IsTailCall = isEligibleForTailCallOptimization(
2600 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2602 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2603 report_fatal_error("failed to perform tail call elimination on a call "
2604 "site marked musttail");
2609 // Chain is the output chain of the last Load/Store or CopyToReg node.
2610 // ByValChain is the output chain of the last Memcpy node created for copying
2611 // byval arguments to the stack.
2612 unsigned StackAlignment = TFL->getStackAlignment();
2613 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2614 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2617 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2620 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
2621 getPointerTy(DAG.getDataLayout()));
2623 // With EABI is it possible to have 16 args on registers.
2624 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2625 SmallVector<SDValue, 8> MemOpChains;
2627 CCInfo.rewindByValRegsInfo();
2629 // Walk the register/memloc assignments, inserting copies/loads.
2630 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2631 SDValue Arg = OutVals[i];
2632 CCValAssign &VA = ArgLocs[i];
2633 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2634 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2635 bool UseUpperBits = false;
2638 if (Flags.isByVal()) {
2639 unsigned FirstByValReg, LastByValReg;
2640 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2641 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2643 assert(Flags.getByValSize() &&
2644 "ByVal args of size 0 should have been ignored by front-end.");
2645 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2646 assert(!IsTailCall &&
2647 "Do not tail-call optimize if there is a byval argument.");
2648 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2649 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2651 CCInfo.nextInRegsParam();
2655 // Promote the value if needed.
2656 switch (VA.getLocInfo()) {
2658 llvm_unreachable("Unknown loc info!");
2659 case CCValAssign::Full:
2660 if (VA.isRegLoc()) {
2661 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2662 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2663 (ValVT == MVT::i64 && LocVT == MVT::f64))
2664 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2665 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2666 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2667 Arg, DAG.getConstant(0, DL, MVT::i32));
2668 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2669 Arg, DAG.getConstant(1, DL, MVT::i32));
2670 if (!Subtarget.isLittle())
2672 unsigned LocRegLo = VA.getLocReg();
2673 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2674 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2675 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2680 case CCValAssign::BCvt:
2681 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2683 case CCValAssign::SExtUpper:
2684 UseUpperBits = true;
2686 case CCValAssign::SExt:
2687 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2689 case CCValAssign::ZExtUpper:
2690 UseUpperBits = true;
2692 case CCValAssign::ZExt:
2693 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2695 case CCValAssign::AExtUpper:
2696 UseUpperBits = true;
2698 case CCValAssign::AExt:
2699 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2704 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2705 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2707 ISD::SHL, DL, VA.getLocVT(), Arg,
2708 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2711 // Arguments that can be passed on register must be kept at
2712 // RegsToPass vector
2713 if (VA.isRegLoc()) {
2714 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2718 // Register can't get to this point...
2719 assert(VA.isMemLoc());
2721 // emit ISD::STORE whichs stores the
2722 // parameter value to a stack Location
2723 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2724 Chain, Arg, DL, IsTailCall, DAG));
2727 // Transform all store nodes into one single node because all store
2728 // nodes are independent of each other.
2729 if (!MemOpChains.empty())
2730 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2732 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2733 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2734 // node so that legalize doesn't hack it.
2735 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2737 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2739 EVT Ty = Callee.getValueType();
2741 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2743 const GlobalValue *Val = G->getGlobal();
2744 InternalLinkage = Val->hasInternalLinkage();
2746 if (InternalLinkage)
2747 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2748 else if (LargeGOT) {
2749 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2750 MipsII::MO_CALL_LO16, Chain,
2751 FuncInfo->callPtrInfo(Val));
2754 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2755 FuncInfo->callPtrInfo(Val));
2759 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
2760 getPointerTy(DAG.getDataLayout()), 0,
2761 MipsII::MO_NO_FLAG);
2762 GlobalOrExternal = true;
2764 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2765 const char *Sym = S->getSymbol();
2767 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2768 Callee = DAG.getTargetExternalSymbol(
2769 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
2770 else if (LargeGOT) {
2771 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2772 MipsII::MO_CALL_LO16, Chain,
2773 FuncInfo->callPtrInfo(Sym));
2775 } else { // N64 || PIC
2776 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2777 FuncInfo->callPtrInfo(Sym));
2781 GlobalOrExternal = true;
2784 SmallVector<SDValue, 8> Ops(1, Chain);
2785 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2787 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2788 IsCallReloc, CLI, Callee, Chain);
2791 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2793 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2794 SDValue InFlag = Chain.getValue(1);
2796 // Create the CALLSEQ_END node.
2797 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2798 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2799 InFlag = Chain.getValue(1);
2801 // Handle result values, copying them out of physregs into vregs that we
2803 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2807 /// LowerCallResult - Lower the result values of a call into the
2808 /// appropriate copies out of appropriate physical registers.
2809 SDValue MipsTargetLowering::LowerCallResult(
2810 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2811 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2812 SmallVectorImpl<SDValue> &InVals,
2813 TargetLowering::CallLoweringInfo &CLI) const {
2814 // Assign locations to each value returned by this call.
2815 SmallVector<CCValAssign, 16> RVLocs;
2816 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2818 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2820 // Copy all of the result registers out of their specified physreg.
2821 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2822 CCValAssign &VA = RVLocs[i];
2823 assert(VA.isRegLoc() && "Can only return in registers!");
2825 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2826 RVLocs[i].getLocVT(), InFlag);
2827 Chain = Val.getValue(1);
2828 InFlag = Val.getValue(2);
2830 if (VA.isUpperBitsInLoc()) {
2831 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2832 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2834 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2836 Shift, DL, VA.getLocVT(), Val,
2837 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2840 switch (VA.getLocInfo()) {
2842 llvm_unreachable("Unknown loc info!");
2843 case CCValAssign::Full:
2845 case CCValAssign::BCvt:
2846 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2848 case CCValAssign::AExt:
2849 case CCValAssign::AExtUpper:
2850 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2852 case CCValAssign::ZExt:
2853 case CCValAssign::ZExtUpper:
2854 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2855 DAG.getValueType(VA.getValVT()));
2856 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2858 case CCValAssign::SExt:
2859 case CCValAssign::SExtUpper:
2860 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2861 DAG.getValueType(VA.getValVT()));
2862 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2866 InVals.push_back(Val);
2872 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2873 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2874 MVT LocVT = VA.getLocVT();
2875 EVT ValVT = VA.getValVT();
2877 // Shift into the upper bits if necessary.
2878 switch (VA.getLocInfo()) {
2881 case CCValAssign::AExtUpper:
2882 case CCValAssign::SExtUpper:
2883 case CCValAssign::ZExtUpper: {
2884 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2885 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2887 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2889 Opcode, DL, VA.getLocVT(), Val,
2890 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2895 // If this is an value smaller than the argument slot size (32-bit for O32,
2896 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2897 // size. Extract the value and insert any appropriate assertions regarding
2898 // sign/zero extension.
2899 switch (VA.getLocInfo()) {
2901 llvm_unreachable("Unknown loc info!");
2902 case CCValAssign::Full:
2904 case CCValAssign::AExtUpper:
2905 case CCValAssign::AExt:
2906 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2908 case CCValAssign::SExtUpper:
2909 case CCValAssign::SExt:
2910 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2911 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2913 case CCValAssign::ZExtUpper:
2914 case CCValAssign::ZExt:
2915 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2916 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2918 case CCValAssign::BCvt:
2919 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2926 //===----------------------------------------------------------------------===//
2927 // Formal Arguments Calling Convention Implementation
2928 //===----------------------------------------------------------------------===//
2929 /// LowerFormalArguments - transform physical registers into virtual registers
2930 /// and generate load operations for arguments places on the stack.
2932 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2933 CallingConv::ID CallConv,
2935 const SmallVectorImpl<ISD::InputArg> &Ins,
2936 SDLoc DL, SelectionDAG &DAG,
2937 SmallVectorImpl<SDValue> &InVals)
2939 MachineFunction &MF = DAG.getMachineFunction();
2940 MachineFrameInfo *MFI = MF.getFrameInfo();
2941 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2943 MipsFI->setVarArgsFrameIndex(0);
2945 // Used with vargs to acumulate store chains.
2946 std::vector<SDValue> OutChains;
2948 // Assign locations to all of the incoming arguments.
2949 SmallVector<CCValAssign, 16> ArgLocs;
2950 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2952 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2953 Function::const_arg_iterator FuncArg =
2954 DAG.getMachineFunction().getFunction()->arg_begin();
2956 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2957 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2958 CCInfo.getInRegsParamsCount() > 0);
2960 unsigned CurArgIdx = 0;
2961 CCInfo.rewindByValRegsInfo();
2963 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2964 CCValAssign &VA = ArgLocs[i];
2965 if (Ins[i].isOrigArg()) {
2966 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2967 CurArgIdx = Ins[i].getOrigArgIndex();
2969 EVT ValVT = VA.getValVT();
2970 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2971 bool IsRegLoc = VA.isRegLoc();
2973 if (Flags.isByVal()) {
2974 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2975 unsigned FirstByValReg, LastByValReg;
2976 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2977 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2979 assert(Flags.getByValSize() &&
2980 "ByVal args of size 0 should have been ignored by front-end.");
2981 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2982 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2983 FirstByValReg, LastByValReg, VA, CCInfo);
2984 CCInfo.nextInRegsParam();
2988 // Arguments stored on registers
2990 MVT RegVT = VA.getLocVT();
2991 unsigned ArgReg = VA.getLocReg();
2992 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2994 // Transform the arguments stored on
2995 // physical registers into virtual ones
2996 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2997 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2999 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3001 // Handle floating point arguments passed in integer registers and
3002 // long double arguments passed in floating point registers.
3003 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3004 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3005 (RegVT == MVT::f64 && ValVT == MVT::i64))
3006 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3007 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3008 ValVT == MVT::f64) {
3009 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3010 getNextIntArgReg(ArgReg), RC);
3011 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3012 if (!Subtarget.isLittle())
3013 std::swap(ArgValue, ArgValue2);
3014 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3015 ArgValue, ArgValue2);
3018 InVals.push_back(ArgValue);
3019 } else { // VA.isRegLoc()
3020 MVT LocVT = VA.getLocVT();
3023 // We ought to be able to use LocVT directly but O32 sets it to i32
3024 // when allocating floating point values to integer registers.
3025 // This shouldn't influence how we load the value into registers unless
3026 // we are targetting softfloat.
3027 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3028 LocVT = VA.getValVT();
3032 assert(VA.isMemLoc());
3034 // The stack pointer offset is relative to the caller stack frame.
3035 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
3036 VA.getLocMemOffset(), true);
3038 // Create load nodes to retrieve arguments from the stack
3039 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3040 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
3041 MachinePointerInfo::getFixedStack(FI),
3042 false, false, false, 0);
3043 OutChains.push_back(ArgValue.getValue(1));
3045 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3047 InVals.push_back(ArgValue);
3051 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3052 // The mips ABIs for returning structs by value requires that we copy
3053 // the sret argument into $v0 for the return. Save the argument into
3054 // a virtual register so that we can access it from the return points.
3055 if (Ins[i].Flags.isSRet()) {
3056 unsigned Reg = MipsFI->getSRetReturnReg();
3058 Reg = MF.getRegInfo().createVirtualRegister(
3059 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3060 MipsFI->setSRetReturnReg(Reg);
3062 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3063 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3069 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3071 // All stores are grouped in one node to allow the matching between
3072 // the size of Ins and InVals. This only happens when on varg functions
3073 if (!OutChains.empty()) {
3074 OutChains.push_back(Chain);
3075 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3081 //===----------------------------------------------------------------------===//
3082 // Return Value Calling Convention Implementation
3083 //===----------------------------------------------------------------------===//
3086 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3087 MachineFunction &MF, bool IsVarArg,
3088 const SmallVectorImpl<ISD::OutputArg> &Outs,
3089 LLVMContext &Context) const {
3090 SmallVector<CCValAssign, 16> RVLocs;
3091 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3092 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3096 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3097 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3098 if (Type == MVT::i32)
3105 MipsTargetLowering::LowerReturn(SDValue Chain,
3106 CallingConv::ID CallConv, bool IsVarArg,
3107 const SmallVectorImpl<ISD::OutputArg> &Outs,
3108 const SmallVectorImpl<SDValue> &OutVals,
3109 SDLoc DL, SelectionDAG &DAG) const {
3110 // CCValAssign - represent the assignment of
3111 // the return value to a location
3112 SmallVector<CCValAssign, 16> RVLocs;
3113 MachineFunction &MF = DAG.getMachineFunction();
3115 // CCState - Info about the registers and stack slot.
3116 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3118 // Analyze return values.
3119 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3122 SmallVector<SDValue, 4> RetOps(1, Chain);
3124 // Copy the result values into the output registers.
3125 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3126 SDValue Val = OutVals[i];
3127 CCValAssign &VA = RVLocs[i];
3128 assert(VA.isRegLoc() && "Can only return in registers!");
3129 bool UseUpperBits = false;
3131 switch (VA.getLocInfo()) {
3133 llvm_unreachable("Unknown loc info!");
3134 case CCValAssign::Full:
3136 case CCValAssign::BCvt:
3137 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3139 case CCValAssign::AExtUpper:
3140 UseUpperBits = true;
3142 case CCValAssign::AExt:
3143 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3145 case CCValAssign::ZExtUpper:
3146 UseUpperBits = true;
3148 case CCValAssign::ZExt:
3149 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3151 case CCValAssign::SExtUpper:
3152 UseUpperBits = true;
3154 case CCValAssign::SExt:
3155 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3160 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3161 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3163 ISD::SHL, DL, VA.getLocVT(), Val,
3164 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3167 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3169 // Guarantee that all emitted copies are stuck together with flags.
3170 Flag = Chain.getValue(1);
3171 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3174 // The mips ABIs for returning structs by value requires that we copy
3175 // the sret argument into $v0 for the return. We saved the argument into
3176 // a virtual register in the entry block, so now we copy the value out
3178 if (MF.getFunction()->hasStructRetAttr()) {
3179 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3180 unsigned Reg = MipsFI->getSRetReturnReg();
3183 llvm_unreachable("sret virtual register not created in the entry block");
3185 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3186 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3188 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3189 Flag = Chain.getValue(1);
3190 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3193 RetOps[0] = Chain; // Update chain.
3195 // Add the flag if we have it.
3197 RetOps.push_back(Flag);
3199 // Return on Mips is always a "jr $ra"
3200 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3203 //===----------------------------------------------------------------------===//
3204 // Mips Inline Assembly Support
3205 //===----------------------------------------------------------------------===//
3207 /// getConstraintType - Given a constraint letter, return the type of
3208 /// constraint it is for this target.
3209 MipsTargetLowering::ConstraintType
3210 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3211 // Mips specific constraints
3212 // GCC config/mips/constraints.md
3214 // 'd' : An address register. Equivalent to r
3215 // unless generating MIPS16 code.
3216 // 'y' : Equivalent to r; retained for
3217 // backwards compatibility.
3218 // 'c' : A register suitable for use in an indirect
3219 // jump. This will always be $25 for -mabicalls.
3220 // 'l' : The lo register. 1 word storage.
3221 // 'x' : The hilo register pair. Double word storage.
3222 if (Constraint.size() == 1) {
3223 switch (Constraint[0]) {
3231 return C_RegisterClass;
3237 if (Constraint == "ZC")
3240 return TargetLowering::getConstraintType(Constraint);
3243 /// Examine constraint type and operand type and determine a weight value.
3244 /// This object must already have been set up with the operand type
3245 /// and the current alternative constraint selected.
3246 TargetLowering::ConstraintWeight
3247 MipsTargetLowering::getSingleConstraintMatchWeight(
3248 AsmOperandInfo &info, const char *constraint) const {
3249 ConstraintWeight weight = CW_Invalid;
3250 Value *CallOperandVal = info.CallOperandVal;
3251 // If we don't have a value, we can't do a match,
3252 // but allow it at the lowest weight.
3253 if (!CallOperandVal)
3255 Type *type = CallOperandVal->getType();
3256 // Look at the constraint type.
3257 switch (*constraint) {
3259 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3263 if (type->isIntegerTy())
3264 weight = CW_Register;
3266 case 'f': // FPU or MSA register
3267 if (Subtarget.hasMSA() && type->isVectorTy() &&
3268 cast<VectorType>(type)->getBitWidth() == 128)
3269 weight = CW_Register;
3270 else if (type->isFloatTy())
3271 weight = CW_Register;
3273 case 'c': // $25 for indirect jumps
3274 case 'l': // lo register
3275 case 'x': // hilo register pair
3276 if (type->isIntegerTy())
3277 weight = CW_SpecificReg;
3279 case 'I': // signed 16 bit immediate
3280 case 'J': // integer zero
3281 case 'K': // unsigned 16 bit immediate
3282 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3283 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3284 case 'O': // signed 15 bit immediate (+- 16383)
3285 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3286 if (isa<ConstantInt>(CallOperandVal))
3287 weight = CW_Constant;
3296 /// This is a helper function to parse a physical register string and split it
3297 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3298 /// that is returned indicates whether parsing was successful. The second flag
3299 /// is true if the numeric part exists.
3300 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3301 unsigned long long &Reg) {
3302 if (C.front() != '{' || C.back() != '}')
3303 return std::make_pair(false, false);
3305 // Search for the first numeric character.
3306 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3307 I = std::find_if(B, E, std::ptr_fun(isdigit));
3309 Prefix = StringRef(B, I - B);
3311 // The second flag is set to false if no numeric characters were found.
3313 return std::make_pair(true, false);
3315 // Parse the numeric characters.
3316 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3320 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3321 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3322 const TargetRegisterInfo *TRI =
3323 Subtarget.getRegisterInfo();
3324 const TargetRegisterClass *RC;
3326 unsigned long long Reg;
3328 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3331 return std::make_pair(0U, nullptr);
3333 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3334 // No numeric characters follow "hi" or "lo".
3336 return std::make_pair(0U, nullptr);
3338 RC = TRI->getRegClass(Prefix == "hi" ?
3339 Mips::HI32RegClassID : Mips::LO32RegClassID);
3340 return std::make_pair(*(RC->begin()), RC);
3341 } else if (Prefix.startswith("$msa")) {
3342 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3344 // No numeric characters follow the name.
3346 return std::make_pair(0U, nullptr);
3348 Reg = StringSwitch<unsigned long long>(Prefix)
3349 .Case("$msair", Mips::MSAIR)
3350 .Case("$msacsr", Mips::MSACSR)
3351 .Case("$msaaccess", Mips::MSAAccess)
3352 .Case("$msasave", Mips::MSASave)
3353 .Case("$msamodify", Mips::MSAModify)
3354 .Case("$msarequest", Mips::MSARequest)
3355 .Case("$msamap", Mips::MSAMap)
3356 .Case("$msaunmap", Mips::MSAUnmap)
3360 return std::make_pair(0U, nullptr);
3362 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3363 return std::make_pair(Reg, RC);
3367 return std::make_pair(0U, nullptr);
3369 if (Prefix == "$f") { // Parse $f0-$f31.
3370 // If the size of FP registers is 64-bit or Reg is an even number, select
3371 // the 64-bit register class. Otherwise, select the 32-bit register class.
3372 if (VT == MVT::Other)
3373 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3375 RC = getRegClassFor(VT);
3377 if (RC == &Mips::AFGR64RegClass) {
3378 assert(Reg % 2 == 0);
3381 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3382 RC = TRI->getRegClass(Mips::FCCRegClassID);
3383 else if (Prefix == "$w") { // Parse $w0-$w31.
3384 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3385 } else { // Parse $0-$31.
3386 assert(Prefix == "$");
3387 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3390 assert(Reg < RC->getNumRegs());
3391 return std::make_pair(*(RC->begin() + Reg), RC);
3394 /// Given a register class constraint, like 'r', if this corresponds directly
3395 /// to an LLVM register class, return a register of 0 and the register class
3397 std::pair<unsigned, const TargetRegisterClass *>
3398 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3399 StringRef Constraint,
3401 if (Constraint.size() == 1) {
3402 switch (Constraint[0]) {
3403 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3404 case 'y': // Same as 'r'. Exists for compatibility.
3406 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3407 if (Subtarget.inMips16Mode())
3408 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3409 return std::make_pair(0U, &Mips::GPR32RegClass);
3411 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3412 return std::make_pair(0U, &Mips::GPR32RegClass);
3413 if (VT == MVT::i64 && Subtarget.isGP64bit())
3414 return std::make_pair(0U, &Mips::GPR64RegClass);
3415 // This will generate an error message
3416 return std::make_pair(0U, nullptr);
3417 case 'f': // FPU or MSA register
3418 if (VT == MVT::v16i8)
3419 return std::make_pair(0U, &Mips::MSA128BRegClass);
3420 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3421 return std::make_pair(0U, &Mips::MSA128HRegClass);
3422 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3423 return std::make_pair(0U, &Mips::MSA128WRegClass);
3424 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3425 return std::make_pair(0U, &Mips::MSA128DRegClass);
3426 else if (VT == MVT::f32)
3427 return std::make_pair(0U, &Mips::FGR32RegClass);
3428 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3429 if (Subtarget.isFP64bit())
3430 return std::make_pair(0U, &Mips::FGR64RegClass);
3431 return std::make_pair(0U, &Mips::AFGR64RegClass);
3434 case 'c': // register suitable for indirect jump
3436 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3437 assert(VT == MVT::i64 && "Unexpected type.");
3438 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3439 case 'l': // register suitable for indirect jump
3441 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3442 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3443 case 'x': // register suitable for indirect jump
3444 // Fixme: Not triggering the use of both hi and low
3445 // This will generate an error message
3446 return std::make_pair(0U, nullptr);
3450 std::pair<unsigned, const TargetRegisterClass *> R;
3451 R = parseRegForInlineAsmConstraint(Constraint, VT);
3456 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3459 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3460 /// vector. If it is invalid, don't add anything to Ops.
3461 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3462 std::string &Constraint,
3463 std::vector<SDValue>&Ops,
3464 SelectionDAG &DAG) const {
3468 // Only support length 1 constraints for now.
3469 if (Constraint.length() > 1) return;
3471 char ConstraintLetter = Constraint[0];
3472 switch (ConstraintLetter) {
3473 default: break; // This will fall through to the generic implementation
3474 case 'I': // Signed 16 bit constant
3475 // If this fails, the parent routine will give an error
3476 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3477 EVT Type = Op.getValueType();
3478 int64_t Val = C->getSExtValue();
3479 if (isInt<16>(Val)) {
3480 Result = DAG.getTargetConstant(Val, DL, Type);
3485 case 'J': // integer zero
3486 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3487 EVT Type = Op.getValueType();
3488 int64_t Val = C->getZExtValue();
3490 Result = DAG.getTargetConstant(0, DL, Type);
3495 case 'K': // unsigned 16 bit immediate
3496 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3497 EVT Type = Op.getValueType();
3498 uint64_t Val = (uint64_t)C->getZExtValue();
3499 if (isUInt<16>(Val)) {
3500 Result = DAG.getTargetConstant(Val, DL, Type);
3505 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3506 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3507 EVT Type = Op.getValueType();
3508 int64_t Val = C->getSExtValue();
3509 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3510 Result = DAG.getTargetConstant(Val, DL, Type);
3515 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3516 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3517 EVT Type = Op.getValueType();
3518 int64_t Val = C->getSExtValue();
3519 if ((Val >= -65535) && (Val <= -1)) {
3520 Result = DAG.getTargetConstant(Val, DL, Type);
3525 case 'O': // signed 15 bit immediate
3526 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3527 EVT Type = Op.getValueType();
3528 int64_t Val = C->getSExtValue();
3529 if ((isInt<15>(Val))) {
3530 Result = DAG.getTargetConstant(Val, DL, Type);
3535 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3536 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3537 EVT Type = Op.getValueType();
3538 int64_t Val = C->getSExtValue();
3539 if ((Val <= 65535) && (Val >= 1)) {
3540 Result = DAG.getTargetConstant(Val, DL, Type);
3547 if (Result.getNode()) {
3548 Ops.push_back(Result);
3552 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3555 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3556 const AddrMode &AM, Type *Ty,
3557 unsigned AS) const {
3558 // No global is ever allowed as a base.
3563 case 0: // "r+i" or just "i", depending on HasBaseReg.
3566 if (!AM.HasBaseReg) // allow "r+i".
3568 return false; // disallow "r+r" or "r+r+i".
3577 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3578 // The Mips target isn't yet aware of offsets.
3582 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3584 bool IsMemset, bool ZeroMemset,
3586 MachineFunction &MF) const {
3587 if (Subtarget.hasMips64())
3593 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3594 if (VT != MVT::f32 && VT != MVT::f64)
3596 if (Imm.isNegZero())
3598 return Imm.isZero();
3601 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3603 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3605 return TargetLowering::getJumpTableEncoding();
3608 bool MipsTargetLowering::useSoftFloat() const {
3609 return Subtarget.useSoftFloat();
3612 void MipsTargetLowering::copyByValRegs(
3613 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3614 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3615 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3616 const CCValAssign &VA, MipsCCState &State) const {
3617 MachineFunction &MF = DAG.getMachineFunction();
3618 MachineFrameInfo *MFI = MF.getFrameInfo();
3619 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3620 unsigned NumRegs = LastReg - FirstReg;
3621 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3622 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3624 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3628 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3629 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3631 FrameObjOffset = VA.getLocMemOffset();
3633 // Create frame object.
3634 EVT PtrTy = getPointerTy(DAG.getDataLayout());
3635 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3636 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3637 InVals.push_back(FIN);
3642 // Copy arg registers.
3643 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3644 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3646 for (unsigned I = 0; I < NumRegs; ++I) {
3647 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3648 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3649 unsigned Offset = I * GPRSizeInBytes;
3650 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3651 DAG.getConstant(Offset, DL, PtrTy));
3652 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3653 StorePtr, MachinePointerInfo(FuncArg, Offset),
3655 OutChains.push_back(Store);
3659 // Copy byVal arg to registers and stack.
3660 void MipsTargetLowering::passByValArg(
3661 SDValue Chain, SDLoc DL,
3662 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3663 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3664 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3665 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3666 const CCValAssign &VA) const {
3667 unsigned ByValSizeInBytes = Flags.getByValSize();
3668 unsigned OffsetInBytes = 0; // From beginning of struct
3669 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3670 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3671 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
3672 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3673 unsigned NumRegs = LastReg - FirstReg;
3676 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3677 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3680 // Copy words to registers.
3681 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3682 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3683 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3684 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3685 MachinePointerInfo(), false, false, false,
3687 MemOpChains.push_back(LoadVal.getValue(1));
3688 unsigned ArgReg = ArgRegs[FirstReg + I];
3689 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3692 // Return if the struct has been fully copied.
3693 if (ByValSizeInBytes == OffsetInBytes)
3696 // Copy the remainder of the byval argument with sub-word loads and shifts.
3697 if (LeftoverBytes) {
3700 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3701 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3702 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3704 if (RemainingSizeInBytes < LoadSizeInBytes)
3708 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3709 DAG.getConstant(OffsetInBytes, DL,
3711 SDValue LoadVal = DAG.getExtLoad(
3712 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3713 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3715 MemOpChains.push_back(LoadVal.getValue(1));
3717 // Shift the loaded value.
3721 Shamt = TotalBytesLoaded * 8;
3723 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3725 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3726 DAG.getConstant(Shamt, DL, MVT::i32));
3729 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3733 OffsetInBytes += LoadSizeInBytes;
3734 TotalBytesLoaded += LoadSizeInBytes;
3735 Alignment = std::min(Alignment, LoadSizeInBytes);
3738 unsigned ArgReg = ArgRegs[FirstReg + I];
3739 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3744 // Copy remainder of byval arg to it with memcpy.
3745 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3746 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3747 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3748 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3749 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3750 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3751 DAG.getConstant(MemCpySize, DL, PtrTy),
3752 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3753 /*isTailCall=*/false,
3754 MachinePointerInfo(), MachinePointerInfo());
3755 MemOpChains.push_back(Chain);
3758 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3759 SDValue Chain, SDLoc DL,
3761 CCState &State) const {
3762 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3763 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3764 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3765 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3766 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3767 MachineFunction &MF = DAG.getMachineFunction();
3768 MachineFrameInfo *MFI = MF.getFrameInfo();
3769 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3771 // Offset of the first variable argument from stack pointer.
3774 if (ArgRegs.size() == Idx)
3776 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3779 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3780 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3783 // Record the frame index of the first variable argument
3784 // which is a value necessary to VASTART.
3785 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3786 MipsFI->setVarArgsFrameIndex(FI);
3788 // Copy the integer registers that have not been used for argument passing
3789 // to the argument register save area. For O32, the save area is allocated
3790 // in the caller's stack frame, while for N32/64, it is allocated in the
3791 // callee's stack frame.
3792 for (unsigned I = Idx; I < ArgRegs.size();
3793 ++I, VaArgOffset += RegSizeInBytes) {
3794 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3795 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3796 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3797 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3798 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3799 MachinePointerInfo(), false, false, 0);
3800 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3802 OutChains.push_back(Store);
3806 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3807 unsigned Align) const {
3808 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3810 assert(Size && "Byval argument's size shouldn't be 0.");
3812 Align = std::min(Align, TFL->getStackAlignment());
3814 unsigned FirstReg = 0;
3815 unsigned NumRegs = 0;
3817 if (State->getCallingConv() != CallingConv::Fast) {
3818 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3819 const ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3820 // FIXME: The O32 case actually describes no shadow registers.
3821 const MCPhysReg *ShadowRegs =
3822 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3824 // We used to check the size as well but we can't do that anymore since
3825 // CCState::HandleByVal() rounds up the size after calling this function.
3826 assert(!(Align % RegSizeInBytes) &&
3827 "Byval argument's alignment should be a multiple of"
3830 FirstReg = State->getFirstUnallocated(IntArgRegs);
3832 // If Align > RegSizeInBytes, the first arg register must be even.
3833 // FIXME: This condition happens to do the right thing but it's not the
3834 // right way to test it. We want to check that the stack frame offset
3835 // of the register is aligned.
3836 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3837 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3841 // Mark the registers allocated.
3842 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3843 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3844 Size -= RegSizeInBytes, ++I, ++NumRegs)
3845 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3848 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3852 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3853 bool isFPCmp, unsigned Opc) const {
3854 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3855 "Subtarget already supports SELECT nodes with the use of"
3856 "conditional-move instructions.");
3858 const TargetInstrInfo *TII =
3859 Subtarget.getInstrInfo();
3860 DebugLoc DL = MI->getDebugLoc();
3862 // To "insert" a SELECT instruction, we actually have to insert the
3863 // diamond control-flow pattern. The incoming instruction knows the
3864 // destination vreg to set, the condition code register to branch on, the
3865 // true/false values to select between, and a branch opcode to use.
3866 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3867 MachineFunction::iterator It = BB;
3874 // bNE r1, r0, copy1MBB
3875 // fallthrough --> copy0MBB
3876 MachineBasicBlock *thisMBB = BB;
3877 MachineFunction *F = BB->getParent();
3878 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3879 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3880 F->insert(It, copy0MBB);
3881 F->insert(It, sinkMBB);
3883 // Transfer the remainder of BB and its successor edges to sinkMBB.
3884 sinkMBB->splice(sinkMBB->begin(), BB,
3885 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3886 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3888 // Next, add the true and fallthrough blocks as its successors.
3889 BB->addSuccessor(copy0MBB);
3890 BB->addSuccessor(sinkMBB);
3893 // bc1[tf] cc, sinkMBB
3894 BuildMI(BB, DL, TII->get(Opc))
3895 .addReg(MI->getOperand(1).getReg())
3898 // bne rs, $0, sinkMBB
3899 BuildMI(BB, DL, TII->get(Opc))
3900 .addReg(MI->getOperand(1).getReg())
3906 // %FalseValue = ...
3907 // # fallthrough to sinkMBB
3910 // Update machine-CFG edges
3911 BB->addSuccessor(sinkMBB);
3914 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3918 BuildMI(*BB, BB->begin(), DL,
3919 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3920 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3921 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3923 MI->eraseFromParent(); // The pseudo instruction is gone now.
3928 // FIXME? Maybe this could be a TableGen attribute on some registers and
3929 // this table could be generated automatically from RegInfo.
3930 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
3931 SelectionDAG &DAG) const {
3932 // Named registers is expected to be fairly rare. For now, just support $28
3933 // since the linux kernel uses it.
3934 if (Subtarget.isGP64bit()) {
3935 unsigned Reg = StringSwitch<unsigned>(RegName)
3936 .Case("$28", Mips::GP_64)
3941 unsigned Reg = StringSwitch<unsigned>(RegName)
3942 .Case("$28", Mips::GP)
3947 report_fatal_error("Invalid register name global variable");