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::Highest: return "MipsISD::Highest";
116 case MipsISD::Higher: return "MipsISD::Higher";
117 case MipsISD::Hi: return "MipsISD::Hi";
118 case MipsISD::Lo: return "MipsISD::Lo";
119 case MipsISD::GotHi: return "MipsISD::GotHi";
120 case MipsISD::GPRel: return "MipsISD::GPRel";
121 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
122 case MipsISD::Ret: return "MipsISD::Ret";
123 case MipsISD::ERet: return "MipsISD::ERet";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
147 case MipsISD::Sync: return "MipsISD::Sync";
148 case MipsISD::Ext: return "MipsISD::Ext";
149 case MipsISD::Ins: return "MipsISD::Ins";
150 case MipsISD::CIns: return "MipsISD::CIns";
151 case MipsISD::LWL: return "MipsISD::LWL";
152 case MipsISD::LWR: return "MipsISD::LWR";
153 case MipsISD::SWL: return "MipsISD::SWL";
154 case MipsISD::SWR: return "MipsISD::SWR";
155 case MipsISD::LDL: return "MipsISD::LDL";
156 case MipsISD::LDR: return "MipsISD::LDR";
157 case MipsISD::SDL: return "MipsISD::SDL";
158 case MipsISD::SDR: return "MipsISD::SDR";
159 case MipsISD::EXTP: return "MipsISD::EXTP";
160 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
161 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
162 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
163 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
164 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
165 case MipsISD::SHILO: return "MipsISD::SHILO";
166 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
167 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
168 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
169 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
170 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
171 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
172 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
173 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
174 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
175 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
176 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
177 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
178 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
179 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
180 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
181 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
182 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
183 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
184 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
185 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
186 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
187 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
188 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
189 case MipsISD::MULT: return "MipsISD::MULT";
190 case MipsISD::MULTU: return "MipsISD::MULTU";
191 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
192 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
193 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
194 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
195 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
196 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
197 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
198 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
199 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
200 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
201 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
202 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
203 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
204 case MipsISD::VCEQ: return "MipsISD::VCEQ";
205 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
206 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
207 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
208 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
209 case MipsISD::VSMAX: return "MipsISD::VSMAX";
210 case MipsISD::VSMIN: return "MipsISD::VSMIN";
211 case MipsISD::VUMAX: return "MipsISD::VUMAX";
212 case MipsISD::VUMIN: return "MipsISD::VUMIN";
213 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
214 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
215 case MipsISD::VNOR: return "MipsISD::VNOR";
216 case MipsISD::VSHF: return "MipsISD::VSHF";
217 case MipsISD::SHF: return "MipsISD::SHF";
218 case MipsISD::ILVEV: return "MipsISD::ILVEV";
219 case MipsISD::ILVOD: return "MipsISD::ILVOD";
220 case MipsISD::ILVL: return "MipsISD::ILVL";
221 case MipsISD::ILVR: return "MipsISD::ILVR";
222 case MipsISD::PCKEV: return "MipsISD::PCKEV";
223 case MipsISD::PCKOD: return "MipsISD::PCKOD";
224 case MipsISD::INSVE: return "MipsISD::INSVE";
229 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
230 const MipsSubtarget &STI)
231 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
232 // Mips does not have i1 type, so use i32 for
233 // setcc operations results (slt, sgt, ...).
234 setBooleanContents(ZeroOrOneBooleanContent);
235 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
236 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
237 // does. Integer booleans still use 0 and 1.
238 if (Subtarget.hasMips32r6())
239 setBooleanContents(ZeroOrOneBooleanContent,
240 ZeroOrNegativeOneBooleanContent);
242 // Load extented operations for i1 types must be promoted
243 for (MVT VT : MVT::integer_valuetypes()) {
244 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
245 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
246 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
249 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
251 for (MVT VT : MVT::fp_valuetypes()) {
252 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
253 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
256 // Set LoadExtAction for f16 vectors to Expand
257 for (MVT VT : MVT::fp_vector_valuetypes()) {
258 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
260 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
263 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
264 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
266 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
268 // Used by legalize types to correctly generate the setcc result.
269 // Without this, every float setcc comes with a AND/OR with the result,
270 // we don't want this, since the fpcmp result goes to a flag register,
271 // which is used implicitly by brcond and select operations.
272 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
274 // Mips Custom Operations
275 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
276 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
277 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
278 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
279 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
280 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
281 setOperationAction(ISD::SELECT, MVT::f32, Custom);
282 setOperationAction(ISD::SELECT, MVT::f64, Custom);
283 setOperationAction(ISD::SELECT, MVT::i32, Custom);
284 setOperationAction(ISD::SETCC, MVT::f32, Custom);
285 setOperationAction(ISD::SETCC, MVT::f64, Custom);
286 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
287 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
288 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
289 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
291 if (Subtarget.isGP64bit()) {
292 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
293 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
294 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
295 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
296 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
297 setOperationAction(ISD::SELECT, MVT::i64, Custom);
298 setOperationAction(ISD::LOAD, MVT::i64, Custom);
299 setOperationAction(ISD::STORE, MVT::i64, Custom);
300 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
301 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
302 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
303 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
306 if (!Subtarget.isGP64bit()) {
307 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
308 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
309 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
312 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
313 if (Subtarget.isGP64bit())
314 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
316 setOperationAction(ISD::SDIV, MVT::i32, Expand);
317 setOperationAction(ISD::SREM, MVT::i32, Expand);
318 setOperationAction(ISD::UDIV, MVT::i32, Expand);
319 setOperationAction(ISD::UREM, MVT::i32, Expand);
320 setOperationAction(ISD::SDIV, MVT::i64, Expand);
321 setOperationAction(ISD::SREM, MVT::i64, Expand);
322 setOperationAction(ISD::UDIV, MVT::i64, Expand);
323 setOperationAction(ISD::UREM, MVT::i64, Expand);
325 // Operations not directly supported by Mips.
326 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
327 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
328 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
329 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
330 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
331 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
332 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
333 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
334 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
335 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
336 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
337 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
338 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
339 if (Subtarget.hasCnMips()) {
340 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
341 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
343 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
344 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
346 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
347 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
348 setOperationAction(ISD::ROTL, MVT::i32, Expand);
349 setOperationAction(ISD::ROTL, MVT::i64, Expand);
350 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
351 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
353 if (!Subtarget.hasMips32r2())
354 setOperationAction(ISD::ROTR, MVT::i32, Expand);
356 if (!Subtarget.hasMips64r2())
357 setOperationAction(ISD::ROTR, MVT::i64, Expand);
359 setOperationAction(ISD::FSIN, MVT::f32, Expand);
360 setOperationAction(ISD::FSIN, MVT::f64, Expand);
361 setOperationAction(ISD::FCOS, MVT::f32, Expand);
362 setOperationAction(ISD::FCOS, MVT::f64, Expand);
363 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
364 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
365 setOperationAction(ISD::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 if (!Subtarget.isGP64bit()) {
394 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
395 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
399 if (!Subtarget.hasMips32r2()) {
400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
401 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
404 // MIPS16 lacks MIPS32's clz and clo instructions.
405 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
406 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
407 if (!Subtarget.hasMips64())
408 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
410 if (!Subtarget.hasMips32r2())
411 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
412 if (!Subtarget.hasMips64r2())
413 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
415 if (Subtarget.isGP64bit()) {
416 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
417 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
418 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
419 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
422 setOperationAction(ISD::TRAP, MVT::Other, Legal);
424 setTargetDAGCombine(ISD::SDIVREM);
425 setTargetDAGCombine(ISD::UDIVREM);
426 setTargetDAGCombine(ISD::SELECT);
427 setTargetDAGCombine(ISD::AND);
428 setTargetDAGCombine(ISD::OR);
429 setTargetDAGCombine(ISD::ADD);
430 setTargetDAGCombine(ISD::AssertZext);
431 setTargetDAGCombine(ISD::SHL);
434 // These libcalls are not available in 32-bit.
435 setLibcallName(RTLIB::SHL_I128, nullptr);
436 setLibcallName(RTLIB::SRL_I128, nullptr);
437 setLibcallName(RTLIB::SRA_I128, nullptr);
440 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
442 // The arguments on the stack are defined in terms of 4-byte slots on O32
443 // and 8-byte slots on N32/N64.
444 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
446 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
448 MaxStoresPerMemcpy = 16;
450 isMicroMips = Subtarget.inMicroMipsMode();
453 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
454 const MipsSubtarget &STI) {
455 if (STI.inMips16Mode())
456 return llvm::createMips16TargetLowering(TM, STI);
458 return llvm::createMipsSETargetLowering(TM, STI);
461 // Create a fast isel object.
463 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
464 const TargetLibraryInfo *libInfo) const {
465 const MipsTargetMachine &TM =
466 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
468 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
469 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
470 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
471 !Subtarget.inMicroMipsMode();
473 // Disable if we don't generate PIC or the ABI isn't O32.
474 if (!TM.isPositionIndependent() || !TM.getABI().IsO32())
477 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
480 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
484 return VT.changeVectorElementTypeToInteger();
487 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
488 TargetLowering::DAGCombinerInfo &DCI,
489 const MipsSubtarget &Subtarget) {
490 if (DCI.isBeforeLegalizeOps())
493 EVT Ty = N->getValueType(0);
494 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
495 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
496 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
500 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
501 N->getOperand(0), N->getOperand(1));
502 SDValue InChain = DAG.getEntryNode();
503 SDValue InGlue = DivRem;
506 if (N->hasAnyUseOfValue(0)) {
507 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
509 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
510 InChain = CopyFromLo.getValue(1);
511 InGlue = CopyFromLo.getValue(2);
515 if (N->hasAnyUseOfValue(1)) {
516 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
524 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
526 default: llvm_unreachable("Unknown fp condition code!");
528 case ISD::SETOEQ: return Mips::FCOND_OEQ;
529 case ISD::SETUNE: return Mips::FCOND_UNE;
531 case ISD::SETOLT: return Mips::FCOND_OLT;
533 case ISD::SETOGT: return Mips::FCOND_OGT;
535 case ISD::SETOLE: return Mips::FCOND_OLE;
537 case ISD::SETOGE: return Mips::FCOND_OGE;
538 case ISD::SETULT: return Mips::FCOND_ULT;
539 case ISD::SETULE: return Mips::FCOND_ULE;
540 case ISD::SETUGT: return Mips::FCOND_UGT;
541 case ISD::SETUGE: return Mips::FCOND_UGE;
542 case ISD::SETUO: return Mips::FCOND_UN;
543 case ISD::SETO: return Mips::FCOND_OR;
545 case ISD::SETONE: return Mips::FCOND_ONE;
546 case ISD::SETUEQ: return Mips::FCOND_UEQ;
551 /// This function returns true if the floating point conditional branches and
552 /// conditional moves which use condition code CC should be inverted.
553 static bool invertFPCondCodeUser(Mips::CondCode CC) {
554 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
557 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
558 "Illegal Condition Code");
563 // Creates and returns an FPCmp node from a setcc node.
564 // Returns Op if setcc is not a floating point comparison.
565 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
566 // must be a SETCC node
567 if (Op.getOpcode() != ISD::SETCC)
570 SDValue LHS = Op.getOperand(0);
572 if (!LHS.getValueType().isFloatingPoint())
575 SDValue RHS = Op.getOperand(1);
578 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
579 // node if necessary.
580 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
582 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
583 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
586 // Creates and returns a CMovFPT/F node.
587 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
588 SDValue False, const SDLoc &DL) {
589 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
590 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
591 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
593 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
594 True.getValueType(), True, FCC0, False, Cond);
597 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
598 TargetLowering::DAGCombinerInfo &DCI,
599 const MipsSubtarget &Subtarget) {
600 if (DCI.isBeforeLegalizeOps())
603 SDValue SetCC = N->getOperand(0);
605 if ((SetCC.getOpcode() != ISD::SETCC) ||
606 !SetCC.getOperand(0).getValueType().isInteger())
609 SDValue False = N->getOperand(2);
610 EVT FalseTy = False.getValueType();
612 if (!FalseTy.isInteger())
615 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
617 // If the RHS (False) is 0, we swap the order of the operands
618 // of ISD::SELECT (obviously also inverting the condition) so that we can
619 // take advantage of conditional moves using the $0 register.
621 // return (a != 0) ? x : 0;
629 if (!FalseC->getZExtValue()) {
630 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
631 SDValue True = N->getOperand(1);
633 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
634 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
636 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
639 // If both operands are integer constants there's a possibility that we
640 // can do some interesting optimizations.
641 SDValue True = N->getOperand(1);
642 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
644 if (!TrueC || !True.getValueType().isInteger())
647 // We'll also ignore MVT::i64 operands as this optimizations proves
648 // to be ineffective because of the required sign extensions as the result
649 // of a SETCC operator is always MVT::i32 for non-vector types.
650 if (True.getValueType() == MVT::i64)
653 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
655 // 1) (a < x) ? y : y-1
657 // addiu $reg2, $reg1, y-1
659 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
661 // 2) (a < x) ? y-1 : y
663 // xor $reg1, $reg1, 1
664 // addiu $reg2, $reg1, y-1
666 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
667 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
668 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
669 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
672 // Couldn't optimize.
676 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
677 TargetLowering::DAGCombinerInfo &DCI,
678 const MipsSubtarget &Subtarget) {
679 if (DCI.isBeforeLegalizeOps())
682 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
684 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
685 if (!FalseC || FalseC->getZExtValue())
688 // Since RHS (False) is 0, we swap the order of the True/False operands
689 // (obviously also inverting the condition) so that we can
690 // take advantage of conditional moves using the $0 register.
692 // return (a != 0) ? x : 0;
695 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
698 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
699 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
700 ValueIfFalse, FCC, ValueIfTrue, Glue);
703 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
704 TargetLowering::DAGCombinerInfo &DCI,
705 const MipsSubtarget &Subtarget) {
706 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
709 SDValue FirstOperand = N->getOperand(0);
710 unsigned FirstOperandOpc = FirstOperand.getOpcode();
711 SDValue Mask = N->getOperand(1);
712 EVT ValTy = N->getValueType(0);
715 uint64_t Pos = 0, SMPos, SMSize;
720 // Op's second operand must be a shifted mask.
721 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
722 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
725 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
726 // Pattern match EXT.
727 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
728 // => ext $dst, $src, pos, size
730 // The second operand of the shift must be an immediate.
731 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
734 Pos = CN->getZExtValue();
736 // Return if the shifted mask does not start at bit 0 or the sum of its size
737 // and Pos exceeds the word's size.
738 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
742 NewOperand = FirstOperand.getOperand(0);
743 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
744 // Pattern match CINS.
745 // $dst = and (shl $src , pos), mask
746 // => cins $dst, $src, pos, size
747 // mask is a shifted mask with consecutive 1's, pos = shift amount,
748 // size = population count.
750 // The second operand of the shift must be an immediate.
751 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
754 Pos = CN->getZExtValue();
756 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
757 Pos + SMSize > ValTy.getSizeInBits())
760 NewOperand = FirstOperand.getOperand(0);
761 // SMSize is 'location' (position) in this case, not size.
765 // Pattern match EXT.
766 // $dst = and $src, (2**size - 1) , if size > 16
767 // => ext $dst, $src, pos, size , pos = 0
769 // If the mask is <= 0xffff, andi can be used instead.
770 if (CN->getZExtValue() <= 0xffff)
773 // Return if the mask doesn't start at position 0.
778 NewOperand = FirstOperand;
780 return DAG.getNode(Opc, DL, ValTy, NewOperand,
781 DAG.getConstant(Pos, DL, MVT::i32),
782 DAG.getConstant(SMSize, DL, MVT::i32));
785 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
786 TargetLowering::DAGCombinerInfo &DCI,
787 const MipsSubtarget &Subtarget) {
788 // Pattern match INS.
789 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
790 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
791 // => ins $dst, $src, size, pos, $src1
792 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
795 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
796 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
797 ConstantSDNode *CN, *CN1;
799 // See if Op's first operand matches (and $src1 , mask0).
800 if (And0.getOpcode() != ISD::AND)
803 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
804 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
807 // See if Op's second operand matches (and (shl $src, pos), mask1).
808 if (And1.getOpcode() == ISD::AND &&
809 And1.getOperand(0).getOpcode() == ISD::SHL) {
811 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
812 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
815 // The shift masks must have the same position and size.
816 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
819 SDValue Shl = And1.getOperand(0);
821 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
824 unsigned Shamt = CN->getZExtValue();
826 // Return if the shift amount and the first bit position of mask are not the
828 EVT ValTy = N->getValueType(0);
829 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
833 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
834 DAG.getConstant(SMPos0, DL, MVT::i32),
835 DAG.getConstant(SMSize0, DL, MVT::i32),
838 // Pattern match DINS.
839 // $dst = or (and $src, mask0), mask1
840 // where mask0 = ((1 << SMSize0) -1) << SMPos0
841 // => dins $dst, $src, pos, size
842 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
843 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
844 (SMSize0 + SMPos0 <= 32))) {
845 // Check if AND instruction has constant as argument
846 bool isConstCase = And1.getOpcode() != ISD::AND;
847 if (And1.getOpcode() == ISD::AND) {
848 if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
851 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
855 EVT ValTy = N->getOperand(0)->getValueType(0);
859 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
860 SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
863 MipsISD::Ins, DL, N->getValueType(0),
865 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
867 DAG.getConstant(SMPos0, DL, MVT::i32),
868 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
871 And0->getOperand(0));
878 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
879 TargetLowering::DAGCombinerInfo &DCI,
880 const MipsSubtarget &Subtarget) {
881 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
883 if (DCI.isBeforeLegalizeOps())
886 SDValue Add = N->getOperand(1);
888 if (Add.getOpcode() != ISD::ADD)
891 SDValue Lo = Add.getOperand(1);
893 if ((Lo.getOpcode() != MipsISD::Lo) ||
894 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
897 EVT ValTy = N->getValueType(0);
900 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
902 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
905 static SDValue performAssertZextCombine(SDNode *N, SelectionDAG &DAG,
906 TargetLowering::DAGCombinerInfo &DCI,
907 const MipsSubtarget &Subtarget) {
908 SDValue N0 = N->getOperand(0);
909 EVT NarrowerVT = cast<VTSDNode>(N->getOperand(1))->getVT();
911 if (N0.getOpcode() != ISD::TRUNCATE)
914 if (N0.getOperand(0).getOpcode() != ISD::AssertZext)
917 // fold (AssertZext (trunc (AssertZext x))) -> (trunc (AssertZext x))
918 // if the type of the extension of the innermost AssertZext node is
919 // smaller from that of the outermost node, eg:
920 // (AssertZext:i32 (trunc:i32 (AssertZext:i64 X, i32)), i8)
921 // -> (trunc:i32 (AssertZext X, i8))
922 SDValue WiderAssertZext = N0.getOperand(0);
923 EVT WiderVT = cast<VTSDNode>(WiderAssertZext->getOperand(1))->getVT();
925 if (NarrowerVT.bitsLT(WiderVT)) {
926 SDValue NewAssertZext = DAG.getNode(
927 ISD::AssertZext, SDLoc(N), WiderAssertZext.getValueType(),
928 WiderAssertZext.getOperand(0), DAG.getValueType(NarrowerVT));
929 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0),
937 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
938 TargetLowering::DAGCombinerInfo &DCI,
939 const MipsSubtarget &Subtarget) {
940 // Pattern match CINS.
941 // $dst = shl (and $src , imm), pos
942 // => cins $dst, $src, pos, size
944 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
947 SDValue FirstOperand = N->getOperand(0);
948 unsigned FirstOperandOpc = FirstOperand.getOpcode();
949 SDValue SecondOperand = N->getOperand(1);
950 EVT ValTy = N->getValueType(0);
953 uint64_t Pos = 0, SMPos, SMSize;
957 // The second operand of the shift must be an immediate.
958 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
961 Pos = CN->getZExtValue();
963 if (Pos >= ValTy.getSizeInBits())
966 if (FirstOperandOpc != ISD::AND)
969 // AND's second operand must be a shifted mask.
970 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
971 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
974 // Return if the shifted mask does not start at bit 0 or the sum of its size
975 // and Pos exceeds the word's size.
976 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
979 NewOperand = FirstOperand.getOperand(0);
980 // SMSize is 'location' (position) in this case, not size.
983 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
984 DAG.getConstant(Pos, DL, MVT::i32),
985 DAG.getConstant(SMSize, DL, MVT::i32));
988 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
990 SelectionDAG &DAG = DCI.DAG;
991 unsigned Opc = N->getOpcode();
997 return performDivRemCombine(N, DAG, DCI, Subtarget);
999 return performSELECTCombine(N, DAG, DCI, Subtarget);
1000 case MipsISD::CMovFP_F:
1001 case MipsISD::CMovFP_T:
1002 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1004 return performANDCombine(N, DAG, DCI, Subtarget);
1006 return performORCombine(N, DAG, DCI, Subtarget);
1008 return performADDCombine(N, DAG, DCI, Subtarget);
1009 case ISD::AssertZext:
1010 return performAssertZextCombine(N, DAG, DCI, Subtarget);
1012 return performSHLCombine(N, DAG, DCI, Subtarget);
1018 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1019 return Subtarget.hasMips32();
1022 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1023 return Subtarget.hasMips32();
1027 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1028 SmallVectorImpl<SDValue> &Results,
1029 SelectionDAG &DAG) const {
1030 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1032 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1033 Results.push_back(Res.getValue(I));
1037 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1038 SmallVectorImpl<SDValue> &Results,
1039 SelectionDAG &DAG) const {
1040 return LowerOperationWrapper(N, Results, DAG);
1043 SDValue MipsTargetLowering::
1044 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1046 switch (Op.getOpcode())
1048 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1049 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1050 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1051 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1052 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1053 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1054 case ISD::SELECT: return lowerSELECT(Op, DAG);
1055 case ISD::SETCC: return lowerSETCC(Op, DAG);
1056 case ISD::VASTART: return lowerVASTART(Op, DAG);
1057 case ISD::VAARG: return lowerVAARG(Op, DAG);
1058 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1059 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1060 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1061 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1062 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1063 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1064 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1065 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1066 case ISD::LOAD: return lowerLOAD(Op, DAG);
1067 case ISD::STORE: return lowerSTORE(Op, DAG);
1068 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1069 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1074 //===----------------------------------------------------------------------===//
1075 // Lower helper functions
1076 //===----------------------------------------------------------------------===//
1078 // addLiveIn - This helper function adds the specified physical register to the
1079 // MachineFunction as a live in value. It also creates a corresponding
1080 // virtual register for it.
1082 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1084 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1085 MF.getRegInfo().addLiveIn(PReg, VReg);
1089 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1090 MachineBasicBlock &MBB,
1091 const TargetInstrInfo &TII,
1092 bool Is64Bit, bool IsMicroMips) {
1096 // Insert instruction "teq $divisor_reg, $zero, 7".
1097 MachineBasicBlock::iterator I(MI);
1098 MachineInstrBuilder MIB;
1099 MachineOperand &Divisor = MI.getOperand(2);
1100 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1101 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1102 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1106 // Use the 32-bit sub-register if this is a 64-bit division.
1108 MIB->getOperand(0).setSubReg(Mips::sub_32);
1110 // Clear Divisor's kill flag.
1111 Divisor.setIsKill(false);
1113 // We would normally delete the original instruction here but in this case
1114 // we only needed to inject an additional instruction rather than replace it.
1120 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1121 MachineBasicBlock *BB) const {
1122 switch (MI.getOpcode()) {
1124 llvm_unreachable("Unexpected instr type to insert");
1125 case Mips::ATOMIC_LOAD_ADD_I8:
1126 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1127 case Mips::ATOMIC_LOAD_ADD_I16:
1128 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1129 case Mips::ATOMIC_LOAD_ADD_I32:
1130 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
1131 case Mips::ATOMIC_LOAD_ADD_I64:
1132 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
1134 case Mips::ATOMIC_LOAD_AND_I8:
1135 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1136 case Mips::ATOMIC_LOAD_AND_I16:
1137 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1138 case Mips::ATOMIC_LOAD_AND_I32:
1139 return emitAtomicBinary(MI, BB, 4, Mips::AND);
1140 case Mips::ATOMIC_LOAD_AND_I64:
1141 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
1143 case Mips::ATOMIC_LOAD_OR_I8:
1144 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1145 case Mips::ATOMIC_LOAD_OR_I16:
1146 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1147 case Mips::ATOMIC_LOAD_OR_I32:
1148 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1149 case Mips::ATOMIC_LOAD_OR_I64:
1150 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1152 case Mips::ATOMIC_LOAD_XOR_I8:
1153 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1154 case Mips::ATOMIC_LOAD_XOR_I16:
1155 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1156 case Mips::ATOMIC_LOAD_XOR_I32:
1157 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1158 case Mips::ATOMIC_LOAD_XOR_I64:
1159 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1161 case Mips::ATOMIC_LOAD_NAND_I8:
1162 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1163 case Mips::ATOMIC_LOAD_NAND_I16:
1164 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1165 case Mips::ATOMIC_LOAD_NAND_I32:
1166 return emitAtomicBinary(MI, BB, 4, 0, true);
1167 case Mips::ATOMIC_LOAD_NAND_I64:
1168 return emitAtomicBinary(MI, BB, 8, 0, true);
1170 case Mips::ATOMIC_LOAD_SUB_I8:
1171 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1172 case Mips::ATOMIC_LOAD_SUB_I16:
1173 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1174 case Mips::ATOMIC_LOAD_SUB_I32:
1175 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1176 case Mips::ATOMIC_LOAD_SUB_I64:
1177 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1179 case Mips::ATOMIC_SWAP_I8:
1180 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1181 case Mips::ATOMIC_SWAP_I16:
1182 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1183 case Mips::ATOMIC_SWAP_I32:
1184 return emitAtomicBinary(MI, BB, 4, 0);
1185 case Mips::ATOMIC_SWAP_I64:
1186 return emitAtomicBinary(MI, BB, 8, 0);
1188 case Mips::ATOMIC_CMP_SWAP_I8:
1189 return emitAtomicCmpSwapPartword(MI, BB, 1);
1190 case Mips::ATOMIC_CMP_SWAP_I16:
1191 return emitAtomicCmpSwapPartword(MI, BB, 2);
1192 case Mips::ATOMIC_CMP_SWAP_I32:
1193 return emitAtomicCmpSwap(MI, BB, 4);
1194 case Mips::ATOMIC_CMP_SWAP_I64:
1195 return emitAtomicCmpSwap(MI, BB, 8);
1196 case Mips::PseudoSDIV:
1197 case Mips::PseudoUDIV:
1202 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1204 case Mips::SDIV_MM_Pseudo:
1205 case Mips::UDIV_MM_Pseudo:
1208 case Mips::DIV_MMR6:
1209 case Mips::DIVU_MMR6:
1210 case Mips::MOD_MMR6:
1211 case Mips::MODU_MMR6:
1212 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1213 case Mips::PseudoDSDIV:
1214 case Mips::PseudoDUDIV:
1219 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1220 case Mips::DDIV_MM64R6:
1221 case Mips::DDIVU_MM64R6:
1222 case Mips::DMOD_MM64R6:
1223 case Mips::DMODU_MM64R6:
1224 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, true);
1226 case Mips::SEL_D_MMR6:
1227 return emitSEL_D(MI, BB);
1229 case Mips::PseudoSELECT_I:
1230 case Mips::PseudoSELECT_I64:
1231 case Mips::PseudoSELECT_S:
1232 case Mips::PseudoSELECT_D32:
1233 case Mips::PseudoSELECT_D64:
1234 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1235 case Mips::PseudoSELECTFP_F_I:
1236 case Mips::PseudoSELECTFP_F_I64:
1237 case Mips::PseudoSELECTFP_F_S:
1238 case Mips::PseudoSELECTFP_F_D32:
1239 case Mips::PseudoSELECTFP_F_D64:
1240 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1241 case Mips::PseudoSELECTFP_T_I:
1242 case Mips::PseudoSELECTFP_T_I64:
1243 case Mips::PseudoSELECTFP_T_S:
1244 case Mips::PseudoSELECTFP_T_D32:
1245 case Mips::PseudoSELECTFP_T_D64:
1246 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1250 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1251 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1252 MachineBasicBlock *MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1253 MachineBasicBlock *BB,
1257 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1259 MachineFunction *MF = BB->getParent();
1260 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1261 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1262 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1263 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1264 DebugLoc DL = MI.getDebugLoc();
1265 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1272 LL = Subtarget.hasMips32r6()
1273 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1274 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1275 SC = Subtarget.hasMips32r6()
1276 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1277 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1285 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1286 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1289 ZERO = Mips::ZERO_64;
1293 unsigned OldVal = MI.getOperand(0).getReg();
1294 unsigned Ptr = MI.getOperand(1).getReg();
1295 unsigned Incr = MI.getOperand(2).getReg();
1297 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1298 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1299 unsigned Success = RegInfo.createVirtualRegister(RC);
1301 // insert new blocks after the current block
1302 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1303 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1304 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1305 MachineFunction::iterator It = ++BB->getIterator();
1306 MF->insert(It, loopMBB);
1307 MF->insert(It, exitMBB);
1309 // Transfer the remainder of BB and its successor edges to exitMBB.
1310 exitMBB->splice(exitMBB->begin(), BB,
1311 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1312 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1316 // fallthrough --> loopMBB
1317 BB->addSuccessor(loopMBB);
1318 loopMBB->addSuccessor(loopMBB);
1319 loopMBB->addSuccessor(exitMBB);
1322 // ll oldval, 0(ptr)
1323 // <binop> storeval, oldval, incr
1324 // sc success, storeval, 0(ptr)
1325 // beq success, $0, loopMBB
1327 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1329 // and andres, oldval, incr
1330 // nor storeval, $0, andres
1331 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1332 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1333 } else if (BinOpcode) {
1334 // <binop> storeval, oldval, incr
1335 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1339 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1340 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1342 MI.eraseFromParent(); // The instruction is gone now.
1347 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1348 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1349 unsigned SrcReg) const {
1350 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1351 const DebugLoc &DL = MI.getDebugLoc();
1353 if (Subtarget.hasMips32r2() && Size == 1) {
1354 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1358 if (Subtarget.hasMips32r2() && Size == 2) {
1359 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1363 MachineFunction *MF = BB->getParent();
1364 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1365 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1366 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1369 int64_t ShiftImm = 32 - (Size * 8);
1371 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1372 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1377 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1378 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1380 assert((Size == 1 || Size == 2) &&
1381 "Unsupported size for EmitAtomicBinaryPartial.");
1383 MachineFunction *MF = BB->getParent();
1384 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1385 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1386 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1387 const TargetRegisterClass *RCp =
1388 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1389 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1390 DebugLoc DL = MI.getDebugLoc();
1392 unsigned Dest = MI.getOperand(0).getReg();
1393 unsigned Ptr = MI.getOperand(1).getReg();
1394 unsigned Incr = MI.getOperand(2).getReg();
1396 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1397 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1398 unsigned Mask = RegInfo.createVirtualRegister(RC);
1399 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1400 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1401 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1402 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1403 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1404 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1405 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1406 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1407 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1408 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1409 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1410 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1411 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1412 unsigned Success = RegInfo.createVirtualRegister(RC);
1419 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1420 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1421 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1422 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1425 // insert new blocks after the current block
1426 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1427 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1428 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1429 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1430 MachineFunction::iterator It = ++BB->getIterator();
1431 MF->insert(It, loopMBB);
1432 MF->insert(It, sinkMBB);
1433 MF->insert(It, exitMBB);
1435 // Transfer the remainder of BB and its successor edges to exitMBB.
1436 exitMBB->splice(exitMBB->begin(), BB,
1437 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1438 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1440 BB->addSuccessor(loopMBB);
1441 loopMBB->addSuccessor(loopMBB);
1442 loopMBB->addSuccessor(sinkMBB);
1443 sinkMBB->addSuccessor(exitMBB);
1446 // addiu masklsb2,$0,-4 # 0xfffffffc
1447 // and alignedaddr,ptr,masklsb2
1448 // andi ptrlsb2,ptr,3
1449 // sll shiftamt,ptrlsb2,3
1450 // ori maskupper,$0,255 # 0xff
1451 // sll mask,maskupper,shiftamt
1452 // nor mask2,$0,mask
1453 // sll incr2,incr,shiftamt
1455 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1456 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1457 .addReg(ABI.GetNullPtr()).addImm(-4);
1458 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1459 .addReg(Ptr).addReg(MaskLSB2);
1460 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1461 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1462 if (Subtarget.isLittle()) {
1463 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1465 unsigned Off = RegInfo.createVirtualRegister(RC);
1466 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1467 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1468 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1470 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1471 .addReg(Mips::ZERO).addImm(MaskImm);
1472 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1473 .addReg(MaskUpper).addReg(ShiftAmt);
1474 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1475 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1477 // atomic.load.binop
1479 // ll oldval,0(alignedaddr)
1480 // binop binopres,oldval,incr2
1481 // and newval,binopres,mask
1482 // and maskedoldval0,oldval,mask2
1483 // or storeval,maskedoldval0,newval
1484 // sc success,storeval,0(alignedaddr)
1485 // beq success,$0,loopMBB
1489 // ll oldval,0(alignedaddr)
1490 // and newval,incr2,mask
1491 // and maskedoldval0,oldval,mask2
1492 // or storeval,maskedoldval0,newval
1493 // sc success,storeval,0(alignedaddr)
1494 // beq success,$0,loopMBB
1497 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1499 // and andres, oldval, incr2
1500 // nor binopres, $0, andres
1501 // and newval, binopres, mask
1502 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1503 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1504 .addReg(Mips::ZERO).addReg(AndRes);
1505 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1506 } else if (BinOpcode) {
1507 // <binop> binopres, oldval, incr2
1508 // and newval, binopres, mask
1509 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1510 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1511 } else { // atomic.swap
1512 // and newval, incr2, mask
1513 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1516 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1517 .addReg(OldVal).addReg(Mask2);
1518 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1519 .addReg(MaskedOldVal0).addReg(NewVal);
1520 BuildMI(BB, DL, TII->get(SC), Success)
1521 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1522 BuildMI(BB, DL, TII->get(Mips::BEQ))
1523 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1526 // and maskedoldval1,oldval,mask
1527 // srl srlres,maskedoldval1,shiftamt
1528 // sign_extend dest,srlres
1531 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1532 .addReg(OldVal).addReg(Mask);
1533 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1534 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1535 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1537 MI.eraseFromParent(); // The instruction is gone now.
1542 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1543 MachineBasicBlock *BB,
1544 unsigned Size) const {
1545 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1547 MachineFunction *MF = BB->getParent();
1548 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1549 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1550 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1551 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1552 DebugLoc DL = MI.getDebugLoc();
1553 unsigned LL, SC, ZERO, BNE, BEQ;
1560 LL = Subtarget.hasMips32r6()
1561 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1562 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1563 SC = Subtarget.hasMips32r6()
1564 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1565 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1572 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1573 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1574 ZERO = Mips::ZERO_64;
1579 unsigned Dest = MI.getOperand(0).getReg();
1580 unsigned Ptr = MI.getOperand(1).getReg();
1581 unsigned OldVal = MI.getOperand(2).getReg();
1582 unsigned NewVal = MI.getOperand(3).getReg();
1584 unsigned Success = RegInfo.createVirtualRegister(RC);
1586 // insert new blocks after the current block
1587 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1588 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1589 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1590 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1591 MachineFunction::iterator It = ++BB->getIterator();
1592 MF->insert(It, loop1MBB);
1593 MF->insert(It, loop2MBB);
1594 MF->insert(It, exitMBB);
1596 // Transfer the remainder of BB and its successor edges to exitMBB.
1597 exitMBB->splice(exitMBB->begin(), BB,
1598 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1599 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1603 // fallthrough --> loop1MBB
1604 BB->addSuccessor(loop1MBB);
1605 loop1MBB->addSuccessor(exitMBB);
1606 loop1MBB->addSuccessor(loop2MBB);
1607 loop2MBB->addSuccessor(loop1MBB);
1608 loop2MBB->addSuccessor(exitMBB);
1612 // bne dest, oldval, exitMBB
1614 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1615 BuildMI(BB, DL, TII->get(BNE))
1616 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1619 // sc success, newval, 0(ptr)
1620 // beq success, $0, loop1MBB
1622 BuildMI(BB, DL, TII->get(SC), Success)
1623 .addReg(NewVal).addReg(Ptr).addImm(0);
1624 BuildMI(BB, DL, TII->get(BEQ))
1625 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1627 MI.eraseFromParent(); // The instruction is gone now.
1632 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1633 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1634 assert((Size == 1 || Size == 2) &&
1635 "Unsupported size for EmitAtomicCmpSwapPartial.");
1637 MachineFunction *MF = BB->getParent();
1638 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1639 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1640 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1641 const TargetRegisterClass *RCp =
1642 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1643 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1644 DebugLoc DL = MI.getDebugLoc();
1646 unsigned Dest = MI.getOperand(0).getReg();
1647 unsigned Ptr = MI.getOperand(1).getReg();
1648 unsigned CmpVal = MI.getOperand(2).getReg();
1649 unsigned NewVal = MI.getOperand(3).getReg();
1651 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1652 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1653 unsigned Mask = RegInfo.createVirtualRegister(RC);
1654 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1655 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1656 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1657 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1658 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1659 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1660 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1661 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1662 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1663 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1664 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1665 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1666 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1667 unsigned Success = RegInfo.createVirtualRegister(RC);
1674 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1675 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1676 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1677 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1680 // insert new blocks after the current block
1681 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1682 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1683 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1684 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1685 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1686 MachineFunction::iterator It = ++BB->getIterator();
1687 MF->insert(It, loop1MBB);
1688 MF->insert(It, loop2MBB);
1689 MF->insert(It, sinkMBB);
1690 MF->insert(It, exitMBB);
1692 // Transfer the remainder of BB and its successor edges to exitMBB.
1693 exitMBB->splice(exitMBB->begin(), BB,
1694 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1695 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1697 BB->addSuccessor(loop1MBB);
1698 loop1MBB->addSuccessor(sinkMBB);
1699 loop1MBB->addSuccessor(loop2MBB);
1700 loop2MBB->addSuccessor(loop1MBB);
1701 loop2MBB->addSuccessor(sinkMBB);
1702 sinkMBB->addSuccessor(exitMBB);
1704 // FIXME: computation of newval2 can be moved to loop2MBB.
1706 // addiu masklsb2,$0,-4 # 0xfffffffc
1707 // and alignedaddr,ptr,masklsb2
1708 // andi ptrlsb2,ptr,3
1709 // xori ptrlsb2,ptrlsb2,3 # Only for BE
1710 // sll shiftamt,ptrlsb2,3
1711 // ori maskupper,$0,255 # 0xff
1712 // sll mask,maskupper,shiftamt
1713 // nor mask2,$0,mask
1714 // andi maskedcmpval,cmpval,255
1715 // sll shiftedcmpval,maskedcmpval,shiftamt
1716 // andi maskednewval,newval,255
1717 // sll shiftednewval,maskednewval,shiftamt
1718 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1719 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1720 .addReg(ABI.GetNullPtr()).addImm(-4);
1721 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1722 .addReg(Ptr).addReg(MaskLSB2);
1723 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1724 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1725 if (Subtarget.isLittle()) {
1726 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1728 unsigned Off = RegInfo.createVirtualRegister(RC);
1729 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1730 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1731 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1733 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1734 .addReg(Mips::ZERO).addImm(MaskImm);
1735 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1736 .addReg(MaskUpper).addReg(ShiftAmt);
1737 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1738 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1739 .addReg(CmpVal).addImm(MaskImm);
1740 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1741 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1742 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1743 .addReg(NewVal).addImm(MaskImm);
1744 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1745 .addReg(MaskedNewVal).addReg(ShiftAmt);
1748 // ll oldval,0(alginedaddr)
1749 // and maskedoldval0,oldval,mask
1750 // bne maskedoldval0,shiftedcmpval,sinkMBB
1752 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1753 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1754 .addReg(OldVal).addReg(Mask);
1755 BuildMI(BB, DL, TII->get(Mips::BNE))
1756 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1759 // and maskedoldval1,oldval,mask2
1760 // or storeval,maskedoldval1,shiftednewval
1761 // sc success,storeval,0(alignedaddr)
1762 // beq success,$0,loop1MBB
1764 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1765 .addReg(OldVal).addReg(Mask2);
1766 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1767 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1768 BuildMI(BB, DL, TII->get(SC), Success)
1769 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1770 BuildMI(BB, DL, TII->get(Mips::BEQ))
1771 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1774 // srl srlres,maskedoldval0,shiftamt
1775 // sign_extend dest,srlres
1778 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1779 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1780 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1782 MI.eraseFromParent(); // The instruction is gone now.
1787 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr &MI,
1788 MachineBasicBlock *BB) const {
1789 MachineFunction *MF = BB->getParent();
1790 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1791 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1792 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1793 DebugLoc DL = MI.getDebugLoc();
1794 MachineBasicBlock::iterator II(MI);
1796 unsigned Fc = MI.getOperand(1).getReg();
1797 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1799 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1801 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1804 .addImm(Mips::sub_lo);
1806 // We don't erase the original instruction, we just replace the condition
1807 // register with the 64-bit super-register.
1808 MI.getOperand(1).setReg(Fc2);
1813 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1814 // The first operand is the chain, the second is the condition, the third is
1815 // the block to branch to if the condition is true.
1816 SDValue Chain = Op.getOperand(0);
1817 SDValue Dest = Op.getOperand(2);
1820 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1821 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1823 // Return if flag is not set by a floating point comparison.
1824 if (CondRes.getOpcode() != MipsISD::FPCmp)
1827 SDValue CCNode = CondRes.getOperand(2);
1829 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1830 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1831 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1832 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1833 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1834 FCC0, Dest, CondRes);
1837 SDValue MipsTargetLowering::
1838 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1840 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1841 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1843 // Return if flag is not set by a floating point comparison.
1844 if (Cond.getOpcode() != MipsISD::FPCmp)
1847 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1851 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1852 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1853 SDValue Cond = createFPCmp(DAG, Op);
1855 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1856 "Floating point operand expected.");
1859 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1860 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1862 return createCMovFP(DAG, Cond, True, False, DL);
1865 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1866 SelectionDAG &DAG) const {
1867 EVT Ty = Op.getValueType();
1868 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1869 const GlobalValue *GV = N->getGlobal();
1871 if (!isPositionIndependent()) {
1872 const MipsTargetObjectFile *TLOF =
1873 static_cast<const MipsTargetObjectFile *>(
1874 getTargetMachine().getObjFileLowering());
1875 const GlobalObject *GO = GV->getBaseObject();
1876 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
1877 // %gp_rel relocation
1878 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1880 // %hi/%lo relocation
1881 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
1882 // %highest/%higher/%hi/%lo relocation
1883 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
1886 // Every other architecture would use shouldAssumeDSOLocal in here, but
1888 // * In PIC code mips requires got loads even for local statics!
1889 // * To save on got entries, for local statics the got entry contains the
1890 // page and an additional add instruction takes care of the low bits.
1891 // * It is legal to access a hidden symbol with a non hidden undefined,
1892 // so one cannot guarantee that all access to a hidden symbol will know
1894 // * Mips linkers don't support creating a page and a full got entry for
1896 // * Given all that, we have to use a full got entry for hidden symbols :-(
1897 if (GV->hasLocalLinkage())
1898 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1901 return getAddrGlobalLargeGOT(
1902 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
1904 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1906 return getAddrGlobal(
1907 N, SDLoc(N), Ty, DAG,
1908 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
1909 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1912 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1913 SelectionDAG &DAG) const {
1914 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1915 EVT Ty = Op.getValueType();
1917 if (!isPositionIndependent())
1918 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
1919 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
1921 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1924 SDValue MipsTargetLowering::
1925 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1927 // If the relocation model is PIC, use the General Dynamic TLS Model or
1928 // Local Dynamic TLS model, otherwise use the Initial Exec or
1929 // Local Exec TLS Model.
1931 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1932 if (DAG.getTarget().Options.EmulatedTLS)
1933 return LowerToTLSEmulatedModel(GA, DAG);
1936 const GlobalValue *GV = GA->getGlobal();
1937 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1939 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1941 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1942 // General Dynamic and Local Dynamic TLS Model.
1943 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1946 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1947 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1948 getGlobalReg(DAG, PtrVT), TGA);
1949 unsigned PtrSize = PtrVT.getSizeInBits();
1950 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1952 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1956 Entry.Node = Argument;
1958 Args.push_back(Entry);
1960 TargetLowering::CallLoweringInfo CLI(DAG);
1962 .setChain(DAG.getEntryNode())
1963 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
1964 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1966 SDValue Ret = CallResult.first;
1968 if (model != TLSModel::LocalDynamic)
1971 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1972 MipsII::MO_DTPREL_HI);
1973 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1974 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1975 MipsII::MO_DTPREL_LO);
1976 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1977 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1978 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1982 if (model == TLSModel::InitialExec) {
1983 // Initial Exec TLS Model
1984 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1985 MipsII::MO_GOTTPREL);
1986 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1989 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
1991 // Local Exec TLS Model
1992 assert(model == TLSModel::LocalExec);
1993 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1994 MipsII::MO_TPREL_HI);
1995 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1996 MipsII::MO_TPREL_LO);
1997 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1998 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1999 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2002 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2003 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2006 SDValue MipsTargetLowering::
2007 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2009 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2010 EVT Ty = Op.getValueType();
2012 if (!isPositionIndependent())
2013 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2014 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2016 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2019 SDValue MipsTargetLowering::
2020 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2022 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2023 EVT Ty = Op.getValueType();
2025 if (!isPositionIndependent()) {
2026 const MipsTargetObjectFile *TLOF =
2027 static_cast<const MipsTargetObjectFile *>(
2028 getTargetMachine().getObjFileLowering());
2030 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2031 getTargetMachine()))
2032 // %gp_rel relocation
2033 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2035 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2036 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2039 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2042 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2043 MachineFunction &MF = DAG.getMachineFunction();
2044 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2047 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2048 getPointerTy(MF.getDataLayout()));
2050 // vastart just stores the address of the VarArgsFrameIndex slot into the
2051 // memory location argument.
2052 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2053 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2054 MachinePointerInfo(SV));
2057 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2058 SDNode *Node = Op.getNode();
2059 EVT VT = Node->getValueType(0);
2060 SDValue Chain = Node->getOperand(0);
2061 SDValue VAListPtr = Node->getOperand(1);
2062 unsigned Align = Node->getConstantOperandVal(3);
2063 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2065 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2067 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2068 VAListPtr, MachinePointerInfo(SV));
2069 SDValue VAList = VAListLoad;
2071 // Re-align the pointer if necessary.
2072 // It should only ever be necessary for 64-bit types on O32 since the minimum
2073 // argument alignment is the same as the maximum type alignment for N32/N64.
2075 // FIXME: We currently align too often. The code generator doesn't notice
2076 // when the pointer is still aligned from the last va_arg (or pair of
2077 // va_args for the i64 on O32 case).
2078 if (Align > getMinStackArgumentAlignment()) {
2079 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2081 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2082 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
2084 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2085 DAG.getConstant(-(int64_t)Align, DL,
2086 VAList.getValueType()));
2089 // Increment the pointer, VAList, to the next vaarg.
2090 auto &TD = DAG.getDataLayout();
2091 unsigned ArgSizeInBytes =
2092 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2094 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2095 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2096 DL, VAList.getValueType()));
2097 // Store the incremented VAList to the legalized pointer
2098 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2099 MachinePointerInfo(SV));
2101 // In big-endian mode we must adjust the pointer when the load size is smaller
2102 // than the argument slot size. We must also reduce the known alignment to
2103 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2104 // the correct half of the slot, and reduce the alignment from 8 (slot
2105 // alignment) down to 4 (type alignment).
2106 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2107 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2108 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2109 DAG.getIntPtrConstant(Adjustment, DL));
2111 // Load the actual argument out of the pointer VAList
2112 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2115 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2116 bool HasExtractInsert) {
2117 EVT TyX = Op.getOperand(0).getValueType();
2118 EVT TyY = Op.getOperand(1).getValueType();
2120 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2121 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2124 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2126 SDValue X = (TyX == MVT::f32) ?
2127 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2128 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2130 SDValue Y = (TyY == MVT::f32) ?
2131 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2132 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2135 if (HasExtractInsert) {
2136 // ext E, Y, 31, 1 ; extract bit31 of Y
2137 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2138 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2139 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2142 // srl SrlX, SllX, 1
2144 // sll SllY, SrlX, 31
2145 // or Or, SrlX, SllY
2146 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2147 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2148 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2149 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2150 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2153 if (TyX == MVT::f32)
2154 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2156 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2158 DAG.getConstant(0, DL, MVT::i32));
2159 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2162 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2163 bool HasExtractInsert) {
2164 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2165 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2166 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2168 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2170 // Bitcast to integer nodes.
2171 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2172 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2174 if (HasExtractInsert) {
2175 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2176 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2177 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2178 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2180 if (WidthX > WidthY)
2181 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2182 else if (WidthY > WidthX)
2183 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2185 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2186 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2188 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2191 // (d)sll SllX, X, 1
2192 // (d)srl SrlX, SllX, 1
2193 // (d)srl SrlY, Y, width(Y)-1
2194 // (d)sll SllY, SrlX, width(Y)-1
2195 // or Or, SrlX, SllY
2196 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2197 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2198 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2199 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2201 if (WidthX > WidthY)
2202 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2203 else if (WidthY > WidthX)
2204 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2206 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2207 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2208 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2209 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2213 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2214 if (Subtarget.isGP64bit())
2215 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2217 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2220 SDValue MipsTargetLowering::
2221 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2223 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2224 "Frame address can only be determined for current frame.");
2226 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2227 MFI.setFrameAddressIsTaken(true);
2228 EVT VT = Op.getValueType();
2230 SDValue FrameAddr = DAG.getCopyFromReg(
2231 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2235 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2236 SelectionDAG &DAG) const {
2237 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2241 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2242 "Return address can be determined only for current frame.");
2244 MachineFunction &MF = DAG.getMachineFunction();
2245 MachineFrameInfo &MFI = MF.getFrameInfo();
2246 MVT VT = Op.getSimpleValueType();
2247 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2248 MFI.setReturnAddressIsTaken(true);
2250 // Return RA, which contains the return address. Mark it an implicit live-in.
2251 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2252 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2255 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2256 // generated from __builtin_eh_return (offset, handler)
2257 // The effect of this is to adjust the stack pointer by "offset"
2258 // and then branch to "handler".
2259 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2261 MachineFunction &MF = DAG.getMachineFunction();
2262 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2264 MipsFI->setCallsEhReturn();
2265 SDValue Chain = Op.getOperand(0);
2266 SDValue Offset = Op.getOperand(1);
2267 SDValue Handler = Op.getOperand(2);
2269 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2271 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2272 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2273 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2274 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2275 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2276 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2277 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2278 DAG.getRegister(OffsetReg, Ty),
2279 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2283 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2284 SelectionDAG &DAG) const {
2285 // FIXME: Need pseudo-fence for 'singlethread' fences
2286 // FIXME: Set SType for weaker fences where supported/appropriate.
2289 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2290 DAG.getConstant(SType, DL, MVT::i32));
2293 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2294 SelectionDAG &DAG) const {
2296 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2298 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2299 SDValue Shamt = Op.getOperand(2);
2300 // if shamt < (VT.bits):
2301 // lo = (shl lo, shamt)
2302 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2305 // hi = (shl lo, shamt[4:0])
2306 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2307 DAG.getConstant(-1, DL, MVT::i32));
2308 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2309 DAG.getConstant(1, DL, VT));
2310 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2311 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2312 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2313 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2314 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2315 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2316 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2317 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2318 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2320 SDValue Ops[2] = {Lo, Hi};
2321 return DAG.getMergeValues(Ops, DL);
2324 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2327 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2328 SDValue Shamt = Op.getOperand(2);
2329 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2331 // if shamt < (VT.bits):
2332 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2334 // hi = (sra hi, shamt)
2336 // hi = (srl hi, shamt)
2339 // lo = (sra hi, shamt[4:0])
2340 // hi = (sra hi, 31)
2342 // lo = (srl hi, shamt[4:0])
2344 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2345 DAG.getConstant(-1, DL, MVT::i32));
2346 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2347 DAG.getConstant(1, DL, VT));
2348 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2349 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2350 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2351 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2353 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2354 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2355 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2356 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2357 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2358 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2359 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2361 SDValue Ops[2] = {Lo, Hi};
2362 return DAG.getMergeValues(Ops, DL);
2365 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2366 SDValue Chain, SDValue Src, unsigned Offset) {
2367 SDValue Ptr = LD->getBasePtr();
2368 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2369 EVT BasePtrVT = Ptr.getValueType();
2371 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2374 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2375 DAG.getConstant(Offset, DL, BasePtrVT));
2377 SDValue Ops[] = { Chain, Ptr, Src };
2378 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2379 LD->getMemOperand());
2382 // Expand an unaligned 32 or 64-bit integer load node.
2383 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2384 LoadSDNode *LD = cast<LoadSDNode>(Op);
2385 EVT MemVT = LD->getMemoryVT();
2387 if (Subtarget.systemSupportsUnalignedAccess())
2390 // Return if load is aligned or if MemVT is neither i32 nor i64.
2391 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2392 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2395 bool IsLittle = Subtarget.isLittle();
2396 EVT VT = Op.getValueType();
2397 ISD::LoadExtType ExtType = LD->getExtensionType();
2398 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2400 assert((VT == MVT::i32) || (VT == MVT::i64));
2403 // (set dst, (i64 (load baseptr)))
2405 // (set tmp, (ldl (add baseptr, 7), undef))
2406 // (set dst, (ldr baseptr, tmp))
2407 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2408 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2410 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2414 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2416 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2420 // (set dst, (i32 (load baseptr))) or
2421 // (set dst, (i64 (sextload baseptr))) or
2422 // (set dst, (i64 (extload baseptr)))
2424 // (set tmp, (lwl (add baseptr, 3), undef))
2425 // (set dst, (lwr baseptr, tmp))
2426 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2427 (ExtType == ISD::EXTLOAD))
2430 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2433 // (set dst, (i64 (zextload baseptr)))
2435 // (set tmp0, (lwl (add baseptr, 3), undef))
2436 // (set tmp1, (lwr baseptr, tmp0))
2437 // (set tmp2, (shl tmp1, 32))
2438 // (set dst, (srl tmp2, 32))
2440 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2441 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2442 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2443 SDValue Ops[] = { SRL, LWR.getValue(1) };
2444 return DAG.getMergeValues(Ops, DL);
2447 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2448 SDValue Chain, unsigned Offset) {
2449 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2450 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2452 SDVTList VTList = DAG.getVTList(MVT::Other);
2455 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2456 DAG.getConstant(Offset, DL, BasePtrVT));
2458 SDValue Ops[] = { Chain, Value, Ptr };
2459 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2460 SD->getMemOperand());
2463 // Expand an unaligned 32 or 64-bit integer store node.
2464 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2466 SDValue Value = SD->getValue(), Chain = SD->getChain();
2467 EVT VT = Value.getValueType();
2470 // (store val, baseptr) or
2471 // (truncstore val, baseptr)
2473 // (swl val, (add baseptr, 3))
2474 // (swr val, baseptr)
2475 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2476 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2478 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2481 assert(VT == MVT::i64);
2484 // (store val, baseptr)
2486 // (sdl val, (add baseptr, 7))
2487 // (sdr val, baseptr)
2488 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2489 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2492 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2493 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2494 SDValue Val = SD->getValue();
2496 if (Val.getOpcode() != ISD::FP_TO_SINT)
2499 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2500 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2502 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2503 SD->getPointerInfo(), SD->getAlignment(),
2504 SD->getMemOperand()->getFlags());
2507 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2508 StoreSDNode *SD = cast<StoreSDNode>(Op);
2509 EVT MemVT = SD->getMemoryVT();
2511 // Lower unaligned integer stores.
2512 if (!Subtarget.systemSupportsUnalignedAccess() &&
2513 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2514 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2515 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2517 return lowerFP_TO_SINT_STORE(SD, DAG);
2520 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2521 SelectionDAG &DAG) const {
2523 // Return a fixed StackObject with offset 0 which points to the old stack
2525 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2526 EVT ValTy = Op->getValueType(0);
2527 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2528 return DAG.getFrameIndex(FI, ValTy);
2531 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2532 SelectionDAG &DAG) const {
2533 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2534 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2536 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2539 //===----------------------------------------------------------------------===//
2540 // Calling Convention Implementation
2541 //===----------------------------------------------------------------------===//
2543 //===----------------------------------------------------------------------===//
2544 // TODO: Implement a generic logic using tblgen that can support this.
2545 // Mips O32 ABI rules:
2547 // i32 - Passed in A0, A1, A2, A3 and stack
2548 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2549 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2550 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2551 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2552 // not used, it must be shadowed. If only A3 is available, shadow it and
2555 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2556 //===----------------------------------------------------------------------===//
2558 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2559 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2560 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2561 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2562 State.getMachineFunction().getSubtarget());
2564 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2565 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2567 // Do not process byval args here.
2568 if (ArgFlags.isByVal())
2571 // Promote i8 and i16
2572 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2573 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2575 if (ArgFlags.isSExt())
2576 LocInfo = CCValAssign::SExtUpper;
2577 else if (ArgFlags.isZExt())
2578 LocInfo = CCValAssign::ZExtUpper;
2580 LocInfo = CCValAssign::AExtUpper;
2584 // Promote i8 and i16
2585 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2587 if (ArgFlags.isSExt())
2588 LocInfo = CCValAssign::SExt;
2589 else if (ArgFlags.isZExt())
2590 LocInfo = CCValAssign::ZExt;
2592 LocInfo = CCValAssign::AExt;
2597 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2598 // is true: function is vararg, argument is 3rd or higher, there is previous
2599 // argument which is not f32 or f64.
2600 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2601 State.getFirstUnallocated(F32Regs) != ValNo;
2602 unsigned OrigAlign = ArgFlags.getOrigAlign();
2603 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2605 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2606 Reg = State.AllocateReg(IntRegs);
2607 // If this is the first part of an i64 arg,
2608 // the allocated register must be either A0 or A2.
2609 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2610 Reg = State.AllocateReg(IntRegs);
2612 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2613 // Allocate int register and shadow next int register. If first
2614 // available register is Mips::A1 or Mips::A3, shadow it too.
2615 Reg = State.AllocateReg(IntRegs);
2616 if (Reg == Mips::A1 || Reg == Mips::A3)
2617 Reg = State.AllocateReg(IntRegs);
2618 State.AllocateReg(IntRegs);
2620 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2621 // we are guaranteed to find an available float register
2622 if (ValVT == MVT::f32) {
2623 Reg = State.AllocateReg(F32Regs);
2624 // Shadow int register
2625 State.AllocateReg(IntRegs);
2627 Reg = State.AllocateReg(F64Regs);
2628 // Shadow int registers
2629 unsigned Reg2 = State.AllocateReg(IntRegs);
2630 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2631 State.AllocateReg(IntRegs);
2632 State.AllocateReg(IntRegs);
2635 llvm_unreachable("Cannot handle this ValVT.");
2638 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2640 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2642 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2647 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2648 MVT LocVT, CCValAssign::LocInfo LocInfo,
2649 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2650 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2652 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2655 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2656 MVT LocVT, CCValAssign::LocInfo LocInfo,
2657 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2658 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2660 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2663 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2664 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2665 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2667 #include "MipsGenCallingConv.inc"
2669 //===----------------------------------------------------------------------===//
2670 // Call Calling Convention Implementation
2671 //===----------------------------------------------------------------------===//
2673 // Return next O32 integer argument register.
2674 static unsigned getNextIntArgReg(unsigned Reg) {
2675 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2676 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2679 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2680 SDValue Chain, SDValue Arg,
2681 const SDLoc &DL, bool IsTailCall,
2682 SelectionDAG &DAG) const {
2685 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2686 DAG.getIntPtrConstant(Offset, DL));
2687 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
2690 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2691 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2692 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2693 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2694 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
2697 void MipsTargetLowering::
2698 getOpndList(SmallVectorImpl<SDValue> &Ops,
2699 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2700 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2701 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2702 SDValue Chain) const {
2703 // Insert node "GP copy globalreg" before call to function.
2705 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2706 // in PIC mode) allow symbols to be resolved via lazy binding.
2707 // The lazy binding stub requires GP to point to the GOT.
2708 // Note that we don't need GP to point to the GOT for indirect calls
2709 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2710 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2711 // used for the function (that is, Mips linker doesn't generate lazy binding
2712 // stub for a function whose address is taken in the program).
2713 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2714 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2715 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2716 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2719 // Build a sequence of copy-to-reg nodes chained together with token
2720 // chain and flag operands which copy the outgoing args into registers.
2721 // The InFlag in necessary since all emitted instructions must be
2725 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2726 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2727 RegsToPass[i].second, InFlag);
2728 InFlag = Chain.getValue(1);
2731 // Add argument registers to the end of the list so that they are
2732 // known live into the call.
2733 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2734 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2735 RegsToPass[i].second.getValueType()));
2737 // Add a register mask operand representing the call-preserved registers.
2738 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2739 const uint32_t *Mask =
2740 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2741 assert(Mask && "Missing call preserved mask for calling convention");
2742 if (Subtarget.inMips16HardFloat()) {
2743 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2744 llvm::StringRef Sym = G->getGlobal()->getName();
2745 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2746 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2747 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2751 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2753 if (InFlag.getNode())
2754 Ops.push_back(InFlag);
2757 /// LowerCall - functions arguments are copied from virtual regs to
2758 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2760 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2761 SmallVectorImpl<SDValue> &InVals) const {
2762 SelectionDAG &DAG = CLI.DAG;
2764 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2765 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2766 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2767 SDValue Chain = CLI.Chain;
2768 SDValue Callee = CLI.Callee;
2769 bool &IsTailCall = CLI.IsTailCall;
2770 CallingConv::ID CallConv = CLI.CallConv;
2771 bool IsVarArg = CLI.IsVarArg;
2773 MachineFunction &MF = DAG.getMachineFunction();
2774 MachineFrameInfo &MFI = MF.getFrameInfo();
2775 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2776 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2777 bool IsPIC = isPositionIndependent();
2779 // Analyze operands of the call, assigning locations to each operand.
2780 SmallVector<CCValAssign, 16> ArgLocs;
2782 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2783 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2785 // Allocate the reserved argument area. It seems strange to do this from the
2786 // caller side but removing it breaks the frame size calculation.
2787 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2789 const ExternalSymbolSDNode *ES =
2790 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
2791 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
2792 ES ? ES->getSymbol() : nullptr);
2794 // Get a count of how many bytes are to be pushed on the stack.
2795 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2797 // Check if it's really possible to do a tail call. Restrict it to functions
2798 // that are part of this compilation unit.
2799 bool InternalLinkage = false;
2801 IsTailCall = isEligibleForTailCallOptimization(
2802 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2803 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2804 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2805 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
2806 G->getGlobal()->hasPrivateLinkage() ||
2807 G->getGlobal()->hasHiddenVisibility() ||
2808 G->getGlobal()->hasProtectedVisibility());
2811 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2812 report_fatal_error("failed to perform tail call elimination on a call "
2813 "site marked musttail");
2818 // Chain is the output chain of the last Load/Store or CopyToReg node.
2819 // ByValChain is the output chain of the last Memcpy node created for copying
2820 // byval arguments to the stack.
2821 unsigned StackAlignment = TFL->getStackAlignment();
2822 NextStackOffset = alignTo(NextStackOffset, StackAlignment);
2823 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2826 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
2829 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
2830 getPointerTy(DAG.getDataLayout()));
2832 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2833 SmallVector<SDValue, 8> MemOpChains;
2835 CCInfo.rewindByValRegsInfo();
2837 // Walk the register/memloc assignments, inserting copies/loads.
2838 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2839 SDValue Arg = OutVals[i];
2840 CCValAssign &VA = ArgLocs[i];
2841 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2842 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2843 bool UseUpperBits = false;
2846 if (Flags.isByVal()) {
2847 unsigned FirstByValReg, LastByValReg;
2848 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2849 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2851 assert(Flags.getByValSize() &&
2852 "ByVal args of size 0 should have been ignored by front-end.");
2853 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2854 assert(!IsTailCall &&
2855 "Do not tail-call optimize if there is a byval argument.");
2856 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2857 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2859 CCInfo.nextInRegsParam();
2863 // Promote the value if needed.
2864 switch (VA.getLocInfo()) {
2866 llvm_unreachable("Unknown loc info!");
2867 case CCValAssign::Full:
2868 if (VA.isRegLoc()) {
2869 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2870 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2871 (ValVT == MVT::i64 && LocVT == MVT::f64))
2872 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2873 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2874 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2875 Arg, DAG.getConstant(0, DL, MVT::i32));
2876 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2877 Arg, DAG.getConstant(1, DL, MVT::i32));
2878 if (!Subtarget.isLittle())
2880 unsigned LocRegLo = VA.getLocReg();
2881 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2882 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2883 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2888 case CCValAssign::BCvt:
2889 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2891 case CCValAssign::SExtUpper:
2892 UseUpperBits = true;
2894 case CCValAssign::SExt:
2895 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2897 case CCValAssign::ZExtUpper:
2898 UseUpperBits = true;
2900 case CCValAssign::ZExt:
2901 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2903 case CCValAssign::AExtUpper:
2904 UseUpperBits = true;
2906 case CCValAssign::AExt:
2907 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2912 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2913 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2915 ISD::SHL, DL, VA.getLocVT(), Arg,
2916 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2919 // Arguments that can be passed on register must be kept at
2920 // RegsToPass vector
2921 if (VA.isRegLoc()) {
2922 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2926 // Register can't get to this point...
2927 assert(VA.isMemLoc());
2929 // emit ISD::STORE whichs stores the
2930 // parameter value to a stack Location
2931 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2932 Chain, Arg, DL, IsTailCall, DAG));
2935 // Transform all store nodes into one single node because all store
2936 // nodes are independent of each other.
2937 if (!MemOpChains.empty())
2938 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2940 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2941 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2942 // node so that legalize doesn't hack it.
2945 EVT Ty = Callee.getValueType();
2946 bool GlobalOrExternal = false, IsCallReloc = false;
2948 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2950 const GlobalValue *Val = G->getGlobal();
2951 InternalLinkage = Val->hasInternalLinkage();
2953 if (InternalLinkage)
2954 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2955 else if (LargeGOT) {
2956 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2957 MipsII::MO_CALL_LO16, Chain,
2958 FuncInfo->callPtrInfo(Val));
2961 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2962 FuncInfo->callPtrInfo(Val));
2966 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
2967 getPointerTy(DAG.getDataLayout()), 0,
2968 MipsII::MO_NO_FLAG);
2969 GlobalOrExternal = true;
2971 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2972 const char *Sym = S->getSymbol();
2974 if (!IsPIC) // static
2975 Callee = DAG.getTargetExternalSymbol(
2976 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
2977 else if (LargeGOT) {
2978 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2979 MipsII::MO_CALL_LO16, Chain,
2980 FuncInfo->callPtrInfo(Sym));
2983 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2984 FuncInfo->callPtrInfo(Sym));
2988 GlobalOrExternal = true;
2991 SmallVector<SDValue, 8> Ops(1, Chain);
2992 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2994 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
2995 IsCallReloc, CLI, Callee, Chain);
2998 MF.getFrameInfo().setHasTailCall();
2999 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3002 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3003 SDValue InFlag = Chain.getValue(1);
3005 // Create the CALLSEQ_END node.
3006 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3007 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3008 InFlag = Chain.getValue(1);
3010 // Handle result values, copying them out of physregs into vregs that we
3012 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3016 /// LowerCallResult - Lower the result values of a call into the
3017 /// appropriate copies out of appropriate physical registers.
3018 SDValue MipsTargetLowering::LowerCallResult(
3019 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3020 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3021 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3022 TargetLowering::CallLoweringInfo &CLI) const {
3023 // Assign locations to each value returned by this call.
3024 SmallVector<CCValAssign, 16> RVLocs;
3025 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3028 const ExternalSymbolSDNode *ES =
3029 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3030 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3031 ES ? ES->getSymbol() : nullptr);
3033 // Copy all of the result registers out of their specified physreg.
3034 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3035 CCValAssign &VA = RVLocs[i];
3036 assert(VA.isRegLoc() && "Can only return in registers!");
3038 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3039 RVLocs[i].getLocVT(), InFlag);
3040 Chain = Val.getValue(1);
3041 InFlag = Val.getValue(2);
3043 if (VA.isUpperBitsInLoc()) {
3044 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3045 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3047 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3049 Shift, DL, VA.getLocVT(), Val,
3050 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3053 switch (VA.getLocInfo()) {
3055 llvm_unreachable("Unknown loc info!");
3056 case CCValAssign::Full:
3058 case CCValAssign::BCvt:
3059 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3061 case CCValAssign::AExt:
3062 case CCValAssign::AExtUpper:
3063 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3065 case CCValAssign::ZExt:
3066 case CCValAssign::ZExtUpper:
3067 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3068 DAG.getValueType(VA.getValVT()));
3069 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3071 case CCValAssign::SExt:
3072 case CCValAssign::SExtUpper:
3073 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3074 DAG.getValueType(VA.getValVT()));
3075 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3079 InVals.push_back(Val);
3085 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3086 EVT ArgVT, const SDLoc &DL,
3087 SelectionDAG &DAG) {
3088 MVT LocVT = VA.getLocVT();
3089 EVT ValVT = VA.getValVT();
3091 // Shift into the upper bits if necessary.
3092 switch (VA.getLocInfo()) {
3095 case CCValAssign::AExtUpper:
3096 case CCValAssign::SExtUpper:
3097 case CCValAssign::ZExtUpper: {
3098 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3099 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3101 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3103 Opcode, DL, VA.getLocVT(), Val,
3104 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3109 // If this is an value smaller than the argument slot size (32-bit for O32,
3110 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3111 // size. Extract the value and insert any appropriate assertions regarding
3112 // sign/zero extension.
3113 switch (VA.getLocInfo()) {
3115 llvm_unreachable("Unknown loc info!");
3116 case CCValAssign::Full:
3118 case CCValAssign::AExtUpper:
3119 case CCValAssign::AExt:
3120 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3122 case CCValAssign::SExtUpper:
3123 case CCValAssign::SExt:
3124 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3125 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3127 case CCValAssign::ZExtUpper:
3128 case CCValAssign::ZExt:
3129 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3130 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3132 case CCValAssign::BCvt:
3133 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3140 //===----------------------------------------------------------------------===//
3141 // Formal Arguments Calling Convention Implementation
3142 //===----------------------------------------------------------------------===//
3143 /// LowerFormalArguments - transform physical registers into virtual registers
3144 /// and generate load operations for arguments places on the stack.
3145 SDValue MipsTargetLowering::LowerFormalArguments(
3146 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3147 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3148 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3149 MachineFunction &MF = DAG.getMachineFunction();
3150 MachineFrameInfo &MFI = MF.getFrameInfo();
3151 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3153 MipsFI->setVarArgsFrameIndex(0);
3155 // Used with vargs to acumulate store chains.
3156 std::vector<SDValue> OutChains;
3158 // Assign locations to all of the incoming arguments.
3159 SmallVector<CCValAssign, 16> ArgLocs;
3160 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3162 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3163 const Function *Func = DAG.getMachineFunction().getFunction();
3164 Function::const_arg_iterator FuncArg = Func->arg_begin();
3166 if (Func->hasFnAttribute("interrupt") && !Func->arg_empty())
3168 "Functions with the interrupt attribute cannot have arguments!");
3170 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3171 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3172 CCInfo.getInRegsParamsCount() > 0);
3174 unsigned CurArgIdx = 0;
3175 CCInfo.rewindByValRegsInfo();
3177 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3178 CCValAssign &VA = ArgLocs[i];
3179 if (Ins[i].isOrigArg()) {
3180 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3181 CurArgIdx = Ins[i].getOrigArgIndex();
3183 EVT ValVT = VA.getValVT();
3184 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3185 bool IsRegLoc = VA.isRegLoc();
3187 if (Flags.isByVal()) {
3188 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3189 unsigned FirstByValReg, LastByValReg;
3190 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3191 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3193 assert(Flags.getByValSize() &&
3194 "ByVal args of size 0 should have been ignored by front-end.");
3195 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3196 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3197 FirstByValReg, LastByValReg, VA, CCInfo);
3198 CCInfo.nextInRegsParam();
3202 // Arguments stored on registers
3204 MVT RegVT = VA.getLocVT();
3205 unsigned ArgReg = VA.getLocReg();
3206 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3208 // Transform the arguments stored on
3209 // physical registers into virtual ones
3210 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3211 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3213 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3215 // Handle floating point arguments passed in integer registers and
3216 // long double arguments passed in floating point registers.
3217 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3218 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3219 (RegVT == MVT::f64 && ValVT == MVT::i64))
3220 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3221 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3222 ValVT == MVT::f64) {
3223 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3224 getNextIntArgReg(ArgReg), RC);
3225 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3226 if (!Subtarget.isLittle())
3227 std::swap(ArgValue, ArgValue2);
3228 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3229 ArgValue, ArgValue2);
3232 InVals.push_back(ArgValue);
3233 } else { // VA.isRegLoc()
3234 MVT LocVT = VA.getLocVT();
3237 // We ought to be able to use LocVT directly but O32 sets it to i32
3238 // when allocating floating point values to integer registers.
3239 // This shouldn't influence how we load the value into registers unless
3240 // we are targeting softfloat.
3241 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3242 LocVT = VA.getValVT();
3246 assert(VA.isMemLoc());
3248 // The stack pointer offset is relative to the caller stack frame.
3249 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3250 VA.getLocMemOffset(), true);
3252 // Create load nodes to retrieve arguments from the stack
3253 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3254 SDValue ArgValue = DAG.getLoad(
3255 LocVT, DL, Chain, FIN,
3256 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3257 OutChains.push_back(ArgValue.getValue(1));
3259 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3261 InVals.push_back(ArgValue);
3265 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3266 // The mips ABIs for returning structs by value requires that we copy
3267 // the sret argument into $v0 for the return. Save the argument into
3268 // a virtual register so that we can access it from the return points.
3269 if (Ins[i].Flags.isSRet()) {
3270 unsigned Reg = MipsFI->getSRetReturnReg();
3272 Reg = MF.getRegInfo().createVirtualRegister(
3273 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3274 MipsFI->setSRetReturnReg(Reg);
3276 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3277 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3283 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3285 // All stores are grouped in one node to allow the matching between
3286 // the size of Ins and InVals. This only happens when on varg functions
3287 if (!OutChains.empty()) {
3288 OutChains.push_back(Chain);
3289 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3295 //===----------------------------------------------------------------------===//
3296 // Return Value Calling Convention Implementation
3297 //===----------------------------------------------------------------------===//
3300 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3301 MachineFunction &MF, bool IsVarArg,
3302 const SmallVectorImpl<ISD::OutputArg> &Outs,
3303 LLVMContext &Context) const {
3304 SmallVector<CCValAssign, 16> RVLocs;
3305 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3306 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3310 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3311 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3312 if (Type == MVT::i32)
3319 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3321 SelectionDAG &DAG) const {
3323 MachineFunction &MF = DAG.getMachineFunction();
3324 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3328 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3332 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3334 const SmallVectorImpl<ISD::OutputArg> &Outs,
3335 const SmallVectorImpl<SDValue> &OutVals,
3336 const SDLoc &DL, SelectionDAG &DAG) const {
3337 // CCValAssign - represent the assignment of
3338 // the return value to a location
3339 SmallVector<CCValAssign, 16> RVLocs;
3340 MachineFunction &MF = DAG.getMachineFunction();
3342 // CCState - Info about the registers and stack slot.
3343 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3345 // Analyze return values.
3346 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3349 SmallVector<SDValue, 4> RetOps(1, Chain);
3351 // Copy the result values into the output registers.
3352 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3353 SDValue Val = OutVals[i];
3354 CCValAssign &VA = RVLocs[i];
3355 assert(VA.isRegLoc() && "Can only return in registers!");
3356 bool UseUpperBits = false;
3358 switch (VA.getLocInfo()) {
3360 llvm_unreachable("Unknown loc info!");
3361 case CCValAssign::Full:
3363 case CCValAssign::BCvt:
3364 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3366 case CCValAssign::AExtUpper:
3367 UseUpperBits = true;
3369 case CCValAssign::AExt:
3370 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3372 case CCValAssign::ZExtUpper:
3373 UseUpperBits = true;
3375 case CCValAssign::ZExt:
3376 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3378 case CCValAssign::SExtUpper:
3379 UseUpperBits = true;
3381 case CCValAssign::SExt:
3382 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3387 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3388 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3390 ISD::SHL, DL, VA.getLocVT(), Val,
3391 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3394 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3396 // Guarantee that all emitted copies are stuck together with flags.
3397 Flag = Chain.getValue(1);
3398 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3401 // The mips ABIs for returning structs by value requires that we copy
3402 // the sret argument into $v0 for the return. We saved the argument into
3403 // a virtual register in the entry block, so now we copy the value out
3405 if (MF.getFunction()->hasStructRetAttr()) {
3406 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3407 unsigned Reg = MipsFI->getSRetReturnReg();
3410 llvm_unreachable("sret virtual register not created in the entry block");
3412 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3413 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3415 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3416 Flag = Chain.getValue(1);
3417 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3420 RetOps[0] = Chain; // Update chain.
3422 // Add the flag if we have it.
3424 RetOps.push_back(Flag);
3426 // ISRs must use "eret".
3427 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
3428 return LowerInterruptReturn(RetOps, DL, DAG);
3430 // Standard return on Mips is a "jr $ra"
3431 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3434 //===----------------------------------------------------------------------===//
3435 // Mips Inline Assembly Support
3436 //===----------------------------------------------------------------------===//
3438 /// getConstraintType - Given a constraint letter, return the type of
3439 /// constraint it is for this target.
3440 MipsTargetLowering::ConstraintType
3441 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3442 // Mips specific constraints
3443 // GCC config/mips/constraints.md
3445 // 'd' : An address register. Equivalent to r
3446 // unless generating MIPS16 code.
3447 // 'y' : Equivalent to r; retained for
3448 // backwards compatibility.
3449 // 'c' : A register suitable for use in an indirect
3450 // jump. This will always be $25 for -mabicalls.
3451 // 'l' : The lo register. 1 word storage.
3452 // 'x' : The hilo register pair. Double word storage.
3453 if (Constraint.size() == 1) {
3454 switch (Constraint[0]) {
3462 return C_RegisterClass;
3468 if (Constraint == "ZC")
3471 return TargetLowering::getConstraintType(Constraint);
3474 /// Examine constraint type and operand type and determine a weight value.
3475 /// This object must already have been set up with the operand type
3476 /// and the current alternative constraint selected.
3477 TargetLowering::ConstraintWeight
3478 MipsTargetLowering::getSingleConstraintMatchWeight(
3479 AsmOperandInfo &info, const char *constraint) const {
3480 ConstraintWeight weight = CW_Invalid;
3481 Value *CallOperandVal = info.CallOperandVal;
3482 // If we don't have a value, we can't do a match,
3483 // but allow it at the lowest weight.
3484 if (!CallOperandVal)
3486 Type *type = CallOperandVal->getType();
3487 // Look at the constraint type.
3488 switch (*constraint) {
3490 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3494 if (type->isIntegerTy())
3495 weight = CW_Register;
3497 case 'f': // FPU or MSA register
3498 if (Subtarget.hasMSA() && type->isVectorTy() &&
3499 cast<VectorType>(type)->getBitWidth() == 128)
3500 weight = CW_Register;
3501 else if (type->isFloatTy())
3502 weight = CW_Register;
3504 case 'c': // $25 for indirect jumps
3505 case 'l': // lo register
3506 case 'x': // hilo register pair
3507 if (type->isIntegerTy())
3508 weight = CW_SpecificReg;
3510 case 'I': // signed 16 bit immediate
3511 case 'J': // integer zero
3512 case 'K': // unsigned 16 bit immediate
3513 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3514 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3515 case 'O': // signed 15 bit immediate (+- 16383)
3516 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3517 if (isa<ConstantInt>(CallOperandVal))
3518 weight = CW_Constant;
3527 /// This is a helper function to parse a physical register string and split it
3528 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3529 /// that is returned indicates whether parsing was successful. The second flag
3530 /// is true if the numeric part exists.
3531 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3532 unsigned long long &Reg) {
3533 if (C.front() != '{' || C.back() != '}')
3534 return std::make_pair(false, false);
3536 // Search for the first numeric character.
3537 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3538 I = std::find_if(B, E, isdigit);
3540 Prefix = StringRef(B, I - B);
3542 // The second flag is set to false if no numeric characters were found.
3544 return std::make_pair(true, false);
3546 // Parse the numeric characters.
3547 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3551 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3552 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3553 const TargetRegisterInfo *TRI =
3554 Subtarget.getRegisterInfo();
3555 const TargetRegisterClass *RC;
3557 unsigned long long Reg;
3559 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3562 return std::make_pair(0U, nullptr);
3564 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3565 // No numeric characters follow "hi" or "lo".
3567 return std::make_pair(0U, nullptr);
3569 RC = TRI->getRegClass(Prefix == "hi" ?
3570 Mips::HI32RegClassID : Mips::LO32RegClassID);
3571 return std::make_pair(*(RC->begin()), RC);
3572 } else if (Prefix.startswith("$msa")) {
3573 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3575 // No numeric characters follow the name.
3577 return std::make_pair(0U, nullptr);
3579 Reg = StringSwitch<unsigned long long>(Prefix)
3580 .Case("$msair", Mips::MSAIR)
3581 .Case("$msacsr", Mips::MSACSR)
3582 .Case("$msaaccess", Mips::MSAAccess)
3583 .Case("$msasave", Mips::MSASave)
3584 .Case("$msamodify", Mips::MSAModify)
3585 .Case("$msarequest", Mips::MSARequest)
3586 .Case("$msamap", Mips::MSAMap)
3587 .Case("$msaunmap", Mips::MSAUnmap)
3591 return std::make_pair(0U, nullptr);
3593 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3594 return std::make_pair(Reg, RC);
3598 return std::make_pair(0U, nullptr);
3600 if (Prefix == "$f") { // Parse $f0-$f31.
3601 // If the size of FP registers is 64-bit or Reg is an even number, select
3602 // the 64-bit register class. Otherwise, select the 32-bit register class.
3603 if (VT == MVT::Other)
3604 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3606 RC = getRegClassFor(VT);
3608 if (RC == &Mips::AFGR64RegClass) {
3609 assert(Reg % 2 == 0);
3612 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3613 RC = TRI->getRegClass(Mips::FCCRegClassID);
3614 else if (Prefix == "$w") { // Parse $w0-$w31.
3615 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3616 } else { // Parse $0-$31.
3617 assert(Prefix == "$");
3618 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3621 assert(Reg < RC->getNumRegs());
3622 return std::make_pair(*(RC->begin() + Reg), RC);
3625 /// Given a register class constraint, like 'r', if this corresponds directly
3626 /// to an LLVM register class, return a register of 0 and the register class
3628 std::pair<unsigned, const TargetRegisterClass *>
3629 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3630 StringRef Constraint,
3632 if (Constraint.size() == 1) {
3633 switch (Constraint[0]) {
3634 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3635 case 'y': // Same as 'r'. Exists for compatibility.
3637 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3638 if (Subtarget.inMips16Mode())
3639 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3640 return std::make_pair(0U, &Mips::GPR32RegClass);
3642 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3643 return std::make_pair(0U, &Mips::GPR32RegClass);
3644 if (VT == MVT::i64 && Subtarget.isGP64bit())
3645 return std::make_pair(0U, &Mips::GPR64RegClass);
3646 // This will generate an error message
3647 return std::make_pair(0U, nullptr);
3648 case 'f': // FPU or MSA register
3649 if (VT == MVT::v16i8)
3650 return std::make_pair(0U, &Mips::MSA128BRegClass);
3651 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3652 return std::make_pair(0U, &Mips::MSA128HRegClass);
3653 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3654 return std::make_pair(0U, &Mips::MSA128WRegClass);
3655 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3656 return std::make_pair(0U, &Mips::MSA128DRegClass);
3657 else if (VT == MVT::f32)
3658 return std::make_pair(0U, &Mips::FGR32RegClass);
3659 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3660 if (Subtarget.isFP64bit())
3661 return std::make_pair(0U, &Mips::FGR64RegClass);
3662 return std::make_pair(0U, &Mips::AFGR64RegClass);
3665 case 'c': // register suitable for indirect jump
3667 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3668 assert(VT == MVT::i64 && "Unexpected type.");
3669 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3670 case 'l': // register suitable for indirect jump
3672 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3673 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3674 case 'x': // register suitable for indirect jump
3675 // Fixme: Not triggering the use of both hi and low
3676 // This will generate an error message
3677 return std::make_pair(0U, nullptr);
3681 std::pair<unsigned, const TargetRegisterClass *> R;
3682 R = parseRegForInlineAsmConstraint(Constraint, VT);
3687 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3690 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3691 /// vector. If it is invalid, don't add anything to Ops.
3692 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3693 std::string &Constraint,
3694 std::vector<SDValue>&Ops,
3695 SelectionDAG &DAG) const {
3699 // Only support length 1 constraints for now.
3700 if (Constraint.length() > 1) return;
3702 char ConstraintLetter = Constraint[0];
3703 switch (ConstraintLetter) {
3704 default: break; // This will fall through to the generic implementation
3705 case 'I': // Signed 16 bit constant
3706 // If this fails, the parent routine will give an error
3707 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3708 EVT Type = Op.getValueType();
3709 int64_t Val = C->getSExtValue();
3710 if (isInt<16>(Val)) {
3711 Result = DAG.getTargetConstant(Val, DL, Type);
3716 case 'J': // integer zero
3717 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3718 EVT Type = Op.getValueType();
3719 int64_t Val = C->getZExtValue();
3721 Result = DAG.getTargetConstant(0, DL, Type);
3726 case 'K': // unsigned 16 bit immediate
3727 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3728 EVT Type = Op.getValueType();
3729 uint64_t Val = (uint64_t)C->getZExtValue();
3730 if (isUInt<16>(Val)) {
3731 Result = DAG.getTargetConstant(Val, DL, Type);
3736 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3737 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3738 EVT Type = Op.getValueType();
3739 int64_t Val = C->getSExtValue();
3740 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3741 Result = DAG.getTargetConstant(Val, DL, Type);
3746 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3747 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3748 EVT Type = Op.getValueType();
3749 int64_t Val = C->getSExtValue();
3750 if ((Val >= -65535) && (Val <= -1)) {
3751 Result = DAG.getTargetConstant(Val, DL, Type);
3756 case 'O': // signed 15 bit immediate
3757 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3758 EVT Type = Op.getValueType();
3759 int64_t Val = C->getSExtValue();
3760 if ((isInt<15>(Val))) {
3761 Result = DAG.getTargetConstant(Val, DL, Type);
3766 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3767 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3768 EVT Type = Op.getValueType();
3769 int64_t Val = C->getSExtValue();
3770 if ((Val <= 65535) && (Val >= 1)) {
3771 Result = DAG.getTargetConstant(Val, DL, Type);
3778 if (Result.getNode()) {
3779 Ops.push_back(Result);
3783 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3786 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3787 const AddrMode &AM, Type *Ty,
3788 unsigned AS) const {
3789 // No global is ever allowed as a base.
3794 case 0: // "r+i" or just "i", depending on HasBaseReg.
3797 if (!AM.HasBaseReg) // allow "r+i".
3799 return false; // disallow "r+r" or "r+r+i".
3808 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3809 // The Mips target isn't yet aware of offsets.
3813 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3815 bool IsMemset, bool ZeroMemset,
3817 MachineFunction &MF) const {
3818 if (Subtarget.hasMips64())
3824 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3825 if (VT != MVT::f32 && VT != MVT::f64)
3827 if (Imm.isNegZero())
3829 return Imm.isZero();
3832 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3834 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
3835 if (ABI.IsN64() && isPositionIndependent())
3836 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3838 return TargetLowering::getJumpTableEncoding();
3841 bool MipsTargetLowering::useSoftFloat() const {
3842 return Subtarget.useSoftFloat();
3845 void MipsTargetLowering::copyByValRegs(
3846 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
3847 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3848 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3849 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
3850 MipsCCState &State) const {
3851 MachineFunction &MF = DAG.getMachineFunction();
3852 MachineFrameInfo &MFI = MF.getFrameInfo();
3853 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3854 unsigned NumRegs = LastReg - FirstReg;
3855 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3856 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3858 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3862 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3863 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3865 FrameObjOffset = VA.getLocMemOffset();
3867 // Create frame object.
3868 EVT PtrTy = getPointerTy(DAG.getDataLayout());
3869 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3870 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3871 InVals.push_back(FIN);
3876 // Copy arg registers.
3877 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3878 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3880 for (unsigned I = 0; I < NumRegs; ++I) {
3881 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3882 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3883 unsigned Offset = I * GPRSizeInBytes;
3884 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3885 DAG.getConstant(Offset, DL, PtrTy));
3886 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3887 StorePtr, MachinePointerInfo(FuncArg, Offset));
3888 OutChains.push_back(Store);
3892 // Copy byVal arg to registers and stack.
3893 void MipsTargetLowering::passByValArg(
3894 SDValue Chain, const SDLoc &DL,
3895 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3896 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3897 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3898 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3899 const CCValAssign &VA) const {
3900 unsigned ByValSizeInBytes = Flags.getByValSize();
3901 unsigned OffsetInBytes = 0; // From beginning of struct
3902 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3903 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3904 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
3905 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3906 unsigned NumRegs = LastReg - FirstReg;
3909 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3910 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3913 // Copy words to registers.
3914 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3915 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3916 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3917 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3918 MachinePointerInfo(), Alignment);
3919 MemOpChains.push_back(LoadVal.getValue(1));
3920 unsigned ArgReg = ArgRegs[FirstReg + I];
3921 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3924 // Return if the struct has been fully copied.
3925 if (ByValSizeInBytes == OffsetInBytes)
3928 // Copy the remainder of the byval argument with sub-word loads and shifts.
3929 if (LeftoverBytes) {
3932 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3933 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3934 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3936 if (RemainingSizeInBytes < LoadSizeInBytes)
3940 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3941 DAG.getConstant(OffsetInBytes, DL,
3943 SDValue LoadVal = DAG.getExtLoad(
3944 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3945 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
3946 MemOpChains.push_back(LoadVal.getValue(1));
3948 // Shift the loaded value.
3952 Shamt = TotalBytesLoaded * 8;
3954 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3956 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3957 DAG.getConstant(Shamt, DL, MVT::i32));
3960 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3964 OffsetInBytes += LoadSizeInBytes;
3965 TotalBytesLoaded += LoadSizeInBytes;
3966 Alignment = std::min(Alignment, LoadSizeInBytes);
3969 unsigned ArgReg = ArgRegs[FirstReg + I];
3970 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3975 // Copy remainder of byval arg to it with memcpy.
3976 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3977 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3978 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3979 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3980 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3981 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3982 DAG.getConstant(MemCpySize, DL, PtrTy),
3983 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3984 /*isTailCall=*/false,
3985 MachinePointerInfo(), MachinePointerInfo());
3986 MemOpChains.push_back(Chain);
3989 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3990 SDValue Chain, const SDLoc &DL,
3992 CCState &State) const {
3993 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3994 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3995 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3996 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3997 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3998 MachineFunction &MF = DAG.getMachineFunction();
3999 MachineFrameInfo &MFI = MF.getFrameInfo();
4000 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4002 // Offset of the first variable argument from stack pointer.
4005 if (ArgRegs.size() == Idx)
4006 VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4009 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4010 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4013 // Record the frame index of the first variable argument
4014 // which is a value necessary to VASTART.
4015 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4016 MipsFI->setVarArgsFrameIndex(FI);
4018 // Copy the integer registers that have not been used for argument passing
4019 // to the argument register save area. For O32, the save area is allocated
4020 // in the caller's stack frame, while for N32/64, it is allocated in the
4021 // callee's stack frame.
4022 for (unsigned I = Idx; I < ArgRegs.size();
4023 ++I, VaArgOffset += RegSizeInBytes) {
4024 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4025 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4026 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4027 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4029 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4030 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4032 OutChains.push_back(Store);
4036 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4037 unsigned Align) const {
4038 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4040 assert(Size && "Byval argument's size shouldn't be 0.");
4042 Align = std::min(Align, TFL->getStackAlignment());
4044 unsigned FirstReg = 0;
4045 unsigned NumRegs = 0;
4047 if (State->getCallingConv() != CallingConv::Fast) {
4048 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4049 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4050 // FIXME: The O32 case actually describes no shadow registers.
4051 const MCPhysReg *ShadowRegs =
4052 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4054 // We used to check the size as well but we can't do that anymore since
4055 // CCState::HandleByVal() rounds up the size after calling this function.
4056 assert(!(Align % RegSizeInBytes) &&
4057 "Byval argument's alignment should be a multiple of"
4060 FirstReg = State->getFirstUnallocated(IntArgRegs);
4062 // If Align > RegSizeInBytes, the first arg register must be even.
4063 // FIXME: This condition happens to do the right thing but it's not the
4064 // right way to test it. We want to check that the stack frame offset
4065 // of the register is aligned.
4066 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4067 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4071 // Mark the registers allocated.
4072 Size = alignTo(Size, RegSizeInBytes);
4073 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4074 Size -= RegSizeInBytes, ++I, ++NumRegs)
4075 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4078 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4081 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4082 MachineBasicBlock *BB,
4084 unsigned Opc) const {
4085 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4086 "Subtarget already supports SELECT nodes with the use of"
4087 "conditional-move instructions.");
4089 const TargetInstrInfo *TII =
4090 Subtarget.getInstrInfo();
4091 DebugLoc DL = MI.getDebugLoc();
4093 // To "insert" a SELECT instruction, we actually have to insert the
4094 // diamond control-flow pattern. The incoming instruction knows the
4095 // destination vreg to set, the condition code register to branch on, the
4096 // true/false values to select between, and a branch opcode to use.
4097 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4098 MachineFunction::iterator It = ++BB->getIterator();
4104 // bNE r1, r0, copy1MBB
4105 // fallthrough --> copy0MBB
4106 MachineBasicBlock *thisMBB = BB;
4107 MachineFunction *F = BB->getParent();
4108 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4109 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4110 F->insert(It, copy0MBB);
4111 F->insert(It, sinkMBB);
4113 // Transfer the remainder of BB and its successor edges to sinkMBB.
4114 sinkMBB->splice(sinkMBB->begin(), BB,
4115 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4116 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4118 // Next, add the true and fallthrough blocks as its successors.
4119 BB->addSuccessor(copy0MBB);
4120 BB->addSuccessor(sinkMBB);
4123 // bc1[tf] cc, sinkMBB
4124 BuildMI(BB, DL, TII->get(Opc))
4125 .addReg(MI.getOperand(1).getReg())
4128 // bne rs, $0, sinkMBB
4129 BuildMI(BB, DL, TII->get(Opc))
4130 .addReg(MI.getOperand(1).getReg())
4136 // %FalseValue = ...
4137 // # fallthrough to sinkMBB
4140 // Update machine-CFG edges
4141 BB->addSuccessor(sinkMBB);
4144 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4148 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4149 .addReg(MI.getOperand(2).getReg())
4151 .addReg(MI.getOperand(3).getReg())
4154 MI.eraseFromParent(); // The pseudo instruction is gone now.
4159 // FIXME? Maybe this could be a TableGen attribute on some registers and
4160 // this table could be generated automatically from RegInfo.
4161 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4162 SelectionDAG &DAG) const {
4163 // Named registers is expected to be fairly rare. For now, just support $28
4164 // since the linux kernel uses it.
4165 if (Subtarget.isGP64bit()) {
4166 unsigned Reg = StringSwitch<unsigned>(RegName)
4167 .Case("$28", Mips::GP_64)
4172 unsigned Reg = StringSwitch<unsigned>(RegName)
4173 .Case("$28", Mips::GP)
4178 report_fatal_error("Invalid register name global variable");