1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/SelectionDAGISel.h"
31 #include "llvm/CodeGen/ValueTypes.h"
32 #include "llvm/IR/CallingConv.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
43 #define DEBUG_TYPE "mips-lower"
45 STATISTIC(NumTailCalls, "Number of tail calls");
48 LargeGOT("mxgot", cl::Hidden,
49 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
52 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
53 cl::desc("MIPS: Don't trap on integer division by zero."),
57 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
58 cl::desc("Allow mips-fast-isel to be used"),
61 static const MCPhysReg Mips64DPRegs[8] = {
62 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
73 Size = countPopulation(I);
74 Pos = countTrailingZeros(I);
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
83 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
85 unsigned Flag) const {
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
89 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
91 unsigned Flag) const {
92 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
95 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
97 unsigned Flag) const {
98 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
103 unsigned Flag) const {
104 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
107 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
109 unsigned Flag) const {
110 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111 N->getOffset(), Flag);
114 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
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), Subtarget(STI), ABI(TM.getABI()) {
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 for (MVT VT : MVT::integer_valuetypes()) {
219 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
220 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
221 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
224 // MIPS doesn't have extending float->double load/store
225 for (MVT VT : MVT::fp_valuetypes())
226 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
227 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
229 // Used by legalize types to correctly generate the setcc result.
230 // Without this, every float setcc comes with a AND/OR with the result,
231 // we don't want this, since the fpcmp result goes to a flag register,
232 // which is used implicitly by brcond and select operations.
233 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
235 // Mips Custom Operations
236 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
237 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
238 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
239 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
240 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
241 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
242 setOperationAction(ISD::SELECT, MVT::f32, Custom);
243 setOperationAction(ISD::SELECT, MVT::f64, Custom);
244 setOperationAction(ISD::SELECT, MVT::i32, Custom);
245 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
246 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
247 setOperationAction(ISD::SETCC, MVT::f32, Custom);
248 setOperationAction(ISD::SETCC, MVT::f64, Custom);
249 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
252 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254 if (Subtarget.isGP64bit()) {
255 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
256 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
258 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
260 setOperationAction(ISD::SELECT, MVT::i64, Custom);
261 setOperationAction(ISD::LOAD, MVT::i64, Custom);
262 setOperationAction(ISD::STORE, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
264 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
265 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
266 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
269 if (!Subtarget.isGP64bit()) {
270 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
271 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
275 setOperationAction(ISD::ADD, MVT::i32, Custom);
276 if (Subtarget.isGP64bit())
277 setOperationAction(ISD::ADD, MVT::i64, Custom);
279 setOperationAction(ISD::SDIV, MVT::i32, Expand);
280 setOperationAction(ISD::SREM, MVT::i32, Expand);
281 setOperationAction(ISD::UDIV, MVT::i32, Expand);
282 setOperationAction(ISD::UREM, MVT::i32, Expand);
283 setOperationAction(ISD::SDIV, MVT::i64, Expand);
284 setOperationAction(ISD::SREM, MVT::i64, Expand);
285 setOperationAction(ISD::UDIV, MVT::i64, Expand);
286 setOperationAction(ISD::UREM, MVT::i64, Expand);
288 // Operations not directly supported by Mips.
289 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
291 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
292 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
293 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
294 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
295 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
296 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
297 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
298 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
299 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
300 if (Subtarget.hasCnMips()) {
301 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
302 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
304 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
305 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
307 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
308 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
309 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
310 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
311 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
312 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
313 setOperationAction(ISD::ROTL, MVT::i32, Expand);
314 setOperationAction(ISD::ROTL, MVT::i64, Expand);
315 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
316 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
318 if (!Subtarget.hasMips32r2())
319 setOperationAction(ISD::ROTR, MVT::i32, Expand);
321 if (!Subtarget.hasMips64r2())
322 setOperationAction(ISD::ROTR, MVT::i64, Expand);
324 setOperationAction(ISD::FSIN, MVT::f32, Expand);
325 setOperationAction(ISD::FSIN, MVT::f64, Expand);
326 setOperationAction(ISD::FCOS, MVT::f32, Expand);
327 setOperationAction(ISD::FCOS, MVT::f64, Expand);
328 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
329 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
330 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
331 setOperationAction(ISD::FPOW, MVT::f32, Expand);
332 setOperationAction(ISD::FPOW, MVT::f64, Expand);
333 setOperationAction(ISD::FLOG, MVT::f32, Expand);
334 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
335 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
336 setOperationAction(ISD::FEXP, MVT::f32, Expand);
337 setOperationAction(ISD::FMA, MVT::f32, Expand);
338 setOperationAction(ISD::FMA, MVT::f64, Expand);
339 setOperationAction(ISD::FREM, MVT::f32, Expand);
340 setOperationAction(ISD::FREM, MVT::f64, Expand);
342 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
344 setOperationAction(ISD::VASTART, MVT::Other, Custom);
345 setOperationAction(ISD::VAARG, MVT::Other, Custom);
346 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
347 setOperationAction(ISD::VAEND, MVT::Other, Expand);
349 // Use the default for now
350 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
351 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
353 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
354 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
355 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
356 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
358 setInsertFencesForAtomic(true);
360 if (!Subtarget.hasMips32r2()) {
361 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
362 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
365 // MIPS16 lacks MIPS32's clz and clo instructions.
366 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
367 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
368 if (!Subtarget.hasMips64())
369 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
371 if (!Subtarget.hasMips32r2())
372 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
373 if (!Subtarget.hasMips64r2())
374 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
376 if (Subtarget.isGP64bit()) {
377 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
378 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
379 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
380 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
383 setOperationAction(ISD::TRAP, MVT::Other, Legal);
385 setTargetDAGCombine(ISD::SDIVREM);
386 setTargetDAGCombine(ISD::UDIVREM);
387 setTargetDAGCombine(ISD::SELECT);
388 setTargetDAGCombine(ISD::AND);
389 setTargetDAGCombine(ISD::OR);
390 setTargetDAGCombine(ISD::ADD);
392 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
394 // The arguments on the stack are defined in terms of 4-byte slots on O32
395 // and 8-byte slots on N32/N64.
396 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
398 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
400 setExceptionPointerRegister(ABI.IsN64() ? Mips::A0_64 : Mips::A0);
401 setExceptionSelectorRegister(ABI.IsN64() ? Mips::A1_64 : Mips::A1);
403 MaxStoresPerMemcpy = 16;
405 isMicroMips = Subtarget.inMicroMipsMode();
408 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
409 const MipsSubtarget &STI) {
410 if (STI.inMips16Mode())
411 return llvm::createMips16TargetLowering(TM, STI);
413 return llvm::createMipsSETargetLowering(TM, STI);
416 // Create a fast isel object.
418 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
419 const TargetLibraryInfo *libInfo) const {
420 if (!EnableMipsFastISel)
421 return TargetLowering::createFastISel(funcInfo, libInfo);
422 return Mips::createFastISel(funcInfo, libInfo);
425 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
428 return VT.changeVectorElementTypeToInteger();
431 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
432 TargetLowering::DAGCombinerInfo &DCI,
433 const MipsSubtarget &Subtarget) {
434 if (DCI.isBeforeLegalizeOps())
437 EVT Ty = N->getValueType(0);
438 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
439 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
440 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
444 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
445 N->getOperand(0), N->getOperand(1));
446 SDValue InChain = DAG.getEntryNode();
447 SDValue InGlue = DivRem;
450 if (N->hasAnyUseOfValue(0)) {
451 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
453 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
454 InChain = CopyFromLo.getValue(1);
455 InGlue = CopyFromLo.getValue(2);
459 if (N->hasAnyUseOfValue(1)) {
460 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
462 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
468 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
470 default: llvm_unreachable("Unknown fp condition code!");
472 case ISD::SETOEQ: return Mips::FCOND_OEQ;
473 case ISD::SETUNE: return Mips::FCOND_UNE;
475 case ISD::SETOLT: return Mips::FCOND_OLT;
477 case ISD::SETOGT: return Mips::FCOND_OGT;
479 case ISD::SETOLE: return Mips::FCOND_OLE;
481 case ISD::SETOGE: return Mips::FCOND_OGE;
482 case ISD::SETULT: return Mips::FCOND_ULT;
483 case ISD::SETULE: return Mips::FCOND_ULE;
484 case ISD::SETUGT: return Mips::FCOND_UGT;
485 case ISD::SETUGE: return Mips::FCOND_UGE;
486 case ISD::SETUO: return Mips::FCOND_UN;
487 case ISD::SETO: return Mips::FCOND_OR;
489 case ISD::SETONE: return Mips::FCOND_ONE;
490 case ISD::SETUEQ: return Mips::FCOND_UEQ;
495 /// This function returns true if the floating point conditional branches and
496 /// conditional moves which use condition code CC should be inverted.
497 static bool invertFPCondCodeUser(Mips::CondCode CC) {
498 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
501 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
502 "Illegal Condition Code");
507 // Creates and returns an FPCmp node from a setcc node.
508 // Returns Op if setcc is not a floating point comparison.
509 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
510 // must be a SETCC node
511 if (Op.getOpcode() != ISD::SETCC)
514 SDValue LHS = Op.getOperand(0);
516 if (!LHS.getValueType().isFloatingPoint())
519 SDValue RHS = Op.getOperand(1);
522 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
523 // node if necessary.
524 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
526 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
527 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
530 // Creates and returns a CMovFPT/F node.
531 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
532 SDValue False, SDLoc DL) {
533 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
534 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
535 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
537 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
538 True.getValueType(), True, FCC0, False, Cond);
541 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
542 TargetLowering::DAGCombinerInfo &DCI,
543 const MipsSubtarget &Subtarget) {
544 if (DCI.isBeforeLegalizeOps())
547 SDValue SetCC = N->getOperand(0);
549 if ((SetCC.getOpcode() != ISD::SETCC) ||
550 !SetCC.getOperand(0).getValueType().isInteger())
553 SDValue False = N->getOperand(2);
554 EVT FalseTy = False.getValueType();
556 if (!FalseTy.isInteger())
559 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
561 // If the RHS (False) is 0, we swap the order of the operands
562 // of ISD::SELECT (obviously also inverting the condition) so that we can
563 // take advantage of conditional moves using the $0 register.
565 // return (a != 0) ? x : 0;
573 if (!FalseC->getZExtValue()) {
574 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
575 SDValue True = N->getOperand(1);
577 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
578 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
580 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
583 // If both operands are integer constants there's a possibility that we
584 // can do some interesting optimizations.
585 SDValue True = N->getOperand(1);
586 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
588 if (!TrueC || !True.getValueType().isInteger())
591 // We'll also ignore MVT::i64 operands as this optimizations proves
592 // to be ineffective because of the required sign extensions as the result
593 // of a SETCC operator is always MVT::i32 for non-vector types.
594 if (True.getValueType() == MVT::i64)
597 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
599 // 1) (a < x) ? y : y-1
601 // addiu $reg2, $reg1, y-1
603 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
605 // 2) (a < x) ? y-1 : y
607 // xor $reg1, $reg1, 1
608 // addiu $reg2, $reg1, y-1
610 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
611 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
612 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
613 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
616 // Couldn't optimize.
620 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
621 TargetLowering::DAGCombinerInfo &DCI,
622 const MipsSubtarget &Subtarget) {
623 if (DCI.isBeforeLegalizeOps())
626 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
628 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
629 if (!FalseC || FalseC->getZExtValue())
632 // Since RHS (False) is 0, we swap the order of the True/False operands
633 // (obviously also inverting the condition) so that we can
634 // take advantage of conditional moves using the $0 register.
636 // return (a != 0) ? x : 0;
639 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
642 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
643 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
644 ValueIfFalse, FCC, ValueIfTrue, Glue);
647 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
648 TargetLowering::DAGCombinerInfo &DCI,
649 const MipsSubtarget &Subtarget) {
650 // Pattern match EXT.
651 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
652 // => ext $dst, $src, size, pos
653 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
656 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
657 unsigned ShiftRightOpc = ShiftRight.getOpcode();
659 // Op's first operand must be a shift right.
660 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
663 // The second operand of the shift must be an immediate.
665 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
668 uint64_t Pos = CN->getZExtValue();
669 uint64_t SMPos, SMSize;
671 // Op's second operand must be a shifted mask.
672 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
673 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
676 // Return if the shifted mask does not start at bit 0 or the sum of its size
677 // and Pos exceeds the word's size.
678 EVT ValTy = N->getValueType(0);
679 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
682 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
683 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
684 DAG.getConstant(SMSize, MVT::i32));
687 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
688 TargetLowering::DAGCombinerInfo &DCI,
689 const MipsSubtarget &Subtarget) {
690 // Pattern match INS.
691 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
692 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
693 // => ins $dst, $src, size, pos, $src1
694 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
697 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
698 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
701 // See if Op's first operand matches (and $src1 , mask0).
702 if (And0.getOpcode() != ISD::AND)
705 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
706 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
709 // See if Op's second operand matches (and (shl $src, pos), mask1).
710 if (And1.getOpcode() != ISD::AND)
713 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
714 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
717 // The shift masks must have the same position and size.
718 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
721 SDValue Shl = And1.getOperand(0);
722 if (Shl.getOpcode() != ISD::SHL)
725 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
728 unsigned Shamt = CN->getZExtValue();
730 // Return if the shift amount and the first bit position of mask are not the
732 EVT ValTy = N->getValueType(0);
733 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
736 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
737 DAG.getConstant(SMPos0, MVT::i32),
738 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
741 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
742 TargetLowering::DAGCombinerInfo &DCI,
743 const MipsSubtarget &Subtarget) {
744 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
746 if (DCI.isBeforeLegalizeOps())
749 SDValue Add = N->getOperand(1);
751 if (Add.getOpcode() != ISD::ADD)
754 SDValue Lo = Add.getOperand(1);
756 if ((Lo.getOpcode() != MipsISD::Lo) ||
757 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
760 EVT ValTy = N->getValueType(0);
763 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
765 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
768 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
770 SelectionDAG &DAG = DCI.DAG;
771 unsigned Opc = N->getOpcode();
777 return performDivRemCombine(N, DAG, DCI, Subtarget);
779 return performSELECTCombine(N, DAG, DCI, Subtarget);
780 case MipsISD::CMovFP_F:
781 case MipsISD::CMovFP_T:
782 return performCMovFPCombine(N, DAG, DCI, Subtarget);
784 return performANDCombine(N, DAG, DCI, Subtarget);
786 return performORCombine(N, DAG, DCI, Subtarget);
788 return performADDCombine(N, DAG, DCI, Subtarget);
795 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
796 SmallVectorImpl<SDValue> &Results,
797 SelectionDAG &DAG) const {
798 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
800 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
801 Results.push_back(Res.getValue(I));
805 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
806 SmallVectorImpl<SDValue> &Results,
807 SelectionDAG &DAG) const {
808 return LowerOperationWrapper(N, Results, DAG);
811 SDValue MipsTargetLowering::
812 LowerOperation(SDValue Op, SelectionDAG &DAG) const
814 switch (Op.getOpcode())
816 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
817 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
818 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
819 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
820 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
821 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
822 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
823 case ISD::SELECT: return lowerSELECT(Op, DAG);
824 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
825 case ISD::SETCC: return lowerSETCC(Op, DAG);
826 case ISD::VASTART: return lowerVASTART(Op, DAG);
827 case ISD::VAARG: return lowerVAARG(Op, DAG);
828 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
829 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
830 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
831 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
832 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
833 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
834 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
835 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
836 case ISD::LOAD: return lowerLOAD(Op, DAG);
837 case ISD::STORE: return lowerSTORE(Op, DAG);
838 case ISD::ADD: return lowerADD(Op, DAG);
839 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
844 //===----------------------------------------------------------------------===//
845 // Lower helper functions
846 //===----------------------------------------------------------------------===//
848 // addLiveIn - This helper function adds the specified physical register to the
849 // MachineFunction as a live in value. It also creates a corresponding
850 // virtual register for it.
852 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
854 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
855 MF.getRegInfo().addLiveIn(PReg, VReg);
859 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
860 MachineBasicBlock &MBB,
861 const TargetInstrInfo &TII,
866 // Insert instruction "teq $divisor_reg, $zero, 7".
867 MachineBasicBlock::iterator I(MI);
868 MachineInstrBuilder MIB;
869 MachineOperand &Divisor = MI->getOperand(2);
870 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
871 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
872 .addReg(Mips::ZERO).addImm(7);
874 // Use the 32-bit sub-register if this is a 64-bit division.
876 MIB->getOperand(0).setSubReg(Mips::sub_32);
878 // Clear Divisor's kill flag.
879 Divisor.setIsKill(false);
881 // We would normally delete the original instruction here but in this case
882 // we only needed to inject an additional instruction rather than replace it.
888 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
889 MachineBasicBlock *BB) const {
890 switch (MI->getOpcode()) {
892 llvm_unreachable("Unexpected instr type to insert");
893 case Mips::ATOMIC_LOAD_ADD_I8:
894 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
895 case Mips::ATOMIC_LOAD_ADD_I16:
896 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
897 case Mips::ATOMIC_LOAD_ADD_I32:
898 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
899 case Mips::ATOMIC_LOAD_ADD_I64:
900 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
902 case Mips::ATOMIC_LOAD_AND_I8:
903 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
904 case Mips::ATOMIC_LOAD_AND_I16:
905 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
906 case Mips::ATOMIC_LOAD_AND_I32:
907 return emitAtomicBinary(MI, BB, 4, Mips::AND);
908 case Mips::ATOMIC_LOAD_AND_I64:
909 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
911 case Mips::ATOMIC_LOAD_OR_I8:
912 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
913 case Mips::ATOMIC_LOAD_OR_I16:
914 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
915 case Mips::ATOMIC_LOAD_OR_I32:
916 return emitAtomicBinary(MI, BB, 4, Mips::OR);
917 case Mips::ATOMIC_LOAD_OR_I64:
918 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
920 case Mips::ATOMIC_LOAD_XOR_I8:
921 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
922 case Mips::ATOMIC_LOAD_XOR_I16:
923 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
924 case Mips::ATOMIC_LOAD_XOR_I32:
925 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
926 case Mips::ATOMIC_LOAD_XOR_I64:
927 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
929 case Mips::ATOMIC_LOAD_NAND_I8:
930 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
931 case Mips::ATOMIC_LOAD_NAND_I16:
932 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
933 case Mips::ATOMIC_LOAD_NAND_I32:
934 return emitAtomicBinary(MI, BB, 4, 0, true);
935 case Mips::ATOMIC_LOAD_NAND_I64:
936 return emitAtomicBinary(MI, BB, 8, 0, true);
938 case Mips::ATOMIC_LOAD_SUB_I8:
939 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
940 case Mips::ATOMIC_LOAD_SUB_I16:
941 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
942 case Mips::ATOMIC_LOAD_SUB_I32:
943 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
944 case Mips::ATOMIC_LOAD_SUB_I64:
945 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
947 case Mips::ATOMIC_SWAP_I8:
948 return emitAtomicBinaryPartword(MI, BB, 1, 0);
949 case Mips::ATOMIC_SWAP_I16:
950 return emitAtomicBinaryPartword(MI, BB, 2, 0);
951 case Mips::ATOMIC_SWAP_I32:
952 return emitAtomicBinary(MI, BB, 4, 0);
953 case Mips::ATOMIC_SWAP_I64:
954 return emitAtomicBinary(MI, BB, 8, 0);
956 case Mips::ATOMIC_CMP_SWAP_I8:
957 return emitAtomicCmpSwapPartword(MI, BB, 1);
958 case Mips::ATOMIC_CMP_SWAP_I16:
959 return emitAtomicCmpSwapPartword(MI, BB, 2);
960 case Mips::ATOMIC_CMP_SWAP_I32:
961 return emitAtomicCmpSwap(MI, BB, 4);
962 case Mips::ATOMIC_CMP_SWAP_I64:
963 return emitAtomicCmpSwap(MI, BB, 8);
964 case Mips::PseudoSDIV:
965 case Mips::PseudoUDIV:
970 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
971 case Mips::PseudoDSDIV:
972 case Mips::PseudoDUDIV:
977 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
979 return emitSEL_D(MI, BB);
981 case Mips::PseudoSELECT_I:
982 case Mips::PseudoSELECT_I64:
983 case Mips::PseudoSELECT_S:
984 case Mips::PseudoSELECT_D32:
985 case Mips::PseudoSELECT_D64:
986 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
987 case Mips::PseudoSELECTFP_F_I:
988 case Mips::PseudoSELECTFP_F_I64:
989 case Mips::PseudoSELECTFP_F_S:
990 case Mips::PseudoSELECTFP_F_D32:
991 case Mips::PseudoSELECTFP_F_D64:
992 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
993 case Mips::PseudoSELECTFP_T_I:
994 case Mips::PseudoSELECTFP_T_I64:
995 case Mips::PseudoSELECTFP_T_S:
996 case Mips::PseudoSELECTFP_T_D32:
997 case Mips::PseudoSELECTFP_T_D64:
998 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1002 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1003 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1005 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1006 unsigned Size, unsigned BinOpcode,
1008 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1010 MachineFunction *MF = BB->getParent();
1011 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1012 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1013 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1014 DebugLoc DL = MI->getDebugLoc();
1015 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1022 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1023 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1030 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1031 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1034 ZERO = Mips::ZERO_64;
1038 unsigned OldVal = MI->getOperand(0).getReg();
1039 unsigned Ptr = MI->getOperand(1).getReg();
1040 unsigned Incr = MI->getOperand(2).getReg();
1042 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1043 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1044 unsigned Success = RegInfo.createVirtualRegister(RC);
1046 // insert new blocks after the current block
1047 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1048 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1049 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1050 MachineFunction::iterator It = BB;
1052 MF->insert(It, loopMBB);
1053 MF->insert(It, exitMBB);
1055 // Transfer the remainder of BB and its successor edges to exitMBB.
1056 exitMBB->splice(exitMBB->begin(), BB,
1057 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1058 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1062 // fallthrough --> loopMBB
1063 BB->addSuccessor(loopMBB);
1064 loopMBB->addSuccessor(loopMBB);
1065 loopMBB->addSuccessor(exitMBB);
1068 // ll oldval, 0(ptr)
1069 // <binop> storeval, oldval, incr
1070 // sc success, storeval, 0(ptr)
1071 // beq success, $0, loopMBB
1073 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1075 // and andres, oldval, incr
1076 // nor storeval, $0, andres
1077 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1078 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1079 } else if (BinOpcode) {
1080 // <binop> storeval, oldval, incr
1081 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1085 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1086 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1088 MI->eraseFromParent(); // The instruction is gone now.
1093 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1094 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1095 unsigned SrcReg) const {
1096 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1097 DebugLoc DL = MI->getDebugLoc();
1099 if (Subtarget.hasMips32r2() && Size == 1) {
1100 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1104 if (Subtarget.hasMips32r2() && Size == 2) {
1105 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1109 MachineFunction *MF = BB->getParent();
1110 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1111 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1112 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1115 int64_t ShiftImm = 32 - (Size * 8);
1117 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1118 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1123 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1124 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1126 assert((Size == 1 || Size == 2) &&
1127 "Unsupported size for EmitAtomicBinaryPartial.");
1129 MachineFunction *MF = BB->getParent();
1130 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1131 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1132 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1133 DebugLoc DL = MI->getDebugLoc();
1135 unsigned Dest = MI->getOperand(0).getReg();
1136 unsigned Ptr = MI->getOperand(1).getReg();
1137 unsigned Incr = MI->getOperand(2).getReg();
1139 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1140 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1141 unsigned Mask = RegInfo.createVirtualRegister(RC);
1142 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1143 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1144 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1145 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1146 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1147 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1148 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1149 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1150 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1151 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1152 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1153 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1154 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1155 unsigned Success = RegInfo.createVirtualRegister(RC);
1157 // insert new blocks after the current block
1158 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1159 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1160 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1161 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1162 MachineFunction::iterator It = BB;
1164 MF->insert(It, loopMBB);
1165 MF->insert(It, sinkMBB);
1166 MF->insert(It, exitMBB);
1168 // Transfer the remainder of BB and its successor edges to exitMBB.
1169 exitMBB->splice(exitMBB->begin(), BB,
1170 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1171 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1173 BB->addSuccessor(loopMBB);
1174 loopMBB->addSuccessor(loopMBB);
1175 loopMBB->addSuccessor(sinkMBB);
1176 sinkMBB->addSuccessor(exitMBB);
1179 // addiu masklsb2,$0,-4 # 0xfffffffc
1180 // and alignedaddr,ptr,masklsb2
1181 // andi ptrlsb2,ptr,3
1182 // sll shiftamt,ptrlsb2,3
1183 // ori maskupper,$0,255 # 0xff
1184 // sll mask,maskupper,shiftamt
1185 // nor mask2,$0,mask
1186 // sll incr2,incr,shiftamt
1188 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1189 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1190 .addReg(Mips::ZERO).addImm(-4);
1191 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1192 .addReg(Ptr).addReg(MaskLSB2);
1193 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1194 if (Subtarget.isLittle()) {
1195 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1197 unsigned Off = RegInfo.createVirtualRegister(RC);
1198 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1199 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1200 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1202 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1203 .addReg(Mips::ZERO).addImm(MaskImm);
1204 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1205 .addReg(MaskUpper).addReg(ShiftAmt);
1206 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1207 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1209 // atomic.load.binop
1211 // ll oldval,0(alignedaddr)
1212 // binop binopres,oldval,incr2
1213 // and newval,binopres,mask
1214 // and maskedoldval0,oldval,mask2
1215 // or storeval,maskedoldval0,newval
1216 // sc success,storeval,0(alignedaddr)
1217 // beq success,$0,loopMBB
1221 // ll oldval,0(alignedaddr)
1222 // and newval,incr2,mask
1223 // and maskedoldval0,oldval,mask2
1224 // or storeval,maskedoldval0,newval
1225 // sc success,storeval,0(alignedaddr)
1226 // beq success,$0,loopMBB
1229 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1230 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1232 // and andres, oldval, incr2
1233 // nor binopres, $0, andres
1234 // and newval, binopres, mask
1235 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1236 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1237 .addReg(Mips::ZERO).addReg(AndRes);
1238 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1239 } else if (BinOpcode) {
1240 // <binop> binopres, oldval, incr2
1241 // and newval, binopres, mask
1242 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1243 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1244 } else { // atomic.swap
1245 // and newval, incr2, mask
1246 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1249 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1250 .addReg(OldVal).addReg(Mask2);
1251 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1252 .addReg(MaskedOldVal0).addReg(NewVal);
1253 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1254 BuildMI(BB, DL, TII->get(SC), Success)
1255 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1256 BuildMI(BB, DL, TII->get(Mips::BEQ))
1257 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1260 // and maskedoldval1,oldval,mask
1261 // srl srlres,maskedoldval1,shiftamt
1262 // sign_extend dest,srlres
1265 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1266 .addReg(OldVal).addReg(Mask);
1267 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1268 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1269 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1271 MI->eraseFromParent(); // The instruction is gone now.
1276 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1277 MachineBasicBlock *BB,
1278 unsigned Size) const {
1279 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1281 MachineFunction *MF = BB->getParent();
1282 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1283 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1284 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1285 DebugLoc DL = MI->getDebugLoc();
1286 unsigned LL, SC, ZERO, BNE, BEQ;
1289 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1290 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1297 ZERO = Mips::ZERO_64;
1302 unsigned Dest = MI->getOperand(0).getReg();
1303 unsigned Ptr = MI->getOperand(1).getReg();
1304 unsigned OldVal = MI->getOperand(2).getReg();
1305 unsigned NewVal = MI->getOperand(3).getReg();
1307 unsigned Success = RegInfo.createVirtualRegister(RC);
1309 // insert new blocks after the current block
1310 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1311 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1312 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1313 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1314 MachineFunction::iterator It = BB;
1316 MF->insert(It, loop1MBB);
1317 MF->insert(It, loop2MBB);
1318 MF->insert(It, exitMBB);
1320 // Transfer the remainder of BB and its successor edges to exitMBB.
1321 exitMBB->splice(exitMBB->begin(), BB,
1322 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1323 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1327 // fallthrough --> loop1MBB
1328 BB->addSuccessor(loop1MBB);
1329 loop1MBB->addSuccessor(exitMBB);
1330 loop1MBB->addSuccessor(loop2MBB);
1331 loop2MBB->addSuccessor(loop1MBB);
1332 loop2MBB->addSuccessor(exitMBB);
1336 // bne dest, oldval, exitMBB
1338 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1339 BuildMI(BB, DL, TII->get(BNE))
1340 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1343 // sc success, newval, 0(ptr)
1344 // beq success, $0, loop1MBB
1346 BuildMI(BB, DL, TII->get(SC), Success)
1347 .addReg(NewVal).addReg(Ptr).addImm(0);
1348 BuildMI(BB, DL, TII->get(BEQ))
1349 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1351 MI->eraseFromParent(); // The instruction is gone now.
1357 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1358 MachineBasicBlock *BB,
1359 unsigned Size) const {
1360 assert((Size == 1 || Size == 2) &&
1361 "Unsupported size for EmitAtomicCmpSwapPartial.");
1363 MachineFunction *MF = BB->getParent();
1364 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1365 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1366 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1367 DebugLoc DL = MI->getDebugLoc();
1369 unsigned Dest = MI->getOperand(0).getReg();
1370 unsigned Ptr = MI->getOperand(1).getReg();
1371 unsigned CmpVal = MI->getOperand(2).getReg();
1372 unsigned NewVal = MI->getOperand(3).getReg();
1374 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1375 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1376 unsigned Mask = RegInfo.createVirtualRegister(RC);
1377 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1378 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1379 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1380 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1381 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1382 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1383 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1384 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1385 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1386 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1387 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1388 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1389 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1390 unsigned Success = RegInfo.createVirtualRegister(RC);
1392 // insert new blocks after the current block
1393 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1394 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1395 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1396 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1397 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1398 MachineFunction::iterator It = BB;
1400 MF->insert(It, loop1MBB);
1401 MF->insert(It, loop2MBB);
1402 MF->insert(It, sinkMBB);
1403 MF->insert(It, exitMBB);
1405 // Transfer the remainder of BB and its successor edges to exitMBB.
1406 exitMBB->splice(exitMBB->begin(), BB,
1407 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1408 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1410 BB->addSuccessor(loop1MBB);
1411 loop1MBB->addSuccessor(sinkMBB);
1412 loop1MBB->addSuccessor(loop2MBB);
1413 loop2MBB->addSuccessor(loop1MBB);
1414 loop2MBB->addSuccessor(sinkMBB);
1415 sinkMBB->addSuccessor(exitMBB);
1417 // FIXME: computation of newval2 can be moved to loop2MBB.
1419 // addiu masklsb2,$0,-4 # 0xfffffffc
1420 // and alignedaddr,ptr,masklsb2
1421 // andi ptrlsb2,ptr,3
1422 // sll shiftamt,ptrlsb2,3
1423 // ori maskupper,$0,255 # 0xff
1424 // sll mask,maskupper,shiftamt
1425 // nor mask2,$0,mask
1426 // andi maskedcmpval,cmpval,255
1427 // sll shiftedcmpval,maskedcmpval,shiftamt
1428 // andi maskednewval,newval,255
1429 // sll shiftednewval,maskednewval,shiftamt
1430 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1431 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1432 .addReg(Mips::ZERO).addImm(-4);
1433 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1434 .addReg(Ptr).addReg(MaskLSB2);
1435 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1436 if (Subtarget.isLittle()) {
1437 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1439 unsigned Off = RegInfo.createVirtualRegister(RC);
1440 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1441 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1442 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1444 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1445 .addReg(Mips::ZERO).addImm(MaskImm);
1446 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1447 .addReg(MaskUpper).addReg(ShiftAmt);
1448 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1449 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1450 .addReg(CmpVal).addImm(MaskImm);
1451 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1452 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1453 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1454 .addReg(NewVal).addImm(MaskImm);
1455 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1456 .addReg(MaskedNewVal).addReg(ShiftAmt);
1459 // ll oldval,0(alginedaddr)
1460 // and maskedoldval0,oldval,mask
1461 // bne maskedoldval0,shiftedcmpval,sinkMBB
1463 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1464 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1465 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1466 .addReg(OldVal).addReg(Mask);
1467 BuildMI(BB, DL, TII->get(Mips::BNE))
1468 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1471 // and maskedoldval1,oldval,mask2
1472 // or storeval,maskedoldval1,shiftednewval
1473 // sc success,storeval,0(alignedaddr)
1474 // beq success,$0,loop1MBB
1476 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1477 .addReg(OldVal).addReg(Mask2);
1478 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1479 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1480 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1481 BuildMI(BB, DL, TII->get(SC), Success)
1482 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1483 BuildMI(BB, DL, TII->get(Mips::BEQ))
1484 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1487 // srl srlres,maskedoldval0,shiftamt
1488 // sign_extend dest,srlres
1491 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1492 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1493 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1495 MI->eraseFromParent(); // The instruction is gone now.
1500 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1501 MachineBasicBlock *BB) const {
1502 MachineFunction *MF = BB->getParent();
1503 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1504 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1505 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1506 DebugLoc DL = MI->getDebugLoc();
1507 MachineBasicBlock::iterator II(MI);
1509 unsigned Fc = MI->getOperand(1).getReg();
1510 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1512 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1514 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1517 .addImm(Mips::sub_lo);
1519 // We don't erase the original instruction, we just replace the condition
1520 // register with the 64-bit super-register.
1521 MI->getOperand(1).setReg(Fc2);
1526 //===----------------------------------------------------------------------===//
1527 // Misc Lower Operation implementation
1528 //===----------------------------------------------------------------------===//
1529 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1530 SDValue Chain = Op.getOperand(0);
1531 SDValue Table = Op.getOperand(1);
1532 SDValue Index = Op.getOperand(2);
1534 EVT PTy = getPointerTy();
1535 unsigned EntrySize =
1536 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1538 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1539 DAG.getConstant(EntrySize, PTy));
1540 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1542 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1543 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1544 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1546 Chain = Addr.getValue(1);
1548 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1549 // For PIC, the sequence is:
1550 // BRIND(load(Jumptable + index) + RelocBase)
1551 // RelocBase can be JumpTable, GOT or some sort of global base.
1552 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1553 getPICJumpTableRelocBase(Table, DAG));
1556 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1559 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1560 // The first operand is the chain, the second is the condition, the third is
1561 // the block to branch to if the condition is true.
1562 SDValue Chain = Op.getOperand(0);
1563 SDValue Dest = Op.getOperand(2);
1566 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1567 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1569 // Return if flag is not set by a floating point comparison.
1570 if (CondRes.getOpcode() != MipsISD::FPCmp)
1573 SDValue CCNode = CondRes.getOperand(2);
1575 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1576 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1577 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1578 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1579 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1580 FCC0, Dest, CondRes);
1583 SDValue MipsTargetLowering::
1584 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1586 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1587 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1589 // Return if flag is not set by a floating point comparison.
1590 if (Cond.getOpcode() != MipsISD::FPCmp)
1593 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1597 SDValue MipsTargetLowering::
1598 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1601 EVT Ty = Op.getOperand(0).getValueType();
1602 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1603 getSetCCResultType(*DAG.getContext(), Ty),
1604 Op.getOperand(0), Op.getOperand(1),
1607 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1611 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1612 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1613 SDValue Cond = createFPCmp(DAG, Op);
1615 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1616 "Floating point operand expected.");
1618 SDValue True = DAG.getConstant(1, MVT::i32);
1619 SDValue False = DAG.getConstant(0, MVT::i32);
1621 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1624 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1625 SelectionDAG &DAG) const {
1626 EVT Ty = Op.getValueType();
1627 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1628 const GlobalValue *GV = N->getGlobal();
1630 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1631 const MipsTargetObjectFile *TLOF =
1632 static_cast<const MipsTargetObjectFile *>(
1633 getTargetMachine().getObjFileLowering());
1634 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1635 // %gp_rel relocation
1636 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1638 // %hi/%lo relocation
1639 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1642 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1643 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1646 return getAddrGlobalLargeGOT(N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16,
1647 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1648 MachinePointerInfo::getGOT());
1650 return getAddrGlobal(N, SDLoc(N), Ty, DAG,
1651 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP
1653 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1656 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1657 SelectionDAG &DAG) const {
1658 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1659 EVT Ty = Op.getValueType();
1661 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1662 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1664 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1667 SDValue MipsTargetLowering::
1668 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1670 // If the relocation model is PIC, use the General Dynamic TLS Model or
1671 // Local Dynamic TLS model, otherwise use the Initial Exec or
1672 // Local Exec TLS Model.
1674 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1676 const GlobalValue *GV = GA->getGlobal();
1677 EVT PtrVT = getPointerTy();
1679 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1681 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1682 // General Dynamic and Local Dynamic TLS Model.
1683 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1686 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1687 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1688 getGlobalReg(DAG, PtrVT), TGA);
1689 unsigned PtrSize = PtrVT.getSizeInBits();
1690 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1692 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1696 Entry.Node = Argument;
1698 Args.push_back(Entry);
1700 TargetLowering::CallLoweringInfo CLI(DAG);
1701 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1702 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1703 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1705 SDValue Ret = CallResult.first;
1707 if (model != TLSModel::LocalDynamic)
1710 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1711 MipsII::MO_DTPREL_HI);
1712 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1713 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1714 MipsII::MO_DTPREL_LO);
1715 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1716 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1717 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1721 if (model == TLSModel::InitialExec) {
1722 // Initial Exec TLS Model
1723 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1724 MipsII::MO_GOTTPREL);
1725 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1727 Offset = DAG.getLoad(PtrVT, DL,
1728 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1729 false, false, false, 0);
1731 // Local Exec TLS Model
1732 assert(model == TLSModel::LocalExec);
1733 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1734 MipsII::MO_TPREL_HI);
1735 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1736 MipsII::MO_TPREL_LO);
1737 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1738 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1739 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1742 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1743 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1746 SDValue MipsTargetLowering::
1747 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1749 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1750 EVT Ty = Op.getValueType();
1752 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1753 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1755 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1758 SDValue MipsTargetLowering::
1759 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1761 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1762 EVT Ty = Op.getValueType();
1764 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1765 const MipsTargetObjectFile *TLOF =
1766 static_cast<const MipsTargetObjectFile *>(
1767 getTargetMachine().getObjFileLowering());
1769 if (TLOF->IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1770 // %gp_rel relocation
1771 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1773 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1776 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1779 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1780 MachineFunction &MF = DAG.getMachineFunction();
1781 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1784 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1787 // vastart just stores the address of the VarArgsFrameIndex slot into the
1788 // memory location argument.
1789 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1790 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1791 MachinePointerInfo(SV), false, false, 0);
1794 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1795 SDNode *Node = Op.getNode();
1796 EVT VT = Node->getValueType(0);
1797 SDValue Chain = Node->getOperand(0);
1798 SDValue VAListPtr = Node->getOperand(1);
1799 unsigned Align = Node->getConstantOperandVal(3);
1800 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1802 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1804 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1805 MachinePointerInfo(SV), false, false, false,
1807 SDValue VAList = VAListLoad;
1809 // Re-align the pointer if necessary.
1810 // It should only ever be necessary for 64-bit types on O32 since the minimum
1811 // argument alignment is the same as the maximum type alignment for N32/N64.
1813 // FIXME: We currently align too often. The code generator doesn't notice
1814 // when the pointer is still aligned from the last va_arg (or pair of
1815 // va_args for the i64 on O32 case).
1816 if (Align > getMinStackArgumentAlignment()) {
1817 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1819 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1820 DAG.getConstant(Align - 1,
1821 VAList.getValueType()));
1823 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1824 DAG.getConstant(-(int64_t)Align,
1825 VAList.getValueType()));
1828 // Increment the pointer, VAList, to the next vaarg.
1829 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1830 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1831 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1832 VAList.getValueType()));
1833 // Store the incremented VAList to the legalized pointer
1834 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1835 MachinePointerInfo(SV), false, false, 0);
1837 // In big-endian mode we must adjust the pointer when the load size is smaller
1838 // than the argument slot size. We must also reduce the known alignment to
1839 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1840 // the correct half of the slot, and reduce the alignment from 8 (slot
1841 // alignment) down to 4 (type alignment).
1842 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1843 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1844 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1845 DAG.getIntPtrConstant(Adjustment));
1847 // Load the actual argument out of the pointer VAList
1848 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1852 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1853 bool HasExtractInsert) {
1854 EVT TyX = Op.getOperand(0).getValueType();
1855 EVT TyY = Op.getOperand(1).getValueType();
1856 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1857 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1861 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1863 SDValue X = (TyX == MVT::f32) ?
1864 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1865 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1867 SDValue Y = (TyY == MVT::f32) ?
1868 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1869 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1872 if (HasExtractInsert) {
1873 // ext E, Y, 31, 1 ; extract bit31 of Y
1874 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1875 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1876 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1879 // srl SrlX, SllX, 1
1881 // sll SllY, SrlX, 31
1882 // or Or, SrlX, SllY
1883 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1884 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1885 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1886 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1887 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1890 if (TyX == MVT::f32)
1891 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1893 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1894 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1895 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1898 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1899 bool HasExtractInsert) {
1900 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1901 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1902 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1903 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1906 // Bitcast to integer nodes.
1907 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1908 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1910 if (HasExtractInsert) {
1911 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1912 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1913 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1914 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1916 if (WidthX > WidthY)
1917 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1918 else if (WidthY > WidthX)
1919 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1921 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1922 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1923 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1926 // (d)sll SllX, X, 1
1927 // (d)srl SrlX, SllX, 1
1928 // (d)srl SrlY, Y, width(Y)-1
1929 // (d)sll SllY, SrlX, width(Y)-1
1930 // or Or, SrlX, SllY
1931 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1932 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1933 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1934 DAG.getConstant(WidthY - 1, MVT::i32));
1936 if (WidthX > WidthY)
1937 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1938 else if (WidthY > WidthX)
1939 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1941 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1942 DAG.getConstant(WidthX - 1, MVT::i32));
1943 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1944 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1948 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1949 if (Subtarget.isGP64bit())
1950 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1952 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1955 SDValue MipsTargetLowering::
1956 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1958 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1959 "Frame address can only be determined for current frame.");
1961 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1962 MFI->setFrameAddressIsTaken(true);
1963 EVT VT = Op.getValueType();
1965 SDValue FrameAddr = DAG.getCopyFromReg(
1966 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
1970 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1971 SelectionDAG &DAG) const {
1972 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1976 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1977 "Return address can be determined only for current frame.");
1979 MachineFunction &MF = DAG.getMachineFunction();
1980 MachineFrameInfo *MFI = MF.getFrameInfo();
1981 MVT VT = Op.getSimpleValueType();
1982 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
1983 MFI->setReturnAddressIsTaken(true);
1985 // Return RA, which contains the return address. Mark it an implicit live-in.
1986 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1987 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1990 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1991 // generated from __builtin_eh_return (offset, handler)
1992 // The effect of this is to adjust the stack pointer by "offset"
1993 // and then branch to "handler".
1994 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1996 MachineFunction &MF = DAG.getMachineFunction();
1997 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1999 MipsFI->setCallsEhReturn();
2000 SDValue Chain = Op.getOperand(0);
2001 SDValue Offset = Op.getOperand(1);
2002 SDValue Handler = Op.getOperand(2);
2004 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2006 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2007 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2008 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2009 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2010 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2011 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2012 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2013 DAG.getRegister(OffsetReg, Ty),
2014 DAG.getRegister(AddrReg, getPointerTy()),
2018 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2019 SelectionDAG &DAG) const {
2020 // FIXME: Need pseudo-fence for 'singlethread' fences
2021 // FIXME: Set SType for weaker fences where supported/appropriate.
2024 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2025 DAG.getConstant(SType, MVT::i32));
2028 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2029 SelectionDAG &DAG) const {
2031 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2033 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2034 SDValue Shamt = Op.getOperand(2);
2035 // if shamt < (VT.bits):
2036 // lo = (shl lo, shamt)
2037 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2040 // hi = (shl lo, shamt[4:0])
2041 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2042 DAG.getConstant(-1, MVT::i32));
2043 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2044 DAG.getConstant(1, VT));
2045 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2046 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2047 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2048 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2049 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2050 DAG.getConstant(0x20, MVT::i32));
2051 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2052 DAG.getConstant(0, VT), ShiftLeftLo);
2053 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2055 SDValue Ops[2] = {Lo, Hi};
2056 return DAG.getMergeValues(Ops, DL);
2059 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2062 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2063 SDValue Shamt = Op.getOperand(2);
2064 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2066 // if shamt < (VT.bits):
2067 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2069 // hi = (sra hi, shamt)
2071 // hi = (srl hi, shamt)
2074 // lo = (sra hi, shamt[4:0])
2075 // hi = (sra hi, 31)
2077 // lo = (srl hi, shamt[4:0])
2079 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2080 DAG.getConstant(-1, MVT::i32));
2081 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2082 DAG.getConstant(1, VT));
2083 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2084 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2085 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2086 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2088 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2089 DAG.getConstant(0x20, MVT::i32));
2090 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, VT, Hi, DAG.getConstant(31, VT));
2091 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2092 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2093 IsSRA ? Shift31 : DAG.getConstant(0, VT), ShiftRightHi);
2095 SDValue Ops[2] = {Lo, Hi};
2096 return DAG.getMergeValues(Ops, DL);
2099 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2100 SDValue Chain, SDValue Src, unsigned Offset) {
2101 SDValue Ptr = LD->getBasePtr();
2102 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2103 EVT BasePtrVT = Ptr.getValueType();
2105 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2108 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2109 DAG.getConstant(Offset, BasePtrVT));
2111 SDValue Ops[] = { Chain, Ptr, Src };
2112 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2113 LD->getMemOperand());
2116 // Expand an unaligned 32 or 64-bit integer load node.
2117 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2118 LoadSDNode *LD = cast<LoadSDNode>(Op);
2119 EVT MemVT = LD->getMemoryVT();
2121 if (Subtarget.systemSupportsUnalignedAccess())
2124 // Return if load is aligned or if MemVT is neither i32 nor i64.
2125 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2126 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2129 bool IsLittle = Subtarget.isLittle();
2130 EVT VT = Op.getValueType();
2131 ISD::LoadExtType ExtType = LD->getExtensionType();
2132 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2134 assert((VT == MVT::i32) || (VT == MVT::i64));
2137 // (set dst, (i64 (load baseptr)))
2139 // (set tmp, (ldl (add baseptr, 7), undef))
2140 // (set dst, (ldr baseptr, tmp))
2141 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2142 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2144 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2148 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2150 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2154 // (set dst, (i32 (load baseptr))) or
2155 // (set dst, (i64 (sextload baseptr))) or
2156 // (set dst, (i64 (extload baseptr)))
2158 // (set tmp, (lwl (add baseptr, 3), undef))
2159 // (set dst, (lwr baseptr, tmp))
2160 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2161 (ExtType == ISD::EXTLOAD))
2164 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2167 // (set dst, (i64 (zextload baseptr)))
2169 // (set tmp0, (lwl (add baseptr, 3), undef))
2170 // (set tmp1, (lwr baseptr, tmp0))
2171 // (set tmp2, (shl tmp1, 32))
2172 // (set dst, (srl tmp2, 32))
2174 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2175 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2176 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2177 SDValue Ops[] = { SRL, LWR.getValue(1) };
2178 return DAG.getMergeValues(Ops, DL);
2181 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2182 SDValue Chain, unsigned Offset) {
2183 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2184 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2186 SDVTList VTList = DAG.getVTList(MVT::Other);
2189 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2190 DAG.getConstant(Offset, BasePtrVT));
2192 SDValue Ops[] = { Chain, Value, Ptr };
2193 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2194 SD->getMemOperand());
2197 // Expand an unaligned 32 or 64-bit integer store node.
2198 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2200 SDValue Value = SD->getValue(), Chain = SD->getChain();
2201 EVT VT = Value.getValueType();
2204 // (store val, baseptr) or
2205 // (truncstore val, baseptr)
2207 // (swl val, (add baseptr, 3))
2208 // (swr val, baseptr)
2209 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2210 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2212 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2215 assert(VT == MVT::i64);
2218 // (store val, baseptr)
2220 // (sdl val, (add baseptr, 7))
2221 // (sdr val, baseptr)
2222 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2223 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2226 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2227 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2228 SDValue Val = SD->getValue();
2230 if (Val.getOpcode() != ISD::FP_TO_SINT)
2233 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2234 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2237 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2238 SD->getPointerInfo(), SD->isVolatile(),
2239 SD->isNonTemporal(), SD->getAlignment());
2242 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2243 StoreSDNode *SD = cast<StoreSDNode>(Op);
2244 EVT MemVT = SD->getMemoryVT();
2246 // Lower unaligned integer stores.
2247 if (!Subtarget.systemSupportsUnalignedAccess() &&
2248 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2249 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2250 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2252 return lowerFP_TO_SINT_STORE(SD, DAG);
2255 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2256 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2257 || cast<ConstantSDNode>
2258 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2259 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2263 // (add (frameaddr 0), (frame_to_args_offset))
2264 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2265 // (add FrameObject, 0)
2266 // where FrameObject is a fixed StackObject with offset 0 which points to
2267 // the old stack pointer.
2268 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2269 EVT ValTy = Op->getValueType(0);
2270 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2271 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2272 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2273 DAG.getConstant(0, ValTy));
2276 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2277 SelectionDAG &DAG) const {
2278 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2279 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2281 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2284 //===----------------------------------------------------------------------===//
2285 // Calling Convention Implementation
2286 //===----------------------------------------------------------------------===//
2288 //===----------------------------------------------------------------------===//
2289 // TODO: Implement a generic logic using tblgen that can support this.
2290 // Mips O32 ABI rules:
2292 // i32 - Passed in A0, A1, A2, A3 and stack
2293 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2294 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2295 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2296 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2297 // not used, it must be shadowed. If only A3 is available, shadow it and
2300 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2301 //===----------------------------------------------------------------------===//
2303 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2304 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2305 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2306 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2307 State.getMachineFunction().getSubtarget());
2309 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2310 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2312 // Do not process byval args here.
2313 if (ArgFlags.isByVal())
2316 // Promote i8 and i16
2317 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2318 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2320 if (ArgFlags.isSExt())
2321 LocInfo = CCValAssign::SExtUpper;
2322 else if (ArgFlags.isZExt())
2323 LocInfo = CCValAssign::ZExtUpper;
2325 LocInfo = CCValAssign::AExtUpper;
2329 // Promote i8 and i16
2330 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2332 if (ArgFlags.isSExt())
2333 LocInfo = CCValAssign::SExt;
2334 else if (ArgFlags.isZExt())
2335 LocInfo = CCValAssign::ZExt;
2337 LocInfo = CCValAssign::AExt;
2342 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2343 // is true: function is vararg, argument is 3rd or higher, there is previous
2344 // argument which is not f32 or f64.
2345 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2346 State.getFirstUnallocated(F32Regs) != ValNo;
2347 unsigned OrigAlign = ArgFlags.getOrigAlign();
2348 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2350 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2351 Reg = State.AllocateReg(IntRegs);
2352 // If this is the first part of an i64 arg,
2353 // the allocated register must be either A0 or A2.
2354 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2355 Reg = State.AllocateReg(IntRegs);
2357 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2358 // Allocate int register and shadow next int register. If first
2359 // available register is Mips::A1 or Mips::A3, shadow it too.
2360 Reg = State.AllocateReg(IntRegs);
2361 if (Reg == Mips::A1 || Reg == Mips::A3)
2362 Reg = State.AllocateReg(IntRegs);
2363 State.AllocateReg(IntRegs);
2365 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2366 // we are guaranteed to find an available float register
2367 if (ValVT == MVT::f32) {
2368 Reg = State.AllocateReg(F32Regs);
2369 // Shadow int register
2370 State.AllocateReg(IntRegs);
2372 Reg = State.AllocateReg(F64Regs);
2373 // Shadow int registers
2374 unsigned Reg2 = State.AllocateReg(IntRegs);
2375 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2376 State.AllocateReg(IntRegs);
2377 State.AllocateReg(IntRegs);
2380 llvm_unreachable("Cannot handle this ValVT.");
2383 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2385 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2387 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2392 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2393 MVT LocVT, CCValAssign::LocInfo LocInfo,
2394 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2395 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2397 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2400 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2401 MVT LocVT, CCValAssign::LocInfo LocInfo,
2402 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2403 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2405 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2408 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2409 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2410 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2412 #include "MipsGenCallingConv.inc"
2414 //===----------------------------------------------------------------------===//
2415 // Call Calling Convention Implementation
2416 //===----------------------------------------------------------------------===//
2418 // Return next O32 integer argument register.
2419 static unsigned getNextIntArgReg(unsigned Reg) {
2420 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2421 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2425 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2426 SDValue Chain, SDValue Arg, SDLoc DL,
2427 bool IsTailCall, SelectionDAG &DAG) const {
2429 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2430 DAG.getIntPtrConstant(Offset));
2431 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2435 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2436 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2437 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2438 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2439 /*isVolatile=*/ true, false, 0);
2442 void MipsTargetLowering::
2443 getOpndList(SmallVectorImpl<SDValue> &Ops,
2444 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2445 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2446 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2447 SDValue Chain) const {
2448 // Insert node "GP copy globalreg" before call to function.
2450 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2451 // in PIC mode) allow symbols to be resolved via lazy binding.
2452 // The lazy binding stub requires GP to point to the GOT.
2453 // Note that we don't need GP to point to the GOT for indirect calls
2454 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2455 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2456 // used for the function (that is, Mips linker doesn't generate lazy binding
2457 // stub for a function whose address is taken in the program).
2458 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2459 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2460 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2461 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2464 // Build a sequence of copy-to-reg nodes chained together with token
2465 // chain and flag operands which copy the outgoing args into registers.
2466 // The InFlag in necessary since all emitted instructions must be
2470 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2471 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2472 RegsToPass[i].second, InFlag);
2473 InFlag = Chain.getValue(1);
2476 // Add argument registers to the end of the list so that they are
2477 // known live into the call.
2478 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2479 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2480 RegsToPass[i].second.getValueType()));
2482 // Add a register mask operand representing the call-preserved registers.
2483 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2484 const uint32_t *Mask =
2485 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2486 assert(Mask && "Missing call preserved mask for calling convention");
2487 if (Subtarget.inMips16HardFloat()) {
2488 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2489 llvm::StringRef Sym = G->getGlobal()->getName();
2490 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2491 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2492 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2496 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2498 if (InFlag.getNode())
2499 Ops.push_back(InFlag);
2502 /// LowerCall - functions arguments are copied from virtual regs to
2503 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2505 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2506 SmallVectorImpl<SDValue> &InVals) const {
2507 SelectionDAG &DAG = CLI.DAG;
2509 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2510 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2511 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2512 SDValue Chain = CLI.Chain;
2513 SDValue Callee = CLI.Callee;
2514 bool &IsTailCall = CLI.IsTailCall;
2515 CallingConv::ID CallConv = CLI.CallConv;
2516 bool IsVarArg = CLI.IsVarArg;
2518 MachineFunction &MF = DAG.getMachineFunction();
2519 MachineFrameInfo *MFI = MF.getFrameInfo();
2520 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2521 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2522 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2524 // Analyze operands of the call, assigning locations to each operand.
2525 SmallVector<CCValAssign, 16> ArgLocs;
2527 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2528 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2530 // Allocate the reserved argument area. It seems strange to do this from the
2531 // caller side but removing it breaks the frame size calculation.
2532 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2534 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2536 // Get a count of how many bytes are to be pushed on the stack.
2537 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2539 // Check if it's really possible to do a tail call.
2541 IsTailCall = isEligibleForTailCallOptimization(
2542 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2544 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2545 report_fatal_error("failed to perform tail call elimination on a call "
2546 "site marked musttail");
2551 // Chain is the output chain of the last Load/Store or CopyToReg node.
2552 // ByValChain is the output chain of the last Memcpy node created for copying
2553 // byval arguments to the stack.
2554 unsigned StackAlignment = TFL->getStackAlignment();
2555 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2556 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2559 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2561 SDValue StackPtr = DAG.getCopyFromReg(
2562 Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2564 // With EABI is it possible to have 16 args on registers.
2565 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2566 SmallVector<SDValue, 8> MemOpChains;
2568 CCInfo.rewindByValRegsInfo();
2570 // Walk the register/memloc assignments, inserting copies/loads.
2571 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2572 SDValue Arg = OutVals[i];
2573 CCValAssign &VA = ArgLocs[i];
2574 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2575 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2576 bool UseUpperBits = false;
2579 if (Flags.isByVal()) {
2580 unsigned FirstByValReg, LastByValReg;
2581 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2582 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2584 assert(Flags.getByValSize() &&
2585 "ByVal args of size 0 should have been ignored by front-end.");
2586 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2587 assert(!IsTailCall &&
2588 "Do not tail-call optimize if there is a byval argument.");
2589 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2590 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2592 CCInfo.nextInRegsParam();
2596 // Promote the value if needed.
2597 switch (VA.getLocInfo()) {
2599 llvm_unreachable("Unknown loc info!");
2600 case CCValAssign::Full:
2601 if (VA.isRegLoc()) {
2602 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2603 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2604 (ValVT == MVT::i64 && LocVT == MVT::f64))
2605 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2606 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2607 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2608 Arg, DAG.getConstant(0, MVT::i32));
2609 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2610 Arg, DAG.getConstant(1, MVT::i32));
2611 if (!Subtarget.isLittle())
2613 unsigned LocRegLo = VA.getLocReg();
2614 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2615 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2616 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2621 case CCValAssign::BCvt:
2622 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2624 case CCValAssign::SExtUpper:
2625 UseUpperBits = true;
2627 case CCValAssign::SExt:
2628 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2630 case CCValAssign::ZExtUpper:
2631 UseUpperBits = true;
2633 case CCValAssign::ZExt:
2634 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2636 case CCValAssign::AExtUpper:
2637 UseUpperBits = true;
2639 case CCValAssign::AExt:
2640 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2645 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2646 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2648 ISD::SHL, DL, VA.getLocVT(), Arg,
2649 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2652 // Arguments that can be passed on register must be kept at
2653 // RegsToPass vector
2654 if (VA.isRegLoc()) {
2655 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2659 // Register can't get to this point...
2660 assert(VA.isMemLoc());
2662 // emit ISD::STORE whichs stores the
2663 // parameter value to a stack Location
2664 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2665 Chain, Arg, DL, IsTailCall, DAG));
2668 // Transform all store nodes into one single node because all store
2669 // nodes are independent of each other.
2670 if (!MemOpChains.empty())
2671 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2673 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2674 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2675 // node so that legalize doesn't hack it.
2676 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2678 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2680 EVT Ty = Callee.getValueType();
2682 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2684 const GlobalValue *Val = G->getGlobal();
2685 InternalLinkage = Val->hasInternalLinkage();
2687 if (InternalLinkage)
2688 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2689 else if (LargeGOT) {
2690 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2691 MipsII::MO_CALL_LO16, Chain,
2692 FuncInfo->callPtrInfo(Val));
2695 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2696 FuncInfo->callPtrInfo(Val));
2700 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2701 MipsII::MO_NO_FLAG);
2702 GlobalOrExternal = true;
2704 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2705 const char *Sym = S->getSymbol();
2707 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2709 DAG.getTargetExternalSymbol(Sym, getPointerTy(), MipsII::MO_NO_FLAG);
2710 else if (LargeGOT) {
2711 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2712 MipsII::MO_CALL_LO16, Chain,
2713 FuncInfo->callPtrInfo(Sym));
2715 } else { // N64 || PIC
2716 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2717 FuncInfo->callPtrInfo(Sym));
2721 GlobalOrExternal = true;
2724 SmallVector<SDValue, 8> Ops(1, Chain);
2725 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2727 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2728 IsCallReloc, CLI, Callee, Chain);
2731 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2733 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2734 SDValue InFlag = Chain.getValue(1);
2736 // Create the CALLSEQ_END node.
2737 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2738 DAG.getIntPtrConstant(0, true), InFlag, DL);
2739 InFlag = Chain.getValue(1);
2741 // Handle result values, copying them out of physregs into vregs that we
2743 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2747 /// LowerCallResult - Lower the result values of a call into the
2748 /// appropriate copies out of appropriate physical registers.
2749 SDValue MipsTargetLowering::LowerCallResult(
2750 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2751 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2752 SmallVectorImpl<SDValue> &InVals,
2753 TargetLowering::CallLoweringInfo &CLI) const {
2754 // Assign locations to each value returned by this call.
2755 SmallVector<CCValAssign, 16> RVLocs;
2756 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2758 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2760 // Copy all of the result registers out of their specified physreg.
2761 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2762 CCValAssign &VA = RVLocs[i];
2763 assert(VA.isRegLoc() && "Can only return in registers!");
2765 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2766 RVLocs[i].getLocVT(), InFlag);
2767 Chain = Val.getValue(1);
2768 InFlag = Val.getValue(2);
2770 if (VA.isUpperBitsInLoc()) {
2771 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2772 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2774 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2776 Shift, DL, VA.getLocVT(), Val,
2777 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2780 switch (VA.getLocInfo()) {
2782 llvm_unreachable("Unknown loc info!");
2783 case CCValAssign::Full:
2785 case CCValAssign::BCvt:
2786 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2788 case CCValAssign::AExt:
2789 case CCValAssign::AExtUpper:
2790 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2792 case CCValAssign::ZExt:
2793 case CCValAssign::ZExtUpper:
2794 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2795 DAG.getValueType(VA.getValVT()));
2796 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2798 case CCValAssign::SExt:
2799 case CCValAssign::SExtUpper:
2800 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2801 DAG.getValueType(VA.getValVT()));
2802 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2806 InVals.push_back(Val);
2812 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2813 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2814 MVT LocVT = VA.getLocVT();
2815 EVT ValVT = VA.getValVT();
2817 // Shift into the upper bits if necessary.
2818 switch (VA.getLocInfo()) {
2821 case CCValAssign::AExtUpper:
2822 case CCValAssign::SExtUpper:
2823 case CCValAssign::ZExtUpper: {
2824 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2825 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2827 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2829 Opcode, DL, VA.getLocVT(), Val,
2830 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2835 // If this is an value smaller than the argument slot size (32-bit for O32,
2836 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2837 // size. Extract the value and insert any appropriate assertions regarding
2838 // sign/zero extension.
2839 switch (VA.getLocInfo()) {
2841 llvm_unreachable("Unknown loc info!");
2842 case CCValAssign::Full:
2844 case CCValAssign::AExtUpper:
2845 case CCValAssign::AExt:
2846 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2848 case CCValAssign::SExtUpper:
2849 case CCValAssign::SExt:
2850 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2851 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2853 case CCValAssign::ZExtUpper:
2854 case CCValAssign::ZExt:
2855 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2856 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2858 case CCValAssign::BCvt:
2859 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2866 //===----------------------------------------------------------------------===//
2867 // Formal Arguments Calling Convention Implementation
2868 //===----------------------------------------------------------------------===//
2869 /// LowerFormalArguments - transform physical registers into virtual registers
2870 /// and generate load operations for arguments places on the stack.
2872 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2873 CallingConv::ID CallConv,
2875 const SmallVectorImpl<ISD::InputArg> &Ins,
2876 SDLoc DL, SelectionDAG &DAG,
2877 SmallVectorImpl<SDValue> &InVals)
2879 MachineFunction &MF = DAG.getMachineFunction();
2880 MachineFrameInfo *MFI = MF.getFrameInfo();
2881 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2883 MipsFI->setVarArgsFrameIndex(0);
2885 // Used with vargs to acumulate store chains.
2886 std::vector<SDValue> OutChains;
2888 // Assign locations to all of the incoming arguments.
2889 SmallVector<CCValAssign, 16> ArgLocs;
2890 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2892 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2893 Function::const_arg_iterator FuncArg =
2894 DAG.getMachineFunction().getFunction()->arg_begin();
2896 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2897 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2898 CCInfo.getInRegsParamsCount() > 0);
2900 unsigned CurArgIdx = 0;
2901 CCInfo.rewindByValRegsInfo();
2903 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2904 CCValAssign &VA = ArgLocs[i];
2905 if (Ins[i].isOrigArg()) {
2906 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2907 CurArgIdx = Ins[i].getOrigArgIndex();
2909 EVT ValVT = VA.getValVT();
2910 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2911 bool IsRegLoc = VA.isRegLoc();
2913 if (Flags.isByVal()) {
2914 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2915 unsigned FirstByValReg, LastByValReg;
2916 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2917 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2919 assert(Flags.getByValSize() &&
2920 "ByVal args of size 0 should have been ignored by front-end.");
2921 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2922 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2923 FirstByValReg, LastByValReg, VA, CCInfo);
2924 CCInfo.nextInRegsParam();
2928 // Arguments stored on registers
2930 MVT RegVT = VA.getLocVT();
2931 unsigned ArgReg = VA.getLocReg();
2932 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2934 // Transform the arguments stored on
2935 // physical registers into virtual ones
2936 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2937 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2939 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2941 // Handle floating point arguments passed in integer registers and
2942 // long double arguments passed in floating point registers.
2943 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2944 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2945 (RegVT == MVT::f64 && ValVT == MVT::i64))
2946 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2947 else if (ABI.IsO32() && RegVT == MVT::i32 &&
2948 ValVT == MVT::f64) {
2949 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2950 getNextIntArgReg(ArgReg), RC);
2951 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2952 if (!Subtarget.isLittle())
2953 std::swap(ArgValue, ArgValue2);
2954 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2955 ArgValue, ArgValue2);
2958 InVals.push_back(ArgValue);
2959 } else { // VA.isRegLoc()
2960 MVT LocVT = VA.getLocVT();
2963 // We ought to be able to use LocVT directly but O32 sets it to i32
2964 // when allocating floating point values to integer registers.
2965 // This shouldn't influence how we load the value into registers unless
2966 // we are targetting softfloat.
2967 if (VA.getValVT().isFloatingPoint() && !Subtarget.abiUsesSoftFloat())
2968 LocVT = VA.getValVT();
2972 assert(VA.isMemLoc());
2974 // The stack pointer offset is relative to the caller stack frame.
2975 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
2976 VA.getLocMemOffset(), true);
2978 // Create load nodes to retrieve arguments from the stack
2979 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2980 SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2981 MachinePointerInfo::getFixedStack(FI),
2982 false, false, false, 0);
2983 OutChains.push_back(ArgValue.getValue(1));
2985 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2987 InVals.push_back(ArgValue);
2991 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2992 // The mips ABIs for returning structs by value requires that we copy
2993 // the sret argument into $v0 for the return. Save the argument into
2994 // a virtual register so that we can access it from the return points.
2995 if (Ins[i].Flags.isSRet()) {
2996 unsigned Reg = MipsFI->getSRetReturnReg();
2998 Reg = MF.getRegInfo().createVirtualRegister(
2999 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3000 MipsFI->setSRetReturnReg(Reg);
3002 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3003 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3009 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3011 // All stores are grouped in one node to allow the matching between
3012 // the size of Ins and InVals. This only happens when on varg functions
3013 if (!OutChains.empty()) {
3014 OutChains.push_back(Chain);
3015 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3021 //===----------------------------------------------------------------------===//
3022 // Return Value Calling Convention Implementation
3023 //===----------------------------------------------------------------------===//
3026 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3027 MachineFunction &MF, bool IsVarArg,
3028 const SmallVectorImpl<ISD::OutputArg> &Outs,
3029 LLVMContext &Context) const {
3030 SmallVector<CCValAssign, 16> RVLocs;
3031 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3032 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3036 MipsTargetLowering::LowerReturn(SDValue Chain,
3037 CallingConv::ID CallConv, bool IsVarArg,
3038 const SmallVectorImpl<ISD::OutputArg> &Outs,
3039 const SmallVectorImpl<SDValue> &OutVals,
3040 SDLoc DL, SelectionDAG &DAG) const {
3041 // CCValAssign - represent the assignment of
3042 // the return value to a location
3043 SmallVector<CCValAssign, 16> RVLocs;
3044 MachineFunction &MF = DAG.getMachineFunction();
3046 // CCState - Info about the registers and stack slot.
3047 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3049 // Analyze return values.
3050 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3053 SmallVector<SDValue, 4> RetOps(1, Chain);
3055 // Copy the result values into the output registers.
3056 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3057 SDValue Val = OutVals[i];
3058 CCValAssign &VA = RVLocs[i];
3059 assert(VA.isRegLoc() && "Can only return in registers!");
3060 bool UseUpperBits = false;
3062 switch (VA.getLocInfo()) {
3064 llvm_unreachable("Unknown loc info!");
3065 case CCValAssign::Full:
3067 case CCValAssign::BCvt:
3068 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3070 case CCValAssign::AExtUpper:
3071 UseUpperBits = true;
3073 case CCValAssign::AExt:
3074 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3076 case CCValAssign::ZExtUpper:
3077 UseUpperBits = true;
3079 case CCValAssign::ZExt:
3080 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3082 case CCValAssign::SExtUpper:
3083 UseUpperBits = true;
3085 case CCValAssign::SExt:
3086 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3091 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3092 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3094 ISD::SHL, DL, VA.getLocVT(), Val,
3095 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3098 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3100 // Guarantee that all emitted copies are stuck together with flags.
3101 Flag = Chain.getValue(1);
3102 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3105 // The mips ABIs for returning structs by value requires that we copy
3106 // the sret argument into $v0 for the return. We saved the argument into
3107 // a virtual register in the entry block, so now we copy the value out
3109 if (MF.getFunction()->hasStructRetAttr()) {
3110 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3111 unsigned Reg = MipsFI->getSRetReturnReg();
3114 llvm_unreachable("sret virtual register not created in the entry block");
3115 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3116 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3118 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3119 Flag = Chain.getValue(1);
3120 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3123 RetOps[0] = Chain; // Update chain.
3125 // Add the flag if we have it.
3127 RetOps.push_back(Flag);
3129 // Return on Mips is always a "jr $ra"
3130 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3133 //===----------------------------------------------------------------------===//
3134 // Mips Inline Assembly Support
3135 //===----------------------------------------------------------------------===//
3137 /// getConstraintType - Given a constraint letter, return the type of
3138 /// constraint it is for this target.
3139 MipsTargetLowering::ConstraintType MipsTargetLowering::
3140 getConstraintType(const std::string &Constraint) const
3142 // Mips specific constraints
3143 // GCC config/mips/constraints.md
3145 // 'd' : An address register. Equivalent to r
3146 // unless generating MIPS16 code.
3147 // 'y' : Equivalent to r; retained for
3148 // backwards compatibility.
3149 // 'c' : A register suitable for use in an indirect
3150 // jump. This will always be $25 for -mabicalls.
3151 // 'l' : The lo register. 1 word storage.
3152 // 'x' : The hilo register pair. Double word storage.
3153 if (Constraint.size() == 1) {
3154 switch (Constraint[0]) {
3162 return C_RegisterClass;
3167 return TargetLowering::getConstraintType(Constraint);
3170 /// Examine constraint type and operand type and determine a weight value.
3171 /// This object must already have been set up with the operand type
3172 /// and the current alternative constraint selected.
3173 TargetLowering::ConstraintWeight
3174 MipsTargetLowering::getSingleConstraintMatchWeight(
3175 AsmOperandInfo &info, const char *constraint) const {
3176 ConstraintWeight weight = CW_Invalid;
3177 Value *CallOperandVal = info.CallOperandVal;
3178 // If we don't have a value, we can't do a match,
3179 // but allow it at the lowest weight.
3180 if (!CallOperandVal)
3182 Type *type = CallOperandVal->getType();
3183 // Look at the constraint type.
3184 switch (*constraint) {
3186 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3190 if (type->isIntegerTy())
3191 weight = CW_Register;
3193 case 'f': // FPU or MSA register
3194 if (Subtarget.hasMSA() && type->isVectorTy() &&
3195 cast<VectorType>(type)->getBitWidth() == 128)
3196 weight = CW_Register;
3197 else if (type->isFloatTy())
3198 weight = CW_Register;
3200 case 'c': // $25 for indirect jumps
3201 case 'l': // lo register
3202 case 'x': // hilo register pair
3203 if (type->isIntegerTy())
3204 weight = CW_SpecificReg;
3206 case 'I': // signed 16 bit immediate
3207 case 'J': // integer zero
3208 case 'K': // unsigned 16 bit immediate
3209 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3210 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3211 case 'O': // signed 15 bit immediate (+- 16383)
3212 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3213 if (isa<ConstantInt>(CallOperandVal))
3214 weight = CW_Constant;
3223 /// This is a helper function to parse a physical register string and split it
3224 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3225 /// that is returned indicates whether parsing was successful. The second flag
3226 /// is true if the numeric part exists.
3227 static std::pair<bool, bool>
3228 parsePhysicalReg(StringRef C, std::string &Prefix,
3229 unsigned long long &Reg) {
3230 if (C.front() != '{' || C.back() != '}')
3231 return std::make_pair(false, false);
3233 // Search for the first numeric character.
3234 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3235 I = std::find_if(B, E, std::ptr_fun(isdigit));
3237 Prefix.assign(B, I - B);
3239 // The second flag is set to false if no numeric characters were found.
3241 return std::make_pair(true, false);
3243 // Parse the numeric characters.
3244 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3248 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3249 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3250 const TargetRegisterInfo *TRI =
3251 Subtarget.getRegisterInfo();
3252 const TargetRegisterClass *RC;
3254 unsigned long long Reg;
3256 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3259 return std::make_pair(0U, nullptr);
3261 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3262 // No numeric characters follow "hi" or "lo".
3264 return std::make_pair(0U, nullptr);
3266 RC = TRI->getRegClass(Prefix == "hi" ?
3267 Mips::HI32RegClassID : Mips::LO32RegClassID);
3268 return std::make_pair(*(RC->begin()), RC);
3269 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3270 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3272 // No numeric characters follow the name.
3274 return std::make_pair(0U, nullptr);
3276 Reg = StringSwitch<unsigned long long>(Prefix)
3277 .Case("$msair", Mips::MSAIR)
3278 .Case("$msacsr", Mips::MSACSR)
3279 .Case("$msaaccess", Mips::MSAAccess)
3280 .Case("$msasave", Mips::MSASave)
3281 .Case("$msamodify", Mips::MSAModify)
3282 .Case("$msarequest", Mips::MSARequest)
3283 .Case("$msamap", Mips::MSAMap)
3284 .Case("$msaunmap", Mips::MSAUnmap)
3288 return std::make_pair(0U, nullptr);
3290 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3291 return std::make_pair(Reg, RC);
3295 return std::make_pair(0U, nullptr);
3297 if (Prefix == "$f") { // Parse $f0-$f31.
3298 // If the size of FP registers is 64-bit or Reg is an even number, select
3299 // the 64-bit register class. Otherwise, select the 32-bit register class.
3300 if (VT == MVT::Other)
3301 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3303 RC = getRegClassFor(VT);
3305 if (RC == &Mips::AFGR64RegClass) {
3306 assert(Reg % 2 == 0);
3309 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3310 RC = TRI->getRegClass(Mips::FCCRegClassID);
3311 else if (Prefix == "$w") { // Parse $w0-$w31.
3312 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3313 } else { // Parse $0-$31.
3314 assert(Prefix == "$");
3315 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3318 assert(Reg < RC->getNumRegs());
3319 return std::make_pair(*(RC->begin() + Reg), RC);
3322 /// Given a register class constraint, like 'r', if this corresponds directly
3323 /// to an LLVM register class, return a register of 0 and the register class
3325 std::pair<unsigned, const TargetRegisterClass *>
3326 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3327 const std::string &Constraint,
3329 if (Constraint.size() == 1) {
3330 switch (Constraint[0]) {
3331 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3332 case 'y': // Same as 'r'. Exists for compatibility.
3334 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3335 if (Subtarget.inMips16Mode())
3336 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3337 return std::make_pair(0U, &Mips::GPR32RegClass);
3339 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3340 return std::make_pair(0U, &Mips::GPR32RegClass);
3341 if (VT == MVT::i64 && Subtarget.isGP64bit())
3342 return std::make_pair(0U, &Mips::GPR64RegClass);
3343 // This will generate an error message
3344 return std::make_pair(0U, nullptr);
3345 case 'f': // FPU or MSA register
3346 if (VT == MVT::v16i8)
3347 return std::make_pair(0U, &Mips::MSA128BRegClass);
3348 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3349 return std::make_pair(0U, &Mips::MSA128HRegClass);
3350 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3351 return std::make_pair(0U, &Mips::MSA128WRegClass);
3352 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3353 return std::make_pair(0U, &Mips::MSA128DRegClass);
3354 else if (VT == MVT::f32)
3355 return std::make_pair(0U, &Mips::FGR32RegClass);
3356 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3357 if (Subtarget.isFP64bit())
3358 return std::make_pair(0U, &Mips::FGR64RegClass);
3359 return std::make_pair(0U, &Mips::AFGR64RegClass);
3362 case 'c': // register suitable for indirect jump
3364 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3365 assert(VT == MVT::i64 && "Unexpected type.");
3366 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3367 case 'l': // register suitable for indirect jump
3369 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3370 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3371 case 'x': // register suitable for indirect jump
3372 // Fixme: Not triggering the use of both hi and low
3373 // This will generate an error message
3374 return std::make_pair(0U, nullptr);
3378 std::pair<unsigned, const TargetRegisterClass *> R;
3379 R = parseRegForInlineAsmConstraint(Constraint, VT);
3384 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3387 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3388 /// vector. If it is invalid, don't add anything to Ops.
3389 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3390 std::string &Constraint,
3391 std::vector<SDValue>&Ops,
3392 SelectionDAG &DAG) const {
3395 // Only support length 1 constraints for now.
3396 if (Constraint.length() > 1) return;
3398 char ConstraintLetter = Constraint[0];
3399 switch (ConstraintLetter) {
3400 default: break; // This will fall through to the generic implementation
3401 case 'I': // Signed 16 bit constant
3402 // If this fails, the parent routine will give an error
3403 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3404 EVT Type = Op.getValueType();
3405 int64_t Val = C->getSExtValue();
3406 if (isInt<16>(Val)) {
3407 Result = DAG.getTargetConstant(Val, Type);
3412 case 'J': // integer zero
3413 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3414 EVT Type = Op.getValueType();
3415 int64_t Val = C->getZExtValue();
3417 Result = DAG.getTargetConstant(0, Type);
3422 case 'K': // unsigned 16 bit immediate
3423 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3424 EVT Type = Op.getValueType();
3425 uint64_t Val = (uint64_t)C->getZExtValue();
3426 if (isUInt<16>(Val)) {
3427 Result = DAG.getTargetConstant(Val, Type);
3432 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3433 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3434 EVT Type = Op.getValueType();
3435 int64_t Val = C->getSExtValue();
3436 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3437 Result = DAG.getTargetConstant(Val, Type);
3442 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3443 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3444 EVT Type = Op.getValueType();
3445 int64_t Val = C->getSExtValue();
3446 if ((Val >= -65535) && (Val <= -1)) {
3447 Result = DAG.getTargetConstant(Val, Type);
3452 case 'O': // signed 15 bit immediate
3453 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3454 EVT Type = Op.getValueType();
3455 int64_t Val = C->getSExtValue();
3456 if ((isInt<15>(Val))) {
3457 Result = DAG.getTargetConstant(Val, Type);
3462 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3463 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3464 EVT Type = Op.getValueType();
3465 int64_t Val = C->getSExtValue();
3466 if ((Val <= 65535) && (Val >= 1)) {
3467 Result = DAG.getTargetConstant(Val, Type);
3474 if (Result.getNode()) {
3475 Ops.push_back(Result);
3479 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3482 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3484 // No global is ever allowed as a base.
3489 case 0: // "r+i" or just "i", depending on HasBaseReg.
3492 if (!AM.HasBaseReg) // allow "r+i".
3494 return false; // disallow "r+r" or "r+r+i".
3503 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3504 // The Mips target isn't yet aware of offsets.
3508 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3510 bool IsMemset, bool ZeroMemset,
3512 MachineFunction &MF) const {
3513 if (Subtarget.hasMips64())
3519 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3520 if (VT != MVT::f32 && VT != MVT::f64)
3522 if (Imm.isNegZero())
3524 return Imm.isZero();
3527 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3529 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3531 return TargetLowering::getJumpTableEncoding();
3534 void MipsTargetLowering::copyByValRegs(
3535 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3536 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3537 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3538 const CCValAssign &VA, MipsCCState &State) const {
3539 MachineFunction &MF = DAG.getMachineFunction();
3540 MachineFrameInfo *MFI = MF.getFrameInfo();
3541 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3542 unsigned NumRegs = LastReg - FirstReg;
3543 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3544 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3546 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3550 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3551 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3553 FrameObjOffset = VA.getLocMemOffset();
3555 // Create frame object.
3556 EVT PtrTy = getPointerTy();
3557 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3558 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3559 InVals.push_back(FIN);
3564 // Copy arg registers.
3565 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3566 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3568 for (unsigned I = 0; I < NumRegs; ++I) {
3569 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3570 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3571 unsigned Offset = I * GPRSizeInBytes;
3572 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3573 DAG.getConstant(Offset, PtrTy));
3574 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3575 StorePtr, MachinePointerInfo(FuncArg, Offset),
3577 OutChains.push_back(Store);
3581 // Copy byVal arg to registers and stack.
3582 void MipsTargetLowering::passByValArg(
3583 SDValue Chain, SDLoc DL,
3584 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3585 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3586 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3587 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3588 const CCValAssign &VA) const {
3589 unsigned ByValSizeInBytes = Flags.getByValSize();
3590 unsigned OffsetInBytes = 0; // From beginning of struct
3591 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3592 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3593 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3594 unsigned NumRegs = LastReg - FirstReg;
3597 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3598 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3601 // Copy words to registers.
3602 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3603 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3604 DAG.getConstant(OffsetInBytes, PtrTy));
3605 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3606 MachinePointerInfo(), false, false, false,
3608 MemOpChains.push_back(LoadVal.getValue(1));
3609 unsigned ArgReg = ArgRegs[FirstReg + I];
3610 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3613 // Return if the struct has been fully copied.
3614 if (ByValSizeInBytes == OffsetInBytes)
3617 // Copy the remainder of the byval argument with sub-word loads and shifts.
3618 if (LeftoverBytes) {
3621 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3622 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3623 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3625 if (RemainingSizeInBytes < LoadSizeInBytes)
3629 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3630 DAG.getConstant(OffsetInBytes, PtrTy));
3631 SDValue LoadVal = DAG.getExtLoad(
3632 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3633 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3635 MemOpChains.push_back(LoadVal.getValue(1));
3637 // Shift the loaded value.
3641 Shamt = TotalBytesLoaded * 8;
3643 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3645 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3646 DAG.getConstant(Shamt, MVT::i32));
3649 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3653 OffsetInBytes += LoadSizeInBytes;
3654 TotalBytesLoaded += LoadSizeInBytes;
3655 Alignment = std::min(Alignment, LoadSizeInBytes);
3658 unsigned ArgReg = ArgRegs[FirstReg + I];
3659 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3664 // Copy remainder of byval arg to it with memcpy.
3665 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3666 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3667 DAG.getConstant(OffsetInBytes, PtrTy));
3668 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3669 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3670 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3671 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3672 MachinePointerInfo(), MachinePointerInfo());
3673 MemOpChains.push_back(Chain);
3676 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3677 SDValue Chain, SDLoc DL,
3679 CCState &State) const {
3680 const ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3681 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3682 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3683 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3684 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3685 MachineFunction &MF = DAG.getMachineFunction();
3686 MachineFrameInfo *MFI = MF.getFrameInfo();
3687 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3689 // Offset of the first variable argument from stack pointer.
3692 if (ArgRegs.size() == Idx)
3694 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3697 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3698 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3701 // Record the frame index of the first variable argument
3702 // which is a value necessary to VASTART.
3703 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3704 MipsFI->setVarArgsFrameIndex(FI);
3706 // Copy the integer registers that have not been used for argument passing
3707 // to the argument register save area. For O32, the save area is allocated
3708 // in the caller's stack frame, while for N32/64, it is allocated in the
3709 // callee's stack frame.
3710 for (unsigned I = Idx; I < ArgRegs.size();
3711 ++I, VaArgOffset += RegSizeInBytes) {
3712 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3713 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3714 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3715 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3716 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3717 MachinePointerInfo(), false, false, 0);
3718 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3720 OutChains.push_back(Store);
3724 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3725 unsigned Align) const {
3726 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3728 assert(Size && "Byval argument's size shouldn't be 0.");
3730 Align = std::min(Align, TFL->getStackAlignment());
3732 unsigned FirstReg = 0;
3733 unsigned NumRegs = 0;
3735 if (State->getCallingConv() != CallingConv::Fast) {
3736 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3737 const ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3738 // FIXME: The O32 case actually describes no shadow registers.
3739 const MCPhysReg *ShadowRegs =
3740 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3742 // We used to check the size as well but we can't do that anymore since
3743 // CCState::HandleByVal() rounds up the size after calling this function.
3744 assert(!(Align % RegSizeInBytes) &&
3745 "Byval argument's alignment should be a multiple of"
3748 FirstReg = State->getFirstUnallocated(IntArgRegs);
3750 // If Align > RegSizeInBytes, the first arg register must be even.
3751 // FIXME: This condition happens to do the right thing but it's not the
3752 // right way to test it. We want to check that the stack frame offset
3753 // of the register is aligned.
3754 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3755 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3759 // Mark the registers allocated.
3760 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3761 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3762 Size -= RegSizeInBytes, ++I, ++NumRegs)
3763 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3766 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3770 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3771 bool isFPCmp, unsigned Opc) const {
3772 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3773 "Subtarget already supports SELECT nodes with the use of"
3774 "conditional-move instructions.");
3776 const TargetInstrInfo *TII =
3777 Subtarget.getInstrInfo();
3778 DebugLoc DL = MI->getDebugLoc();
3780 // To "insert" a SELECT instruction, we actually have to insert the
3781 // diamond control-flow pattern. The incoming instruction knows the
3782 // destination vreg to set, the condition code register to branch on, the
3783 // true/false values to select between, and a branch opcode to use.
3784 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3785 MachineFunction::iterator It = BB;
3792 // bNE r1, r0, copy1MBB
3793 // fallthrough --> copy0MBB
3794 MachineBasicBlock *thisMBB = BB;
3795 MachineFunction *F = BB->getParent();
3796 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3797 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3798 F->insert(It, copy0MBB);
3799 F->insert(It, sinkMBB);
3801 // Transfer the remainder of BB and its successor edges to sinkMBB.
3802 sinkMBB->splice(sinkMBB->begin(), BB,
3803 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3804 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3806 // Next, add the true and fallthrough blocks as its successors.
3807 BB->addSuccessor(copy0MBB);
3808 BB->addSuccessor(sinkMBB);
3811 // bc1[tf] cc, sinkMBB
3812 BuildMI(BB, DL, TII->get(Opc))
3813 .addReg(MI->getOperand(1).getReg())
3816 // bne rs, $0, sinkMBB
3817 BuildMI(BB, DL, TII->get(Opc))
3818 .addReg(MI->getOperand(1).getReg())
3824 // %FalseValue = ...
3825 // # fallthrough to sinkMBB
3828 // Update machine-CFG edges
3829 BB->addSuccessor(sinkMBB);
3832 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3836 BuildMI(*BB, BB->begin(), DL,
3837 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3838 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3839 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3841 MI->eraseFromParent(); // The pseudo instruction is gone now.
3846 // FIXME? Maybe this could be a TableGen attribute on some registers and
3847 // this table could be generated automatically from RegInfo.
3848 unsigned MipsTargetLowering::getRegisterByName(const char* RegName,
3850 // Named registers is expected to be fairly rare. For now, just support $28
3851 // since the linux kernel uses it.
3852 if (Subtarget.isGP64bit()) {
3853 unsigned Reg = StringSwitch<unsigned>(RegName)
3854 .Case("$28", Mips::GP_64)
3859 unsigned Reg = StringSwitch<unsigned>(RegName)
3860 .Case("$28", Mips::GP)
3865 report_fatal_error("Invalid register name global variable");