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 "MipsMachineFunction.h"
18 #include "MipsSubtarget.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsTargetObjectFile.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "mips-lower"
43 STATISTIC(NumTailCalls, "Number of tail calls");
46 LargeGOT("mxgot", cl::Hidden,
47 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
50 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
51 cl::desc("MIPS: Don't trap on integer division by zero."),
55 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
56 cl::desc("Allow mips-fast-isel to be used"),
59 static const MCPhysReg O32IntRegs[4] = {
60 Mips::A0, Mips::A1, Mips::A2, Mips::A3
63 static const MCPhysReg Mips64IntRegs[8] = {
64 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
65 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
68 static const MCPhysReg Mips64DPRegs[8] = {
69 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
70 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
73 // If I is a shifted mask, set the size (Size) and the first bit of the
74 // mask (Pos), and return true.
75 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
76 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
77 if (!isShiftedMask_64(I))
80 Size = CountPopulation_64(I);
81 Pos = countTrailingZeros(I);
85 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
86 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
87 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
90 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
96 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
102 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
108 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
114 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
116 unsigned Flag) const {
117 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
118 N->getOffset(), Flag);
121 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
123 case MipsISD::JmpLink: return "MipsISD::JmpLink";
124 case MipsISD::TailCall: return "MipsISD::TailCall";
125 case MipsISD::Hi: return "MipsISD::Hi";
126 case MipsISD::Lo: return "MipsISD::Lo";
127 case MipsISD::GPRel: return "MipsISD::GPRel";
128 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
129 case MipsISD::Ret: return "MipsISD::Ret";
130 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
131 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
132 case MipsISD::FPCmp: return "MipsISD::FPCmp";
133 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
134 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
135 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
136 case MipsISD::MFHI: return "MipsISD::MFHI";
137 case MipsISD::MFLO: return "MipsISD::MFLO";
138 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
139 case MipsISD::Mult: return "MipsISD::Mult";
140 case MipsISD::Multu: return "MipsISD::Multu";
141 case MipsISD::MAdd: return "MipsISD::MAdd";
142 case MipsISD::MAddu: return "MipsISD::MAddu";
143 case MipsISD::MSub: return "MipsISD::MSub";
144 case MipsISD::MSubu: return "MipsISD::MSubu";
145 case MipsISD::DivRem: return "MipsISD::DivRem";
146 case MipsISD::DivRemU: return "MipsISD::DivRemU";
147 case MipsISD::DivRem16: return "MipsISD::DivRem16";
148 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
149 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
150 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
151 case MipsISD::Wrapper: return "MipsISD::Wrapper";
152 case MipsISD::Sync: return "MipsISD::Sync";
153 case MipsISD::Ext: return "MipsISD::Ext";
154 case MipsISD::Ins: return "MipsISD::Ins";
155 case MipsISD::LWL: return "MipsISD::LWL";
156 case MipsISD::LWR: return "MipsISD::LWR";
157 case MipsISD::SWL: return "MipsISD::SWL";
158 case MipsISD::SWR: return "MipsISD::SWR";
159 case MipsISD::LDL: return "MipsISD::LDL";
160 case MipsISD::LDR: return "MipsISD::LDR";
161 case MipsISD::SDL: return "MipsISD::SDL";
162 case MipsISD::SDR: return "MipsISD::SDR";
163 case MipsISD::EXTP: return "MipsISD::EXTP";
164 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
165 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
166 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
167 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
168 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
169 case MipsISD::SHILO: return "MipsISD::SHILO";
170 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
171 case MipsISD::MULT: return "MipsISD::MULT";
172 case MipsISD::MULTU: return "MipsISD::MULTU";
173 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
174 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
175 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
176 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
177 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
178 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
179 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
180 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
181 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
182 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
183 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
184 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
185 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
186 case MipsISD::VCEQ: return "MipsISD::VCEQ";
187 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
188 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
189 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
190 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
191 case MipsISD::VSMAX: return "MipsISD::VSMAX";
192 case MipsISD::VSMIN: return "MipsISD::VSMIN";
193 case MipsISD::VUMAX: return "MipsISD::VUMAX";
194 case MipsISD::VUMIN: return "MipsISD::VUMIN";
195 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
196 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
197 case MipsISD::VNOR: return "MipsISD::VNOR";
198 case MipsISD::VSHF: return "MipsISD::VSHF";
199 case MipsISD::SHF: return "MipsISD::SHF";
200 case MipsISD::ILVEV: return "MipsISD::ILVEV";
201 case MipsISD::ILVOD: return "MipsISD::ILVOD";
202 case MipsISD::ILVL: return "MipsISD::ILVL";
203 case MipsISD::ILVR: return "MipsISD::ILVR";
204 case MipsISD::PCKEV: return "MipsISD::PCKEV";
205 case MipsISD::PCKOD: return "MipsISD::PCKOD";
206 case MipsISD::INSVE: return "MipsISD::INSVE";
207 default: return nullptr;
211 MipsTargetLowering::MipsTargetLowering(MipsTargetMachine &TM)
212 : TargetLowering(TM, new MipsTargetObjectFile()),
213 Subtarget(&TM.getSubtarget<MipsSubtarget>()) {
214 // Mips does not have i1 type, so use i32 for
215 // setcc operations results (slt, sgt, ...).
216 setBooleanContents(ZeroOrOneBooleanContent);
217 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
219 // Load extented operations for i1 types must be promoted
220 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
221 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
222 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
224 // MIPS doesn't have extending float->double load/store
225 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
226 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
228 // Used by legalize types to correctly generate the setcc result.
229 // Without this, every float setcc comes with a AND/OR with the result,
230 // we don't want this, since the fpcmp result goes to a flag register,
231 // which is used implicitly by brcond and select operations.
232 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
234 // Mips Custom Operations
235 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
236 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
237 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
238 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
239 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
240 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
241 setOperationAction(ISD::SELECT, MVT::f32, Custom);
242 setOperationAction(ISD::SELECT, MVT::f64, Custom);
243 setOperationAction(ISD::SELECT, MVT::i32, Custom);
244 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
245 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
246 setOperationAction(ISD::SETCC, MVT::f32, Custom);
247 setOperationAction(ISD::SETCC, MVT::f64, Custom);
248 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
249 setOperationAction(ISD::VASTART, 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);
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);
267 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
268 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::ADD, MVT::i32, Custom);
274 setOperationAction(ISD::ADD, MVT::i64, Custom);
276 setOperationAction(ISD::SDIV, MVT::i32, Expand);
277 setOperationAction(ISD::SREM, MVT::i32, Expand);
278 setOperationAction(ISD::UDIV, MVT::i32, Expand);
279 setOperationAction(ISD::UREM, MVT::i32, Expand);
280 setOperationAction(ISD::SDIV, MVT::i64, Expand);
281 setOperationAction(ISD::SREM, MVT::i64, Expand);
282 setOperationAction(ISD::UDIV, MVT::i64, Expand);
283 setOperationAction(ISD::UREM, MVT::i64, Expand);
285 // Operations not directly supported by Mips.
286 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
287 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
288 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
289 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
290 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
291 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
292 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
293 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
294 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
295 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
296 if (Subtarget->hasCnMips()) {
297 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
298 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
300 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
301 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
303 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
304 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
305 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
306 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
307 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
308 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
309 setOperationAction(ISD::ROTL, MVT::i32, Expand);
310 setOperationAction(ISD::ROTL, MVT::i64, Expand);
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
314 if (!Subtarget->hasMips32r2())
315 setOperationAction(ISD::ROTR, MVT::i32, Expand);
317 if (!Subtarget->hasMips64r2())
318 setOperationAction(ISD::ROTR, MVT::i64, Expand);
320 setOperationAction(ISD::FSIN, MVT::f32, Expand);
321 setOperationAction(ISD::FSIN, MVT::f64, Expand);
322 setOperationAction(ISD::FCOS, MVT::f32, Expand);
323 setOperationAction(ISD::FCOS, MVT::f64, Expand);
324 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
325 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
326 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
327 setOperationAction(ISD::FPOW, MVT::f32, Expand);
328 setOperationAction(ISD::FPOW, MVT::f64, Expand);
329 setOperationAction(ISD::FLOG, MVT::f32, Expand);
330 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
331 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
332 setOperationAction(ISD::FEXP, MVT::f32, Expand);
333 setOperationAction(ISD::FMA, MVT::f32, Expand);
334 setOperationAction(ISD::FMA, MVT::f64, Expand);
335 setOperationAction(ISD::FREM, MVT::f32, Expand);
336 setOperationAction(ISD::FREM, MVT::f64, Expand);
338 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
340 setOperationAction(ISD::VAARG, MVT::Other, Expand);
341 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
342 setOperationAction(ISD::VAEND, MVT::Other, Expand);
344 // Use the default for now
345 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
346 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
348 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
349 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
350 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
351 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
353 setInsertFencesForAtomic(true);
355 if (!Subtarget->hasSEInReg()) {
356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
360 if (!Subtarget->hasBitCount()) {
361 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
362 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
365 if (!Subtarget->hasMips32r2())
366 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
367 if (!Subtarget->hasMips64r2())
368 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
371 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
372 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
374 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
377 setOperationAction(ISD::TRAP, MVT::Other, Legal);
379 setTargetDAGCombine(ISD::SDIVREM);
380 setTargetDAGCombine(ISD::UDIVREM);
381 setTargetDAGCombine(ISD::SELECT);
382 setTargetDAGCombine(ISD::AND);
383 setTargetDAGCombine(ISD::OR);
384 setTargetDAGCombine(ISD::ADD);
386 setMinFunctionAlignment(isGP64bit() ? 3 : 2);
388 setStackPointerRegisterToSaveRestore(isN64() ? Mips::SP_64 : Mips::SP);
390 setExceptionPointerRegister(isN64() ? Mips::A0_64 : Mips::A0);
391 setExceptionSelectorRegister(isN64() ? Mips::A1_64 : Mips::A1);
393 MaxStoresPerMemcpy = 16;
395 isMicroMips = Subtarget->inMicroMipsMode();
398 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
399 if (TM.getSubtargetImpl()->inMips16Mode())
400 return llvm::createMips16TargetLowering(TM);
402 return llvm::createMipsSETargetLowering(TM);
405 // Create a fast isel object.
407 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
408 const TargetLibraryInfo *libInfo) const {
409 if (!EnableMipsFastISel)
410 return TargetLowering::createFastISel(funcInfo, libInfo);
411 return Mips::createFastISel(funcInfo, libInfo);
414 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
417 return VT.changeVectorElementTypeToInteger();
420 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
421 TargetLowering::DAGCombinerInfo &DCI,
422 const MipsSubtarget *Subtarget) {
423 if (DCI.isBeforeLegalizeOps())
426 EVT Ty = N->getValueType(0);
427 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
428 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
429 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
433 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
434 N->getOperand(0), N->getOperand(1));
435 SDValue InChain = DAG.getEntryNode();
436 SDValue InGlue = DivRem;
439 if (N->hasAnyUseOfValue(0)) {
440 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
443 InChain = CopyFromLo.getValue(1);
444 InGlue = CopyFromLo.getValue(2);
448 if (N->hasAnyUseOfValue(1)) {
449 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
451 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
457 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
459 default: llvm_unreachable("Unknown fp condition code!");
461 case ISD::SETOEQ: return Mips::FCOND_OEQ;
462 case ISD::SETUNE: return Mips::FCOND_UNE;
464 case ISD::SETOLT: return Mips::FCOND_OLT;
466 case ISD::SETOGT: return Mips::FCOND_OGT;
468 case ISD::SETOLE: return Mips::FCOND_OLE;
470 case ISD::SETOGE: return Mips::FCOND_OGE;
471 case ISD::SETULT: return Mips::FCOND_ULT;
472 case ISD::SETULE: return Mips::FCOND_ULE;
473 case ISD::SETUGT: return Mips::FCOND_UGT;
474 case ISD::SETUGE: return Mips::FCOND_UGE;
475 case ISD::SETUO: return Mips::FCOND_UN;
476 case ISD::SETO: return Mips::FCOND_OR;
478 case ISD::SETONE: return Mips::FCOND_ONE;
479 case ISD::SETUEQ: return Mips::FCOND_UEQ;
484 /// This function returns true if the floating point conditional branches and
485 /// conditional moves which use condition code CC should be inverted.
486 static bool invertFPCondCodeUser(Mips::CondCode CC) {
487 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
490 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
491 "Illegal Condition Code");
496 // Creates and returns an FPCmp node from a setcc node.
497 // Returns Op if setcc is not a floating point comparison.
498 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
499 // must be a SETCC node
500 if (Op.getOpcode() != ISD::SETCC)
503 SDValue LHS = Op.getOperand(0);
505 if (!LHS.getValueType().isFloatingPoint())
508 SDValue RHS = Op.getOperand(1);
511 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
512 // node if necessary.
513 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
515 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
516 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
519 // Creates and returns a CMovFPT/F node.
520 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
521 SDValue False, SDLoc DL) {
522 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
523 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
524 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
526 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
527 True.getValueType(), True, FCC0, False, Cond);
530 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
531 TargetLowering::DAGCombinerInfo &DCI,
532 const MipsSubtarget *Subtarget) {
533 if (DCI.isBeforeLegalizeOps())
536 SDValue SetCC = N->getOperand(0);
538 if ((SetCC.getOpcode() != ISD::SETCC) ||
539 !SetCC.getOperand(0).getValueType().isInteger())
542 SDValue False = N->getOperand(2);
543 EVT FalseTy = False.getValueType();
545 if (!FalseTy.isInteger())
548 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
550 // If the RHS (False) is 0, we swap the order of the operands
551 // of ISD::SELECT (obviously also inverting the condition) so that we can
552 // take advantage of conditional moves using the $0 register.
554 // return (a != 0) ? x : 0;
562 if (!FalseC->getZExtValue()) {
563 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
564 SDValue True = N->getOperand(1);
566 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
567 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
569 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
572 // If both operands are integer constants there's a possibility that we
573 // can do some interesting optimizations.
574 SDValue True = N->getOperand(1);
575 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
577 if (!TrueC || !True.getValueType().isInteger())
580 // We'll also ignore MVT::i64 operands as this optimizations proves
581 // to be ineffective because of the required sign extensions as the result
582 // of a SETCC operator is always MVT::i32 for non-vector types.
583 if (True.getValueType() == MVT::i64)
586 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
588 // 1) (a < x) ? y : y-1
590 // addiu $reg2, $reg1, y-1
592 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
594 // 2) (a < x) ? y-1 : y
596 // xor $reg1, $reg1, 1
597 // addiu $reg2, $reg1, y-1
599 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
600 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
601 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
602 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
605 // Couldn't optimize.
609 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
610 TargetLowering::DAGCombinerInfo &DCI,
611 const MipsSubtarget *Subtarget) {
612 // Pattern match EXT.
613 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
614 // => ext $dst, $src, size, pos
615 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
618 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
619 unsigned ShiftRightOpc = ShiftRight.getOpcode();
621 // Op's first operand must be a shift right.
622 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
625 // The second operand of the shift must be an immediate.
627 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
630 uint64_t Pos = CN->getZExtValue();
631 uint64_t SMPos, SMSize;
633 // Op's second operand must be a shifted mask.
634 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
635 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
638 // Return if the shifted mask does not start at bit 0 or the sum of its size
639 // and Pos exceeds the word's size.
640 EVT ValTy = N->getValueType(0);
641 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
644 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
645 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
646 DAG.getConstant(SMSize, MVT::i32));
649 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
650 TargetLowering::DAGCombinerInfo &DCI,
651 const MipsSubtarget *Subtarget) {
652 // Pattern match INS.
653 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
654 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
655 // => ins $dst, $src, size, pos, $src1
656 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
659 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
660 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
663 // See if Op's first operand matches (and $src1 , mask0).
664 if (And0.getOpcode() != ISD::AND)
667 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
668 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
671 // See if Op's second operand matches (and (shl $src, pos), mask1).
672 if (And1.getOpcode() != ISD::AND)
675 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
676 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
679 // The shift masks must have the same position and size.
680 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
683 SDValue Shl = And1.getOperand(0);
684 if (Shl.getOpcode() != ISD::SHL)
687 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
690 unsigned Shamt = CN->getZExtValue();
692 // Return if the shift amount and the first bit position of mask are not the
694 EVT ValTy = N->getValueType(0);
695 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
698 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
699 DAG.getConstant(SMPos0, MVT::i32),
700 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
703 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
704 TargetLowering::DAGCombinerInfo &DCI,
705 const MipsSubtarget *Subtarget) {
706 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
708 if (DCI.isBeforeLegalizeOps())
711 SDValue Add = N->getOperand(1);
713 if (Add.getOpcode() != ISD::ADD)
716 SDValue Lo = Add.getOperand(1);
718 if ((Lo.getOpcode() != MipsISD::Lo) ||
719 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
722 EVT ValTy = N->getValueType(0);
725 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
727 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
730 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
732 SelectionDAG &DAG = DCI.DAG;
733 unsigned Opc = N->getOpcode();
739 return performDivRemCombine(N, DAG, DCI, Subtarget);
741 return performSELECTCombine(N, DAG, DCI, Subtarget);
743 return performANDCombine(N, DAG, DCI, Subtarget);
745 return performORCombine(N, DAG, DCI, Subtarget);
747 return performADDCombine(N, DAG, DCI, Subtarget);
754 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
755 SmallVectorImpl<SDValue> &Results,
756 SelectionDAG &DAG) const {
757 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
759 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
760 Results.push_back(Res.getValue(I));
764 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
765 SmallVectorImpl<SDValue> &Results,
766 SelectionDAG &DAG) const {
767 return LowerOperationWrapper(N, Results, DAG);
770 SDValue MipsTargetLowering::
771 LowerOperation(SDValue Op, SelectionDAG &DAG) const
773 switch (Op.getOpcode())
775 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
776 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
777 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
778 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
779 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
780 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
781 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
782 case ISD::SELECT: return lowerSELECT(Op, DAG);
783 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
784 case ISD::SETCC: return lowerSETCC(Op, DAG);
785 case ISD::VASTART: return lowerVASTART(Op, DAG);
786 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
787 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
788 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
789 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
790 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
791 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
792 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
793 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
794 case ISD::LOAD: return lowerLOAD(Op, DAG);
795 case ISD::STORE: return lowerSTORE(Op, DAG);
796 case ISD::ADD: return lowerADD(Op, DAG);
797 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
802 //===----------------------------------------------------------------------===//
803 // Lower helper functions
804 //===----------------------------------------------------------------------===//
806 // addLiveIn - This helper function adds the specified physical register to the
807 // MachineFunction as a live in value. It also creates a corresponding
808 // virtual register for it.
810 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
812 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
813 MF.getRegInfo().addLiveIn(PReg, VReg);
817 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
818 MachineBasicBlock &MBB,
819 const TargetInstrInfo &TII,
824 // Insert instruction "teq $divisor_reg, $zero, 7".
825 MachineBasicBlock::iterator I(MI);
826 MachineInstrBuilder MIB;
827 MachineOperand &Divisor = MI->getOperand(2);
828 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
829 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
830 .addReg(Mips::ZERO).addImm(7);
832 // Use the 32-bit sub-register if this is a 64-bit division.
834 MIB->getOperand(0).setSubReg(Mips::sub_32);
836 // Clear Divisor's kill flag.
837 Divisor.setIsKill(false);
842 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
843 MachineBasicBlock *BB) const {
844 switch (MI->getOpcode()) {
846 llvm_unreachable("Unexpected instr type to insert");
847 case Mips::ATOMIC_LOAD_ADD_I8:
848 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
849 case Mips::ATOMIC_LOAD_ADD_I16:
850 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
851 case Mips::ATOMIC_LOAD_ADD_I32:
852 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
853 case Mips::ATOMIC_LOAD_ADD_I64:
854 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
856 case Mips::ATOMIC_LOAD_AND_I8:
857 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
858 case Mips::ATOMIC_LOAD_AND_I16:
859 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
860 case Mips::ATOMIC_LOAD_AND_I32:
861 return emitAtomicBinary(MI, BB, 4, Mips::AND);
862 case Mips::ATOMIC_LOAD_AND_I64:
863 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
865 case Mips::ATOMIC_LOAD_OR_I8:
866 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
867 case Mips::ATOMIC_LOAD_OR_I16:
868 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
869 case Mips::ATOMIC_LOAD_OR_I32:
870 return emitAtomicBinary(MI, BB, 4, Mips::OR);
871 case Mips::ATOMIC_LOAD_OR_I64:
872 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
874 case Mips::ATOMIC_LOAD_XOR_I8:
875 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
876 case Mips::ATOMIC_LOAD_XOR_I16:
877 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
878 case Mips::ATOMIC_LOAD_XOR_I32:
879 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
880 case Mips::ATOMIC_LOAD_XOR_I64:
881 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
883 case Mips::ATOMIC_LOAD_NAND_I8:
884 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
885 case Mips::ATOMIC_LOAD_NAND_I16:
886 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
887 case Mips::ATOMIC_LOAD_NAND_I32:
888 return emitAtomicBinary(MI, BB, 4, 0, true);
889 case Mips::ATOMIC_LOAD_NAND_I64:
890 return emitAtomicBinary(MI, BB, 8, 0, true);
892 case Mips::ATOMIC_LOAD_SUB_I8:
893 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
894 case Mips::ATOMIC_LOAD_SUB_I16:
895 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
896 case Mips::ATOMIC_LOAD_SUB_I32:
897 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
898 case Mips::ATOMIC_LOAD_SUB_I64:
899 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
901 case Mips::ATOMIC_SWAP_I8:
902 return emitAtomicBinaryPartword(MI, BB, 1, 0);
903 case Mips::ATOMIC_SWAP_I16:
904 return emitAtomicBinaryPartword(MI, BB, 2, 0);
905 case Mips::ATOMIC_SWAP_I32:
906 return emitAtomicBinary(MI, BB, 4, 0);
907 case Mips::ATOMIC_SWAP_I64:
908 return emitAtomicBinary(MI, BB, 8, 0);
910 case Mips::ATOMIC_CMP_SWAP_I8:
911 return emitAtomicCmpSwapPartword(MI, BB, 1);
912 case Mips::ATOMIC_CMP_SWAP_I16:
913 return emitAtomicCmpSwapPartword(MI, BB, 2);
914 case Mips::ATOMIC_CMP_SWAP_I32:
915 return emitAtomicCmpSwap(MI, BB, 4);
916 case Mips::ATOMIC_CMP_SWAP_I64:
917 return emitAtomicCmpSwap(MI, BB, 8);
918 case Mips::PseudoSDIV:
919 case Mips::PseudoUDIV:
920 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
921 case Mips::PseudoDSDIV:
922 case Mips::PseudoDUDIV:
923 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
927 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
928 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
930 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
931 unsigned Size, unsigned BinOpcode,
933 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
935 MachineFunction *MF = BB->getParent();
936 MachineRegisterInfo &RegInfo = MF->getRegInfo();
937 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
938 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
939 DebugLoc DL = MI->getDebugLoc();
940 unsigned LL, SC, AND, NOR, ZERO, BEQ;
943 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
944 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
955 ZERO = Mips::ZERO_64;
959 unsigned OldVal = MI->getOperand(0).getReg();
960 unsigned Ptr = MI->getOperand(1).getReg();
961 unsigned Incr = MI->getOperand(2).getReg();
963 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
964 unsigned AndRes = RegInfo.createVirtualRegister(RC);
965 unsigned Success = RegInfo.createVirtualRegister(RC);
967 // insert new blocks after the current block
968 const BasicBlock *LLVM_BB = BB->getBasicBlock();
969 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
970 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
971 MachineFunction::iterator It = BB;
973 MF->insert(It, loopMBB);
974 MF->insert(It, exitMBB);
976 // Transfer the remainder of BB and its successor edges to exitMBB.
977 exitMBB->splice(exitMBB->begin(), BB,
978 std::next(MachineBasicBlock::iterator(MI)), BB->end());
979 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
983 // fallthrough --> loopMBB
984 BB->addSuccessor(loopMBB);
985 loopMBB->addSuccessor(loopMBB);
986 loopMBB->addSuccessor(exitMBB);
990 // <binop> storeval, oldval, incr
991 // sc success, storeval, 0(ptr)
992 // beq success, $0, loopMBB
994 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
996 // and andres, oldval, incr
997 // nor storeval, $0, andres
998 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
999 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1000 } else if (BinOpcode) {
1001 // <binop> storeval, oldval, incr
1002 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1006 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1007 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1009 MI->eraseFromParent(); // The instruction is gone now.
1015 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1016 MachineBasicBlock *BB,
1017 unsigned Size, unsigned BinOpcode,
1019 assert((Size == 1 || Size == 2) &&
1020 "Unsupported size for EmitAtomicBinaryPartial.");
1022 MachineFunction *MF = BB->getParent();
1023 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1024 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1025 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1026 DebugLoc DL = MI->getDebugLoc();
1028 unsigned Dest = MI->getOperand(0).getReg();
1029 unsigned Ptr = MI->getOperand(1).getReg();
1030 unsigned Incr = MI->getOperand(2).getReg();
1032 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1033 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1034 unsigned Mask = RegInfo.createVirtualRegister(RC);
1035 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1036 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1037 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1038 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1039 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1040 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1041 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1042 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1043 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1044 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1045 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1046 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1047 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1048 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1049 unsigned Success = RegInfo.createVirtualRegister(RC);
1051 // insert new blocks after the current block
1052 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1053 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1054 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1055 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1056 MachineFunction::iterator It = BB;
1058 MF->insert(It, loopMBB);
1059 MF->insert(It, sinkMBB);
1060 MF->insert(It, exitMBB);
1062 // Transfer the remainder of BB and its successor edges to exitMBB.
1063 exitMBB->splice(exitMBB->begin(), BB,
1064 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1065 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1067 BB->addSuccessor(loopMBB);
1068 loopMBB->addSuccessor(loopMBB);
1069 loopMBB->addSuccessor(sinkMBB);
1070 sinkMBB->addSuccessor(exitMBB);
1073 // addiu masklsb2,$0,-4 # 0xfffffffc
1074 // and alignedaddr,ptr,masklsb2
1075 // andi ptrlsb2,ptr,3
1076 // sll shiftamt,ptrlsb2,3
1077 // ori maskupper,$0,255 # 0xff
1078 // sll mask,maskupper,shiftamt
1079 // nor mask2,$0,mask
1080 // sll incr2,incr,shiftamt
1082 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1083 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1084 .addReg(Mips::ZERO).addImm(-4);
1085 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1086 .addReg(Ptr).addReg(MaskLSB2);
1087 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1088 if (Subtarget->isLittle()) {
1089 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1091 unsigned Off = RegInfo.createVirtualRegister(RC);
1092 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1093 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1094 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1096 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1097 .addReg(Mips::ZERO).addImm(MaskImm);
1098 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1099 .addReg(MaskUpper).addReg(ShiftAmt);
1100 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1101 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1103 // atomic.load.binop
1105 // ll oldval,0(alignedaddr)
1106 // binop binopres,oldval,incr2
1107 // and newval,binopres,mask
1108 // and maskedoldval0,oldval,mask2
1109 // or storeval,maskedoldval0,newval
1110 // sc success,storeval,0(alignedaddr)
1111 // beq success,$0,loopMBB
1115 // ll oldval,0(alignedaddr)
1116 // and newval,incr2,mask
1117 // and maskedoldval0,oldval,mask2
1118 // or storeval,maskedoldval0,newval
1119 // sc success,storeval,0(alignedaddr)
1120 // beq success,$0,loopMBB
1123 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1125 // and andres, oldval, incr2
1126 // nor binopres, $0, andres
1127 // and newval, binopres, mask
1128 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1129 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1130 .addReg(Mips::ZERO).addReg(AndRes);
1131 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1132 } else if (BinOpcode) {
1133 // <binop> binopres, oldval, incr2
1134 // and newval, binopres, mask
1135 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1136 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1137 } else { // atomic.swap
1138 // and newval, incr2, mask
1139 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1142 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1143 .addReg(OldVal).addReg(Mask2);
1144 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1145 .addReg(MaskedOldVal0).addReg(NewVal);
1146 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1147 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1148 BuildMI(BB, DL, TII->get(Mips::BEQ))
1149 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1152 // and maskedoldval1,oldval,mask
1153 // srl srlres,maskedoldval1,shiftamt
1154 // sll sllres,srlres,24
1155 // sra dest,sllres,24
1157 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1159 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1160 .addReg(OldVal).addReg(Mask);
1161 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1162 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1163 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1164 .addReg(SrlRes).addImm(ShiftImm);
1165 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1166 .addReg(SllRes).addImm(ShiftImm);
1168 MI->eraseFromParent(); // The instruction is gone now.
1173 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1174 MachineBasicBlock *BB,
1175 unsigned Size) const {
1176 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1178 MachineFunction *MF = BB->getParent();
1179 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1180 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1181 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1182 DebugLoc DL = MI->getDebugLoc();
1183 unsigned LL, SC, ZERO, BNE, BEQ;
1186 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1187 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1194 ZERO = Mips::ZERO_64;
1199 unsigned Dest = MI->getOperand(0).getReg();
1200 unsigned Ptr = MI->getOperand(1).getReg();
1201 unsigned OldVal = MI->getOperand(2).getReg();
1202 unsigned NewVal = MI->getOperand(3).getReg();
1204 unsigned Success = RegInfo.createVirtualRegister(RC);
1206 // insert new blocks after the current block
1207 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1208 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1209 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1210 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1211 MachineFunction::iterator It = BB;
1213 MF->insert(It, loop1MBB);
1214 MF->insert(It, loop2MBB);
1215 MF->insert(It, exitMBB);
1217 // Transfer the remainder of BB and its successor edges to exitMBB.
1218 exitMBB->splice(exitMBB->begin(), BB,
1219 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1220 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1224 // fallthrough --> loop1MBB
1225 BB->addSuccessor(loop1MBB);
1226 loop1MBB->addSuccessor(exitMBB);
1227 loop1MBB->addSuccessor(loop2MBB);
1228 loop2MBB->addSuccessor(loop1MBB);
1229 loop2MBB->addSuccessor(exitMBB);
1233 // bne dest, oldval, exitMBB
1235 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1236 BuildMI(BB, DL, TII->get(BNE))
1237 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1240 // sc success, newval, 0(ptr)
1241 // beq success, $0, loop1MBB
1243 BuildMI(BB, DL, TII->get(SC), Success)
1244 .addReg(NewVal).addReg(Ptr).addImm(0);
1245 BuildMI(BB, DL, TII->get(BEQ))
1246 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1248 MI->eraseFromParent(); // The instruction is gone now.
1254 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1255 MachineBasicBlock *BB,
1256 unsigned Size) const {
1257 assert((Size == 1 || Size == 2) &&
1258 "Unsupported size for EmitAtomicCmpSwapPartial.");
1260 MachineFunction *MF = BB->getParent();
1261 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1262 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1263 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1264 DebugLoc DL = MI->getDebugLoc();
1266 unsigned Dest = MI->getOperand(0).getReg();
1267 unsigned Ptr = MI->getOperand(1).getReg();
1268 unsigned CmpVal = MI->getOperand(2).getReg();
1269 unsigned NewVal = MI->getOperand(3).getReg();
1271 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1272 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1273 unsigned Mask = RegInfo.createVirtualRegister(RC);
1274 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1275 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1276 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1277 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1278 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1279 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1280 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1281 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1282 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1283 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1284 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1285 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1286 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1287 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1288 unsigned Success = RegInfo.createVirtualRegister(RC);
1290 // insert new blocks after the current block
1291 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1292 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1293 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1294 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1295 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1296 MachineFunction::iterator It = BB;
1298 MF->insert(It, loop1MBB);
1299 MF->insert(It, loop2MBB);
1300 MF->insert(It, sinkMBB);
1301 MF->insert(It, exitMBB);
1303 // Transfer the remainder of BB and its successor edges to exitMBB.
1304 exitMBB->splice(exitMBB->begin(), BB,
1305 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1306 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1308 BB->addSuccessor(loop1MBB);
1309 loop1MBB->addSuccessor(sinkMBB);
1310 loop1MBB->addSuccessor(loop2MBB);
1311 loop2MBB->addSuccessor(loop1MBB);
1312 loop2MBB->addSuccessor(sinkMBB);
1313 sinkMBB->addSuccessor(exitMBB);
1315 // FIXME: computation of newval2 can be moved to loop2MBB.
1317 // addiu masklsb2,$0,-4 # 0xfffffffc
1318 // and alignedaddr,ptr,masklsb2
1319 // andi ptrlsb2,ptr,3
1320 // sll shiftamt,ptrlsb2,3
1321 // ori maskupper,$0,255 # 0xff
1322 // sll mask,maskupper,shiftamt
1323 // nor mask2,$0,mask
1324 // andi maskedcmpval,cmpval,255
1325 // sll shiftedcmpval,maskedcmpval,shiftamt
1326 // andi maskednewval,newval,255
1327 // sll shiftednewval,maskednewval,shiftamt
1328 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1329 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1330 .addReg(Mips::ZERO).addImm(-4);
1331 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1332 .addReg(Ptr).addReg(MaskLSB2);
1333 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1334 if (Subtarget->isLittle()) {
1335 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1337 unsigned Off = RegInfo.createVirtualRegister(RC);
1338 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1339 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1340 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1342 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1343 .addReg(Mips::ZERO).addImm(MaskImm);
1344 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1345 .addReg(MaskUpper).addReg(ShiftAmt);
1346 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1347 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1348 .addReg(CmpVal).addImm(MaskImm);
1349 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1350 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1351 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1352 .addReg(NewVal).addImm(MaskImm);
1353 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1354 .addReg(MaskedNewVal).addReg(ShiftAmt);
1357 // ll oldval,0(alginedaddr)
1358 // and maskedoldval0,oldval,mask
1359 // bne maskedoldval0,shiftedcmpval,sinkMBB
1361 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1362 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1363 .addReg(OldVal).addReg(Mask);
1364 BuildMI(BB, DL, TII->get(Mips::BNE))
1365 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1368 // and maskedoldval1,oldval,mask2
1369 // or storeval,maskedoldval1,shiftednewval
1370 // sc success,storeval,0(alignedaddr)
1371 // beq success,$0,loop1MBB
1373 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1374 .addReg(OldVal).addReg(Mask2);
1375 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1376 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1377 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1378 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1379 BuildMI(BB, DL, TII->get(Mips::BEQ))
1380 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1383 // srl srlres,maskedoldval0,shiftamt
1384 // sll sllres,srlres,24
1385 // sra dest,sllres,24
1387 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1389 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1390 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1391 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1392 .addReg(SrlRes).addImm(ShiftImm);
1393 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1394 .addReg(SllRes).addImm(ShiftImm);
1396 MI->eraseFromParent(); // The instruction is gone now.
1401 //===----------------------------------------------------------------------===//
1402 // Misc Lower Operation implementation
1403 //===----------------------------------------------------------------------===//
1404 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1405 SDValue Chain = Op.getOperand(0);
1406 SDValue Table = Op.getOperand(1);
1407 SDValue Index = Op.getOperand(2);
1409 EVT PTy = getPointerTy();
1410 unsigned EntrySize =
1411 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1413 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1414 DAG.getConstant(EntrySize, PTy));
1415 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1417 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1418 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1419 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1421 Chain = Addr.getValue(1);
1423 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || isN64()) {
1424 // For PIC, the sequence is:
1425 // BRIND(load(Jumptable + index) + RelocBase)
1426 // RelocBase can be JumpTable, GOT or some sort of global base.
1427 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1428 getPICJumpTableRelocBase(Table, DAG));
1431 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1434 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1435 // The first operand is the chain, the second is the condition, the third is
1436 // the block to branch to if the condition is true.
1437 SDValue Chain = Op.getOperand(0);
1438 SDValue Dest = Op.getOperand(2);
1441 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1443 // Return if flag is not set by a floating point comparison.
1444 if (CondRes.getOpcode() != MipsISD::FPCmp)
1447 SDValue CCNode = CondRes.getOperand(2);
1449 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1450 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1451 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1452 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1453 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1454 FCC0, Dest, CondRes);
1457 SDValue MipsTargetLowering::
1458 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1460 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1462 // Return if flag is not set by a floating point comparison.
1463 if (Cond.getOpcode() != MipsISD::FPCmp)
1466 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1470 SDValue MipsTargetLowering::
1471 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1474 EVT Ty = Op.getOperand(0).getValueType();
1475 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1476 getSetCCResultType(*DAG.getContext(), Ty),
1477 Op.getOperand(0), Op.getOperand(1),
1480 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1484 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1485 SDValue Cond = createFPCmp(DAG, Op);
1487 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1488 "Floating point operand expected.");
1490 SDValue True = DAG.getConstant(1, MVT::i32);
1491 SDValue False = DAG.getConstant(0, MVT::i32);
1493 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1496 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1497 SelectionDAG &DAG) const {
1498 // FIXME there isn't actually debug info here
1500 EVT Ty = Op.getValueType();
1501 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1502 const GlobalValue *GV = N->getGlobal();
1504 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64()) {
1505 const MipsTargetObjectFile &TLOF =
1506 (const MipsTargetObjectFile&)getObjFileLowering();
1508 // %gp_rel relocation
1509 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1510 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1512 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1513 DAG.getVTList(MVT::i32), GA);
1514 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1515 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1518 // %hi/%lo relocation
1519 return getAddrNonPIC(N, Ty, DAG);
1522 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1523 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1526 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1527 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1528 MachinePointerInfo::getGOT());
1530 return getAddrGlobal(N, Ty, DAG, (isN32() || isN64()) ? MipsII::MO_GOT_DISP
1532 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1535 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1536 SelectionDAG &DAG) const {
1537 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1538 EVT Ty = Op.getValueType();
1540 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1541 return getAddrNonPIC(N, Ty, DAG);
1543 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1546 SDValue MipsTargetLowering::
1547 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1549 // If the relocation model is PIC, use the General Dynamic TLS Model or
1550 // Local Dynamic TLS model, otherwise use the Initial Exec or
1551 // Local Exec TLS Model.
1553 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1555 const GlobalValue *GV = GA->getGlobal();
1556 EVT PtrVT = getPointerTy();
1558 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1560 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1561 // General Dynamic and Local Dynamic TLS Model.
1562 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1565 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1566 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1567 getGlobalReg(DAG, PtrVT), TGA);
1568 unsigned PtrSize = PtrVT.getSizeInBits();
1569 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1571 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1575 Entry.Node = Argument;
1577 Args.push_back(Entry);
1579 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1580 false, false, false, false, 0, CallingConv::C,
1581 /*IsTailCall=*/false, /*doesNotRet=*/false,
1582 /*isReturnValueUsed=*/true,
1583 TlsGetAddr, Args, DAG, DL);
1584 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1586 SDValue Ret = CallResult.first;
1588 if (model != TLSModel::LocalDynamic)
1591 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1592 MipsII::MO_DTPREL_HI);
1593 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1594 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1595 MipsII::MO_DTPREL_LO);
1596 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1597 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1598 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1602 if (model == TLSModel::InitialExec) {
1603 // Initial Exec TLS Model
1604 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1605 MipsII::MO_GOTTPREL);
1606 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1608 Offset = DAG.getLoad(PtrVT, DL,
1609 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1610 false, false, false, 0);
1612 // Local Exec TLS Model
1613 assert(model == TLSModel::LocalExec);
1614 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1615 MipsII::MO_TPREL_HI);
1616 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1617 MipsII::MO_TPREL_LO);
1618 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1619 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1620 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1623 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1624 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1627 SDValue MipsTargetLowering::
1628 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1630 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1631 EVT Ty = Op.getValueType();
1633 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1634 return getAddrNonPIC(N, Ty, DAG);
1636 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1639 SDValue MipsTargetLowering::
1640 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1642 // gp_rel relocation
1643 // FIXME: we should reference the constant pool using small data sections,
1644 // but the asm printer currently doesn't support this feature without
1645 // hacking it. This feature should come soon so we can uncomment the
1647 //if (IsInSmallSection(C->getType())) {
1648 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1649 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1650 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1651 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1652 EVT Ty = Op.getValueType();
1654 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1655 return getAddrNonPIC(N, Ty, DAG);
1657 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1660 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1661 MachineFunction &MF = DAG.getMachineFunction();
1662 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1665 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1668 // vastart just stores the address of the VarArgsFrameIndex slot into the
1669 // memory location argument.
1670 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1671 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1672 MachinePointerInfo(SV), false, false, 0);
1675 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1676 bool HasExtractInsert) {
1677 EVT TyX = Op.getOperand(0).getValueType();
1678 EVT TyY = Op.getOperand(1).getValueType();
1679 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1680 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1684 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1686 SDValue X = (TyX == MVT::f32) ?
1687 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1688 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1690 SDValue Y = (TyY == MVT::f32) ?
1691 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1692 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1695 if (HasExtractInsert) {
1696 // ext E, Y, 31, 1 ; extract bit31 of Y
1697 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1698 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1699 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1702 // srl SrlX, SllX, 1
1704 // sll SllY, SrlX, 31
1705 // or Or, SrlX, SllY
1706 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1707 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1708 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1709 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1710 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1713 if (TyX == MVT::f32)
1714 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1716 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1717 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1718 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1721 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1722 bool HasExtractInsert) {
1723 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1724 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1725 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1726 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1729 // Bitcast to integer nodes.
1730 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1731 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1733 if (HasExtractInsert) {
1734 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1735 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1736 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1737 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1739 if (WidthX > WidthY)
1740 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1741 else if (WidthY > WidthX)
1742 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1744 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1745 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1746 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1749 // (d)sll SllX, X, 1
1750 // (d)srl SrlX, SllX, 1
1751 // (d)srl SrlY, Y, width(Y)-1
1752 // (d)sll SllY, SrlX, width(Y)-1
1753 // or Or, SrlX, SllY
1754 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1755 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1756 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1757 DAG.getConstant(WidthY - 1, MVT::i32));
1759 if (WidthX > WidthY)
1760 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1761 else if (WidthY > WidthX)
1762 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1764 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1765 DAG.getConstant(WidthX - 1, MVT::i32));
1766 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1767 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1771 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1772 if (Subtarget->isGP64bit())
1773 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1775 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1778 SDValue MipsTargetLowering::
1779 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1781 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1782 "Frame address can only be determined for current frame.");
1784 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1785 MFI->setFrameAddressIsTaken(true);
1786 EVT VT = Op.getValueType();
1788 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1789 isN64() ? Mips::FP_64 : Mips::FP, VT);
1793 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1794 SelectionDAG &DAG) const {
1795 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1799 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1800 "Return address can be determined only for current frame.");
1802 MachineFunction &MF = DAG.getMachineFunction();
1803 MachineFrameInfo *MFI = MF.getFrameInfo();
1804 MVT VT = Op.getSimpleValueType();
1805 unsigned RA = isN64() ? Mips::RA_64 : Mips::RA;
1806 MFI->setReturnAddressIsTaken(true);
1808 // Return RA, which contains the return address. Mark it an implicit live-in.
1809 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1810 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1813 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1814 // generated from __builtin_eh_return (offset, handler)
1815 // The effect of this is to adjust the stack pointer by "offset"
1816 // and then branch to "handler".
1817 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1819 MachineFunction &MF = DAG.getMachineFunction();
1820 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1822 MipsFI->setCallsEhReturn();
1823 SDValue Chain = Op.getOperand(0);
1824 SDValue Offset = Op.getOperand(1);
1825 SDValue Handler = Op.getOperand(2);
1827 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
1829 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1830 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1831 unsigned OffsetReg = isN64() ? Mips::V1_64 : Mips::V1;
1832 unsigned AddrReg = isN64() ? Mips::V0_64 : Mips::V0;
1833 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1834 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1835 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1836 DAG.getRegister(OffsetReg, Ty),
1837 DAG.getRegister(AddrReg, getPointerTy()),
1841 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1842 SelectionDAG &DAG) const {
1843 // FIXME: Need pseudo-fence for 'singlethread' fences
1844 // FIXME: Set SType for weaker fences where supported/appropriate.
1847 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1848 DAG.getConstant(SType, MVT::i32));
1851 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1852 SelectionDAG &DAG) const {
1854 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1855 SDValue Shamt = Op.getOperand(2);
1858 // lo = (shl lo, shamt)
1859 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1862 // hi = (shl lo, shamt[4:0])
1863 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1864 DAG.getConstant(-1, MVT::i32));
1865 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1866 DAG.getConstant(1, MVT::i32));
1867 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1869 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1870 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1871 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1872 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1873 DAG.getConstant(0x20, MVT::i32));
1874 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1875 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1876 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1878 SDValue Ops[2] = {Lo, Hi};
1879 return DAG.getMergeValues(Ops, DL);
1882 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1885 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1886 SDValue Shamt = Op.getOperand(2);
1889 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1891 // hi = (sra hi, shamt)
1893 // hi = (srl hi, shamt)
1896 // lo = (sra hi, shamt[4:0])
1897 // hi = (sra hi, 31)
1899 // lo = (srl hi, shamt[4:0])
1901 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1902 DAG.getConstant(-1, MVT::i32));
1903 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1904 DAG.getConstant(1, MVT::i32));
1905 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1906 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1907 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1908 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1910 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1911 DAG.getConstant(0x20, MVT::i32));
1912 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1913 DAG.getConstant(31, MVT::i32));
1914 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1915 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1916 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1919 SDValue Ops[2] = {Lo, Hi};
1920 return DAG.getMergeValues(Ops, DL);
1923 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1924 SDValue Chain, SDValue Src, unsigned Offset) {
1925 SDValue Ptr = LD->getBasePtr();
1926 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1927 EVT BasePtrVT = Ptr.getValueType();
1929 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1932 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1933 DAG.getConstant(Offset, BasePtrVT));
1935 SDValue Ops[] = { Chain, Ptr, Src };
1936 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
1937 LD->getMemOperand());
1940 // Expand an unaligned 32 or 64-bit integer load node.
1941 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1942 LoadSDNode *LD = cast<LoadSDNode>(Op);
1943 EVT MemVT = LD->getMemoryVT();
1945 // Return if load is aligned or if MemVT is neither i32 nor i64.
1946 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1947 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1950 bool IsLittle = Subtarget->isLittle();
1951 EVT VT = Op.getValueType();
1952 ISD::LoadExtType ExtType = LD->getExtensionType();
1953 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1955 assert((VT == MVT::i32) || (VT == MVT::i64));
1958 // (set dst, (i64 (load baseptr)))
1960 // (set tmp, (ldl (add baseptr, 7), undef))
1961 // (set dst, (ldr baseptr, tmp))
1962 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1963 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1965 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1969 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1971 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1975 // (set dst, (i32 (load baseptr))) or
1976 // (set dst, (i64 (sextload baseptr))) or
1977 // (set dst, (i64 (extload baseptr)))
1979 // (set tmp, (lwl (add baseptr, 3), undef))
1980 // (set dst, (lwr baseptr, tmp))
1981 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1982 (ExtType == ISD::EXTLOAD))
1985 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1988 // (set dst, (i64 (zextload baseptr)))
1990 // (set tmp0, (lwl (add baseptr, 3), undef))
1991 // (set tmp1, (lwr baseptr, tmp0))
1992 // (set tmp2, (shl tmp1, 32))
1993 // (set dst, (srl tmp2, 32))
1995 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1996 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1997 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1998 SDValue Ops[] = { SRL, LWR.getValue(1) };
1999 return DAG.getMergeValues(Ops, DL);
2002 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2003 SDValue Chain, unsigned Offset) {
2004 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2005 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2007 SDVTList VTList = DAG.getVTList(MVT::Other);
2010 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2011 DAG.getConstant(Offset, BasePtrVT));
2013 SDValue Ops[] = { Chain, Value, Ptr };
2014 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2015 SD->getMemOperand());
2018 // Expand an unaligned 32 or 64-bit integer store node.
2019 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2021 SDValue Value = SD->getValue(), Chain = SD->getChain();
2022 EVT VT = Value.getValueType();
2025 // (store val, baseptr) or
2026 // (truncstore val, baseptr)
2028 // (swl val, (add baseptr, 3))
2029 // (swr val, baseptr)
2030 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2031 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2033 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2036 assert(VT == MVT::i64);
2039 // (store val, baseptr)
2041 // (sdl val, (add baseptr, 7))
2042 // (sdr val, baseptr)
2043 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2044 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2047 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2048 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2049 SDValue Val = SD->getValue();
2051 if (Val.getOpcode() != ISD::FP_TO_SINT)
2054 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2055 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2058 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2059 SD->getPointerInfo(), SD->isVolatile(),
2060 SD->isNonTemporal(), SD->getAlignment());
2063 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2064 StoreSDNode *SD = cast<StoreSDNode>(Op);
2065 EVT MemVT = SD->getMemoryVT();
2067 // Lower unaligned integer stores.
2068 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2069 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2070 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2072 return lowerFP_TO_SINT_STORE(SD, DAG);
2075 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2076 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2077 || cast<ConstantSDNode>
2078 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2079 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2083 // (add (frameaddr 0), (frame_to_args_offset))
2084 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2085 // (add FrameObject, 0)
2086 // where FrameObject is a fixed StackObject with offset 0 which points to
2087 // the old stack pointer.
2088 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2089 EVT ValTy = Op->getValueType(0);
2090 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2091 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2092 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2093 DAG.getConstant(0, ValTy));
2096 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2097 SelectionDAG &DAG) const {
2098 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2099 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2101 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2104 //===----------------------------------------------------------------------===//
2105 // Calling Convention Implementation
2106 //===----------------------------------------------------------------------===//
2108 //===----------------------------------------------------------------------===//
2109 // TODO: Implement a generic logic using tblgen that can support this.
2110 // Mips O32 ABI rules:
2112 // i32 - Passed in A0, A1, A2, A3 and stack
2113 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2114 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2115 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2116 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2117 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2120 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2121 //===----------------------------------------------------------------------===//
2123 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2124 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2125 CCState &State, const MCPhysReg *F64Regs) {
2127 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2129 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2130 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2132 // Do not process byval args here.
2133 if (ArgFlags.isByVal())
2136 // Promote i8 and i16
2137 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2139 if (ArgFlags.isSExt())
2140 LocInfo = CCValAssign::SExt;
2141 else if (ArgFlags.isZExt())
2142 LocInfo = CCValAssign::ZExt;
2144 LocInfo = CCValAssign::AExt;
2149 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2150 // is true: function is vararg, argument is 3rd or higher, there is previous
2151 // argument which is not f32 or f64.
2152 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2153 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2154 unsigned OrigAlign = ArgFlags.getOrigAlign();
2155 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2157 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2158 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2159 // If this is the first part of an i64 arg,
2160 // the allocated register must be either A0 or A2.
2161 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2162 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2164 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2165 // Allocate int register and shadow next int register. If first
2166 // available register is Mips::A1 or Mips::A3, shadow it too.
2167 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2168 if (Reg == Mips::A1 || Reg == Mips::A3)
2169 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2170 State.AllocateReg(IntRegs, IntRegsSize);
2172 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2173 // we are guaranteed to find an available float register
2174 if (ValVT == MVT::f32) {
2175 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2176 // Shadow int register
2177 State.AllocateReg(IntRegs, IntRegsSize);
2179 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2180 // Shadow int registers
2181 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2182 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2183 State.AllocateReg(IntRegs, IntRegsSize);
2184 State.AllocateReg(IntRegs, IntRegsSize);
2187 llvm_unreachable("Cannot handle this ValVT.");
2190 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2192 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2194 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2199 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2200 MVT LocVT, CCValAssign::LocInfo LocInfo,
2201 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2202 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2204 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2207 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2208 MVT LocVT, CCValAssign::LocInfo LocInfo,
2209 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2210 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2212 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2215 #include "MipsGenCallingConv.inc"
2217 //===----------------------------------------------------------------------===//
2218 // Call Calling Convention Implementation
2219 //===----------------------------------------------------------------------===//
2221 // Return next O32 integer argument register.
2222 static unsigned getNextIntArgReg(unsigned Reg) {
2223 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2224 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2228 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2229 SDValue Chain, SDValue Arg, SDLoc DL,
2230 bool IsTailCall, SelectionDAG &DAG) const {
2232 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2233 DAG.getIntPtrConstant(Offset));
2234 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2238 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2239 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2240 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2241 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2242 /*isVolatile=*/ true, false, 0);
2245 void MipsTargetLowering::
2246 getOpndList(SmallVectorImpl<SDValue> &Ops,
2247 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2248 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2249 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2250 // Insert node "GP copy globalreg" before call to function.
2252 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2253 // in PIC mode) allow symbols to be resolved via lazy binding.
2254 // The lazy binding stub requires GP to point to the GOT.
2255 if (IsPICCall && !InternalLinkage) {
2256 unsigned GPReg = isN64() ? Mips::GP_64 : Mips::GP;
2257 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
2258 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2261 // Build a sequence of copy-to-reg nodes chained together with token
2262 // chain and flag operands which copy the outgoing args into registers.
2263 // The InFlag in necessary since all emitted instructions must be
2267 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2268 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2269 RegsToPass[i].second, InFlag);
2270 InFlag = Chain.getValue(1);
2273 // Add argument registers to the end of the list so that they are
2274 // known live into the call.
2275 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2276 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2277 RegsToPass[i].second.getValueType()));
2279 // Add a register mask operand representing the call-preserved registers.
2280 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2281 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2282 assert(Mask && "Missing call preserved mask for calling convention");
2283 if (Subtarget->inMips16HardFloat()) {
2284 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2285 llvm::StringRef Sym = G->getGlobal()->getName();
2286 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2287 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2288 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2292 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2294 if (InFlag.getNode())
2295 Ops.push_back(InFlag);
2298 /// LowerCall - functions arguments are copied from virtual regs to
2299 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2301 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2302 SmallVectorImpl<SDValue> &InVals) const {
2303 SelectionDAG &DAG = CLI.DAG;
2305 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2306 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2307 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2308 SDValue Chain = CLI.Chain;
2309 SDValue Callee = CLI.Callee;
2310 bool &IsTailCall = CLI.IsTailCall;
2311 CallingConv::ID CallConv = CLI.CallConv;
2312 bool IsVarArg = CLI.IsVarArg;
2314 MachineFunction &MF = DAG.getMachineFunction();
2315 MachineFrameInfo *MFI = MF.getFrameInfo();
2316 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2317 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2318 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2320 // Analyze operands of the call, assigning locations to each operand.
2321 SmallVector<CCValAssign, 16> ArgLocs;
2322 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2323 getTargetMachine(), ArgLocs, *DAG.getContext());
2324 MipsCC::SpecialCallingConvType SpecialCallingConv =
2325 getSpecialCallingConv(Callee);
2326 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo,
2327 SpecialCallingConv);
2329 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2330 Subtarget->mipsSEUsesSoftFloat(),
2331 Callee.getNode(), CLI.Args);
2333 // Get a count of how many bytes are to be pushed on the stack.
2334 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2336 // Check if it's really possible to do a tail call.
2339 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2340 *MF.getInfo<MipsFunctionInfo>());
2342 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2343 report_fatal_error("failed to perform tail call elimination on a call "
2344 "site marked musttail");
2349 // Chain is the output chain of the last Load/Store or CopyToReg node.
2350 // ByValChain is the output chain of the last Memcpy node created for copying
2351 // byval arguments to the stack.
2352 unsigned StackAlignment = TFL->getStackAlignment();
2353 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2354 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2357 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2359 SDValue StackPtr = DAG.getCopyFromReg(
2360 Chain, DL, isN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2362 // With EABI is it possible to have 16 args on registers.
2363 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2364 SmallVector<SDValue, 8> MemOpChains;
2365 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2367 // Walk the register/memloc assignments, inserting copies/loads.
2368 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2369 SDValue Arg = OutVals[i];
2370 CCValAssign &VA = ArgLocs[i];
2371 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2372 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2375 if (Flags.isByVal()) {
2376 assert(Flags.getByValSize() &&
2377 "ByVal args of size 0 should have been ignored by front-end.");
2378 assert(ByValArg != MipsCCInfo.byval_end());
2379 assert(!IsTailCall &&
2380 "Do not tail-call optimize if there is a byval argument.");
2381 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2382 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2387 // Promote the value if needed.
2388 switch (VA.getLocInfo()) {
2389 default: llvm_unreachable("Unknown loc info!");
2390 case CCValAssign::Full:
2391 if (VA.isRegLoc()) {
2392 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2393 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2394 (ValVT == MVT::i64 && LocVT == MVT::f64))
2395 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2396 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2397 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2398 Arg, DAG.getConstant(0, MVT::i32));
2399 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2400 Arg, DAG.getConstant(1, MVT::i32));
2401 if (!Subtarget->isLittle())
2403 unsigned LocRegLo = VA.getLocReg();
2404 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2405 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2406 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2411 case CCValAssign::SExt:
2412 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2414 case CCValAssign::ZExt:
2415 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2417 case CCValAssign::AExt:
2418 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2422 // Arguments that can be passed on register must be kept at
2423 // RegsToPass vector
2424 if (VA.isRegLoc()) {
2425 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2429 // Register can't get to this point...
2430 assert(VA.isMemLoc());
2432 // emit ISD::STORE whichs stores the
2433 // parameter value to a stack Location
2434 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2435 Chain, Arg, DL, IsTailCall, DAG));
2438 // Transform all store nodes into one single node because all store
2439 // nodes are independent of each other.
2440 if (!MemOpChains.empty())
2441 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2443 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2444 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2445 // node so that legalize doesn't hack it.
2446 bool IsPICCall = (isN64() || IsPIC); // true if calls are translated to
2448 bool GlobalOrExternal = false, InternalLinkage = false;
2450 EVT Ty = Callee.getValueType();
2452 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2454 const GlobalValue *Val = G->getGlobal();
2455 InternalLinkage = Val->hasInternalLinkage();
2457 if (InternalLinkage)
2458 Callee = getAddrLocal(G, Ty, DAG, isN32() || isN64());
2460 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2461 MipsII::MO_CALL_LO16, Chain,
2462 FuncInfo->callPtrInfo(Val));
2464 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2465 FuncInfo->callPtrInfo(Val));
2467 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2468 MipsII::MO_NO_FLAG);
2469 GlobalOrExternal = true;
2471 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2472 const char *Sym = S->getSymbol();
2474 if (!isN64() && !IsPIC) // !N64 && static
2475 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2476 MipsII::MO_NO_FLAG);
2478 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2479 MipsII::MO_CALL_LO16, Chain,
2480 FuncInfo->callPtrInfo(Sym));
2482 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2483 FuncInfo->callPtrInfo(Sym));
2485 GlobalOrExternal = true;
2488 SmallVector<SDValue, 8> Ops(1, Chain);
2489 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2491 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2492 CLI, Callee, Chain);
2495 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2497 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2498 SDValue InFlag = Chain.getValue(1);
2500 // Create the CALLSEQ_END node.
2501 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2502 DAG.getIntPtrConstant(0, true), InFlag, DL);
2503 InFlag = Chain.getValue(1);
2505 // Handle result values, copying them out of physregs into vregs that we
2507 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2508 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2511 /// LowerCallResult - Lower the result values of a call into the
2512 /// appropriate copies out of appropriate physical registers.
2514 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2515 CallingConv::ID CallConv, bool IsVarArg,
2516 const SmallVectorImpl<ISD::InputArg> &Ins,
2517 SDLoc DL, SelectionDAG &DAG,
2518 SmallVectorImpl<SDValue> &InVals,
2519 const SDNode *CallNode,
2520 const Type *RetTy) const {
2521 // Assign locations to each value returned by this call.
2522 SmallVector<CCValAssign, 16> RVLocs;
2523 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2524 getTargetMachine(), RVLocs, *DAG.getContext());
2525 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2527 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2530 // Copy all of the result registers out of their specified physreg.
2531 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2532 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2533 RVLocs[i].getLocVT(), InFlag);
2534 Chain = Val.getValue(1);
2535 InFlag = Val.getValue(2);
2537 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2538 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2540 InVals.push_back(Val);
2546 //===----------------------------------------------------------------------===//
2547 // Formal Arguments Calling Convention Implementation
2548 //===----------------------------------------------------------------------===//
2549 /// LowerFormalArguments - transform physical registers into virtual registers
2550 /// and generate load operations for arguments places on the stack.
2552 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2553 CallingConv::ID CallConv,
2555 const SmallVectorImpl<ISD::InputArg> &Ins,
2556 SDLoc DL, SelectionDAG &DAG,
2557 SmallVectorImpl<SDValue> &InVals)
2559 MachineFunction &MF = DAG.getMachineFunction();
2560 MachineFrameInfo *MFI = MF.getFrameInfo();
2561 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2563 MipsFI->setVarArgsFrameIndex(0);
2565 // Used with vargs to acumulate store chains.
2566 std::vector<SDValue> OutChains;
2568 // Assign locations to all of the incoming arguments.
2569 SmallVector<CCValAssign, 16> ArgLocs;
2570 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2571 getTargetMachine(), ArgLocs, *DAG.getContext());
2572 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2573 Function::const_arg_iterator FuncArg =
2574 DAG.getMachineFunction().getFunction()->arg_begin();
2575 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2577 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2578 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2579 MipsCCInfo.hasByValArg());
2581 unsigned CurArgIdx = 0;
2582 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2584 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2585 CCValAssign &VA = ArgLocs[i];
2586 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2587 CurArgIdx = Ins[i].OrigArgIndex;
2588 EVT ValVT = VA.getValVT();
2589 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2590 bool IsRegLoc = VA.isRegLoc();
2592 if (Flags.isByVal()) {
2593 assert(Flags.getByValSize() &&
2594 "ByVal args of size 0 should have been ignored by front-end.");
2595 assert(ByValArg != MipsCCInfo.byval_end());
2596 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2597 MipsCCInfo, *ByValArg);
2602 // Arguments stored on registers
2604 MVT RegVT = VA.getLocVT();
2605 unsigned ArgReg = VA.getLocReg();
2606 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2608 // Transform the arguments stored on
2609 // physical registers into virtual ones
2610 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2611 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2613 // If this is an 8 or 16-bit value, it has been passed promoted
2614 // to 32 bits. Insert an assert[sz]ext to capture this, then
2615 // truncate to the right size.
2616 if (VA.getLocInfo() != CCValAssign::Full) {
2617 unsigned Opcode = 0;
2618 if (VA.getLocInfo() == CCValAssign::SExt)
2619 Opcode = ISD::AssertSext;
2620 else if (VA.getLocInfo() == CCValAssign::ZExt)
2621 Opcode = ISD::AssertZext;
2623 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2624 DAG.getValueType(ValVT));
2625 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2628 // Handle floating point arguments passed in integer registers and
2629 // long double arguments passed in floating point registers.
2630 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2631 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2632 (RegVT == MVT::f64 && ValVT == MVT::i64))
2633 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2634 else if (isO32() && RegVT == MVT::i32 && ValVT == MVT::f64) {
2635 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2636 getNextIntArgReg(ArgReg), RC);
2637 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2638 if (!Subtarget->isLittle())
2639 std::swap(ArgValue, ArgValue2);
2640 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2641 ArgValue, ArgValue2);
2644 InVals.push_back(ArgValue);
2645 } else { // VA.isRegLoc()
2648 assert(VA.isMemLoc());
2650 // The stack pointer offset is relative to the caller stack frame.
2651 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2652 VA.getLocMemOffset(), true);
2654 // Create load nodes to retrieve arguments from the stack
2655 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2656 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2657 MachinePointerInfo::getFixedStack(FI),
2658 false, false, false, 0);
2659 InVals.push_back(Load);
2660 OutChains.push_back(Load.getValue(1));
2663 // The mips ABIs for returning structs by value requires that we copy
2664 // the sret argument into $v0 for the return. Save the argument into
2665 // a virtual register so that we can access it from the return points.
2666 if (Flags.isSRet()) {
2667 unsigned Reg = MipsFI->getSRetReturnReg();
2669 Reg = MF.getRegInfo().createVirtualRegister(
2670 getRegClassFor(isN64() ? MVT::i64 : MVT::i32));
2671 MipsFI->setSRetReturnReg(Reg);
2674 DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals.back());
2675 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2680 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2682 // All stores are grouped in one node to allow the matching between
2683 // the size of Ins and InVals. This only happens when on varg functions
2684 if (!OutChains.empty()) {
2685 OutChains.push_back(Chain);
2686 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2692 //===----------------------------------------------------------------------===//
2693 // Return Value Calling Convention Implementation
2694 //===----------------------------------------------------------------------===//
2697 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2698 MachineFunction &MF, bool IsVarArg,
2699 const SmallVectorImpl<ISD::OutputArg> &Outs,
2700 LLVMContext &Context) const {
2701 SmallVector<CCValAssign, 16> RVLocs;
2702 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2704 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2708 MipsTargetLowering::LowerReturn(SDValue Chain,
2709 CallingConv::ID CallConv, bool IsVarArg,
2710 const SmallVectorImpl<ISD::OutputArg> &Outs,
2711 const SmallVectorImpl<SDValue> &OutVals,
2712 SDLoc DL, SelectionDAG &DAG) const {
2713 // CCValAssign - represent the assignment of
2714 // the return value to a location
2715 SmallVector<CCValAssign, 16> RVLocs;
2716 MachineFunction &MF = DAG.getMachineFunction();
2718 // CCState - Info about the registers and stack slot.
2719 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2721 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2723 // Analyze return values.
2724 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2725 MF.getFunction()->getReturnType());
2728 SmallVector<SDValue, 4> RetOps(1, Chain);
2730 // Copy the result values into the output registers.
2731 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2732 SDValue Val = OutVals[i];
2733 CCValAssign &VA = RVLocs[i];
2734 assert(VA.isRegLoc() && "Can only return in registers!");
2736 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2737 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2739 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2741 // Guarantee that all emitted copies are stuck together with flags.
2742 Flag = Chain.getValue(1);
2743 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2746 // The mips ABIs for returning structs by value requires that we copy
2747 // the sret argument into $v0 for the return. We saved the argument into
2748 // a virtual register in the entry block, so now we copy the value out
2750 if (MF.getFunction()->hasStructRetAttr()) {
2751 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2752 unsigned Reg = MipsFI->getSRetReturnReg();
2755 llvm_unreachable("sret virtual register not created in the entry block");
2756 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2757 unsigned V0 = isN64() ? Mips::V0_64 : Mips::V0;
2759 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2760 Flag = Chain.getValue(1);
2761 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2764 RetOps[0] = Chain; // Update chain.
2766 // Add the flag if we have it.
2768 RetOps.push_back(Flag);
2770 // Return on Mips is always a "jr $ra"
2771 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
2774 //===----------------------------------------------------------------------===//
2775 // Mips Inline Assembly Support
2776 //===----------------------------------------------------------------------===//
2778 /// getConstraintType - Given a constraint letter, return the type of
2779 /// constraint it is for this target.
2780 MipsTargetLowering::ConstraintType MipsTargetLowering::
2781 getConstraintType(const std::string &Constraint) const
2783 // Mips specific constraints
2784 // GCC config/mips/constraints.md
2786 // 'd' : An address register. Equivalent to r
2787 // unless generating MIPS16 code.
2788 // 'y' : Equivalent to r; retained for
2789 // backwards compatibility.
2790 // 'c' : A register suitable for use in an indirect
2791 // jump. This will always be $25 for -mabicalls.
2792 // 'l' : The lo register. 1 word storage.
2793 // 'x' : The hilo register pair. Double word storage.
2794 if (Constraint.size() == 1) {
2795 switch (Constraint[0]) {
2803 return C_RegisterClass;
2808 return TargetLowering::getConstraintType(Constraint);
2811 /// Examine constraint type and operand type and determine a weight value.
2812 /// This object must already have been set up with the operand type
2813 /// and the current alternative constraint selected.
2814 TargetLowering::ConstraintWeight
2815 MipsTargetLowering::getSingleConstraintMatchWeight(
2816 AsmOperandInfo &info, const char *constraint) const {
2817 ConstraintWeight weight = CW_Invalid;
2818 Value *CallOperandVal = info.CallOperandVal;
2819 // If we don't have a value, we can't do a match,
2820 // but allow it at the lowest weight.
2821 if (!CallOperandVal)
2823 Type *type = CallOperandVal->getType();
2824 // Look at the constraint type.
2825 switch (*constraint) {
2827 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2831 if (type->isIntegerTy())
2832 weight = CW_Register;
2834 case 'f': // FPU or MSA register
2835 if (Subtarget->hasMSA() && type->isVectorTy() &&
2836 cast<VectorType>(type)->getBitWidth() == 128)
2837 weight = CW_Register;
2838 else if (type->isFloatTy())
2839 weight = CW_Register;
2841 case 'c': // $25 for indirect jumps
2842 case 'l': // lo register
2843 case 'x': // hilo register pair
2844 if (type->isIntegerTy())
2845 weight = CW_SpecificReg;
2847 case 'I': // signed 16 bit immediate
2848 case 'J': // integer zero
2849 case 'K': // unsigned 16 bit immediate
2850 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2851 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2852 case 'O': // signed 15 bit immediate (+- 16383)
2853 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2854 if (isa<ConstantInt>(CallOperandVal))
2855 weight = CW_Constant;
2864 /// This is a helper function to parse a physical register string and split it
2865 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2866 /// that is returned indicates whether parsing was successful. The second flag
2867 /// is true if the numeric part exists.
2868 static std::pair<bool, bool>
2869 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2870 unsigned long long &Reg) {
2871 if (C.front() != '{' || C.back() != '}')
2872 return std::make_pair(false, false);
2874 // Search for the first numeric character.
2875 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2876 I = std::find_if(B, E, std::ptr_fun(isdigit));
2878 Prefix.assign(B, I - B);
2880 // The second flag is set to false if no numeric characters were found.
2882 return std::make_pair(true, false);
2884 // Parse the numeric characters.
2885 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2889 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2890 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2891 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2892 const TargetRegisterClass *RC;
2894 unsigned long long Reg;
2896 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2899 return std::make_pair(0U, nullptr);
2901 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2902 // No numeric characters follow "hi" or "lo".
2904 return std::make_pair(0U, nullptr);
2906 RC = TRI->getRegClass(Prefix == "hi" ?
2907 Mips::HI32RegClassID : Mips::LO32RegClassID);
2908 return std::make_pair(*(RC->begin()), RC);
2909 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2910 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2912 // No numeric characters follow the name.
2914 return std::make_pair(0U, nullptr);
2916 Reg = StringSwitch<unsigned long long>(Prefix)
2917 .Case("$msair", Mips::MSAIR)
2918 .Case("$msacsr", Mips::MSACSR)
2919 .Case("$msaaccess", Mips::MSAAccess)
2920 .Case("$msasave", Mips::MSASave)
2921 .Case("$msamodify", Mips::MSAModify)
2922 .Case("$msarequest", Mips::MSARequest)
2923 .Case("$msamap", Mips::MSAMap)
2924 .Case("$msaunmap", Mips::MSAUnmap)
2928 return std::make_pair(0U, nullptr);
2930 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2931 return std::make_pair(Reg, RC);
2935 return std::make_pair(0U, nullptr);
2937 if (Prefix == "$f") { // Parse $f0-$f31.
2938 // If the size of FP registers is 64-bit or Reg is an even number, select
2939 // the 64-bit register class. Otherwise, select the 32-bit register class.
2940 if (VT == MVT::Other)
2941 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2943 RC = getRegClassFor(VT);
2945 if (RC == &Mips::AFGR64RegClass) {
2946 assert(Reg % 2 == 0);
2949 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2950 RC = TRI->getRegClass(Mips::FCCRegClassID);
2951 else if (Prefix == "$w") { // Parse $w0-$w31.
2952 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2953 } else { // Parse $0-$31.
2954 assert(Prefix == "$");
2955 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2958 assert(Reg < RC->getNumRegs());
2959 return std::make_pair(*(RC->begin() + Reg), RC);
2962 /// Given a register class constraint, like 'r', if this corresponds directly
2963 /// to an LLVM register class, return a register of 0 and the register class
2965 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2966 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2968 if (Constraint.size() == 1) {
2969 switch (Constraint[0]) {
2970 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2971 case 'y': // Same as 'r'. Exists for compatibility.
2973 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2974 if (Subtarget->inMips16Mode())
2975 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2976 return std::make_pair(0U, &Mips::GPR32RegClass);
2978 if (VT == MVT::i64 && !isGP64bit())
2979 return std::make_pair(0U, &Mips::GPR32RegClass);
2980 if (VT == MVT::i64 && isGP64bit())
2981 return std::make_pair(0U, &Mips::GPR64RegClass);
2982 // This will generate an error message
2983 return std::make_pair(0U, nullptr);
2984 case 'f': // FPU or MSA register
2985 if (VT == MVT::v16i8)
2986 return std::make_pair(0U, &Mips::MSA128BRegClass);
2987 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
2988 return std::make_pair(0U, &Mips::MSA128HRegClass);
2989 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2990 return std::make_pair(0U, &Mips::MSA128WRegClass);
2991 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2992 return std::make_pair(0U, &Mips::MSA128DRegClass);
2993 else if (VT == MVT::f32)
2994 return std::make_pair(0U, &Mips::FGR32RegClass);
2995 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2996 if (Subtarget->isFP64bit())
2997 return std::make_pair(0U, &Mips::FGR64RegClass);
2998 return std::make_pair(0U, &Mips::AFGR64RegClass);
3001 case 'c': // register suitable for indirect jump
3003 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3004 assert(VT == MVT::i64 && "Unexpected type.");
3005 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3006 case 'l': // register suitable for indirect jump
3008 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3009 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3010 case 'x': // register suitable for indirect jump
3011 // Fixme: Not triggering the use of both hi and low
3012 // This will generate an error message
3013 return std::make_pair(0U, nullptr);
3017 std::pair<unsigned, const TargetRegisterClass *> R;
3018 R = parseRegForInlineAsmConstraint(Constraint, VT);
3023 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3026 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3027 /// vector. If it is invalid, don't add anything to Ops.
3028 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3029 std::string &Constraint,
3030 std::vector<SDValue>&Ops,
3031 SelectionDAG &DAG) const {
3034 // Only support length 1 constraints for now.
3035 if (Constraint.length() > 1) return;
3037 char ConstraintLetter = Constraint[0];
3038 switch (ConstraintLetter) {
3039 default: break; // This will fall through to the generic implementation
3040 case 'I': // Signed 16 bit constant
3041 // If this fails, the parent routine will give an error
3042 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3043 EVT Type = Op.getValueType();
3044 int64_t Val = C->getSExtValue();
3045 if (isInt<16>(Val)) {
3046 Result = DAG.getTargetConstant(Val, Type);
3051 case 'J': // integer zero
3052 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3053 EVT Type = Op.getValueType();
3054 int64_t Val = C->getZExtValue();
3056 Result = DAG.getTargetConstant(0, Type);
3061 case 'K': // unsigned 16 bit immediate
3062 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3063 EVT Type = Op.getValueType();
3064 uint64_t Val = (uint64_t)C->getZExtValue();
3065 if (isUInt<16>(Val)) {
3066 Result = DAG.getTargetConstant(Val, Type);
3071 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3072 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3073 EVT Type = Op.getValueType();
3074 int64_t Val = C->getSExtValue();
3075 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3076 Result = DAG.getTargetConstant(Val, Type);
3081 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3082 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3083 EVT Type = Op.getValueType();
3084 int64_t Val = C->getSExtValue();
3085 if ((Val >= -65535) && (Val <= -1)) {
3086 Result = DAG.getTargetConstant(Val, Type);
3091 case 'O': // signed 15 bit immediate
3092 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3093 EVT Type = Op.getValueType();
3094 int64_t Val = C->getSExtValue();
3095 if ((isInt<15>(Val))) {
3096 Result = DAG.getTargetConstant(Val, Type);
3101 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3102 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3103 EVT Type = Op.getValueType();
3104 int64_t Val = C->getSExtValue();
3105 if ((Val <= 65535) && (Val >= 1)) {
3106 Result = DAG.getTargetConstant(Val, Type);
3113 if (Result.getNode()) {
3114 Ops.push_back(Result);
3118 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3121 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3123 // No global is ever allowed as a base.
3128 case 0: // "r+i" or just "i", depending on HasBaseReg.
3131 if (!AM.HasBaseReg) // allow "r+i".
3133 return false; // disallow "r+r" or "r+r+i".
3142 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3143 // The Mips target isn't yet aware of offsets.
3147 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3149 bool IsMemset, bool ZeroMemset,
3151 MachineFunction &MF) const {
3152 if (Subtarget->hasMips64())
3158 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3159 if (VT != MVT::f32 && VT != MVT::f64)
3161 if (Imm.isNegZero())
3163 return Imm.isZero();
3166 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3168 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3170 return TargetLowering::getJumpTableEncoding();
3173 /// This function returns true if CallSym is a long double emulation routine.
3174 static bool isF128SoftLibCall(const char *CallSym) {
3175 const char *const LibCalls[] =
3176 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3177 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3178 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3179 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3180 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3181 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3182 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3183 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3186 const char *const *End = LibCalls + array_lengthof(LibCalls);
3188 // Check that LibCalls is sorted alphabetically.
3189 MipsTargetLowering::LTStr Comp;
3192 for (const char *const *I = LibCalls; I < End - 1; ++I)
3193 assert(Comp(*I, *(I + 1)));
3196 return std::binary_search(LibCalls, End, CallSym, Comp);
3199 /// This function returns true if Ty is fp128 or i128 which was originally a
3201 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3202 if (Ty->isFP128Ty())
3205 const ExternalSymbolSDNode *ES =
3206 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3208 // If the Ty is i128 and the function being called is a long double emulation
3209 // routine, then the original type is f128.
3210 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3213 MipsTargetLowering::MipsCC::SpecialCallingConvType
3214 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3215 MipsCC::SpecialCallingConvType SpecialCallingConv =
3216 MipsCC::NoSpecialCallingConv;
3217 if (Subtarget->inMips16HardFloat()) {
3218 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3219 llvm::StringRef Sym = G->getGlobal()->getName();
3220 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3221 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3222 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3226 return SpecialCallingConv;
3229 MipsTargetLowering::MipsCC::MipsCC(
3230 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3231 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3232 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3233 SpecialCallingConv(SpecialCallingConv_){
3234 // Pre-allocate reserved argument area.
3235 CCInfo.AllocateStack(reservedArgArea(), 1);
3239 void MipsTargetLowering::MipsCC::
3240 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3241 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3242 std::vector<ArgListEntry> &FuncArgs) {
3243 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3244 "CallingConv::Fast shouldn't be used for vararg functions.");
3246 unsigned NumOpnds = Args.size();
3247 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3249 for (unsigned I = 0; I != NumOpnds; ++I) {
3250 MVT ArgVT = Args[I].VT;
3251 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3254 if (ArgFlags.isByVal()) {
3255 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3259 if (IsVarArg && !Args[I].IsFixed)
3260 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3262 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3264 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3269 dbgs() << "Call operand #" << I << " has unhandled type "
3270 << EVT(ArgVT).getEVTString();
3272 llvm_unreachable(nullptr);
3277 void MipsTargetLowering::MipsCC::
3278 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3279 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3280 unsigned NumArgs = Args.size();
3281 llvm::CCAssignFn *FixedFn = fixedArgFn();
3282 unsigned CurArgIdx = 0;
3284 for (unsigned I = 0; I != NumArgs; ++I) {
3285 MVT ArgVT = Args[I].VT;
3286 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3287 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3288 CurArgIdx = Args[I].OrigArgIndex;
3290 if (ArgFlags.isByVal()) {
3291 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3295 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
3297 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3301 dbgs() << "Formal Arg #" << I << " has unhandled type "
3302 << EVT(ArgVT).getEVTString();
3304 llvm_unreachable(nullptr);
3308 template<typename Ty>
3309 void MipsTargetLowering::MipsCC::
3310 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3311 const SDNode *CallNode, const Type *RetTy) const {
3314 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3315 Fn = RetCC_F128Soft;
3319 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3320 MVT VT = RetVals[I].VT;
3321 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3322 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3324 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3326 dbgs() << "Call result #" << I << " has unhandled type "
3327 << EVT(VT).getEVTString() << '\n';
3329 llvm_unreachable(nullptr);
3334 void MipsTargetLowering::MipsCC::
3335 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3336 const SDNode *CallNode, const Type *RetTy) const {
3337 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3340 void MipsTargetLowering::MipsCC::
3341 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3342 const Type *RetTy) const {
3343 analyzeReturn(Outs, IsSoftFloat, nullptr, RetTy);
3346 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3348 CCValAssign::LocInfo LocInfo,
3349 ISD::ArgFlagsTy ArgFlags) {
3350 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3352 struct ByValArgInfo ByVal;
3353 unsigned RegSize = regSize();
3354 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3355 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3358 if (useRegsForByval())
3359 allocateRegs(ByVal, ByValSize, Align);
3361 // Allocate space on caller's stack.
3362 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3364 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3366 ByValArgs.push_back(ByVal);
3369 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3370 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3373 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3374 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3377 const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
3378 return IsO32 ? O32IntRegs : Mips64IntRegs;
3381 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3382 if (CallConv == CallingConv::Fast)
3383 return CC_Mips_FastCC;
3385 if (SpecialCallingConv == Mips16RetHelperConv)
3386 return CC_Mips16RetHelper;
3387 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3390 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3391 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3394 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3395 return IsO32 ? O32IntRegs : Mips64DPRegs;
3398 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3401 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3402 const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3403 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3404 "Byval argument's size and alignment should be a multiple of"
3407 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3409 // If Align > RegSize, the first arg register must be even.
3410 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3411 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3415 // Mark the registers allocated.
3416 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3417 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3418 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3421 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3422 const SDNode *CallNode,
3423 bool IsSoftFloat) const {
3424 if (IsSoftFloat || IsO32)
3427 // Check if the original type was fp128.
3428 if (originalTypeIsF128(OrigTy, CallNode)) {
3429 assert(VT == MVT::i64);
3436 void MipsTargetLowering::
3437 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3438 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3439 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3440 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3441 MachineFunction &MF = DAG.getMachineFunction();
3442 MachineFrameInfo *MFI = MF.getFrameInfo();
3443 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3444 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3448 FrameObjOffset = (int)CC.reservedArgArea() -
3449 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3451 FrameObjOffset = ByVal.Address;
3453 // Create frame object.
3454 EVT PtrTy = getPointerTy();
3455 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3456 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3457 InVals.push_back(FIN);
3462 // Copy arg registers.
3463 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3464 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3466 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3467 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3468 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3469 unsigned Offset = I * CC.regSize();
3470 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3471 DAG.getConstant(Offset, PtrTy));
3472 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3473 StorePtr, MachinePointerInfo(FuncArg, Offset),
3475 OutChains.push_back(Store);
3479 // Copy byVal arg to registers and stack.
3480 void MipsTargetLowering::
3481 passByValArg(SDValue Chain, SDLoc DL,
3482 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3483 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3484 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3485 const MipsCC &CC, const ByValArgInfo &ByVal,
3486 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3487 unsigned ByValSize = Flags.getByValSize();
3488 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3489 unsigned RegSize = CC.regSize();
3490 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3491 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3493 if (ByVal.NumRegs) {
3494 const MCPhysReg *ArgRegs = CC.intArgRegs();
3495 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3498 // Copy words to registers.
3499 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3500 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3501 DAG.getConstant(Offset, PtrTy));
3502 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3503 MachinePointerInfo(), false, false, false,
3505 MemOpChains.push_back(LoadVal.getValue(1));
3506 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3507 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3510 // Return if the struct has been fully copied.
3511 if (ByValSize == Offset)
3514 // Copy the remainder of the byval argument with sub-word loads and shifts.
3515 if (LeftoverBytes) {
3516 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3517 "Size of the remainder should be smaller than RegSize.");
3520 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3521 Offset < ByValSize; LoadSize /= 2) {
3522 unsigned RemSize = ByValSize - Offset;
3524 if (RemSize < LoadSize)
3528 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3529 DAG.getConstant(Offset, PtrTy));
3531 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3532 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3533 false, false, Alignment);
3534 MemOpChains.push_back(LoadVal.getValue(1));
3536 // Shift the loaded value.
3540 Shamt = TotalSizeLoaded;
3542 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3544 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3545 DAG.getConstant(Shamt, MVT::i32));
3548 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3553 TotalSizeLoaded += LoadSize;
3554 Alignment = std::min(Alignment, LoadSize);
3557 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3558 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3563 // Copy remainder of byval arg to it with memcpy.
3564 unsigned MemCpySize = ByValSize - Offset;
3565 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3566 DAG.getConstant(Offset, PtrTy));
3567 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3568 DAG.getIntPtrConstant(ByVal.Address));
3569 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3570 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3571 MachinePointerInfo(), MachinePointerInfo());
3572 MemOpChains.push_back(Chain);
3575 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3576 const MipsCC &CC, SDValue Chain,
3577 SDLoc DL, SelectionDAG &DAG) const {
3578 unsigned NumRegs = CC.numIntArgRegs();
3579 const MCPhysReg *ArgRegs = CC.intArgRegs();
3580 const CCState &CCInfo = CC.getCCInfo();
3581 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3582 unsigned RegSize = CC.regSize();
3583 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3584 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3585 MachineFunction &MF = DAG.getMachineFunction();
3586 MachineFrameInfo *MFI = MF.getFrameInfo();
3587 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3589 // Offset of the first variable argument from stack pointer.
3593 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3595 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3597 // Record the frame index of the first variable argument
3598 // which is a value necessary to VASTART.
3599 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3600 MipsFI->setVarArgsFrameIndex(FI);
3602 // Copy the integer registers that have not been used for argument passing
3603 // to the argument register save area. For O32, the save area is allocated
3604 // in the caller's stack frame, while for N32/64, it is allocated in the
3605 // callee's stack frame.
3606 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3607 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3608 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3609 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3610 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3611 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3612 MachinePointerInfo(), false, false, 0);
3613 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue((Value*)nullptr);
3614 OutChains.push_back(Store);