1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGISel.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
43 #define DEBUG_TYPE "mips-lower"
45 STATISTIC(NumTailCalls, "Number of tail calls");
48 LargeGOT("mxgot", cl::Hidden,
49 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
52 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
53 cl::desc("MIPS: Don't trap on integer division by zero."),
57 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
58 cl::desc("Allow mips-fast-isel to be used"),
61 static const MCPhysReg Mips64DPRegs[8] = {
62 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
73 Size = CountPopulation_64(I);
74 Pos = countTrailingZeros(I);
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
83 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
85 unsigned Flag) const {
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
89 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
91 unsigned Flag) const {
92 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
95 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
97 unsigned Flag) const {
98 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
103 unsigned Flag) const {
104 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
107 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
109 unsigned Flag) const {
110 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111 N->getOffset(), Flag);
114 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
116 case MipsISD::JmpLink: return "MipsISD::JmpLink";
117 case MipsISD::TailCall: return "MipsISD::TailCall";
118 case MipsISD::Hi: return "MipsISD::Hi";
119 case MipsISD::Lo: return "MipsISD::Lo";
120 case MipsISD::GPRel: return "MipsISD::GPRel";
121 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
122 case MipsISD::Ret: return "MipsISD::Ret";
123 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
124 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
125 case MipsISD::FPCmp: return "MipsISD::FPCmp";
126 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
127 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
128 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
129 case MipsISD::MFHI: return "MipsISD::MFHI";
130 case MipsISD::MFLO: return "MipsISD::MFLO";
131 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
132 case MipsISD::Mult: return "MipsISD::Mult";
133 case MipsISD::Multu: return "MipsISD::Multu";
134 case MipsISD::MAdd: return "MipsISD::MAdd";
135 case MipsISD::MAddu: return "MipsISD::MAddu";
136 case MipsISD::MSub: return "MipsISD::MSub";
137 case MipsISD::MSubu: return "MipsISD::MSubu";
138 case MipsISD::DivRem: return "MipsISD::DivRem";
139 case MipsISD::DivRemU: return "MipsISD::DivRemU";
140 case MipsISD::DivRem16: return "MipsISD::DivRem16";
141 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
142 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
143 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
144 case MipsISD::Wrapper: return "MipsISD::Wrapper";
145 case MipsISD::Sync: return "MipsISD::Sync";
146 case MipsISD::Ext: return "MipsISD::Ext";
147 case MipsISD::Ins: return "MipsISD::Ins";
148 case MipsISD::LWL: return "MipsISD::LWL";
149 case MipsISD::LWR: return "MipsISD::LWR";
150 case MipsISD::SWL: return "MipsISD::SWL";
151 case MipsISD::SWR: return "MipsISD::SWR";
152 case MipsISD::LDL: return "MipsISD::LDL";
153 case MipsISD::LDR: return "MipsISD::LDR";
154 case MipsISD::SDL: return "MipsISD::SDL";
155 case MipsISD::SDR: return "MipsISD::SDR";
156 case MipsISD::EXTP: return "MipsISD::EXTP";
157 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
158 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
159 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
160 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
161 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
162 case MipsISD::SHILO: return "MipsISD::SHILO";
163 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
164 case MipsISD::MULT: return "MipsISD::MULT";
165 case MipsISD::MULTU: return "MipsISD::MULTU";
166 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
167 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
168 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
169 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
170 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
171 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
172 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
173 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
174 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
175 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
176 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
177 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
178 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
179 case MipsISD::VCEQ: return "MipsISD::VCEQ";
180 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
181 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
182 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
183 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
184 case MipsISD::VSMAX: return "MipsISD::VSMAX";
185 case MipsISD::VSMIN: return "MipsISD::VSMIN";
186 case MipsISD::VUMAX: return "MipsISD::VUMAX";
187 case MipsISD::VUMIN: return "MipsISD::VUMIN";
188 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
189 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
190 case MipsISD::VNOR: return "MipsISD::VNOR";
191 case MipsISD::VSHF: return "MipsISD::VSHF";
192 case MipsISD::SHF: return "MipsISD::SHF";
193 case MipsISD::ILVEV: return "MipsISD::ILVEV";
194 case MipsISD::ILVOD: return "MipsISD::ILVOD";
195 case MipsISD::ILVL: return "MipsISD::ILVL";
196 case MipsISD::ILVR: return "MipsISD::ILVR";
197 case MipsISD::PCKEV: return "MipsISD::PCKEV";
198 case MipsISD::PCKOD: return "MipsISD::PCKOD";
199 case MipsISD::INSVE: return "MipsISD::INSVE";
200 default: return nullptr;
204 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
205 const MipsSubtarget &STI)
206 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
207 // Mips does not have i1 type, so use i32 for
208 // setcc operations results (slt, sgt, ...).
209 setBooleanContents(ZeroOrOneBooleanContent);
210 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
211 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
212 // does. Integer booleans still use 0 and 1.
213 if (Subtarget.hasMips32r6())
214 setBooleanContents(ZeroOrOneBooleanContent,
215 ZeroOrNegativeOneBooleanContent);
217 // Load extented operations for i1 types must be promoted
218 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
219 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
220 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
222 // MIPS doesn't have extending float->double load/store
223 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
224 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
226 // Used by legalize types to correctly generate the setcc result.
227 // Without this, every float setcc comes with a AND/OR with the result,
228 // we don't want this, since the fpcmp result goes to a flag register,
229 // which is used implicitly by brcond and select operations.
230 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
232 // Mips Custom Operations
233 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
234 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
235 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
236 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
237 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
238 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
239 setOperationAction(ISD::SELECT, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT, MVT::f64, Custom);
241 setOperationAction(ISD::SELECT, MVT::i32, Custom);
242 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
243 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
244 setOperationAction(ISD::SETCC, MVT::f32, Custom);
245 setOperationAction(ISD::SETCC, MVT::f64, Custom);
246 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
247 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
248 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
249 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
251 if (Subtarget.isGP64bit()) {
252 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
253 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
254 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
255 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
256 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
257 setOperationAction(ISD::SELECT, MVT::i64, Custom);
258 setOperationAction(ISD::LOAD, MVT::i64, Custom);
259 setOperationAction(ISD::STORE, MVT::i64, Custom);
260 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
263 if (!Subtarget.isGP64bit()) {
264 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
265 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
266 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::ADD, MVT::i32, Custom);
270 if (Subtarget.isGP64bit())
271 setOperationAction(ISD::ADD, MVT::i64, Custom);
273 setOperationAction(ISD::SDIV, MVT::i32, Expand);
274 setOperationAction(ISD::SREM, MVT::i32, Expand);
275 setOperationAction(ISD::UDIV, MVT::i32, Expand);
276 setOperationAction(ISD::UREM, MVT::i32, Expand);
277 setOperationAction(ISD::SDIV, MVT::i64, Expand);
278 setOperationAction(ISD::SREM, MVT::i64, Expand);
279 setOperationAction(ISD::UDIV, MVT::i64, Expand);
280 setOperationAction(ISD::UREM, MVT::i64, Expand);
282 // Operations not directly supported by Mips.
283 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
284 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
285 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
286 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
287 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
288 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
289 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
290 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
291 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
292 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
293 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
294 if (Subtarget.hasCnMips()) {
295 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
296 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
298 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
299 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
301 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
302 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
303 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
304 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
305 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
306 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
307 setOperationAction(ISD::ROTL, MVT::i32, Expand);
308 setOperationAction(ISD::ROTL, MVT::i64, Expand);
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
312 if (!Subtarget.hasMips32r2())
313 setOperationAction(ISD::ROTR, MVT::i32, Expand);
315 if (!Subtarget.hasMips64r2())
316 setOperationAction(ISD::ROTR, MVT::i64, Expand);
318 setOperationAction(ISD::FSIN, MVT::f32, Expand);
319 setOperationAction(ISD::FSIN, MVT::f64, Expand);
320 setOperationAction(ISD::FCOS, MVT::f32, Expand);
321 setOperationAction(ISD::FCOS, MVT::f64, Expand);
322 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
323 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
324 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
325 setOperationAction(ISD::FPOW, MVT::f32, Expand);
326 setOperationAction(ISD::FPOW, MVT::f64, Expand);
327 setOperationAction(ISD::FLOG, MVT::f32, Expand);
328 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
329 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
330 setOperationAction(ISD::FEXP, MVT::f32, Expand);
331 setOperationAction(ISD::FMA, MVT::f32, Expand);
332 setOperationAction(ISD::FMA, MVT::f64, Expand);
333 setOperationAction(ISD::FREM, MVT::f32, Expand);
334 setOperationAction(ISD::FREM, MVT::f64, Expand);
336 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
338 setOperationAction(ISD::VASTART, MVT::Other, Custom);
339 setOperationAction(ISD::VAARG, MVT::Other, Custom);
340 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
341 setOperationAction(ISD::VAEND, MVT::Other, Expand);
343 // Use the default for now
344 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
345 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
347 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
348 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
349 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
350 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
352 setInsertFencesForAtomic(true);
354 if (!Subtarget.hasMips32r2()) {
355 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
359 // MIPS16 lacks MIPS32's clz and clo instructions.
360 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
361 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
362 if (!Subtarget.hasMips64())
363 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
365 if (!Subtarget.hasMips32r2())
366 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
367 if (!Subtarget.hasMips64r2())
368 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
370 if (Subtarget.isGP64bit()) {
371 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
372 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
374 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
377 setOperationAction(ISD::TRAP, MVT::Other, Legal);
379 setTargetDAGCombine(ISD::SDIVREM);
380 setTargetDAGCombine(ISD::UDIVREM);
381 setTargetDAGCombine(ISD::SELECT);
382 setTargetDAGCombine(ISD::AND);
383 setTargetDAGCombine(ISD::OR);
384 setTargetDAGCombine(ISD::ADD);
386 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
388 // The arguments on the stack are defined in terms of 4-byte slots on O32
389 // and 8-byte slots on N32/N64.
390 setMinStackArgumentAlignment(
391 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
393 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
396 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
397 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
399 MaxStoresPerMemcpy = 16;
401 isMicroMips = Subtarget.inMicroMipsMode();
404 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
405 const MipsSubtarget &STI) {
406 if (STI.inMips16Mode())
407 return llvm::createMips16TargetLowering(TM, STI);
409 return llvm::createMipsSETargetLowering(TM, STI);
412 // Create a fast isel object.
414 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
415 const TargetLibraryInfo *libInfo) const {
416 if (!EnableMipsFastISel)
417 return TargetLowering::createFastISel(funcInfo, libInfo);
418 return Mips::createFastISel(funcInfo, libInfo);
421 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
424 return VT.changeVectorElementTypeToInteger();
427 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
428 TargetLowering::DAGCombinerInfo &DCI,
429 const MipsSubtarget &Subtarget) {
430 if (DCI.isBeforeLegalizeOps())
433 EVT Ty = N->getValueType(0);
434 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
435 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
436 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
440 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
441 N->getOperand(0), N->getOperand(1));
442 SDValue InChain = DAG.getEntryNode();
443 SDValue InGlue = DivRem;
446 if (N->hasAnyUseOfValue(0)) {
447 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
450 InChain = CopyFromLo.getValue(1);
451 InGlue = CopyFromLo.getValue(2);
455 if (N->hasAnyUseOfValue(1)) {
456 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
458 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
464 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
466 default: llvm_unreachable("Unknown fp condition code!");
468 case ISD::SETOEQ: return Mips::FCOND_OEQ;
469 case ISD::SETUNE: return Mips::FCOND_UNE;
471 case ISD::SETOLT: return Mips::FCOND_OLT;
473 case ISD::SETOGT: return Mips::FCOND_OGT;
475 case ISD::SETOLE: return Mips::FCOND_OLE;
477 case ISD::SETOGE: return Mips::FCOND_OGE;
478 case ISD::SETULT: return Mips::FCOND_ULT;
479 case ISD::SETULE: return Mips::FCOND_ULE;
480 case ISD::SETUGT: return Mips::FCOND_UGT;
481 case ISD::SETUGE: return Mips::FCOND_UGE;
482 case ISD::SETUO: return Mips::FCOND_UN;
483 case ISD::SETO: return Mips::FCOND_OR;
485 case ISD::SETONE: return Mips::FCOND_ONE;
486 case ISD::SETUEQ: return Mips::FCOND_UEQ;
491 /// This function returns true if the floating point conditional branches and
492 /// conditional moves which use condition code CC should be inverted.
493 static bool invertFPCondCodeUser(Mips::CondCode CC) {
494 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
497 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
498 "Illegal Condition Code");
503 // Creates and returns an FPCmp node from a setcc node.
504 // Returns Op if setcc is not a floating point comparison.
505 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
506 // must be a SETCC node
507 if (Op.getOpcode() != ISD::SETCC)
510 SDValue LHS = Op.getOperand(0);
512 if (!LHS.getValueType().isFloatingPoint())
515 SDValue RHS = Op.getOperand(1);
518 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
519 // node if necessary.
520 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
522 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
523 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
526 // Creates and returns a CMovFPT/F node.
527 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
528 SDValue False, SDLoc DL) {
529 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
530 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
531 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
533 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
534 True.getValueType(), True, FCC0, False, Cond);
537 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
538 TargetLowering::DAGCombinerInfo &DCI,
539 const MipsSubtarget &Subtarget) {
540 if (DCI.isBeforeLegalizeOps())
543 SDValue SetCC = N->getOperand(0);
545 if ((SetCC.getOpcode() != ISD::SETCC) ||
546 !SetCC.getOperand(0).getValueType().isInteger())
549 SDValue False = N->getOperand(2);
550 EVT FalseTy = False.getValueType();
552 if (!FalseTy.isInteger())
555 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
557 // If the RHS (False) is 0, we swap the order of the operands
558 // of ISD::SELECT (obviously also inverting the condition) so that we can
559 // take advantage of conditional moves using the $0 register.
561 // return (a != 0) ? x : 0;
569 if (!FalseC->getZExtValue()) {
570 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
571 SDValue True = N->getOperand(1);
573 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
574 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
576 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
579 // If both operands are integer constants there's a possibility that we
580 // can do some interesting optimizations.
581 SDValue True = N->getOperand(1);
582 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
584 if (!TrueC || !True.getValueType().isInteger())
587 // We'll also ignore MVT::i64 operands as this optimizations proves
588 // to be ineffective because of the required sign extensions as the result
589 // of a SETCC operator is always MVT::i32 for non-vector types.
590 if (True.getValueType() == MVT::i64)
593 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
595 // 1) (a < x) ? y : y-1
597 // addiu $reg2, $reg1, y-1
599 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
601 // 2) (a < x) ? y-1 : y
603 // xor $reg1, $reg1, 1
604 // addiu $reg2, $reg1, y-1
606 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
607 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
608 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
609 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
612 // Couldn't optimize.
616 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
617 TargetLowering::DAGCombinerInfo &DCI,
618 const MipsSubtarget &Subtarget) {
619 // Pattern match EXT.
620 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
621 // => ext $dst, $src, size, pos
622 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
625 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
626 unsigned ShiftRightOpc = ShiftRight.getOpcode();
628 // Op's first operand must be a shift right.
629 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
632 // The second operand of the shift must be an immediate.
634 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
637 uint64_t Pos = CN->getZExtValue();
638 uint64_t SMPos, SMSize;
640 // Op's second operand must be a shifted mask.
641 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
642 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
645 // Return if the shifted mask does not start at bit 0 or the sum of its size
646 // and Pos exceeds the word's size.
647 EVT ValTy = N->getValueType(0);
648 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
651 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
652 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
653 DAG.getConstant(SMSize, MVT::i32));
656 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
657 TargetLowering::DAGCombinerInfo &DCI,
658 const MipsSubtarget &Subtarget) {
659 // Pattern match INS.
660 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
661 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
662 // => ins $dst, $src, size, pos, $src1
663 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
666 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
667 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
670 // See if Op's first operand matches (and $src1 , mask0).
671 if (And0.getOpcode() != ISD::AND)
674 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
675 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
678 // See if Op's second operand matches (and (shl $src, pos), mask1).
679 if (And1.getOpcode() != ISD::AND)
682 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
683 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
686 // The shift masks must have the same position and size.
687 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
690 SDValue Shl = And1.getOperand(0);
691 if (Shl.getOpcode() != ISD::SHL)
694 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
697 unsigned Shamt = CN->getZExtValue();
699 // Return if the shift amount and the first bit position of mask are not the
701 EVT ValTy = N->getValueType(0);
702 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
705 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
706 DAG.getConstant(SMPos0, MVT::i32),
707 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
710 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
711 TargetLowering::DAGCombinerInfo &DCI,
712 const MipsSubtarget &Subtarget) {
713 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
715 if (DCI.isBeforeLegalizeOps())
718 SDValue Add = N->getOperand(1);
720 if (Add.getOpcode() != ISD::ADD)
723 SDValue Lo = Add.getOperand(1);
725 if ((Lo.getOpcode() != MipsISD::Lo) ||
726 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
729 EVT ValTy = N->getValueType(0);
732 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
734 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
737 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
739 SelectionDAG &DAG = DCI.DAG;
740 unsigned Opc = N->getOpcode();
746 return performDivRemCombine(N, DAG, DCI, Subtarget);
748 return performSELECTCombine(N, DAG, DCI, Subtarget);
750 return performANDCombine(N, DAG, DCI, Subtarget);
752 return performORCombine(N, DAG, DCI, Subtarget);
754 return performADDCombine(N, DAG, DCI, Subtarget);
761 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
762 SmallVectorImpl<SDValue> &Results,
763 SelectionDAG &DAG) const {
764 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
766 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
767 Results.push_back(Res.getValue(I));
771 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
772 SmallVectorImpl<SDValue> &Results,
773 SelectionDAG &DAG) const {
774 return LowerOperationWrapper(N, Results, DAG);
777 SDValue MipsTargetLowering::
778 LowerOperation(SDValue Op, SelectionDAG &DAG) const
780 switch (Op.getOpcode())
782 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
783 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
784 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
785 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
786 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
787 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
788 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
789 case ISD::SELECT: return lowerSELECT(Op, DAG);
790 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
791 case ISD::SETCC: return lowerSETCC(Op, DAG);
792 case ISD::VASTART: return lowerVASTART(Op, DAG);
793 case ISD::VAARG: return lowerVAARG(Op, DAG);
794 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
795 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
796 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
797 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
798 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
799 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
800 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
801 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
802 case ISD::LOAD: return lowerLOAD(Op, DAG);
803 case ISD::STORE: return lowerSTORE(Op, DAG);
804 case ISD::ADD: return lowerADD(Op, DAG);
805 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
810 //===----------------------------------------------------------------------===//
811 // Lower helper functions
812 //===----------------------------------------------------------------------===//
814 // addLiveIn - This helper function adds the specified physical register to the
815 // MachineFunction as a live in value. It also creates a corresponding
816 // virtual register for it.
818 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
820 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
821 MF.getRegInfo().addLiveIn(PReg, VReg);
825 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
826 MachineBasicBlock &MBB,
827 const TargetInstrInfo &TII,
832 // Insert instruction "teq $divisor_reg, $zero, 7".
833 MachineBasicBlock::iterator I(MI);
834 MachineInstrBuilder MIB;
835 MachineOperand &Divisor = MI->getOperand(2);
836 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
837 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
838 .addReg(Mips::ZERO).addImm(7);
840 // Use the 32-bit sub-register if this is a 64-bit division.
842 MIB->getOperand(0).setSubReg(Mips::sub_32);
844 // Clear Divisor's kill flag.
845 Divisor.setIsKill(false);
847 // We would normally delete the original instruction here but in this case
848 // we only needed to inject an additional instruction rather than replace it.
854 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
855 MachineBasicBlock *BB) const {
856 switch (MI->getOpcode()) {
858 llvm_unreachable("Unexpected instr type to insert");
859 case Mips::ATOMIC_LOAD_ADD_I8:
860 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
861 case Mips::ATOMIC_LOAD_ADD_I16:
862 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
863 case Mips::ATOMIC_LOAD_ADD_I32:
864 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
865 case Mips::ATOMIC_LOAD_ADD_I64:
866 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
868 case Mips::ATOMIC_LOAD_AND_I8:
869 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
870 case Mips::ATOMIC_LOAD_AND_I16:
871 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
872 case Mips::ATOMIC_LOAD_AND_I32:
873 return emitAtomicBinary(MI, BB, 4, Mips::AND);
874 case Mips::ATOMIC_LOAD_AND_I64:
875 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
877 case Mips::ATOMIC_LOAD_OR_I8:
878 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
879 case Mips::ATOMIC_LOAD_OR_I16:
880 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
881 case Mips::ATOMIC_LOAD_OR_I32:
882 return emitAtomicBinary(MI, BB, 4, Mips::OR);
883 case Mips::ATOMIC_LOAD_OR_I64:
884 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
886 case Mips::ATOMIC_LOAD_XOR_I8:
887 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
888 case Mips::ATOMIC_LOAD_XOR_I16:
889 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
890 case Mips::ATOMIC_LOAD_XOR_I32:
891 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
892 case Mips::ATOMIC_LOAD_XOR_I64:
893 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
895 case Mips::ATOMIC_LOAD_NAND_I8:
896 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
897 case Mips::ATOMIC_LOAD_NAND_I16:
898 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
899 case Mips::ATOMIC_LOAD_NAND_I32:
900 return emitAtomicBinary(MI, BB, 4, 0, true);
901 case Mips::ATOMIC_LOAD_NAND_I64:
902 return emitAtomicBinary(MI, BB, 8, 0, true);
904 case Mips::ATOMIC_LOAD_SUB_I8:
905 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
906 case Mips::ATOMIC_LOAD_SUB_I16:
907 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
908 case Mips::ATOMIC_LOAD_SUB_I32:
909 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
910 case Mips::ATOMIC_LOAD_SUB_I64:
911 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
913 case Mips::ATOMIC_SWAP_I8:
914 return emitAtomicBinaryPartword(MI, BB, 1, 0);
915 case Mips::ATOMIC_SWAP_I16:
916 return emitAtomicBinaryPartword(MI, BB, 2, 0);
917 case Mips::ATOMIC_SWAP_I32:
918 return emitAtomicBinary(MI, BB, 4, 0);
919 case Mips::ATOMIC_SWAP_I64:
920 return emitAtomicBinary(MI, BB, 8, 0);
922 case Mips::ATOMIC_CMP_SWAP_I8:
923 return emitAtomicCmpSwapPartword(MI, BB, 1);
924 case Mips::ATOMIC_CMP_SWAP_I16:
925 return emitAtomicCmpSwapPartword(MI, BB, 2);
926 case Mips::ATOMIC_CMP_SWAP_I32:
927 return emitAtomicCmpSwap(MI, BB, 4);
928 case Mips::ATOMIC_CMP_SWAP_I64:
929 return emitAtomicCmpSwap(MI, BB, 8);
930 case Mips::PseudoSDIV:
931 case Mips::PseudoUDIV:
936 return insertDivByZeroTrap(
937 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
938 case Mips::PseudoDSDIV:
939 case Mips::PseudoDUDIV:
944 return insertDivByZeroTrap(
945 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
947 return emitSEL_D(MI, BB);
951 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
952 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
954 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
955 unsigned Size, unsigned BinOpcode,
957 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
959 MachineFunction *MF = BB->getParent();
960 MachineRegisterInfo &RegInfo = MF->getRegInfo();
961 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
962 const TargetInstrInfo *TII =
963 getTargetMachine().getSubtargetImpl()->getInstrInfo();
964 DebugLoc DL = MI->getDebugLoc();
965 unsigned LL, SC, AND, NOR, ZERO, BEQ;
972 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
973 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
980 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
981 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
984 ZERO = Mips::ZERO_64;
988 unsigned OldVal = MI->getOperand(0).getReg();
989 unsigned Ptr = MI->getOperand(1).getReg();
990 unsigned Incr = MI->getOperand(2).getReg();
992 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
993 unsigned AndRes = RegInfo.createVirtualRegister(RC);
994 unsigned Success = RegInfo.createVirtualRegister(RC);
996 // insert new blocks after the current block
997 const BasicBlock *LLVM_BB = BB->getBasicBlock();
998 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
999 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1000 MachineFunction::iterator It = BB;
1002 MF->insert(It, loopMBB);
1003 MF->insert(It, exitMBB);
1005 // Transfer the remainder of BB and its successor edges to exitMBB.
1006 exitMBB->splice(exitMBB->begin(), BB,
1007 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1008 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1012 // fallthrough --> loopMBB
1013 BB->addSuccessor(loopMBB);
1014 loopMBB->addSuccessor(loopMBB);
1015 loopMBB->addSuccessor(exitMBB);
1018 // ll oldval, 0(ptr)
1019 // <binop> storeval, oldval, incr
1020 // sc success, storeval, 0(ptr)
1021 // beq success, $0, loopMBB
1023 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1025 // and andres, oldval, incr
1026 // nor storeval, $0, andres
1027 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1028 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1029 } else if (BinOpcode) {
1030 // <binop> storeval, oldval, incr
1031 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1035 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1036 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1038 MI->eraseFromParent(); // The instruction is gone now.
1043 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1044 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1045 unsigned SrcReg) const {
1046 const TargetInstrInfo *TII =
1047 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1048 DebugLoc DL = MI->getDebugLoc();
1050 if (Subtarget.hasMips32r2() && Size == 1) {
1051 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1055 if (Subtarget.hasMips32r2() && Size == 2) {
1056 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1060 MachineFunction *MF = BB->getParent();
1061 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1062 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1063 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1066 int64_t ShiftImm = 32 - (Size * 8);
1068 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1069 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1074 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1075 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1077 assert((Size == 1 || Size == 2) &&
1078 "Unsupported size for EmitAtomicBinaryPartial.");
1080 MachineFunction *MF = BB->getParent();
1081 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1082 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1083 const TargetInstrInfo *TII =
1084 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1085 DebugLoc DL = MI->getDebugLoc();
1087 unsigned Dest = MI->getOperand(0).getReg();
1088 unsigned Ptr = MI->getOperand(1).getReg();
1089 unsigned Incr = MI->getOperand(2).getReg();
1091 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1092 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1093 unsigned Mask = RegInfo.createVirtualRegister(RC);
1094 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1095 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1096 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1097 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1098 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1099 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1100 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1101 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1102 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1103 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1104 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1105 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1106 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1107 unsigned Success = RegInfo.createVirtualRegister(RC);
1109 // insert new blocks after the current block
1110 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1111 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1112 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1113 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1114 MachineFunction::iterator It = BB;
1116 MF->insert(It, loopMBB);
1117 MF->insert(It, sinkMBB);
1118 MF->insert(It, exitMBB);
1120 // Transfer the remainder of BB and its successor edges to exitMBB.
1121 exitMBB->splice(exitMBB->begin(), BB,
1122 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1123 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1125 BB->addSuccessor(loopMBB);
1126 loopMBB->addSuccessor(loopMBB);
1127 loopMBB->addSuccessor(sinkMBB);
1128 sinkMBB->addSuccessor(exitMBB);
1131 // addiu masklsb2,$0,-4 # 0xfffffffc
1132 // and alignedaddr,ptr,masklsb2
1133 // andi ptrlsb2,ptr,3
1134 // sll shiftamt,ptrlsb2,3
1135 // ori maskupper,$0,255 # 0xff
1136 // sll mask,maskupper,shiftamt
1137 // nor mask2,$0,mask
1138 // sll incr2,incr,shiftamt
1140 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1141 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1142 .addReg(Mips::ZERO).addImm(-4);
1143 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1144 .addReg(Ptr).addReg(MaskLSB2);
1145 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1146 if (Subtarget.isLittle()) {
1147 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1149 unsigned Off = RegInfo.createVirtualRegister(RC);
1150 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1151 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1152 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1154 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1155 .addReg(Mips::ZERO).addImm(MaskImm);
1156 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1157 .addReg(MaskUpper).addReg(ShiftAmt);
1158 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1159 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1161 // atomic.load.binop
1163 // ll oldval,0(alignedaddr)
1164 // binop binopres,oldval,incr2
1165 // and newval,binopres,mask
1166 // and maskedoldval0,oldval,mask2
1167 // or storeval,maskedoldval0,newval
1168 // sc success,storeval,0(alignedaddr)
1169 // beq success,$0,loopMBB
1173 // ll oldval,0(alignedaddr)
1174 // and newval,incr2,mask
1175 // and maskedoldval0,oldval,mask2
1176 // or storeval,maskedoldval0,newval
1177 // sc success,storeval,0(alignedaddr)
1178 // beq success,$0,loopMBB
1181 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1183 // and andres, oldval, incr2
1184 // nor binopres, $0, andres
1185 // and newval, binopres, mask
1186 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1187 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1188 .addReg(Mips::ZERO).addReg(AndRes);
1189 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1190 } else if (BinOpcode) {
1191 // <binop> binopres, oldval, incr2
1192 // and newval, binopres, mask
1193 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1194 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1195 } else { // atomic.swap
1196 // and newval, incr2, mask
1197 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1200 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1201 .addReg(OldVal).addReg(Mask2);
1202 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1203 .addReg(MaskedOldVal0).addReg(NewVal);
1204 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1205 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1206 BuildMI(BB, DL, TII->get(Mips::BEQ))
1207 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1210 // and maskedoldval1,oldval,mask
1211 // srl srlres,maskedoldval1,shiftamt
1212 // sign_extend dest,srlres
1215 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1216 .addReg(OldVal).addReg(Mask);
1217 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1218 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1219 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1221 MI->eraseFromParent(); // The instruction is gone now.
1226 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1227 MachineBasicBlock *BB,
1228 unsigned Size) const {
1229 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1231 MachineFunction *MF = BB->getParent();
1232 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1233 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1234 const TargetInstrInfo *TII =
1235 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1236 DebugLoc DL = MI->getDebugLoc();
1237 unsigned LL, SC, ZERO, BNE, BEQ;
1240 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1241 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1248 ZERO = Mips::ZERO_64;
1253 unsigned Dest = MI->getOperand(0).getReg();
1254 unsigned Ptr = MI->getOperand(1).getReg();
1255 unsigned OldVal = MI->getOperand(2).getReg();
1256 unsigned NewVal = MI->getOperand(3).getReg();
1258 unsigned Success = RegInfo.createVirtualRegister(RC);
1260 // insert new blocks after the current block
1261 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1262 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1263 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1264 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1265 MachineFunction::iterator It = BB;
1267 MF->insert(It, loop1MBB);
1268 MF->insert(It, loop2MBB);
1269 MF->insert(It, exitMBB);
1271 // Transfer the remainder of BB and its successor edges to exitMBB.
1272 exitMBB->splice(exitMBB->begin(), BB,
1273 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1274 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1278 // fallthrough --> loop1MBB
1279 BB->addSuccessor(loop1MBB);
1280 loop1MBB->addSuccessor(exitMBB);
1281 loop1MBB->addSuccessor(loop2MBB);
1282 loop2MBB->addSuccessor(loop1MBB);
1283 loop2MBB->addSuccessor(exitMBB);
1287 // bne dest, oldval, exitMBB
1289 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1290 BuildMI(BB, DL, TII->get(BNE))
1291 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1294 // sc success, newval, 0(ptr)
1295 // beq success, $0, loop1MBB
1297 BuildMI(BB, DL, TII->get(SC), Success)
1298 .addReg(NewVal).addReg(Ptr).addImm(0);
1299 BuildMI(BB, DL, TII->get(BEQ))
1300 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1302 MI->eraseFromParent(); // The instruction is gone now.
1308 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1309 MachineBasicBlock *BB,
1310 unsigned Size) const {
1311 assert((Size == 1 || Size == 2) &&
1312 "Unsupported size for EmitAtomicCmpSwapPartial.");
1314 MachineFunction *MF = BB->getParent();
1315 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1316 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1317 const TargetInstrInfo *TII =
1318 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1319 DebugLoc DL = MI->getDebugLoc();
1321 unsigned Dest = MI->getOperand(0).getReg();
1322 unsigned Ptr = MI->getOperand(1).getReg();
1323 unsigned CmpVal = MI->getOperand(2).getReg();
1324 unsigned NewVal = MI->getOperand(3).getReg();
1326 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1327 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1328 unsigned Mask = RegInfo.createVirtualRegister(RC);
1329 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1330 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1331 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1332 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1333 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1334 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1335 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1336 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1337 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1338 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1339 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1340 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1341 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1342 unsigned Success = RegInfo.createVirtualRegister(RC);
1344 // insert new blocks after the current block
1345 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1346 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1347 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1348 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1349 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1350 MachineFunction::iterator It = BB;
1352 MF->insert(It, loop1MBB);
1353 MF->insert(It, loop2MBB);
1354 MF->insert(It, sinkMBB);
1355 MF->insert(It, exitMBB);
1357 // Transfer the remainder of BB and its successor edges to exitMBB.
1358 exitMBB->splice(exitMBB->begin(), BB,
1359 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1360 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1362 BB->addSuccessor(loop1MBB);
1363 loop1MBB->addSuccessor(sinkMBB);
1364 loop1MBB->addSuccessor(loop2MBB);
1365 loop2MBB->addSuccessor(loop1MBB);
1366 loop2MBB->addSuccessor(sinkMBB);
1367 sinkMBB->addSuccessor(exitMBB);
1369 // FIXME: computation of newval2 can be moved to loop2MBB.
1371 // addiu masklsb2,$0,-4 # 0xfffffffc
1372 // and alignedaddr,ptr,masklsb2
1373 // andi ptrlsb2,ptr,3
1374 // sll shiftamt,ptrlsb2,3
1375 // ori maskupper,$0,255 # 0xff
1376 // sll mask,maskupper,shiftamt
1377 // nor mask2,$0,mask
1378 // andi maskedcmpval,cmpval,255
1379 // sll shiftedcmpval,maskedcmpval,shiftamt
1380 // andi maskednewval,newval,255
1381 // sll shiftednewval,maskednewval,shiftamt
1382 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1383 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1384 .addReg(Mips::ZERO).addImm(-4);
1385 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1386 .addReg(Ptr).addReg(MaskLSB2);
1387 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1388 if (Subtarget.isLittle()) {
1389 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1391 unsigned Off = RegInfo.createVirtualRegister(RC);
1392 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1393 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1394 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1396 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1397 .addReg(Mips::ZERO).addImm(MaskImm);
1398 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1399 .addReg(MaskUpper).addReg(ShiftAmt);
1400 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1401 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1402 .addReg(CmpVal).addImm(MaskImm);
1403 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1404 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1405 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1406 .addReg(NewVal).addImm(MaskImm);
1407 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1408 .addReg(MaskedNewVal).addReg(ShiftAmt);
1411 // ll oldval,0(alginedaddr)
1412 // and maskedoldval0,oldval,mask
1413 // bne maskedoldval0,shiftedcmpval,sinkMBB
1415 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1416 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1417 .addReg(OldVal).addReg(Mask);
1418 BuildMI(BB, DL, TII->get(Mips::BNE))
1419 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1422 // and maskedoldval1,oldval,mask2
1423 // or storeval,maskedoldval1,shiftednewval
1424 // sc success,storeval,0(alignedaddr)
1425 // beq success,$0,loop1MBB
1427 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1428 .addReg(OldVal).addReg(Mask2);
1429 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1430 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1431 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1432 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1433 BuildMI(BB, DL, TII->get(Mips::BEQ))
1434 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1437 // srl srlres,maskedoldval0,shiftamt
1438 // sign_extend dest,srlres
1441 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1442 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1443 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1445 MI->eraseFromParent(); // The instruction is gone now.
1450 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1451 MachineBasicBlock *BB) const {
1452 MachineFunction *MF = BB->getParent();
1453 const TargetRegisterInfo *TRI =
1454 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1455 const TargetInstrInfo *TII =
1456 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1457 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1458 DebugLoc DL = MI->getDebugLoc();
1459 MachineBasicBlock::iterator II(MI);
1461 unsigned Fc = MI->getOperand(1).getReg();
1462 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1464 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1466 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1469 .addImm(Mips::sub_lo);
1471 // We don't erase the original instruction, we just replace the condition
1472 // register with the 64-bit super-register.
1473 MI->getOperand(1).setReg(Fc2);
1478 //===----------------------------------------------------------------------===//
1479 // Misc Lower Operation implementation
1480 //===----------------------------------------------------------------------===//
1481 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1482 SDValue Chain = Op.getOperand(0);
1483 SDValue Table = Op.getOperand(1);
1484 SDValue Index = Op.getOperand(2);
1486 EVT PTy = getPointerTy();
1487 unsigned EntrySize =
1488 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1490 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1491 DAG.getConstant(EntrySize, PTy));
1492 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1494 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1495 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1496 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1498 Chain = Addr.getValue(1);
1500 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1501 Subtarget.isABI_N64()) {
1502 // For PIC, the sequence is:
1503 // BRIND(load(Jumptable + index) + RelocBase)
1504 // RelocBase can be JumpTable, GOT or some sort of global base.
1505 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1506 getPICJumpTableRelocBase(Table, DAG));
1509 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1512 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1513 // The first operand is the chain, the second is the condition, the third is
1514 // the block to branch to if the condition is true.
1515 SDValue Chain = Op.getOperand(0);
1516 SDValue Dest = Op.getOperand(2);
1519 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1520 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1522 // Return if flag is not set by a floating point comparison.
1523 if (CondRes.getOpcode() != MipsISD::FPCmp)
1526 SDValue CCNode = CondRes.getOperand(2);
1528 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1529 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1530 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1531 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1532 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1533 FCC0, Dest, CondRes);
1536 SDValue MipsTargetLowering::
1537 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1539 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1540 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1542 // Return if flag is not set by a floating point comparison.
1543 if (Cond.getOpcode() != MipsISD::FPCmp)
1546 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1550 SDValue MipsTargetLowering::
1551 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1554 EVT Ty = Op.getOperand(0).getValueType();
1555 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1556 getSetCCResultType(*DAG.getContext(), Ty),
1557 Op.getOperand(0), Op.getOperand(1),
1560 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1564 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1565 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1566 SDValue Cond = createFPCmp(DAG, Op);
1568 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1569 "Floating point operand expected.");
1571 SDValue True = DAG.getConstant(1, MVT::i32);
1572 SDValue False = DAG.getConstant(0, MVT::i32);
1574 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1577 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1578 SelectionDAG &DAG) const {
1579 EVT Ty = Op.getValueType();
1580 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1581 const GlobalValue *GV = N->getGlobal();
1583 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1584 !Subtarget.isABI_N64()) {
1585 const MipsTargetObjectFile &TLOF =
1586 (const MipsTargetObjectFile&)getObjFileLowering();
1588 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine()))
1589 // %gp_rel relocation
1590 return getAddrGPRel(N, Ty, DAG);
1592 // %hi/%lo relocation
1593 return getAddrNonPIC(N, Ty, DAG);
1596 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1597 return getAddrLocal(N, Ty, DAG,
1598 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1601 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1602 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1603 MachinePointerInfo::getGOT());
1605 return getAddrGlobal(N, Ty, DAG,
1606 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1607 ? MipsII::MO_GOT_DISP
1609 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1612 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1613 SelectionDAG &DAG) const {
1614 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1615 EVT Ty = Op.getValueType();
1617 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1618 !Subtarget.isABI_N64())
1619 return getAddrNonPIC(N, Ty, DAG);
1621 return getAddrLocal(N, Ty, DAG,
1622 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1625 SDValue MipsTargetLowering::
1626 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1628 // If the relocation model is PIC, use the General Dynamic TLS Model or
1629 // Local Dynamic TLS model, otherwise use the Initial Exec or
1630 // Local Exec TLS Model.
1632 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1634 const GlobalValue *GV = GA->getGlobal();
1635 EVT PtrVT = getPointerTy();
1637 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1639 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1640 // General Dynamic and Local Dynamic TLS Model.
1641 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1644 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1645 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1646 getGlobalReg(DAG, PtrVT), TGA);
1647 unsigned PtrSize = PtrVT.getSizeInBits();
1648 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1650 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1654 Entry.Node = Argument;
1656 Args.push_back(Entry);
1658 TargetLowering::CallLoweringInfo CLI(DAG);
1659 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1660 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1661 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1663 SDValue Ret = CallResult.first;
1665 if (model != TLSModel::LocalDynamic)
1668 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1669 MipsII::MO_DTPREL_HI);
1670 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1671 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1672 MipsII::MO_DTPREL_LO);
1673 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1674 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1675 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1679 if (model == TLSModel::InitialExec) {
1680 // Initial Exec TLS Model
1681 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1682 MipsII::MO_GOTTPREL);
1683 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1685 Offset = DAG.getLoad(PtrVT, DL,
1686 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1687 false, false, false, 0);
1689 // Local Exec TLS Model
1690 assert(model == TLSModel::LocalExec);
1691 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1692 MipsII::MO_TPREL_HI);
1693 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1694 MipsII::MO_TPREL_LO);
1695 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1696 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1697 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1700 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1701 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1704 SDValue MipsTargetLowering::
1705 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1707 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1708 EVT Ty = Op.getValueType();
1710 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1711 !Subtarget.isABI_N64())
1712 return getAddrNonPIC(N, Ty, DAG);
1714 return getAddrLocal(N, Ty, DAG,
1715 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1718 SDValue MipsTargetLowering::
1719 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1721 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1722 EVT Ty = Op.getValueType();
1724 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1725 !Subtarget.isABI_N64()) {
1726 const MipsTargetObjectFile &TLOF =
1727 (const MipsTargetObjectFile&)getObjFileLowering();
1729 if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1730 // %gp_rel relocation
1731 return getAddrGPRel(N, Ty, DAG);
1733 return getAddrNonPIC(N, Ty, DAG);
1736 return getAddrLocal(N, Ty, DAG,
1737 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1740 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1741 MachineFunction &MF = DAG.getMachineFunction();
1742 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1745 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1748 // vastart just stores the address of the VarArgsFrameIndex slot into the
1749 // memory location argument.
1750 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1751 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1752 MachinePointerInfo(SV), false, false, 0);
1755 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1756 SDNode *Node = Op.getNode();
1757 EVT VT = Node->getValueType(0);
1758 SDValue Chain = Node->getOperand(0);
1759 SDValue VAListPtr = Node->getOperand(1);
1760 unsigned Align = Node->getConstantOperandVal(3);
1761 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1763 unsigned ArgSlotSizeInBytes =
1764 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1766 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1767 MachinePointerInfo(SV), false, false, false,
1769 SDValue VAList = VAListLoad;
1771 // Re-align the pointer if necessary.
1772 // It should only ever be necessary for 64-bit types on O32 since the minimum
1773 // argument alignment is the same as the maximum type alignment for N32/N64.
1775 // FIXME: We currently align too often. The code generator doesn't notice
1776 // when the pointer is still aligned from the last va_arg (or pair of
1777 // va_args for the i64 on O32 case).
1778 if (Align > getMinStackArgumentAlignment()) {
1779 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1781 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1782 DAG.getConstant(Align - 1,
1783 VAList.getValueType()));
1785 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1786 DAG.getConstant(-(int64_t)Align,
1787 VAList.getValueType()));
1790 // Increment the pointer, VAList, to the next vaarg.
1791 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1792 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1793 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1794 VAList.getValueType()));
1795 // Store the incremented VAList to the legalized pointer
1796 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1797 MachinePointerInfo(SV), false, false, 0);
1799 // In big-endian mode we must adjust the pointer when the load size is smaller
1800 // than the argument slot size. We must also reduce the known alignment to
1801 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1802 // the correct half of the slot, and reduce the alignment from 8 (slot
1803 // alignment) down to 4 (type alignment).
1804 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1805 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1806 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1807 DAG.getIntPtrConstant(Adjustment));
1809 // Load the actual argument out of the pointer VAList
1810 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1814 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1815 bool HasExtractInsert) {
1816 EVT TyX = Op.getOperand(0).getValueType();
1817 EVT TyY = Op.getOperand(1).getValueType();
1818 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1819 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1823 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1825 SDValue X = (TyX == MVT::f32) ?
1826 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1827 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1829 SDValue Y = (TyY == MVT::f32) ?
1830 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1831 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1834 if (HasExtractInsert) {
1835 // ext E, Y, 31, 1 ; extract bit31 of Y
1836 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1837 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1838 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1841 // srl SrlX, SllX, 1
1843 // sll SllY, SrlX, 31
1844 // or Or, SrlX, SllY
1845 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1846 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1847 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1848 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1849 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1852 if (TyX == MVT::f32)
1853 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1855 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1856 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1857 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1860 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1861 bool HasExtractInsert) {
1862 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1863 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1864 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1865 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1868 // Bitcast to integer nodes.
1869 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1870 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1872 if (HasExtractInsert) {
1873 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1874 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1875 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1876 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1878 if (WidthX > WidthY)
1879 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1880 else if (WidthY > WidthX)
1881 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1883 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1884 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1885 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1888 // (d)sll SllX, X, 1
1889 // (d)srl SrlX, SllX, 1
1890 // (d)srl SrlY, Y, width(Y)-1
1891 // (d)sll SllY, SrlX, width(Y)-1
1892 // or Or, SrlX, SllY
1893 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1894 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1895 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1896 DAG.getConstant(WidthY - 1, MVT::i32));
1898 if (WidthX > WidthY)
1899 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1900 else if (WidthY > WidthX)
1901 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1903 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1904 DAG.getConstant(WidthX - 1, MVT::i32));
1905 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1906 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1910 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1911 if (Subtarget.isGP64bit())
1912 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1914 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1917 SDValue MipsTargetLowering::
1918 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1920 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1921 "Frame address can only be determined for current frame.");
1923 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1924 MFI->setFrameAddressIsTaken(true);
1925 EVT VT = Op.getValueType();
1928 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1929 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
1933 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1934 SelectionDAG &DAG) const {
1935 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1939 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1940 "Return address can be determined only for current frame.");
1942 MachineFunction &MF = DAG.getMachineFunction();
1943 MachineFrameInfo *MFI = MF.getFrameInfo();
1944 MVT VT = Op.getSimpleValueType();
1945 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
1946 MFI->setReturnAddressIsTaken(true);
1948 // Return RA, which contains the return address. Mark it an implicit live-in.
1949 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1950 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1953 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1954 // generated from __builtin_eh_return (offset, handler)
1955 // The effect of this is to adjust the stack pointer by "offset"
1956 // and then branch to "handler".
1957 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1959 MachineFunction &MF = DAG.getMachineFunction();
1960 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1962 MipsFI->setCallsEhReturn();
1963 SDValue Chain = Op.getOperand(0);
1964 SDValue Offset = Op.getOperand(1);
1965 SDValue Handler = Op.getOperand(2);
1967 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
1969 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1970 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1971 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
1972 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
1973 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1974 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1975 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1976 DAG.getRegister(OffsetReg, Ty),
1977 DAG.getRegister(AddrReg, getPointerTy()),
1981 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1982 SelectionDAG &DAG) const {
1983 // FIXME: Need pseudo-fence for 'singlethread' fences
1984 // FIXME: Set SType for weaker fences where supported/appropriate.
1987 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1988 DAG.getConstant(SType, MVT::i32));
1991 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1992 SelectionDAG &DAG) const {
1994 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1995 SDValue Shamt = Op.getOperand(2);
1998 // lo = (shl lo, shamt)
1999 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2002 // hi = (shl lo, shamt[4:0])
2003 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2004 DAG.getConstant(-1, MVT::i32));
2005 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2006 DAG.getConstant(1, MVT::i32));
2007 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2009 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2010 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2011 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2012 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2013 DAG.getConstant(0x20, MVT::i32));
2014 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2015 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2016 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2018 SDValue Ops[2] = {Lo, Hi};
2019 return DAG.getMergeValues(Ops, DL);
2022 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2025 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2026 SDValue Shamt = Op.getOperand(2);
2029 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2031 // hi = (sra hi, shamt)
2033 // hi = (srl hi, shamt)
2036 // lo = (sra hi, shamt[4:0])
2037 // hi = (sra hi, 31)
2039 // lo = (srl hi, shamt[4:0])
2041 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2042 DAG.getConstant(-1, MVT::i32));
2043 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2044 DAG.getConstant(1, MVT::i32));
2045 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2046 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2047 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2048 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2050 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2051 DAG.getConstant(0x20, MVT::i32));
2052 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2053 DAG.getConstant(31, MVT::i32));
2054 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2055 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2056 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2059 SDValue Ops[2] = {Lo, Hi};
2060 return DAG.getMergeValues(Ops, DL);
2063 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2064 SDValue Chain, SDValue Src, unsigned Offset) {
2065 SDValue Ptr = LD->getBasePtr();
2066 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2067 EVT BasePtrVT = Ptr.getValueType();
2069 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2072 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2073 DAG.getConstant(Offset, BasePtrVT));
2075 SDValue Ops[] = { Chain, Ptr, Src };
2076 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2077 LD->getMemOperand());
2080 // Expand an unaligned 32 or 64-bit integer load node.
2081 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2082 LoadSDNode *LD = cast<LoadSDNode>(Op);
2083 EVT MemVT = LD->getMemoryVT();
2085 if (Subtarget.systemSupportsUnalignedAccess())
2088 // Return if load is aligned or if MemVT is neither i32 nor i64.
2089 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2090 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2093 bool IsLittle = Subtarget.isLittle();
2094 EVT VT = Op.getValueType();
2095 ISD::LoadExtType ExtType = LD->getExtensionType();
2096 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2098 assert((VT == MVT::i32) || (VT == MVT::i64));
2101 // (set dst, (i64 (load baseptr)))
2103 // (set tmp, (ldl (add baseptr, 7), undef))
2104 // (set dst, (ldr baseptr, tmp))
2105 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2106 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2108 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2112 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2114 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2118 // (set dst, (i32 (load baseptr))) or
2119 // (set dst, (i64 (sextload baseptr))) or
2120 // (set dst, (i64 (extload baseptr)))
2122 // (set tmp, (lwl (add baseptr, 3), undef))
2123 // (set dst, (lwr baseptr, tmp))
2124 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2125 (ExtType == ISD::EXTLOAD))
2128 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2131 // (set dst, (i64 (zextload baseptr)))
2133 // (set tmp0, (lwl (add baseptr, 3), undef))
2134 // (set tmp1, (lwr baseptr, tmp0))
2135 // (set tmp2, (shl tmp1, 32))
2136 // (set dst, (srl tmp2, 32))
2138 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2139 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2140 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2141 SDValue Ops[] = { SRL, LWR.getValue(1) };
2142 return DAG.getMergeValues(Ops, DL);
2145 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2146 SDValue Chain, unsigned Offset) {
2147 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2148 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2150 SDVTList VTList = DAG.getVTList(MVT::Other);
2153 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2154 DAG.getConstant(Offset, BasePtrVT));
2156 SDValue Ops[] = { Chain, Value, Ptr };
2157 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2158 SD->getMemOperand());
2161 // Expand an unaligned 32 or 64-bit integer store node.
2162 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2164 SDValue Value = SD->getValue(), Chain = SD->getChain();
2165 EVT VT = Value.getValueType();
2168 // (store val, baseptr) or
2169 // (truncstore val, baseptr)
2171 // (swl val, (add baseptr, 3))
2172 // (swr val, baseptr)
2173 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2174 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2176 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2179 assert(VT == MVT::i64);
2182 // (store val, baseptr)
2184 // (sdl val, (add baseptr, 7))
2185 // (sdr val, baseptr)
2186 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2187 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2190 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2191 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2192 SDValue Val = SD->getValue();
2194 if (Val.getOpcode() != ISD::FP_TO_SINT)
2197 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2198 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2201 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2202 SD->getPointerInfo(), SD->isVolatile(),
2203 SD->isNonTemporal(), SD->getAlignment());
2206 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2207 StoreSDNode *SD = cast<StoreSDNode>(Op);
2208 EVT MemVT = SD->getMemoryVT();
2210 // Lower unaligned integer stores.
2211 if (!Subtarget.systemSupportsUnalignedAccess() &&
2212 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2213 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2214 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2216 return lowerFP_TO_SINT_STORE(SD, DAG);
2219 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2220 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2221 || cast<ConstantSDNode>
2222 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2223 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2227 // (add (frameaddr 0), (frame_to_args_offset))
2228 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2229 // (add FrameObject, 0)
2230 // where FrameObject is a fixed StackObject with offset 0 which points to
2231 // the old stack pointer.
2232 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2233 EVT ValTy = Op->getValueType(0);
2234 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2235 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2236 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2237 DAG.getConstant(0, ValTy));
2240 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2241 SelectionDAG &DAG) const {
2242 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2243 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2245 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2248 //===----------------------------------------------------------------------===//
2249 // Calling Convention Implementation
2250 //===----------------------------------------------------------------------===//
2252 //===----------------------------------------------------------------------===//
2253 // TODO: Implement a generic logic using tblgen that can support this.
2254 // Mips O32 ABI rules:
2256 // i32 - Passed in A0, A1, A2, A3 and stack
2257 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2258 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2259 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2260 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2261 // not used, it must be shadowed. If only A3 is available, shadow it and
2264 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2265 //===----------------------------------------------------------------------===//
2267 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2268 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2269 CCState &State, const MCPhysReg *F64Regs) {
2271 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2273 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2274 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2276 // Do not process byval args here.
2277 if (ArgFlags.isByVal())
2280 // Promote i8 and i16
2281 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2283 if (ArgFlags.isSExt())
2284 LocInfo = CCValAssign::SExt;
2285 else if (ArgFlags.isZExt())
2286 LocInfo = CCValAssign::ZExt;
2288 LocInfo = CCValAssign::AExt;
2293 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2294 // is true: function is vararg, argument is 3rd or higher, there is previous
2295 // argument which is not f32 or f64.
2296 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2297 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2298 unsigned OrigAlign = ArgFlags.getOrigAlign();
2299 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2301 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2302 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2303 // If this is the first part of an i64 arg,
2304 // the allocated register must be either A0 or A2.
2305 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2306 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2308 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2309 // Allocate int register and shadow next int register. If first
2310 // available register is Mips::A1 or Mips::A3, shadow it too.
2311 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2312 if (Reg == Mips::A1 || Reg == Mips::A3)
2313 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2314 State.AllocateReg(IntRegs, IntRegsSize);
2316 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2317 // we are guaranteed to find an available float register
2318 if (ValVT == MVT::f32) {
2319 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2320 // Shadow int register
2321 State.AllocateReg(IntRegs, IntRegsSize);
2323 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2324 // Shadow int registers
2325 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2326 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2327 State.AllocateReg(IntRegs, IntRegsSize);
2328 State.AllocateReg(IntRegs, IntRegsSize);
2331 llvm_unreachable("Cannot handle this ValVT.");
2334 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2336 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2338 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2343 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2344 MVT LocVT, CCValAssign::LocInfo LocInfo,
2345 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2346 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2348 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2351 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2352 MVT LocVT, CCValAssign::LocInfo LocInfo,
2353 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2354 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2356 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2359 #include "MipsGenCallingConv.inc"
2361 //===----------------------------------------------------------------------===//
2362 // Call Calling Convention Implementation
2363 //===----------------------------------------------------------------------===//
2365 // Return next O32 integer argument register.
2366 static unsigned getNextIntArgReg(unsigned Reg) {
2367 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2368 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2372 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2373 SDValue Chain, SDValue Arg, SDLoc DL,
2374 bool IsTailCall, SelectionDAG &DAG) const {
2376 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2377 DAG.getIntPtrConstant(Offset));
2378 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2382 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2383 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2384 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2385 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2386 /*isVolatile=*/ true, false, 0);
2389 void MipsTargetLowering::
2390 getOpndList(SmallVectorImpl<SDValue> &Ops,
2391 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2392 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2393 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2394 SDValue Chain) const {
2395 // Insert node "GP copy globalreg" before call to function.
2397 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2398 // in PIC mode) allow symbols to be resolved via lazy binding.
2399 // The lazy binding stub requires GP to point to the GOT.
2400 // Note that we don't need GP to point to the GOT for indirect calls
2401 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2402 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2403 // used for the function (that is, Mips linker doesn't generate lazy binding
2404 // stub for a function whose address is taken in the program).
2405 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2406 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2407 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2408 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2411 // Build a sequence of copy-to-reg nodes chained together with token
2412 // chain and flag operands which copy the outgoing args into registers.
2413 // The InFlag in necessary since all emitted instructions must be
2417 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2418 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2419 RegsToPass[i].second, InFlag);
2420 InFlag = Chain.getValue(1);
2423 // Add argument registers to the end of the list so that they are
2424 // known live into the call.
2425 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2426 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2427 RegsToPass[i].second.getValueType()));
2429 // Add a register mask operand representing the call-preserved registers.
2430 const TargetRegisterInfo *TRI =
2431 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2432 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2433 assert(Mask && "Missing call preserved mask for calling convention");
2434 if (Subtarget.inMips16HardFloat()) {
2435 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2436 llvm::StringRef Sym = G->getGlobal()->getName();
2437 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2438 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2439 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2443 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2445 if (InFlag.getNode())
2446 Ops.push_back(InFlag);
2449 /// LowerCall - functions arguments are copied from virtual regs to
2450 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2452 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2453 SmallVectorImpl<SDValue> &InVals) const {
2454 SelectionDAG &DAG = CLI.DAG;
2456 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2457 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2458 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2459 SDValue Chain = CLI.Chain;
2460 SDValue Callee = CLI.Callee;
2461 bool &IsTailCall = CLI.IsTailCall;
2462 CallingConv::ID CallConv = CLI.CallConv;
2463 bool IsVarArg = CLI.IsVarArg;
2465 MachineFunction &MF = DAG.getMachineFunction();
2466 MachineFrameInfo *MFI = MF.getFrameInfo();
2467 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2468 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2469 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2471 // Analyze operands of the call, assigning locations to each operand.
2472 SmallVector<CCValAssign, 16> ArgLocs;
2474 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2475 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2477 // Allocate the reserved argument area. It seems strange to do this from the
2478 // caller side but removing it breaks the frame size calculation.
2479 const MipsABIInfo &ABI = Subtarget.getABI();
2480 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2482 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2484 // Get a count of how many bytes are to be pushed on the stack.
2485 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2487 // Check if it's really possible to do a tail call.
2489 IsTailCall = isEligibleForTailCallOptimization(
2490 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2492 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2493 report_fatal_error("failed to perform tail call elimination on a call "
2494 "site marked musttail");
2499 // Chain is the output chain of the last Load/Store or CopyToReg node.
2500 // ByValChain is the output chain of the last Memcpy node created for copying
2501 // byval arguments to the stack.
2502 unsigned StackAlignment = TFL->getStackAlignment();
2503 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2504 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2507 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2509 SDValue StackPtr = DAG.getCopyFromReg(
2510 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2513 // With EABI is it possible to have 16 args on registers.
2514 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2515 SmallVector<SDValue, 8> MemOpChains;
2517 CCInfo.rewindByValRegsInfo();
2519 // Walk the register/memloc assignments, inserting copies/loads.
2520 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2521 SDValue Arg = OutVals[i];
2522 CCValAssign &VA = ArgLocs[i];
2523 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2524 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2527 if (Flags.isByVal()) {
2528 unsigned FirstByValReg, LastByValReg;
2529 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2530 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2532 assert(Flags.getByValSize() &&
2533 "ByVal args of size 0 should have been ignored by front-end.");
2534 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2535 assert(!IsTailCall &&
2536 "Do not tail-call optimize if there is a byval argument.");
2537 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2538 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2540 CCInfo.nextInRegsParam();
2544 // Promote the value if needed.
2545 switch (VA.getLocInfo()) {
2546 default: llvm_unreachable("Unknown loc info!");
2547 case CCValAssign::Full:
2548 if (VA.isRegLoc()) {
2549 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2550 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2551 (ValVT == MVT::i64 && LocVT == MVT::f64))
2552 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2553 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2554 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2555 Arg, DAG.getConstant(0, MVT::i32));
2556 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2557 Arg, DAG.getConstant(1, MVT::i32));
2558 if (!Subtarget.isLittle())
2560 unsigned LocRegLo = VA.getLocReg();
2561 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2562 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2563 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2568 case CCValAssign::BCvt:
2569 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2571 case CCValAssign::SExt:
2572 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2574 case CCValAssign::ZExt:
2575 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2577 case CCValAssign::AExt:
2578 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2582 // Arguments that can be passed on register must be kept at
2583 // RegsToPass vector
2584 if (VA.isRegLoc()) {
2585 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2589 // Register can't get to this point...
2590 assert(VA.isMemLoc());
2592 // emit ISD::STORE whichs stores the
2593 // parameter value to a stack Location
2594 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2595 Chain, Arg, DL, IsTailCall, DAG));
2598 // Transform all store nodes into one single node because all store
2599 // nodes are independent of each other.
2600 if (!MemOpChains.empty())
2601 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2603 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2604 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2605 // node so that legalize doesn't hack it.
2607 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2609 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2611 EVT Ty = Callee.getValueType();
2613 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2615 const GlobalValue *Val = G->getGlobal();
2616 InternalLinkage = Val->hasInternalLinkage();
2618 if (InternalLinkage)
2619 Callee = getAddrLocal(G, Ty, DAG,
2620 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2621 else if (LargeGOT) {
2622 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2623 MipsII::MO_CALL_LO16, Chain,
2624 FuncInfo->callPtrInfo(Val));
2627 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2628 FuncInfo->callPtrInfo(Val));
2632 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2633 MipsII::MO_NO_FLAG);
2634 GlobalOrExternal = true;
2636 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2637 const char *Sym = S->getSymbol();
2639 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2640 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2641 MipsII::MO_NO_FLAG);
2642 else if (LargeGOT) {
2643 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2644 MipsII::MO_CALL_LO16, Chain,
2645 FuncInfo->callPtrInfo(Sym));
2647 } else { // N64 || PIC
2648 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2649 FuncInfo->callPtrInfo(Sym));
2653 GlobalOrExternal = true;
2656 SmallVector<SDValue, 8> Ops(1, Chain);
2657 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2659 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2660 IsCallReloc, CLI, Callee, Chain);
2663 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2665 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2666 SDValue InFlag = Chain.getValue(1);
2668 // Create the CALLSEQ_END node.
2669 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2670 DAG.getIntPtrConstant(0, true), InFlag, DL);
2671 InFlag = Chain.getValue(1);
2673 // Handle result values, copying them out of physregs into vregs that we
2675 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2679 /// LowerCallResult - Lower the result values of a call into the
2680 /// appropriate copies out of appropriate physical registers.
2681 SDValue MipsTargetLowering::LowerCallResult(
2682 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2683 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2684 SmallVectorImpl<SDValue> &InVals,
2685 TargetLowering::CallLoweringInfo &CLI) const {
2686 // Assign locations to each value returned by this call.
2687 SmallVector<CCValAssign, 16> RVLocs;
2688 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2690 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2692 // Copy all of the result registers out of their specified physreg.
2693 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2694 CCValAssign &VA = RVLocs[i];
2695 assert(VA.isRegLoc() && "Can only return in registers!");
2697 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2698 RVLocs[i].getLocVT(), InFlag);
2699 Chain = Val.getValue(1);
2700 InFlag = Val.getValue(2);
2702 if (VA.isUpperBitsInLoc()) {
2703 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2704 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2706 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2708 Shift, DL, VA.getLocVT(), Val,
2709 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2712 switch (VA.getLocInfo()) {
2714 llvm_unreachable("Unknown loc info!");
2715 case CCValAssign::Full:
2717 case CCValAssign::BCvt:
2718 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2720 case CCValAssign::AExt:
2721 case CCValAssign::AExtUpper:
2722 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2724 case CCValAssign::ZExt:
2725 case CCValAssign::ZExtUpper:
2726 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2727 DAG.getValueType(VA.getValVT()));
2728 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2730 case CCValAssign::SExt:
2731 case CCValAssign::SExtUpper:
2732 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2733 DAG.getValueType(VA.getValVT()));
2734 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2738 InVals.push_back(Val);
2744 //===----------------------------------------------------------------------===//
2745 // Formal Arguments Calling Convention Implementation
2746 //===----------------------------------------------------------------------===//
2747 /// LowerFormalArguments - transform physical registers into virtual registers
2748 /// and generate load operations for arguments places on the stack.
2750 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2751 CallingConv::ID CallConv,
2753 const SmallVectorImpl<ISD::InputArg> &Ins,
2754 SDLoc DL, SelectionDAG &DAG,
2755 SmallVectorImpl<SDValue> &InVals)
2757 MachineFunction &MF = DAG.getMachineFunction();
2758 MachineFrameInfo *MFI = MF.getFrameInfo();
2759 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2761 MipsFI->setVarArgsFrameIndex(0);
2763 // Used with vargs to acumulate store chains.
2764 std::vector<SDValue> OutChains;
2766 // Assign locations to all of the incoming arguments.
2767 SmallVector<CCValAssign, 16> ArgLocs;
2768 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2770 const MipsABIInfo &ABI = Subtarget.getABI();
2771 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2772 Function::const_arg_iterator FuncArg =
2773 DAG.getMachineFunction().getFunction()->arg_begin();
2775 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2776 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2777 CCInfo.getInRegsParamsCount() > 0);
2779 unsigned CurArgIdx = 0;
2780 CCInfo.rewindByValRegsInfo();
2782 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2783 CCValAssign &VA = ArgLocs[i];
2784 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2785 CurArgIdx = Ins[i].OrigArgIndex;
2786 EVT ValVT = VA.getValVT();
2787 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2788 bool IsRegLoc = VA.isRegLoc();
2790 if (Flags.isByVal()) {
2791 unsigned FirstByValReg, LastByValReg;
2792 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2793 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2795 assert(Flags.getByValSize() &&
2796 "ByVal args of size 0 should have been ignored by front-end.");
2797 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2798 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2799 FirstByValReg, LastByValReg, VA, CCInfo);
2800 CCInfo.nextInRegsParam();
2804 // Arguments stored on registers
2806 MVT RegVT = VA.getLocVT();
2807 unsigned ArgReg = VA.getLocReg();
2808 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2810 // Transform the arguments stored on
2811 // physical registers into virtual ones
2812 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2813 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2815 // If this is an 8 or 16-bit value, it has been passed promoted
2816 // to 32 bits. Insert an assert[sz]ext to capture this, then
2817 // truncate to the right size.
2818 switch (VA.getLocInfo()) {
2820 llvm_unreachable("Unknown loc info!");
2821 case CCValAssign::Full:
2823 case CCValAssign::SExt:
2824 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2825 DAG.getValueType(ValVT));
2826 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2828 case CCValAssign::ZExt:
2829 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2830 DAG.getValueType(ValVT));
2831 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2833 case CCValAssign::BCvt:
2834 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2838 // Handle floating point arguments passed in integer registers and
2839 // long double arguments passed in floating point registers.
2840 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2841 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2842 (RegVT == MVT::f64 && ValVT == MVT::i64))
2843 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2844 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2845 ValVT == MVT::f64) {
2846 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2847 getNextIntArgReg(ArgReg), RC);
2848 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2849 if (!Subtarget.isLittle())
2850 std::swap(ArgValue, ArgValue2);
2851 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2852 ArgValue, ArgValue2);
2855 InVals.push_back(ArgValue);
2856 } else { // VA.isRegLoc()
2859 assert(VA.isMemLoc());
2861 // The stack pointer offset is relative to the caller stack frame.
2862 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2863 VA.getLocMemOffset(), true);
2865 // Create load nodes to retrieve arguments from the stack
2866 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2867 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2868 MachinePointerInfo::getFixedStack(FI),
2869 false, false, false, 0);
2870 InVals.push_back(Load);
2871 OutChains.push_back(Load.getValue(1));
2875 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2876 // The mips ABIs for returning structs by value requires that we copy
2877 // the sret argument into $v0 for the return. Save the argument into
2878 // a virtual register so that we can access it from the return points.
2879 if (Ins[i].Flags.isSRet()) {
2880 unsigned Reg = MipsFI->getSRetReturnReg();
2882 Reg = MF.getRegInfo().createVirtualRegister(
2883 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2884 MipsFI->setSRetReturnReg(Reg);
2886 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2887 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2893 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
2895 // All stores are grouped in one node to allow the matching between
2896 // the size of Ins and InVals. This only happens when on varg functions
2897 if (!OutChains.empty()) {
2898 OutChains.push_back(Chain);
2899 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2905 //===----------------------------------------------------------------------===//
2906 // Return Value Calling Convention Implementation
2907 //===----------------------------------------------------------------------===//
2910 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2911 MachineFunction &MF, bool IsVarArg,
2912 const SmallVectorImpl<ISD::OutputArg> &Outs,
2913 LLVMContext &Context) const {
2914 SmallVector<CCValAssign, 16> RVLocs;
2915 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2916 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2920 MipsTargetLowering::LowerReturn(SDValue Chain,
2921 CallingConv::ID CallConv, bool IsVarArg,
2922 const SmallVectorImpl<ISD::OutputArg> &Outs,
2923 const SmallVectorImpl<SDValue> &OutVals,
2924 SDLoc DL, SelectionDAG &DAG) const {
2925 // CCValAssign - represent the assignment of
2926 // the return value to a location
2927 SmallVector<CCValAssign, 16> RVLocs;
2928 MachineFunction &MF = DAG.getMachineFunction();
2930 // CCState - Info about the registers and stack slot.
2931 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
2933 // Analyze return values.
2934 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2937 SmallVector<SDValue, 4> RetOps(1, Chain);
2939 // Copy the result values into the output registers.
2940 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2941 SDValue Val = OutVals[i];
2942 CCValAssign &VA = RVLocs[i];
2943 assert(VA.isRegLoc() && "Can only return in registers!");
2944 bool UseUpperBits = false;
2946 switch (VA.getLocInfo()) {
2948 llvm_unreachable("Unknown loc info!");
2949 case CCValAssign::Full:
2951 case CCValAssign::BCvt:
2952 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
2954 case CCValAssign::AExtUpper:
2955 UseUpperBits = true;
2957 case CCValAssign::AExt:
2958 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
2960 case CCValAssign::ZExtUpper:
2961 UseUpperBits = true;
2963 case CCValAssign::ZExt:
2964 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
2966 case CCValAssign::SExtUpper:
2967 UseUpperBits = true;
2969 case CCValAssign::SExt:
2970 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
2975 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2976 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2978 ISD::SHL, DL, VA.getLocVT(), Val,
2979 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2982 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2984 // Guarantee that all emitted copies are stuck together with flags.
2985 Flag = Chain.getValue(1);
2986 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2989 // The mips ABIs for returning structs by value requires that we copy
2990 // the sret argument into $v0 for the return. We saved the argument into
2991 // a virtual register in the entry block, so now we copy the value out
2993 if (MF.getFunction()->hasStructRetAttr()) {
2994 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2995 unsigned Reg = MipsFI->getSRetReturnReg();
2998 llvm_unreachable("sret virtual register not created in the entry block");
2999 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3000 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3002 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3003 Flag = Chain.getValue(1);
3004 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3007 RetOps[0] = Chain; // Update chain.
3009 // Add the flag if we have it.
3011 RetOps.push_back(Flag);
3013 // Return on Mips is always a "jr $ra"
3014 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3017 //===----------------------------------------------------------------------===//
3018 // Mips Inline Assembly Support
3019 //===----------------------------------------------------------------------===//
3021 /// getConstraintType - Given a constraint letter, return the type of
3022 /// constraint it is for this target.
3023 MipsTargetLowering::ConstraintType MipsTargetLowering::
3024 getConstraintType(const std::string &Constraint) const
3026 // Mips specific constraints
3027 // GCC config/mips/constraints.md
3029 // 'd' : An address register. Equivalent to r
3030 // unless generating MIPS16 code.
3031 // 'y' : Equivalent to r; retained for
3032 // backwards compatibility.
3033 // 'c' : A register suitable for use in an indirect
3034 // jump. This will always be $25 for -mabicalls.
3035 // 'l' : The lo register. 1 word storage.
3036 // 'x' : The hilo register pair. Double word storage.
3037 if (Constraint.size() == 1) {
3038 switch (Constraint[0]) {
3046 return C_RegisterClass;
3051 return TargetLowering::getConstraintType(Constraint);
3054 /// Examine constraint type and operand type and determine a weight value.
3055 /// This object must already have been set up with the operand type
3056 /// and the current alternative constraint selected.
3057 TargetLowering::ConstraintWeight
3058 MipsTargetLowering::getSingleConstraintMatchWeight(
3059 AsmOperandInfo &info, const char *constraint) const {
3060 ConstraintWeight weight = CW_Invalid;
3061 Value *CallOperandVal = info.CallOperandVal;
3062 // If we don't have a value, we can't do a match,
3063 // but allow it at the lowest weight.
3064 if (!CallOperandVal)
3066 Type *type = CallOperandVal->getType();
3067 // Look at the constraint type.
3068 switch (*constraint) {
3070 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3074 if (type->isIntegerTy())
3075 weight = CW_Register;
3077 case 'f': // FPU or MSA register
3078 if (Subtarget.hasMSA() && type->isVectorTy() &&
3079 cast<VectorType>(type)->getBitWidth() == 128)
3080 weight = CW_Register;
3081 else if (type->isFloatTy())
3082 weight = CW_Register;
3084 case 'c': // $25 for indirect jumps
3085 case 'l': // lo register
3086 case 'x': // hilo register pair
3087 if (type->isIntegerTy())
3088 weight = CW_SpecificReg;
3090 case 'I': // signed 16 bit immediate
3091 case 'J': // integer zero
3092 case 'K': // unsigned 16 bit immediate
3093 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3094 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3095 case 'O': // signed 15 bit immediate (+- 16383)
3096 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3097 if (isa<ConstantInt>(CallOperandVal))
3098 weight = CW_Constant;
3107 /// This is a helper function to parse a physical register string and split it
3108 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3109 /// that is returned indicates whether parsing was successful. The second flag
3110 /// is true if the numeric part exists.
3111 static std::pair<bool, bool>
3112 parsePhysicalReg(StringRef C, std::string &Prefix,
3113 unsigned long long &Reg) {
3114 if (C.front() != '{' || C.back() != '}')
3115 return std::make_pair(false, false);
3117 // Search for the first numeric character.
3118 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3119 I = std::find_if(B, E, std::ptr_fun(isdigit));
3121 Prefix.assign(B, I - B);
3123 // The second flag is set to false if no numeric characters were found.
3125 return std::make_pair(true, false);
3127 // Parse the numeric characters.
3128 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3132 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3133 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3134 const TargetRegisterInfo *TRI =
3135 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3136 const TargetRegisterClass *RC;
3138 unsigned long long Reg;
3140 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3143 return std::make_pair(0U, nullptr);
3145 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3146 // No numeric characters follow "hi" or "lo".
3148 return std::make_pair(0U, nullptr);
3150 RC = TRI->getRegClass(Prefix == "hi" ?
3151 Mips::HI32RegClassID : Mips::LO32RegClassID);
3152 return std::make_pair(*(RC->begin()), RC);
3153 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3154 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3156 // No numeric characters follow the name.
3158 return std::make_pair(0U, nullptr);
3160 Reg = StringSwitch<unsigned long long>(Prefix)
3161 .Case("$msair", Mips::MSAIR)
3162 .Case("$msacsr", Mips::MSACSR)
3163 .Case("$msaaccess", Mips::MSAAccess)
3164 .Case("$msasave", Mips::MSASave)
3165 .Case("$msamodify", Mips::MSAModify)
3166 .Case("$msarequest", Mips::MSARequest)
3167 .Case("$msamap", Mips::MSAMap)
3168 .Case("$msaunmap", Mips::MSAUnmap)
3172 return std::make_pair(0U, nullptr);
3174 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3175 return std::make_pair(Reg, RC);
3179 return std::make_pair(0U, nullptr);
3181 if (Prefix == "$f") { // Parse $f0-$f31.
3182 // If the size of FP registers is 64-bit or Reg is an even number, select
3183 // the 64-bit register class. Otherwise, select the 32-bit register class.
3184 if (VT == MVT::Other)
3185 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3187 RC = getRegClassFor(VT);
3189 if (RC == &Mips::AFGR64RegClass) {
3190 assert(Reg % 2 == 0);
3193 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3194 RC = TRI->getRegClass(Mips::FCCRegClassID);
3195 else if (Prefix == "$w") { // Parse $w0-$w31.
3196 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3197 } else { // Parse $0-$31.
3198 assert(Prefix == "$");
3199 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3202 assert(Reg < RC->getNumRegs());
3203 return std::make_pair(*(RC->begin() + Reg), RC);
3206 /// Given a register class constraint, like 'r', if this corresponds directly
3207 /// to an LLVM register class, return a register of 0 and the register class
3209 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3210 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3212 if (Constraint.size() == 1) {
3213 switch (Constraint[0]) {
3214 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3215 case 'y': // Same as 'r'. Exists for compatibility.
3217 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3218 if (Subtarget.inMips16Mode())
3219 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3220 return std::make_pair(0U, &Mips::GPR32RegClass);
3222 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3223 return std::make_pair(0U, &Mips::GPR32RegClass);
3224 if (VT == MVT::i64 && Subtarget.isGP64bit())
3225 return std::make_pair(0U, &Mips::GPR64RegClass);
3226 // This will generate an error message
3227 return std::make_pair(0U, nullptr);
3228 case 'f': // FPU or MSA register
3229 if (VT == MVT::v16i8)
3230 return std::make_pair(0U, &Mips::MSA128BRegClass);
3231 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3232 return std::make_pair(0U, &Mips::MSA128HRegClass);
3233 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3234 return std::make_pair(0U, &Mips::MSA128WRegClass);
3235 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3236 return std::make_pair(0U, &Mips::MSA128DRegClass);
3237 else if (VT == MVT::f32)
3238 return std::make_pair(0U, &Mips::FGR32RegClass);
3239 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3240 if (Subtarget.isFP64bit())
3241 return std::make_pair(0U, &Mips::FGR64RegClass);
3242 return std::make_pair(0U, &Mips::AFGR64RegClass);
3245 case 'c': // register suitable for indirect jump
3247 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3248 assert(VT == MVT::i64 && "Unexpected type.");
3249 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3250 case 'l': // register suitable for indirect jump
3252 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3253 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3254 case 'x': // register suitable for indirect jump
3255 // Fixme: Not triggering the use of both hi and low
3256 // This will generate an error message
3257 return std::make_pair(0U, nullptr);
3261 std::pair<unsigned, const TargetRegisterClass *> R;
3262 R = parseRegForInlineAsmConstraint(Constraint, VT);
3267 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3270 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3271 /// vector. If it is invalid, don't add anything to Ops.
3272 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3273 std::string &Constraint,
3274 std::vector<SDValue>&Ops,
3275 SelectionDAG &DAG) const {
3278 // Only support length 1 constraints for now.
3279 if (Constraint.length() > 1) return;
3281 char ConstraintLetter = Constraint[0];
3282 switch (ConstraintLetter) {
3283 default: break; // This will fall through to the generic implementation
3284 case 'I': // Signed 16 bit constant
3285 // If this fails, the parent routine will give an error
3286 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3287 EVT Type = Op.getValueType();
3288 int64_t Val = C->getSExtValue();
3289 if (isInt<16>(Val)) {
3290 Result = DAG.getTargetConstant(Val, Type);
3295 case 'J': // integer zero
3296 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3297 EVT Type = Op.getValueType();
3298 int64_t Val = C->getZExtValue();
3300 Result = DAG.getTargetConstant(0, Type);
3305 case 'K': // unsigned 16 bit immediate
3306 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3307 EVT Type = Op.getValueType();
3308 uint64_t Val = (uint64_t)C->getZExtValue();
3309 if (isUInt<16>(Val)) {
3310 Result = DAG.getTargetConstant(Val, Type);
3315 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3316 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3317 EVT Type = Op.getValueType();
3318 int64_t Val = C->getSExtValue();
3319 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3320 Result = DAG.getTargetConstant(Val, Type);
3325 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3326 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3327 EVT Type = Op.getValueType();
3328 int64_t Val = C->getSExtValue();
3329 if ((Val >= -65535) && (Val <= -1)) {
3330 Result = DAG.getTargetConstant(Val, Type);
3335 case 'O': // signed 15 bit immediate
3336 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3337 EVT Type = Op.getValueType();
3338 int64_t Val = C->getSExtValue();
3339 if ((isInt<15>(Val))) {
3340 Result = DAG.getTargetConstant(Val, Type);
3345 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3346 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3347 EVT Type = Op.getValueType();
3348 int64_t Val = C->getSExtValue();
3349 if ((Val <= 65535) && (Val >= 1)) {
3350 Result = DAG.getTargetConstant(Val, Type);
3357 if (Result.getNode()) {
3358 Ops.push_back(Result);
3362 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3365 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3367 // No global is ever allowed as a base.
3372 case 0: // "r+i" or just "i", depending on HasBaseReg.
3375 if (!AM.HasBaseReg) // allow "r+i".
3377 return false; // disallow "r+r" or "r+r+i".
3386 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3387 // The Mips target isn't yet aware of offsets.
3391 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3393 bool IsMemset, bool ZeroMemset,
3395 MachineFunction &MF) const {
3396 if (Subtarget.hasMips64())
3402 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3403 if (VT != MVT::f32 && VT != MVT::f64)
3405 if (Imm.isNegZero())
3407 return Imm.isZero();
3410 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3411 if (Subtarget.isABI_N64())
3412 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3414 return TargetLowering::getJumpTableEncoding();
3417 void MipsTargetLowering::copyByValRegs(
3418 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3419 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3420 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3421 const CCValAssign &VA, MipsCCState &State) const {
3422 MachineFunction &MF = DAG.getMachineFunction();
3423 MachineFrameInfo *MFI = MF.getFrameInfo();
3424 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3425 unsigned NumRegs = LastReg - FirstReg;
3426 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3427 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3429 const MipsABIInfo &ABI = Subtarget.getABI();
3430 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3434 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3435 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3437 FrameObjOffset = VA.getLocMemOffset();
3439 // Create frame object.
3440 EVT PtrTy = getPointerTy();
3441 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3442 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3443 InVals.push_back(FIN);
3448 // Copy arg registers.
3449 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3450 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3452 for (unsigned I = 0; I < NumRegs; ++I) {
3453 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3454 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3455 unsigned Offset = I * GPRSizeInBytes;
3456 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3457 DAG.getConstant(Offset, PtrTy));
3458 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3459 StorePtr, MachinePointerInfo(FuncArg, Offset),
3461 OutChains.push_back(Store);
3465 // Copy byVal arg to registers and stack.
3466 void MipsTargetLowering::passByValArg(
3467 SDValue Chain, SDLoc DL,
3468 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3469 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3470 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3471 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3472 const CCValAssign &VA) const {
3473 unsigned ByValSizeInBytes = Flags.getByValSize();
3474 unsigned OffsetInBytes = 0; // From beginning of struct
3475 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3476 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3477 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3478 unsigned NumRegs = LastReg - FirstReg;
3481 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetByValArgRegs();
3482 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3485 // Copy words to registers.
3486 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3487 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3488 DAG.getConstant(OffsetInBytes, PtrTy));
3489 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3490 MachinePointerInfo(), false, false, false,
3492 MemOpChains.push_back(LoadVal.getValue(1));
3493 unsigned ArgReg = ArgRegs[FirstReg + I];
3494 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3497 // Return if the struct has been fully copied.
3498 if (ByValSizeInBytes == OffsetInBytes)
3501 // Copy the remainder of the byval argument with sub-word loads and shifts.
3502 if (LeftoverBytes) {
3505 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3506 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3507 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3509 if (RemainingSizeInBytes < LoadSizeInBytes)
3513 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3514 DAG.getConstant(OffsetInBytes, PtrTy));
3515 SDValue LoadVal = DAG.getExtLoad(
3516 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3517 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3519 MemOpChains.push_back(LoadVal.getValue(1));
3521 // Shift the loaded value.
3525 Shamt = TotalBytesLoaded * 8;
3527 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3529 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3530 DAG.getConstant(Shamt, MVT::i32));
3533 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3537 OffsetInBytes += LoadSizeInBytes;
3538 TotalBytesLoaded += LoadSizeInBytes;
3539 Alignment = std::min(Alignment, LoadSizeInBytes);
3542 unsigned ArgReg = ArgRegs[FirstReg + I];
3543 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3548 // Copy remainder of byval arg to it with memcpy.
3549 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3550 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3551 DAG.getConstant(OffsetInBytes, PtrTy));
3552 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3553 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3554 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3555 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3556 MachinePointerInfo(), MachinePointerInfo());
3557 MemOpChains.push_back(Chain);
3560 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3561 SDValue Chain, SDLoc DL,
3563 CCState &State) const {
3564 const ArrayRef<MCPhysReg> ArgRegs = Subtarget.getABI().GetVarArgRegs();
3565 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3566 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3567 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3568 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3569 MachineFunction &MF = DAG.getMachineFunction();
3570 MachineFrameInfo *MFI = MF.getFrameInfo();
3571 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3573 // Offset of the first variable argument from stack pointer.
3576 if (ArgRegs.size() == Idx)
3578 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3580 const MipsABIInfo &ABI = Subtarget.getABI();
3582 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3583 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3586 // Record the frame index of the first variable argument
3587 // which is a value necessary to VASTART.
3588 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3589 MipsFI->setVarArgsFrameIndex(FI);
3591 // Copy the integer registers that have not been used for argument passing
3592 // to the argument register save area. For O32, the save area is allocated
3593 // in the caller's stack frame, while for N32/64, it is allocated in the
3594 // callee's stack frame.
3595 for (unsigned I = Idx; I < ArgRegs.size();
3596 ++I, VaArgOffset += RegSizeInBytes) {
3597 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3598 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3599 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3600 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3601 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3602 MachinePointerInfo(), false, false, 0);
3603 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3605 OutChains.push_back(Store);
3609 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3610 unsigned Align) const {
3611 MachineFunction &MF = State->getMachineFunction();
3612 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3614 assert(Size && "Byval argument's size shouldn't be 0.");
3616 Align = std::min(Align, TFL->getStackAlignment());
3618 unsigned FirstReg = 0;
3619 unsigned NumRegs = 0;
3621 if (State->getCallingConv() != CallingConv::Fast) {
3622 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3623 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3624 // FIXME: The O32 case actually describes no shadow registers.
3625 const MCPhysReg *ShadowRegs =
3626 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3628 // We used to check the size as well but we can't do that anymore since
3629 // CCState::HandleByVal() rounds up the size after calling this function.
3630 assert(!(Align % RegSizeInBytes) &&
3631 "Byval argument's alignment should be a multiple of"
3634 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3636 // If Align > RegSizeInBytes, the first arg register must be even.
3637 // FIXME: This condition happens to do the right thing but it's not the
3638 // right way to test it. We want to check that the stack frame offset
3639 // of the register is aligned.
3640 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3641 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3645 // Mark the registers allocated.
3646 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3647 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3648 Size -= RegSizeInBytes, ++I, ++NumRegs)
3649 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3652 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);