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 #define DEBUG_TYPE "mips-lower"
15 #include "MipsISelLowering.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NumTailCalls, "Number of tail calls");
45 LargeGOT("mxgot", cl::Hidden,
46 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
49 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
50 cl::desc("MIPS: Don't trap on integer division by zero."),
53 static const MCPhysReg O32IntRegs[4] = {
54 Mips::A0, Mips::A1, Mips::A2, Mips::A3
57 static const MCPhysReg Mips64IntRegs[8] = {
58 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
59 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
62 static const MCPhysReg Mips64DPRegs[8] = {
63 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
64 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
67 // If I is a shifted mask, set the size (Size) and the first bit of the
68 // mask (Pos), and return true.
69 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
70 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
71 if (!isShiftedMask_64(I))
74 Size = CountPopulation_64(I);
75 Pos = countTrailingZeros(I);
79 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
80 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
81 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
84 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
86 unsigned Flag) const {
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
90 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
96 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
102 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
108 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
112 N->getOffset(), Flag);
115 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
117 case MipsISD::JmpLink: return "MipsISD::JmpLink";
118 case MipsISD::TailCall: return "MipsISD::TailCall";
119 case MipsISD::Hi: return "MipsISD::Hi";
120 case MipsISD::Lo: return "MipsISD::Lo";
121 case MipsISD::GPRel: return "MipsISD::GPRel";
122 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
123 case MipsISD::Ret: return "MipsISD::Ret";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::Sync: return "MipsISD::Sync";
147 case MipsISD::Ext: return "MipsISD::Ext";
148 case MipsISD::Ins: return "MipsISD::Ins";
149 case MipsISD::LWL: return "MipsISD::LWL";
150 case MipsISD::LWR: return "MipsISD::LWR";
151 case MipsISD::SWL: return "MipsISD::SWL";
152 case MipsISD::SWR: return "MipsISD::SWR";
153 case MipsISD::LDL: return "MipsISD::LDL";
154 case MipsISD::LDR: return "MipsISD::LDR";
155 case MipsISD::SDL: return "MipsISD::SDL";
156 case MipsISD::SDR: return "MipsISD::SDR";
157 case MipsISD::EXTP: return "MipsISD::EXTP";
158 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
159 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
160 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
161 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
162 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
163 case MipsISD::SHILO: return "MipsISD::SHILO";
164 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
165 case MipsISD::MULT: return "MipsISD::MULT";
166 case MipsISD::MULTU: return "MipsISD::MULTU";
167 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
168 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
169 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
170 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
171 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
172 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
173 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
174 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
175 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
176 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
177 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
178 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
179 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
180 case MipsISD::VCEQ: return "MipsISD::VCEQ";
181 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
182 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
183 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
184 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
185 case MipsISD::VSMAX: return "MipsISD::VSMAX";
186 case MipsISD::VSMIN: return "MipsISD::VSMIN";
187 case MipsISD::VUMAX: return "MipsISD::VUMAX";
188 case MipsISD::VUMIN: return "MipsISD::VUMIN";
189 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
190 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
191 case MipsISD::VNOR: return "MipsISD::VNOR";
192 case MipsISD::VSHF: return "MipsISD::VSHF";
193 case MipsISD::SHF: return "MipsISD::SHF";
194 case MipsISD::ILVEV: return "MipsISD::ILVEV";
195 case MipsISD::ILVOD: return "MipsISD::ILVOD";
196 case MipsISD::ILVL: return "MipsISD::ILVL";
197 case MipsISD::ILVR: return "MipsISD::ILVR";
198 case MipsISD::PCKEV: return "MipsISD::PCKEV";
199 case MipsISD::PCKOD: return "MipsISD::PCKOD";
200 case MipsISD::INSVE: return "MipsISD::INSVE";
201 default: return NULL;
205 MipsTargetLowering::MipsTargetLowering(MipsTargetMachine &TM)
206 : TargetLowering(TM, new MipsTargetObjectFile()),
207 Subtarget(&TM.getSubtarget<MipsSubtarget>()) {
208 // Mips does not have i1 type, so use i32 for
209 // setcc operations results (slt, sgt, ...).
210 setBooleanContents(ZeroOrOneBooleanContent);
211 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
213 // Load extented operations for i1 types must be promoted
214 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
215 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
216 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
218 // MIPS doesn't have extending float->double load/store
219 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
220 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
222 // Used by legalize types to correctly generate the setcc result.
223 // Without this, every float setcc comes with a AND/OR with the result,
224 // we don't want this, since the fpcmp result goes to a flag register,
225 // which is used implicitly by brcond and select operations.
226 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
228 // Mips Custom Operations
229 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
230 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
231 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
232 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
233 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
234 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
235 setOperationAction(ISD::SELECT, MVT::f32, Custom);
236 setOperationAction(ISD::SELECT, MVT::f64, Custom);
237 setOperationAction(ISD::SELECT, MVT::i32, Custom);
238 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
239 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
240 setOperationAction(ISD::SETCC, MVT::f32, Custom);
241 setOperationAction(ISD::SETCC, MVT::f64, Custom);
242 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
243 setOperationAction(ISD::VASTART, MVT::Other, Custom);
244 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
245 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
246 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
249 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
250 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
251 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
252 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
253 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
254 setOperationAction(ISD::SELECT, MVT::i64, Custom);
255 setOperationAction(ISD::LOAD, MVT::i64, Custom);
256 setOperationAction(ISD::STORE, MVT::i64, Custom);
257 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
261 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
262 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
263 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
266 setOperationAction(ISD::ADD, MVT::i32, Custom);
268 setOperationAction(ISD::ADD, MVT::i64, Custom);
270 setOperationAction(ISD::SDIV, MVT::i32, Expand);
271 setOperationAction(ISD::SREM, MVT::i32, Expand);
272 setOperationAction(ISD::UDIV, MVT::i32, Expand);
273 setOperationAction(ISD::UREM, MVT::i32, Expand);
274 setOperationAction(ISD::SDIV, MVT::i64, Expand);
275 setOperationAction(ISD::SREM, MVT::i64, Expand);
276 setOperationAction(ISD::UDIV, MVT::i64, Expand);
277 setOperationAction(ISD::UREM, MVT::i64, Expand);
279 // Operations not directly supported by Mips.
280 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
281 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
282 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
283 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
284 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
285 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
286 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
287 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
288 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
289 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
290 if (Subtarget->hasCnMips()) {
291 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
292 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
294 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
295 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
297 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
298 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
299 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
300 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
301 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
302 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
303 setOperationAction(ISD::ROTL, MVT::i32, Expand);
304 setOperationAction(ISD::ROTL, MVT::i64, Expand);
305 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
306 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
308 if (!Subtarget->hasMips32r2())
309 setOperationAction(ISD::ROTR, MVT::i32, Expand);
311 if (!Subtarget->hasMips64r2())
312 setOperationAction(ISD::ROTR, MVT::i64, Expand);
314 setOperationAction(ISD::FSIN, MVT::f32, Expand);
315 setOperationAction(ISD::FSIN, MVT::f64, Expand);
316 setOperationAction(ISD::FCOS, MVT::f32, Expand);
317 setOperationAction(ISD::FCOS, MVT::f64, Expand);
318 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
319 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
320 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
321 setOperationAction(ISD::FPOW, MVT::f32, Expand);
322 setOperationAction(ISD::FPOW, MVT::f64, Expand);
323 setOperationAction(ISD::FLOG, MVT::f32, Expand);
324 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
325 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
326 setOperationAction(ISD::FEXP, MVT::f32, Expand);
327 setOperationAction(ISD::FMA, MVT::f32, Expand);
328 setOperationAction(ISD::FMA, MVT::f64, Expand);
329 setOperationAction(ISD::FREM, MVT::f32, Expand);
330 setOperationAction(ISD::FREM, MVT::f64, Expand);
332 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
334 setOperationAction(ISD::VAARG, MVT::Other, Expand);
335 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
336 setOperationAction(ISD::VAEND, MVT::Other, Expand);
338 // Use the default for now
339 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
340 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
342 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
343 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
344 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
345 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
347 setInsertFencesForAtomic(true);
349 if (!Subtarget->hasSEInReg()) {
350 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
351 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
354 if (!Subtarget->hasBitCount()) {
355 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
356 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
359 if (!Subtarget->hasSwap()) {
360 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
361 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
365 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
366 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
367 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
368 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
371 setOperationAction(ISD::TRAP, MVT::Other, Legal);
373 setTargetDAGCombine(ISD::SDIVREM);
374 setTargetDAGCombine(ISD::UDIVREM);
375 setTargetDAGCombine(ISD::SELECT);
376 setTargetDAGCombine(ISD::AND);
377 setTargetDAGCombine(ISD::OR);
378 setTargetDAGCombine(ISD::ADD);
380 setMinFunctionAlignment(isGP64bit() ? 3 : 2);
382 setStackPointerRegisterToSaveRestore(isN64() ? Mips::SP_64 : Mips::SP);
384 setExceptionPointerRegister(isN64() ? Mips::A0_64 : Mips::A0);
385 setExceptionSelectorRegister(isN64() ? Mips::A1_64 : Mips::A1);
387 MaxStoresPerMemcpy = 16;
389 isMicroMips = Subtarget->inMicroMipsMode();
392 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
393 if (TM.getSubtargetImpl()->inMips16Mode())
394 return llvm::createMips16TargetLowering(TM);
396 return llvm::createMipsSETargetLowering(TM);
399 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
402 return VT.changeVectorElementTypeToInteger();
405 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
406 TargetLowering::DAGCombinerInfo &DCI,
407 const MipsSubtarget *Subtarget) {
408 if (DCI.isBeforeLegalizeOps())
411 EVT Ty = N->getValueType(0);
412 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
413 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
414 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
418 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
419 N->getOperand(0), N->getOperand(1));
420 SDValue InChain = DAG.getEntryNode();
421 SDValue InGlue = DivRem;
424 if (N->hasAnyUseOfValue(0)) {
425 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
427 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
428 InChain = CopyFromLo.getValue(1);
429 InGlue = CopyFromLo.getValue(2);
433 if (N->hasAnyUseOfValue(1)) {
434 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
436 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
442 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
444 default: llvm_unreachable("Unknown fp condition code!");
446 case ISD::SETOEQ: return Mips::FCOND_OEQ;
447 case ISD::SETUNE: return Mips::FCOND_UNE;
449 case ISD::SETOLT: return Mips::FCOND_OLT;
451 case ISD::SETOGT: return Mips::FCOND_OGT;
453 case ISD::SETOLE: return Mips::FCOND_OLE;
455 case ISD::SETOGE: return Mips::FCOND_OGE;
456 case ISD::SETULT: return Mips::FCOND_ULT;
457 case ISD::SETULE: return Mips::FCOND_ULE;
458 case ISD::SETUGT: return Mips::FCOND_UGT;
459 case ISD::SETUGE: return Mips::FCOND_UGE;
460 case ISD::SETUO: return Mips::FCOND_UN;
461 case ISD::SETO: return Mips::FCOND_OR;
463 case ISD::SETONE: return Mips::FCOND_ONE;
464 case ISD::SETUEQ: return Mips::FCOND_UEQ;
469 /// This function returns true if the floating point conditional branches and
470 /// conditional moves which use condition code CC should be inverted.
471 static bool invertFPCondCodeUser(Mips::CondCode CC) {
472 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
475 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
476 "Illegal Condition Code");
481 // Creates and returns an FPCmp node from a setcc node.
482 // Returns Op if setcc is not a floating point comparison.
483 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
484 // must be a SETCC node
485 if (Op.getOpcode() != ISD::SETCC)
488 SDValue LHS = Op.getOperand(0);
490 if (!LHS.getValueType().isFloatingPoint())
493 SDValue RHS = Op.getOperand(1);
496 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
497 // node if necessary.
498 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
500 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
501 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
504 // Creates and returns a CMovFPT/F node.
505 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
506 SDValue False, SDLoc DL) {
507 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
508 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
509 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
511 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
512 True.getValueType(), True, FCC0, False, Cond);
515 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
516 TargetLowering::DAGCombinerInfo &DCI,
517 const MipsSubtarget *Subtarget) {
518 if (DCI.isBeforeLegalizeOps())
521 SDValue SetCC = N->getOperand(0);
523 if ((SetCC.getOpcode() != ISD::SETCC) ||
524 !SetCC.getOperand(0).getValueType().isInteger())
527 SDValue False = N->getOperand(2);
528 EVT FalseTy = False.getValueType();
530 if (!FalseTy.isInteger())
533 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
535 // If the RHS (False) is 0, we swap the order of the operands
536 // of ISD::SELECT (obviously also inverting the condition) so that we can
537 // take advantage of conditional moves using the $0 register.
539 // return (a != 0) ? x : 0;
547 if (!FalseC->getZExtValue()) {
548 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
549 SDValue True = N->getOperand(1);
551 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
552 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
554 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
557 // If both operands are integer constants there's a possibility that we
558 // can do some interesting optimizations.
559 SDValue True = N->getOperand(1);
560 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
562 if (!TrueC || !True.getValueType().isInteger())
565 // We'll also ignore MVT::i64 operands as this optimizations proves
566 // to be ineffective because of the required sign extensions as the result
567 // of a SETCC operator is always MVT::i32 for non-vector types.
568 if (True.getValueType() == MVT::i64)
571 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
573 // 1) (a < x) ? y : y-1
575 // addiu $reg2, $reg1, y-1
577 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
579 // 2) (a < x) ? y-1 : y
581 // xor $reg1, $reg1, 1
582 // addiu $reg2, $reg1, y-1
584 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
585 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
586 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
587 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
590 // Couldn't optimize.
594 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
595 TargetLowering::DAGCombinerInfo &DCI,
596 const MipsSubtarget *Subtarget) {
597 // Pattern match EXT.
598 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
599 // => ext $dst, $src, size, pos
600 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
603 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
604 unsigned ShiftRightOpc = ShiftRight.getOpcode();
606 // Op's first operand must be a shift right.
607 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
610 // The second operand of the shift must be an immediate.
612 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
615 uint64_t Pos = CN->getZExtValue();
616 uint64_t SMPos, SMSize;
618 // Op's second operand must be a shifted mask.
619 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
620 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
623 // Return if the shifted mask does not start at bit 0 or the sum of its size
624 // and Pos exceeds the word's size.
625 EVT ValTy = N->getValueType(0);
626 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
629 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
630 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
631 DAG.getConstant(SMSize, MVT::i32));
634 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
635 TargetLowering::DAGCombinerInfo &DCI,
636 const MipsSubtarget *Subtarget) {
637 // Pattern match INS.
638 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
639 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
640 // => ins $dst, $src, size, pos, $src1
641 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
644 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
645 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
648 // See if Op's first operand matches (and $src1 , mask0).
649 if (And0.getOpcode() != ISD::AND)
652 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
653 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
656 // See if Op's second operand matches (and (shl $src, pos), mask1).
657 if (And1.getOpcode() != ISD::AND)
660 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
661 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
664 // The shift masks must have the same position and size.
665 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
668 SDValue Shl = And1.getOperand(0);
669 if (Shl.getOpcode() != ISD::SHL)
672 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
675 unsigned Shamt = CN->getZExtValue();
677 // Return if the shift amount and the first bit position of mask are not the
679 EVT ValTy = N->getValueType(0);
680 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
683 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
684 DAG.getConstant(SMPos0, MVT::i32),
685 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
688 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
689 TargetLowering::DAGCombinerInfo &DCI,
690 const MipsSubtarget *Subtarget) {
691 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
693 if (DCI.isBeforeLegalizeOps())
696 SDValue Add = N->getOperand(1);
698 if (Add.getOpcode() != ISD::ADD)
701 SDValue Lo = Add.getOperand(1);
703 if ((Lo.getOpcode() != MipsISD::Lo) ||
704 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
707 EVT ValTy = N->getValueType(0);
710 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
712 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
715 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
717 SelectionDAG &DAG = DCI.DAG;
718 unsigned Opc = N->getOpcode();
724 return performDivRemCombine(N, DAG, DCI, Subtarget);
726 return performSELECTCombine(N, DAG, DCI, Subtarget);
728 return performANDCombine(N, DAG, DCI, Subtarget);
730 return performORCombine(N, DAG, DCI, Subtarget);
732 return performADDCombine(N, DAG, DCI, Subtarget);
739 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
740 SmallVectorImpl<SDValue> &Results,
741 SelectionDAG &DAG) const {
742 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
744 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
745 Results.push_back(Res.getValue(I));
749 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
750 SmallVectorImpl<SDValue> &Results,
751 SelectionDAG &DAG) const {
752 return LowerOperationWrapper(N, Results, DAG);
755 SDValue MipsTargetLowering::
756 LowerOperation(SDValue Op, SelectionDAG &DAG) const
758 switch (Op.getOpcode())
760 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
761 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
762 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
763 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
764 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
765 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
766 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
767 case ISD::SELECT: return lowerSELECT(Op, DAG);
768 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
769 case ISD::SETCC: return lowerSETCC(Op, DAG);
770 case ISD::VASTART: return lowerVASTART(Op, DAG);
771 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
772 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
773 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
774 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
775 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
776 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
777 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
778 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
779 case ISD::LOAD: return lowerLOAD(Op, DAG);
780 case ISD::STORE: return lowerSTORE(Op, DAG);
781 case ISD::ADD: return lowerADD(Op, DAG);
782 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
787 //===----------------------------------------------------------------------===//
788 // Lower helper functions
789 //===----------------------------------------------------------------------===//
791 // addLiveIn - This helper function adds the specified physical register to the
792 // MachineFunction as a live in value. It also creates a corresponding
793 // virtual register for it.
795 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
797 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
798 MF.getRegInfo().addLiveIn(PReg, VReg);
802 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
803 MachineBasicBlock &MBB,
804 const TargetInstrInfo &TII,
809 // Insert instruction "teq $divisor_reg, $zero, 7".
810 MachineBasicBlock::iterator I(MI);
811 MachineInstrBuilder MIB;
812 MachineOperand &Divisor = MI->getOperand(2);
813 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
814 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
815 .addReg(Mips::ZERO).addImm(7);
817 // Use the 32-bit sub-register if this is a 64-bit division.
819 MIB->getOperand(0).setSubReg(Mips::sub_32);
821 // Clear Divisor's kill flag.
822 Divisor.setIsKill(false);
827 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
828 MachineBasicBlock *BB) const {
829 switch (MI->getOpcode()) {
831 llvm_unreachable("Unexpected instr type to insert");
832 case Mips::ATOMIC_LOAD_ADD_I8:
833 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
834 case Mips::ATOMIC_LOAD_ADD_I16:
835 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
836 case Mips::ATOMIC_LOAD_ADD_I32:
837 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
838 case Mips::ATOMIC_LOAD_ADD_I64:
839 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
841 case Mips::ATOMIC_LOAD_AND_I8:
842 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
843 case Mips::ATOMIC_LOAD_AND_I16:
844 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
845 case Mips::ATOMIC_LOAD_AND_I32:
846 return emitAtomicBinary(MI, BB, 4, Mips::AND);
847 case Mips::ATOMIC_LOAD_AND_I64:
848 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
850 case Mips::ATOMIC_LOAD_OR_I8:
851 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
852 case Mips::ATOMIC_LOAD_OR_I16:
853 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
854 case Mips::ATOMIC_LOAD_OR_I32:
855 return emitAtomicBinary(MI, BB, 4, Mips::OR);
856 case Mips::ATOMIC_LOAD_OR_I64:
857 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
859 case Mips::ATOMIC_LOAD_XOR_I8:
860 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
861 case Mips::ATOMIC_LOAD_XOR_I16:
862 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
863 case Mips::ATOMIC_LOAD_XOR_I32:
864 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
865 case Mips::ATOMIC_LOAD_XOR_I64:
866 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
868 case Mips::ATOMIC_LOAD_NAND_I8:
869 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
870 case Mips::ATOMIC_LOAD_NAND_I16:
871 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
872 case Mips::ATOMIC_LOAD_NAND_I32:
873 return emitAtomicBinary(MI, BB, 4, 0, true);
874 case Mips::ATOMIC_LOAD_NAND_I64:
875 return emitAtomicBinary(MI, BB, 8, 0, true);
877 case Mips::ATOMIC_LOAD_SUB_I8:
878 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
879 case Mips::ATOMIC_LOAD_SUB_I16:
880 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
881 case Mips::ATOMIC_LOAD_SUB_I32:
882 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
883 case Mips::ATOMIC_LOAD_SUB_I64:
884 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
886 case Mips::ATOMIC_SWAP_I8:
887 return emitAtomicBinaryPartword(MI, BB, 1, 0);
888 case Mips::ATOMIC_SWAP_I16:
889 return emitAtomicBinaryPartword(MI, BB, 2, 0);
890 case Mips::ATOMIC_SWAP_I32:
891 return emitAtomicBinary(MI, BB, 4, 0);
892 case Mips::ATOMIC_SWAP_I64:
893 return emitAtomicBinary(MI, BB, 8, 0);
895 case Mips::ATOMIC_CMP_SWAP_I8:
896 return emitAtomicCmpSwapPartword(MI, BB, 1);
897 case Mips::ATOMIC_CMP_SWAP_I16:
898 return emitAtomicCmpSwapPartword(MI, BB, 2);
899 case Mips::ATOMIC_CMP_SWAP_I32:
900 return emitAtomicCmpSwap(MI, BB, 4);
901 case Mips::ATOMIC_CMP_SWAP_I64:
902 return emitAtomicCmpSwap(MI, BB, 8);
903 case Mips::PseudoSDIV:
904 case Mips::PseudoUDIV:
905 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
906 case Mips::PseudoDSDIV:
907 case Mips::PseudoDUDIV:
908 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
912 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
913 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
915 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
916 unsigned Size, unsigned BinOpcode,
918 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
920 MachineFunction *MF = BB->getParent();
921 MachineRegisterInfo &RegInfo = MF->getRegInfo();
922 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
923 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
924 DebugLoc DL = MI->getDebugLoc();
925 unsigned LL, SC, AND, NOR, ZERO, BEQ;
928 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
929 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
940 ZERO = Mips::ZERO_64;
944 unsigned OldVal = MI->getOperand(0).getReg();
945 unsigned Ptr = MI->getOperand(1).getReg();
946 unsigned Incr = MI->getOperand(2).getReg();
948 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
949 unsigned AndRes = RegInfo.createVirtualRegister(RC);
950 unsigned Success = RegInfo.createVirtualRegister(RC);
952 // insert new blocks after the current block
953 const BasicBlock *LLVM_BB = BB->getBasicBlock();
954 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
955 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
956 MachineFunction::iterator It = BB;
958 MF->insert(It, loopMBB);
959 MF->insert(It, exitMBB);
961 // Transfer the remainder of BB and its successor edges to exitMBB.
962 exitMBB->splice(exitMBB->begin(), BB,
963 std::next(MachineBasicBlock::iterator(MI)), BB->end());
964 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
968 // fallthrough --> loopMBB
969 BB->addSuccessor(loopMBB);
970 loopMBB->addSuccessor(loopMBB);
971 loopMBB->addSuccessor(exitMBB);
975 // <binop> storeval, oldval, incr
976 // sc success, storeval, 0(ptr)
977 // beq success, $0, loopMBB
979 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
981 // and andres, oldval, incr
982 // nor storeval, $0, andres
983 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
984 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
985 } else if (BinOpcode) {
986 // <binop> storeval, oldval, incr
987 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
991 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
992 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
994 MI->eraseFromParent(); // The instruction is gone now.
1000 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1001 MachineBasicBlock *BB,
1002 unsigned Size, unsigned BinOpcode,
1004 assert((Size == 1 || Size == 2) &&
1005 "Unsupported size for EmitAtomicBinaryPartial.");
1007 MachineFunction *MF = BB->getParent();
1008 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1009 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1010 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1011 DebugLoc DL = MI->getDebugLoc();
1013 unsigned Dest = MI->getOperand(0).getReg();
1014 unsigned Ptr = MI->getOperand(1).getReg();
1015 unsigned Incr = MI->getOperand(2).getReg();
1017 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1018 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1019 unsigned Mask = RegInfo.createVirtualRegister(RC);
1020 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1021 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1022 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1023 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1024 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1025 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1026 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1027 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1028 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1029 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1030 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1031 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1032 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1033 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1034 unsigned Success = RegInfo.createVirtualRegister(RC);
1036 // insert new blocks after the current block
1037 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1038 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1039 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1040 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1041 MachineFunction::iterator It = BB;
1043 MF->insert(It, loopMBB);
1044 MF->insert(It, sinkMBB);
1045 MF->insert(It, exitMBB);
1047 // Transfer the remainder of BB and its successor edges to exitMBB.
1048 exitMBB->splice(exitMBB->begin(), BB,
1049 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1050 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1052 BB->addSuccessor(loopMBB);
1053 loopMBB->addSuccessor(loopMBB);
1054 loopMBB->addSuccessor(sinkMBB);
1055 sinkMBB->addSuccessor(exitMBB);
1058 // addiu masklsb2,$0,-4 # 0xfffffffc
1059 // and alignedaddr,ptr,masklsb2
1060 // andi ptrlsb2,ptr,3
1061 // sll shiftamt,ptrlsb2,3
1062 // ori maskupper,$0,255 # 0xff
1063 // sll mask,maskupper,shiftamt
1064 // nor mask2,$0,mask
1065 // sll incr2,incr,shiftamt
1067 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1068 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1069 .addReg(Mips::ZERO).addImm(-4);
1070 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1071 .addReg(Ptr).addReg(MaskLSB2);
1072 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1073 if (Subtarget->isLittle()) {
1074 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1076 unsigned Off = RegInfo.createVirtualRegister(RC);
1077 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1078 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1079 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1081 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1082 .addReg(Mips::ZERO).addImm(MaskImm);
1083 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1084 .addReg(MaskUpper).addReg(ShiftAmt);
1085 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1086 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1088 // atomic.load.binop
1090 // ll oldval,0(alignedaddr)
1091 // binop binopres,oldval,incr2
1092 // and newval,binopres,mask
1093 // and maskedoldval0,oldval,mask2
1094 // or storeval,maskedoldval0,newval
1095 // sc success,storeval,0(alignedaddr)
1096 // beq success,$0,loopMBB
1100 // ll oldval,0(alignedaddr)
1101 // and newval,incr2,mask
1102 // and maskedoldval0,oldval,mask2
1103 // or storeval,maskedoldval0,newval
1104 // sc success,storeval,0(alignedaddr)
1105 // beq success,$0,loopMBB
1108 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1110 // and andres, oldval, incr2
1111 // nor binopres, $0, andres
1112 // and newval, binopres, mask
1113 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1114 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1115 .addReg(Mips::ZERO).addReg(AndRes);
1116 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1117 } else if (BinOpcode) {
1118 // <binop> binopres, oldval, incr2
1119 // and newval, binopres, mask
1120 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1121 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1122 } else { // atomic.swap
1123 // and newval, incr2, mask
1124 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1127 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1128 .addReg(OldVal).addReg(Mask2);
1129 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1130 .addReg(MaskedOldVal0).addReg(NewVal);
1131 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1132 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1133 BuildMI(BB, DL, TII->get(Mips::BEQ))
1134 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1137 // and maskedoldval1,oldval,mask
1138 // srl srlres,maskedoldval1,shiftamt
1139 // sll sllres,srlres,24
1140 // sra dest,sllres,24
1142 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1144 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1145 .addReg(OldVal).addReg(Mask);
1146 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1147 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1148 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1149 .addReg(SrlRes).addImm(ShiftImm);
1150 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1151 .addReg(SllRes).addImm(ShiftImm);
1153 MI->eraseFromParent(); // The instruction is gone now.
1158 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1159 MachineBasicBlock *BB,
1160 unsigned Size) const {
1161 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1163 MachineFunction *MF = BB->getParent();
1164 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1165 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1166 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1167 DebugLoc DL = MI->getDebugLoc();
1168 unsigned LL, SC, ZERO, BNE, BEQ;
1171 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1172 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1179 ZERO = Mips::ZERO_64;
1184 unsigned Dest = MI->getOperand(0).getReg();
1185 unsigned Ptr = MI->getOperand(1).getReg();
1186 unsigned OldVal = MI->getOperand(2).getReg();
1187 unsigned NewVal = MI->getOperand(3).getReg();
1189 unsigned Success = RegInfo.createVirtualRegister(RC);
1191 // insert new blocks after the current block
1192 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1193 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1194 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1195 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1196 MachineFunction::iterator It = BB;
1198 MF->insert(It, loop1MBB);
1199 MF->insert(It, loop2MBB);
1200 MF->insert(It, exitMBB);
1202 // Transfer the remainder of BB and its successor edges to exitMBB.
1203 exitMBB->splice(exitMBB->begin(), BB,
1204 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1205 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1209 // fallthrough --> loop1MBB
1210 BB->addSuccessor(loop1MBB);
1211 loop1MBB->addSuccessor(exitMBB);
1212 loop1MBB->addSuccessor(loop2MBB);
1213 loop2MBB->addSuccessor(loop1MBB);
1214 loop2MBB->addSuccessor(exitMBB);
1218 // bne dest, oldval, exitMBB
1220 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1221 BuildMI(BB, DL, TII->get(BNE))
1222 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1225 // sc success, newval, 0(ptr)
1226 // beq success, $0, loop1MBB
1228 BuildMI(BB, DL, TII->get(SC), Success)
1229 .addReg(NewVal).addReg(Ptr).addImm(0);
1230 BuildMI(BB, DL, TII->get(BEQ))
1231 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1233 MI->eraseFromParent(); // The instruction is gone now.
1239 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1240 MachineBasicBlock *BB,
1241 unsigned Size) const {
1242 assert((Size == 1 || Size == 2) &&
1243 "Unsupported size for EmitAtomicCmpSwapPartial.");
1245 MachineFunction *MF = BB->getParent();
1246 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1247 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1248 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1249 DebugLoc DL = MI->getDebugLoc();
1251 unsigned Dest = MI->getOperand(0).getReg();
1252 unsigned Ptr = MI->getOperand(1).getReg();
1253 unsigned CmpVal = MI->getOperand(2).getReg();
1254 unsigned NewVal = MI->getOperand(3).getReg();
1256 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1257 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1258 unsigned Mask = RegInfo.createVirtualRegister(RC);
1259 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1260 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1261 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1262 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1263 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1264 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1265 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1266 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1267 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1268 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1269 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1270 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1271 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1272 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1273 unsigned Success = RegInfo.createVirtualRegister(RC);
1275 // insert new blocks after the current block
1276 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1277 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1278 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1279 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1280 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1281 MachineFunction::iterator It = BB;
1283 MF->insert(It, loop1MBB);
1284 MF->insert(It, loop2MBB);
1285 MF->insert(It, sinkMBB);
1286 MF->insert(It, exitMBB);
1288 // Transfer the remainder of BB and its successor edges to exitMBB.
1289 exitMBB->splice(exitMBB->begin(), BB,
1290 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1291 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1293 BB->addSuccessor(loop1MBB);
1294 loop1MBB->addSuccessor(sinkMBB);
1295 loop1MBB->addSuccessor(loop2MBB);
1296 loop2MBB->addSuccessor(loop1MBB);
1297 loop2MBB->addSuccessor(sinkMBB);
1298 sinkMBB->addSuccessor(exitMBB);
1300 // FIXME: computation of newval2 can be moved to loop2MBB.
1302 // addiu masklsb2,$0,-4 # 0xfffffffc
1303 // and alignedaddr,ptr,masklsb2
1304 // andi ptrlsb2,ptr,3
1305 // sll shiftamt,ptrlsb2,3
1306 // ori maskupper,$0,255 # 0xff
1307 // sll mask,maskupper,shiftamt
1308 // nor mask2,$0,mask
1309 // andi maskedcmpval,cmpval,255
1310 // sll shiftedcmpval,maskedcmpval,shiftamt
1311 // andi maskednewval,newval,255
1312 // sll shiftednewval,maskednewval,shiftamt
1313 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1314 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1315 .addReg(Mips::ZERO).addImm(-4);
1316 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1317 .addReg(Ptr).addReg(MaskLSB2);
1318 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1319 if (Subtarget->isLittle()) {
1320 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1322 unsigned Off = RegInfo.createVirtualRegister(RC);
1323 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1324 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1325 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1327 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1328 .addReg(Mips::ZERO).addImm(MaskImm);
1329 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1330 .addReg(MaskUpper).addReg(ShiftAmt);
1331 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1332 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1333 .addReg(CmpVal).addImm(MaskImm);
1334 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1335 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1336 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1337 .addReg(NewVal).addImm(MaskImm);
1338 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1339 .addReg(MaskedNewVal).addReg(ShiftAmt);
1342 // ll oldval,0(alginedaddr)
1343 // and maskedoldval0,oldval,mask
1344 // bne maskedoldval0,shiftedcmpval,sinkMBB
1346 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1347 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1348 .addReg(OldVal).addReg(Mask);
1349 BuildMI(BB, DL, TII->get(Mips::BNE))
1350 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1353 // and maskedoldval1,oldval,mask2
1354 // or storeval,maskedoldval1,shiftednewval
1355 // sc success,storeval,0(alignedaddr)
1356 // beq success,$0,loop1MBB
1358 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1359 .addReg(OldVal).addReg(Mask2);
1360 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1361 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1362 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1363 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1364 BuildMI(BB, DL, TII->get(Mips::BEQ))
1365 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1368 // srl srlres,maskedoldval0,shiftamt
1369 // sll sllres,srlres,24
1370 // sra dest,sllres,24
1372 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1374 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1375 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1376 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1377 .addReg(SrlRes).addImm(ShiftImm);
1378 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1379 .addReg(SllRes).addImm(ShiftImm);
1381 MI->eraseFromParent(); // The instruction is gone now.
1386 //===----------------------------------------------------------------------===//
1387 // Misc Lower Operation implementation
1388 //===----------------------------------------------------------------------===//
1389 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1390 SDValue Chain = Op.getOperand(0);
1391 SDValue Table = Op.getOperand(1);
1392 SDValue Index = Op.getOperand(2);
1394 EVT PTy = getPointerTy();
1395 unsigned EntrySize =
1396 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1398 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1399 DAG.getConstant(EntrySize, PTy));
1400 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1402 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1403 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1404 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1406 Chain = Addr.getValue(1);
1408 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || isN64()) {
1409 // For PIC, the sequence is:
1410 // BRIND(load(Jumptable + index) + RelocBase)
1411 // RelocBase can be JumpTable, GOT or some sort of global base.
1412 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1413 getPICJumpTableRelocBase(Table, DAG));
1416 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1419 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1420 // The first operand is the chain, the second is the condition, the third is
1421 // the block to branch to if the condition is true.
1422 SDValue Chain = Op.getOperand(0);
1423 SDValue Dest = Op.getOperand(2);
1426 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1428 // Return if flag is not set by a floating point comparison.
1429 if (CondRes.getOpcode() != MipsISD::FPCmp)
1432 SDValue CCNode = CondRes.getOperand(2);
1434 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1435 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1436 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1437 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1438 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1439 FCC0, Dest, CondRes);
1442 SDValue MipsTargetLowering::
1443 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1445 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1447 // Return if flag is not set by a floating point comparison.
1448 if (Cond.getOpcode() != MipsISD::FPCmp)
1451 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1455 SDValue MipsTargetLowering::
1456 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1459 EVT Ty = Op.getOperand(0).getValueType();
1460 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1461 getSetCCResultType(*DAG.getContext(), Ty),
1462 Op.getOperand(0), Op.getOperand(1),
1465 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1469 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1470 SDValue Cond = createFPCmp(DAG, Op);
1472 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1473 "Floating point operand expected.");
1475 SDValue True = DAG.getConstant(1, MVT::i32);
1476 SDValue False = DAG.getConstant(0, MVT::i32);
1478 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1481 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1482 SelectionDAG &DAG) const {
1483 // FIXME there isn't actually debug info here
1485 EVT Ty = Op.getValueType();
1486 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1487 const GlobalValue *GV = N->getGlobal();
1489 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64()) {
1490 const MipsTargetObjectFile &TLOF =
1491 (const MipsTargetObjectFile&)getObjFileLowering();
1493 // %gp_rel relocation
1494 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1495 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1497 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1498 DAG.getVTList(MVT::i32), &GA, 1);
1499 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1500 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1503 // %hi/%lo relocation
1504 return getAddrNonPIC(N, Ty, DAG);
1507 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1508 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1511 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1512 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1513 MachinePointerInfo::getGOT());
1515 return getAddrGlobal(N, Ty, DAG, (isN32() || isN64()) ? MipsII::MO_GOT_DISP
1517 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1520 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1521 SelectionDAG &DAG) const {
1522 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1523 EVT Ty = Op.getValueType();
1525 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1526 return getAddrNonPIC(N, Ty, DAG);
1528 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1531 SDValue MipsTargetLowering::
1532 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1534 // If the relocation model is PIC, use the General Dynamic TLS Model or
1535 // Local Dynamic TLS model, otherwise use the Initial Exec or
1536 // Local Exec TLS Model.
1538 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1540 const GlobalValue *GV = GA->getGlobal();
1541 EVT PtrVT = getPointerTy();
1543 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1545 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1546 // General Dynamic and Local Dynamic TLS Model.
1547 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1550 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1551 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1552 getGlobalReg(DAG, PtrVT), TGA);
1553 unsigned PtrSize = PtrVT.getSizeInBits();
1554 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1556 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1560 Entry.Node = Argument;
1562 Args.push_back(Entry);
1564 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1565 false, false, false, false, 0, CallingConv::C,
1566 /*IsTailCall=*/false, /*doesNotRet=*/false,
1567 /*isReturnValueUsed=*/true,
1568 TlsGetAddr, Args, DAG, DL);
1569 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1571 SDValue Ret = CallResult.first;
1573 if (model != TLSModel::LocalDynamic)
1576 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1577 MipsII::MO_DTPREL_HI);
1578 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1579 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1580 MipsII::MO_DTPREL_LO);
1581 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1582 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1583 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1587 if (model == TLSModel::InitialExec) {
1588 // Initial Exec TLS Model
1589 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1590 MipsII::MO_GOTTPREL);
1591 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1593 Offset = DAG.getLoad(PtrVT, DL,
1594 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1595 false, false, false, 0);
1597 // Local Exec TLS Model
1598 assert(model == TLSModel::LocalExec);
1599 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1600 MipsII::MO_TPREL_HI);
1601 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1602 MipsII::MO_TPREL_LO);
1603 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1604 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1605 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1608 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1609 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1612 SDValue MipsTargetLowering::
1613 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1615 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1616 EVT Ty = Op.getValueType();
1618 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1619 return getAddrNonPIC(N, Ty, DAG);
1621 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1624 SDValue MipsTargetLowering::
1625 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1627 // gp_rel relocation
1628 // FIXME: we should reference the constant pool using small data sections,
1629 // but the asm printer currently doesn't support this feature without
1630 // hacking it. This feature should come soon so we can uncomment the
1632 //if (IsInSmallSection(C->getType())) {
1633 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1634 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1635 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1636 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1637 EVT Ty = Op.getValueType();
1639 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1640 return getAddrNonPIC(N, Ty, DAG);
1642 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1645 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1646 MachineFunction &MF = DAG.getMachineFunction();
1647 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1650 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1653 // vastart just stores the address of the VarArgsFrameIndex slot into the
1654 // memory location argument.
1655 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1656 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1657 MachinePointerInfo(SV), false, false, 0);
1660 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1661 bool HasExtractInsert) {
1662 EVT TyX = Op.getOperand(0).getValueType();
1663 EVT TyY = Op.getOperand(1).getValueType();
1664 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1665 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1669 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1671 SDValue X = (TyX == MVT::f32) ?
1672 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1673 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1675 SDValue Y = (TyY == MVT::f32) ?
1676 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1677 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1680 if (HasExtractInsert) {
1681 // ext E, Y, 31, 1 ; extract bit31 of Y
1682 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1683 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1684 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1687 // srl SrlX, SllX, 1
1689 // sll SllY, SrlX, 31
1690 // or Or, SrlX, SllY
1691 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1692 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1693 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1694 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1695 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1698 if (TyX == MVT::f32)
1699 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1701 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1702 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1703 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1706 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1707 bool HasExtractInsert) {
1708 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1709 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1710 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1711 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1714 // Bitcast to integer nodes.
1715 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1716 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1718 if (HasExtractInsert) {
1719 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1720 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1721 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1722 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1724 if (WidthX > WidthY)
1725 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1726 else if (WidthY > WidthX)
1727 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1729 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1730 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1731 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1734 // (d)sll SllX, X, 1
1735 // (d)srl SrlX, SllX, 1
1736 // (d)srl SrlY, Y, width(Y)-1
1737 // (d)sll SllY, SrlX, width(Y)-1
1738 // or Or, SrlX, SllY
1739 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1740 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1741 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1742 DAG.getConstant(WidthY - 1, MVT::i32));
1744 if (WidthX > WidthY)
1745 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1746 else if (WidthY > WidthX)
1747 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1749 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1750 DAG.getConstant(WidthX - 1, MVT::i32));
1751 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1752 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1756 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1757 if (Subtarget->isGP64bit())
1758 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1760 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1763 SDValue MipsTargetLowering::
1764 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1766 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1767 "Frame address can only be determined for current frame.");
1769 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1770 MFI->setFrameAddressIsTaken(true);
1771 EVT VT = Op.getValueType();
1773 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1774 isN64() ? Mips::FP_64 : Mips::FP, VT);
1778 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1779 SelectionDAG &DAG) const {
1780 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1784 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1785 "Return address can be determined only for current frame.");
1787 MachineFunction &MF = DAG.getMachineFunction();
1788 MachineFrameInfo *MFI = MF.getFrameInfo();
1789 MVT VT = Op.getSimpleValueType();
1790 unsigned RA = isN64() ? Mips::RA_64 : Mips::RA;
1791 MFI->setReturnAddressIsTaken(true);
1793 // Return RA, which contains the return address. Mark it an implicit live-in.
1794 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1795 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1798 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1799 // generated from __builtin_eh_return (offset, handler)
1800 // The effect of this is to adjust the stack pointer by "offset"
1801 // and then branch to "handler".
1802 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1804 MachineFunction &MF = DAG.getMachineFunction();
1805 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1807 MipsFI->setCallsEhReturn();
1808 SDValue Chain = Op.getOperand(0);
1809 SDValue Offset = Op.getOperand(1);
1810 SDValue Handler = Op.getOperand(2);
1812 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
1814 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1815 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1816 unsigned OffsetReg = isN64() ? Mips::V1_64 : Mips::V1;
1817 unsigned AddrReg = isN64() ? Mips::V0_64 : Mips::V0;
1818 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1819 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1820 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1821 DAG.getRegister(OffsetReg, Ty),
1822 DAG.getRegister(AddrReg, getPointerTy()),
1826 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1827 SelectionDAG &DAG) const {
1828 // FIXME: Need pseudo-fence for 'singlethread' fences
1829 // FIXME: Set SType for weaker fences where supported/appropriate.
1832 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1833 DAG.getConstant(SType, MVT::i32));
1836 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1837 SelectionDAG &DAG) const {
1839 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1840 SDValue Shamt = Op.getOperand(2);
1843 // lo = (shl lo, shamt)
1844 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1847 // hi = (shl lo, shamt[4:0])
1848 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1849 DAG.getConstant(-1, MVT::i32));
1850 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1851 DAG.getConstant(1, MVT::i32));
1852 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1854 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1855 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1856 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1857 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1858 DAG.getConstant(0x20, MVT::i32));
1859 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1860 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1861 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1863 SDValue Ops[2] = {Lo, Hi};
1864 return DAG.getMergeValues(Ops, 2, DL);
1867 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1870 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1871 SDValue Shamt = Op.getOperand(2);
1874 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1876 // hi = (sra hi, shamt)
1878 // hi = (srl hi, shamt)
1881 // lo = (sra hi, shamt[4:0])
1882 // hi = (sra hi, 31)
1884 // lo = (srl hi, shamt[4:0])
1886 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1887 DAG.getConstant(-1, MVT::i32));
1888 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1889 DAG.getConstant(1, MVT::i32));
1890 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1891 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1892 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1893 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1895 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1896 DAG.getConstant(0x20, MVT::i32));
1897 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1898 DAG.getConstant(31, MVT::i32));
1899 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1900 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1901 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1904 SDValue Ops[2] = {Lo, Hi};
1905 return DAG.getMergeValues(Ops, 2, DL);
1908 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1909 SDValue Chain, SDValue Src, unsigned Offset) {
1910 SDValue Ptr = LD->getBasePtr();
1911 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1912 EVT BasePtrVT = Ptr.getValueType();
1914 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1917 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1918 DAG.getConstant(Offset, BasePtrVT));
1920 SDValue Ops[] = { Chain, Ptr, Src };
1921 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1922 LD->getMemOperand());
1925 // Expand an unaligned 32 or 64-bit integer load node.
1926 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1927 LoadSDNode *LD = cast<LoadSDNode>(Op);
1928 EVT MemVT = LD->getMemoryVT();
1930 // Return if load is aligned or if MemVT is neither i32 nor i64.
1931 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1932 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1935 bool IsLittle = Subtarget->isLittle();
1936 EVT VT = Op.getValueType();
1937 ISD::LoadExtType ExtType = LD->getExtensionType();
1938 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1940 assert((VT == MVT::i32) || (VT == MVT::i64));
1943 // (set dst, (i64 (load baseptr)))
1945 // (set tmp, (ldl (add baseptr, 7), undef))
1946 // (set dst, (ldr baseptr, tmp))
1947 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1948 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1950 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1954 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1956 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1960 // (set dst, (i32 (load baseptr))) or
1961 // (set dst, (i64 (sextload baseptr))) or
1962 // (set dst, (i64 (extload baseptr)))
1964 // (set tmp, (lwl (add baseptr, 3), undef))
1965 // (set dst, (lwr baseptr, tmp))
1966 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1967 (ExtType == ISD::EXTLOAD))
1970 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1973 // (set dst, (i64 (zextload baseptr)))
1975 // (set tmp0, (lwl (add baseptr, 3), undef))
1976 // (set tmp1, (lwr baseptr, tmp0))
1977 // (set tmp2, (shl tmp1, 32))
1978 // (set dst, (srl tmp2, 32))
1980 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1981 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1982 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1983 SDValue Ops[] = { SRL, LWR.getValue(1) };
1984 return DAG.getMergeValues(Ops, 2, DL);
1987 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
1988 SDValue Chain, unsigned Offset) {
1989 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
1990 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
1992 SDVTList VTList = DAG.getVTList(MVT::Other);
1995 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1996 DAG.getConstant(Offset, BasePtrVT));
1998 SDValue Ops[] = { Chain, Value, Ptr };
1999 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2000 SD->getMemOperand());
2003 // Expand an unaligned 32 or 64-bit integer store node.
2004 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2006 SDValue Value = SD->getValue(), Chain = SD->getChain();
2007 EVT VT = Value.getValueType();
2010 // (store val, baseptr) or
2011 // (truncstore val, baseptr)
2013 // (swl val, (add baseptr, 3))
2014 // (swr val, baseptr)
2015 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2016 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2018 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2021 assert(VT == MVT::i64);
2024 // (store val, baseptr)
2026 // (sdl val, (add baseptr, 7))
2027 // (sdr val, baseptr)
2028 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2029 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2032 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2033 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2034 SDValue Val = SD->getValue();
2036 if (Val.getOpcode() != ISD::FP_TO_SINT)
2039 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2040 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2043 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2044 SD->getPointerInfo(), SD->isVolatile(),
2045 SD->isNonTemporal(), SD->getAlignment());
2048 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2049 StoreSDNode *SD = cast<StoreSDNode>(Op);
2050 EVT MemVT = SD->getMemoryVT();
2052 // Lower unaligned integer stores.
2053 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2054 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2055 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2057 return lowerFP_TO_SINT_STORE(SD, DAG);
2060 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2061 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2062 || cast<ConstantSDNode>
2063 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2064 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2068 // (add (frameaddr 0), (frame_to_args_offset))
2069 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2070 // (add FrameObject, 0)
2071 // where FrameObject is a fixed StackObject with offset 0 which points to
2072 // the old stack pointer.
2073 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2074 EVT ValTy = Op->getValueType(0);
2075 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2076 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2077 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2078 DAG.getConstant(0, ValTy));
2081 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2082 SelectionDAG &DAG) const {
2083 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2084 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2086 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2089 //===----------------------------------------------------------------------===//
2090 // Calling Convention Implementation
2091 //===----------------------------------------------------------------------===//
2093 //===----------------------------------------------------------------------===//
2094 // TODO: Implement a generic logic using tblgen that can support this.
2095 // Mips O32 ABI rules:
2097 // i32 - Passed in A0, A1, A2, A3 and stack
2098 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2099 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2100 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2101 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2102 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2105 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2106 //===----------------------------------------------------------------------===//
2108 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2109 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2110 CCState &State, const MCPhysReg *F64Regs) {
2112 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2114 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2115 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2117 // Do not process byval args here.
2118 if (ArgFlags.isByVal())
2121 // Promote i8 and i16
2122 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2124 if (ArgFlags.isSExt())
2125 LocInfo = CCValAssign::SExt;
2126 else if (ArgFlags.isZExt())
2127 LocInfo = CCValAssign::ZExt;
2129 LocInfo = CCValAssign::AExt;
2134 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2135 // is true: function is vararg, argument is 3rd or higher, there is previous
2136 // argument which is not f32 or f64.
2137 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2138 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2139 unsigned OrigAlign = ArgFlags.getOrigAlign();
2140 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2142 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2143 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2144 // If this is the first part of an i64 arg,
2145 // the allocated register must be either A0 or A2.
2146 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2147 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2149 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2150 // Allocate int register and shadow next int register. If first
2151 // available register is Mips::A1 or Mips::A3, shadow it too.
2152 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2153 if (Reg == Mips::A1 || Reg == Mips::A3)
2154 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2155 State.AllocateReg(IntRegs, IntRegsSize);
2157 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2158 // we are guaranteed to find an available float register
2159 if (ValVT == MVT::f32) {
2160 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2161 // Shadow int register
2162 State.AllocateReg(IntRegs, IntRegsSize);
2164 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2165 // Shadow int registers
2166 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2167 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2168 State.AllocateReg(IntRegs, IntRegsSize);
2169 State.AllocateReg(IntRegs, IntRegsSize);
2172 llvm_unreachable("Cannot handle this ValVT.");
2175 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2177 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2179 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2184 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2185 MVT LocVT, CCValAssign::LocInfo LocInfo,
2186 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2187 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2189 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2192 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2193 MVT LocVT, CCValAssign::LocInfo LocInfo,
2194 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2195 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2197 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2200 #include "MipsGenCallingConv.inc"
2202 //===----------------------------------------------------------------------===//
2203 // Call Calling Convention Implementation
2204 //===----------------------------------------------------------------------===//
2206 // Return next O32 integer argument register.
2207 static unsigned getNextIntArgReg(unsigned Reg) {
2208 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2209 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2213 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2214 SDValue Chain, SDValue Arg, SDLoc DL,
2215 bool IsTailCall, SelectionDAG &DAG) const {
2217 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2218 DAG.getIntPtrConstant(Offset));
2219 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2223 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2224 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2225 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2226 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2227 /*isVolatile=*/ true, false, 0);
2230 void MipsTargetLowering::
2231 getOpndList(SmallVectorImpl<SDValue> &Ops,
2232 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2233 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2234 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2235 // Insert node "GP copy globalreg" before call to function.
2237 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2238 // in PIC mode) allow symbols to be resolved via lazy binding.
2239 // The lazy binding stub requires GP to point to the GOT.
2240 if (IsPICCall && !InternalLinkage) {
2241 unsigned GPReg = isN64() ? Mips::GP_64 : Mips::GP;
2242 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
2243 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2246 // Build a sequence of copy-to-reg nodes chained together with token
2247 // chain and flag operands which copy the outgoing args into registers.
2248 // The InFlag in necessary since all emitted instructions must be
2252 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2253 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2254 RegsToPass[i].second, InFlag);
2255 InFlag = Chain.getValue(1);
2258 // Add argument registers to the end of the list so that they are
2259 // known live into the call.
2260 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2261 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2262 RegsToPass[i].second.getValueType()));
2264 // Add a register mask operand representing the call-preserved registers.
2265 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2266 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2267 assert(Mask && "Missing call preserved mask for calling convention");
2268 if (Subtarget->inMips16HardFloat()) {
2269 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2270 llvm::StringRef Sym = G->getGlobal()->getName();
2271 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2272 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2273 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2277 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2279 if (InFlag.getNode())
2280 Ops.push_back(InFlag);
2283 /// LowerCall - functions arguments are copied from virtual regs to
2284 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2286 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2287 SmallVectorImpl<SDValue> &InVals) const {
2288 SelectionDAG &DAG = CLI.DAG;
2290 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2291 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2292 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2293 SDValue Chain = CLI.Chain;
2294 SDValue Callee = CLI.Callee;
2295 bool &IsTailCall = CLI.IsTailCall;
2296 CallingConv::ID CallConv = CLI.CallConv;
2297 bool IsVarArg = CLI.IsVarArg;
2299 MachineFunction &MF = DAG.getMachineFunction();
2300 MachineFrameInfo *MFI = MF.getFrameInfo();
2301 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2302 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2303 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2305 // Analyze operands of the call, assigning locations to each operand.
2306 SmallVector<CCValAssign, 16> ArgLocs;
2307 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2308 getTargetMachine(), ArgLocs, *DAG.getContext());
2309 MipsCC::SpecialCallingConvType SpecialCallingConv =
2310 getSpecialCallingConv(Callee);
2311 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo,
2312 SpecialCallingConv);
2314 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2315 Subtarget->mipsSEUsesSoftFloat(),
2316 Callee.getNode(), CLI.Args);
2318 // Get a count of how many bytes are to be pushed on the stack.
2319 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2321 // Check if it's really possible to do a tail call.
2324 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2325 *MF.getInfo<MipsFunctionInfo>());
2330 // Chain is the output chain of the last Load/Store or CopyToReg node.
2331 // ByValChain is the output chain of the last Memcpy node created for copying
2332 // byval arguments to the stack.
2333 unsigned StackAlignment = TFL->getStackAlignment();
2334 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2335 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2338 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2340 SDValue StackPtr = DAG.getCopyFromReg(
2341 Chain, DL, isN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2343 // With EABI is it possible to have 16 args on registers.
2344 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2345 SmallVector<SDValue, 8> MemOpChains;
2346 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2348 // Walk the register/memloc assignments, inserting copies/loads.
2349 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2350 SDValue Arg = OutVals[i];
2351 CCValAssign &VA = ArgLocs[i];
2352 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2353 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2356 if (Flags.isByVal()) {
2357 assert(Flags.getByValSize() &&
2358 "ByVal args of size 0 should have been ignored by front-end.");
2359 assert(ByValArg != MipsCCInfo.byval_end());
2360 assert(!IsTailCall &&
2361 "Do not tail-call optimize if there is a byval argument.");
2362 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2363 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2368 // Promote the value if needed.
2369 switch (VA.getLocInfo()) {
2370 default: llvm_unreachable("Unknown loc info!");
2371 case CCValAssign::Full:
2372 if (VA.isRegLoc()) {
2373 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2374 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2375 (ValVT == MVT::i64 && LocVT == MVT::f64))
2376 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2377 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2378 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2379 Arg, DAG.getConstant(0, MVT::i32));
2380 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2381 Arg, DAG.getConstant(1, MVT::i32));
2382 if (!Subtarget->isLittle())
2384 unsigned LocRegLo = VA.getLocReg();
2385 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2386 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2387 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2392 case CCValAssign::SExt:
2393 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2395 case CCValAssign::ZExt:
2396 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2398 case CCValAssign::AExt:
2399 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2403 // Arguments that can be passed on register must be kept at
2404 // RegsToPass vector
2405 if (VA.isRegLoc()) {
2406 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2410 // Register can't get to this point...
2411 assert(VA.isMemLoc());
2413 // emit ISD::STORE whichs stores the
2414 // parameter value to a stack Location
2415 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2416 Chain, Arg, DL, IsTailCall, DAG));
2419 // Transform all store nodes into one single node because all store
2420 // nodes are independent of each other.
2421 if (!MemOpChains.empty())
2422 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2423 &MemOpChains[0], MemOpChains.size());
2425 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2426 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2427 // node so that legalize doesn't hack it.
2428 bool IsPICCall = (isN64() || IsPIC); // true if calls are translated to
2430 bool GlobalOrExternal = false, InternalLinkage = false;
2432 EVT Ty = Callee.getValueType();
2434 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2436 const GlobalValue *Val = G->getGlobal();
2437 InternalLinkage = Val->hasInternalLinkage();
2439 if (InternalLinkage)
2440 Callee = getAddrLocal(G, Ty, DAG, isN32() || isN64());
2442 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2443 MipsII::MO_CALL_LO16, Chain,
2444 FuncInfo->callPtrInfo(Val));
2446 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2447 FuncInfo->callPtrInfo(Val));
2449 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2450 MipsII::MO_NO_FLAG);
2451 GlobalOrExternal = true;
2453 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2454 const char *Sym = S->getSymbol();
2456 if (!isN64() && !IsPIC) // !N64 && static
2457 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2458 MipsII::MO_NO_FLAG);
2460 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2461 MipsII::MO_CALL_LO16, Chain,
2462 FuncInfo->callPtrInfo(Sym));
2464 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2465 FuncInfo->callPtrInfo(Sym));
2467 GlobalOrExternal = true;
2470 SmallVector<SDValue, 8> Ops(1, Chain);
2471 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2473 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2474 CLI, Callee, Chain);
2477 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2479 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2480 SDValue InFlag = Chain.getValue(1);
2482 // Create the CALLSEQ_END node.
2483 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2484 DAG.getIntPtrConstant(0, true), InFlag, DL);
2485 InFlag = Chain.getValue(1);
2487 // Handle result values, copying them out of physregs into vregs that we
2489 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2490 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2493 /// LowerCallResult - Lower the result values of a call into the
2494 /// appropriate copies out of appropriate physical registers.
2496 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2497 CallingConv::ID CallConv, bool IsVarArg,
2498 const SmallVectorImpl<ISD::InputArg> &Ins,
2499 SDLoc DL, SelectionDAG &DAG,
2500 SmallVectorImpl<SDValue> &InVals,
2501 const SDNode *CallNode,
2502 const Type *RetTy) const {
2503 // Assign locations to each value returned by this call.
2504 SmallVector<CCValAssign, 16> RVLocs;
2505 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2506 getTargetMachine(), RVLocs, *DAG.getContext());
2507 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2509 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2512 // Copy all of the result registers out of their specified physreg.
2513 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2514 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2515 RVLocs[i].getLocVT(), InFlag);
2516 Chain = Val.getValue(1);
2517 InFlag = Val.getValue(2);
2519 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2520 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2522 InVals.push_back(Val);
2528 //===----------------------------------------------------------------------===//
2529 // Formal Arguments Calling Convention Implementation
2530 //===----------------------------------------------------------------------===//
2531 /// LowerFormalArguments - transform physical registers into virtual registers
2532 /// and generate load operations for arguments places on the stack.
2534 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2535 CallingConv::ID CallConv,
2537 const SmallVectorImpl<ISD::InputArg> &Ins,
2538 SDLoc DL, SelectionDAG &DAG,
2539 SmallVectorImpl<SDValue> &InVals)
2541 MachineFunction &MF = DAG.getMachineFunction();
2542 MachineFrameInfo *MFI = MF.getFrameInfo();
2543 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2545 MipsFI->setVarArgsFrameIndex(0);
2547 // Used with vargs to acumulate store chains.
2548 std::vector<SDValue> OutChains;
2550 // Assign locations to all of the incoming arguments.
2551 SmallVector<CCValAssign, 16> ArgLocs;
2552 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2553 getTargetMachine(), ArgLocs, *DAG.getContext());
2554 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2555 Function::const_arg_iterator FuncArg =
2556 DAG.getMachineFunction().getFunction()->arg_begin();
2557 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2559 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2560 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2561 MipsCCInfo.hasByValArg());
2563 unsigned CurArgIdx = 0;
2564 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2566 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2567 CCValAssign &VA = ArgLocs[i];
2568 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2569 CurArgIdx = Ins[i].OrigArgIndex;
2570 EVT ValVT = VA.getValVT();
2571 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2572 bool IsRegLoc = VA.isRegLoc();
2574 if (Flags.isByVal()) {
2575 assert(Flags.getByValSize() &&
2576 "ByVal args of size 0 should have been ignored by front-end.");
2577 assert(ByValArg != MipsCCInfo.byval_end());
2578 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2579 MipsCCInfo, *ByValArg);
2584 // Arguments stored on registers
2586 MVT RegVT = VA.getLocVT();
2587 unsigned ArgReg = VA.getLocReg();
2588 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2590 // Transform the arguments stored on
2591 // physical registers into virtual ones
2592 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2593 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2595 // If this is an 8 or 16-bit value, it has been passed promoted
2596 // to 32 bits. Insert an assert[sz]ext to capture this, then
2597 // truncate to the right size.
2598 if (VA.getLocInfo() != CCValAssign::Full) {
2599 unsigned Opcode = 0;
2600 if (VA.getLocInfo() == CCValAssign::SExt)
2601 Opcode = ISD::AssertSext;
2602 else if (VA.getLocInfo() == CCValAssign::ZExt)
2603 Opcode = ISD::AssertZext;
2605 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2606 DAG.getValueType(ValVT));
2607 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2610 // Handle floating point arguments passed in integer registers and
2611 // long double arguments passed in floating point registers.
2612 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2613 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2614 (RegVT == MVT::f64 && ValVT == MVT::i64))
2615 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2616 else if (isO32() && RegVT == MVT::i32 && ValVT == MVT::f64) {
2617 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2618 getNextIntArgReg(ArgReg), RC);
2619 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2620 if (!Subtarget->isLittle())
2621 std::swap(ArgValue, ArgValue2);
2622 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2623 ArgValue, ArgValue2);
2626 InVals.push_back(ArgValue);
2627 } else { // VA.isRegLoc()
2630 assert(VA.isMemLoc());
2632 // The stack pointer offset is relative to the caller stack frame.
2633 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2634 VA.getLocMemOffset(), true);
2636 // Create load nodes to retrieve arguments from the stack
2637 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2638 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2639 MachinePointerInfo::getFixedStack(FI),
2640 false, false, false, 0);
2641 InVals.push_back(Load);
2642 OutChains.push_back(Load.getValue(1));
2646 // The mips ABIs for returning structs by value requires that we copy
2647 // the sret argument into $v0 for the return. Save the argument into
2648 // a virtual register so that we can access it from the return points.
2649 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2650 unsigned Reg = MipsFI->getSRetReturnReg();
2652 Reg = MF.getRegInfo().createVirtualRegister(
2653 getRegClassFor(isN64() ? MVT::i64 : MVT::i32));
2654 MipsFI->setSRetReturnReg(Reg);
2656 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2657 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2661 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2663 // All stores are grouped in one node to allow the matching between
2664 // the size of Ins and InVals. This only happens when on varg functions
2665 if (!OutChains.empty()) {
2666 OutChains.push_back(Chain);
2667 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2668 &OutChains[0], OutChains.size());
2674 //===----------------------------------------------------------------------===//
2675 // Return Value Calling Convention Implementation
2676 //===----------------------------------------------------------------------===//
2679 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2680 MachineFunction &MF, bool IsVarArg,
2681 const SmallVectorImpl<ISD::OutputArg> &Outs,
2682 LLVMContext &Context) const {
2683 SmallVector<CCValAssign, 16> RVLocs;
2684 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2686 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2690 MipsTargetLowering::LowerReturn(SDValue Chain,
2691 CallingConv::ID CallConv, bool IsVarArg,
2692 const SmallVectorImpl<ISD::OutputArg> &Outs,
2693 const SmallVectorImpl<SDValue> &OutVals,
2694 SDLoc DL, SelectionDAG &DAG) const {
2695 // CCValAssign - represent the assignment of
2696 // the return value to a location
2697 SmallVector<CCValAssign, 16> RVLocs;
2698 MachineFunction &MF = DAG.getMachineFunction();
2700 // CCState - Info about the registers and stack slot.
2701 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2703 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2705 // Analyze return values.
2706 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2707 MF.getFunction()->getReturnType());
2710 SmallVector<SDValue, 4> RetOps(1, Chain);
2712 // Copy the result values into the output registers.
2713 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2714 SDValue Val = OutVals[i];
2715 CCValAssign &VA = RVLocs[i];
2716 assert(VA.isRegLoc() && "Can only return in registers!");
2718 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2719 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2721 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2723 // Guarantee that all emitted copies are stuck together with flags.
2724 Flag = Chain.getValue(1);
2725 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2728 // The mips ABIs for returning structs by value requires that we copy
2729 // the sret argument into $v0 for the return. We saved the argument into
2730 // a virtual register in the entry block, so now we copy the value out
2732 if (MF.getFunction()->hasStructRetAttr()) {
2733 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2734 unsigned Reg = MipsFI->getSRetReturnReg();
2737 llvm_unreachable("sret virtual register not created in the entry block");
2738 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2739 unsigned V0 = isN64() ? Mips::V0_64 : Mips::V0;
2741 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2742 Flag = Chain.getValue(1);
2743 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2746 RetOps[0] = Chain; // Update chain.
2748 // Add the flag if we have it.
2750 RetOps.push_back(Flag);
2752 // Return on Mips is always a "jr $ra"
2753 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2756 //===----------------------------------------------------------------------===//
2757 // Mips Inline Assembly Support
2758 //===----------------------------------------------------------------------===//
2760 /// getConstraintType - Given a constraint letter, return the type of
2761 /// constraint it is for this target.
2762 MipsTargetLowering::ConstraintType MipsTargetLowering::
2763 getConstraintType(const std::string &Constraint) const
2765 // Mips specific constraints
2766 // GCC config/mips/constraints.md
2768 // 'd' : An address register. Equivalent to r
2769 // unless generating MIPS16 code.
2770 // 'y' : Equivalent to r; retained for
2771 // backwards compatibility.
2772 // 'c' : A register suitable for use in an indirect
2773 // jump. This will always be $25 for -mabicalls.
2774 // 'l' : The lo register. 1 word storage.
2775 // 'x' : The hilo register pair. Double word storage.
2776 if (Constraint.size() == 1) {
2777 switch (Constraint[0]) {
2785 return C_RegisterClass;
2790 return TargetLowering::getConstraintType(Constraint);
2793 /// Examine constraint type and operand type and determine a weight value.
2794 /// This object must already have been set up with the operand type
2795 /// and the current alternative constraint selected.
2796 TargetLowering::ConstraintWeight
2797 MipsTargetLowering::getSingleConstraintMatchWeight(
2798 AsmOperandInfo &info, const char *constraint) const {
2799 ConstraintWeight weight = CW_Invalid;
2800 Value *CallOperandVal = info.CallOperandVal;
2801 // If we don't have a value, we can't do a match,
2802 // but allow it at the lowest weight.
2803 if (CallOperandVal == NULL)
2805 Type *type = CallOperandVal->getType();
2806 // Look at the constraint type.
2807 switch (*constraint) {
2809 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2813 if (type->isIntegerTy())
2814 weight = CW_Register;
2816 case 'f': // FPU or MSA register
2817 if (Subtarget->hasMSA() && type->isVectorTy() &&
2818 cast<VectorType>(type)->getBitWidth() == 128)
2819 weight = CW_Register;
2820 else if (type->isFloatTy())
2821 weight = CW_Register;
2823 case 'c': // $25 for indirect jumps
2824 case 'l': // lo register
2825 case 'x': // hilo register pair
2826 if (type->isIntegerTy())
2827 weight = CW_SpecificReg;
2829 case 'I': // signed 16 bit immediate
2830 case 'J': // integer zero
2831 case 'K': // unsigned 16 bit immediate
2832 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2833 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2834 case 'O': // signed 15 bit immediate (+- 16383)
2835 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2836 if (isa<ConstantInt>(CallOperandVal))
2837 weight = CW_Constant;
2846 /// This is a helper function to parse a physical register string and split it
2847 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2848 /// that is returned indicates whether parsing was successful. The second flag
2849 /// is true if the numeric part exists.
2850 static std::pair<bool, bool>
2851 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2852 unsigned long long &Reg) {
2853 if (C.front() != '{' || C.back() != '}')
2854 return std::make_pair(false, false);
2856 // Search for the first numeric character.
2857 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2858 I = std::find_if(B, E, std::ptr_fun(isdigit));
2860 Prefix.assign(B, I - B);
2862 // The second flag is set to false if no numeric characters were found.
2864 return std::make_pair(true, false);
2866 // Parse the numeric characters.
2867 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2871 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2872 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2873 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2874 const TargetRegisterClass *RC;
2876 unsigned long long Reg;
2878 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2881 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2883 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2884 // No numeric characters follow "hi" or "lo".
2886 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2888 RC = TRI->getRegClass(Prefix == "hi" ?
2889 Mips::HI32RegClassID : Mips::LO32RegClassID);
2890 return std::make_pair(*(RC->begin()), RC);
2891 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2892 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2894 // No numeric characters follow the name.
2896 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2898 Reg = StringSwitch<unsigned long long>(Prefix)
2899 .Case("$msair", Mips::MSAIR)
2900 .Case("$msacsr", Mips::MSACSR)
2901 .Case("$msaaccess", Mips::MSAAccess)
2902 .Case("$msasave", Mips::MSASave)
2903 .Case("$msamodify", Mips::MSAModify)
2904 .Case("$msarequest", Mips::MSARequest)
2905 .Case("$msamap", Mips::MSAMap)
2906 .Case("$msaunmap", Mips::MSAUnmap)
2910 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2912 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2913 return std::make_pair(Reg, RC);
2917 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2919 if (Prefix == "$f") { // Parse $f0-$f31.
2920 // If the size of FP registers is 64-bit or Reg is an even number, select
2921 // the 64-bit register class. Otherwise, select the 32-bit register class.
2922 if (VT == MVT::Other)
2923 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2925 RC = getRegClassFor(VT);
2927 if (RC == &Mips::AFGR64RegClass) {
2928 assert(Reg % 2 == 0);
2931 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2932 RC = TRI->getRegClass(Mips::FCCRegClassID);
2933 else if (Prefix == "$w") { // Parse $w0-$w31.
2934 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2935 } else { // Parse $0-$31.
2936 assert(Prefix == "$");
2937 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2940 assert(Reg < RC->getNumRegs());
2941 return std::make_pair(*(RC->begin() + Reg), RC);
2944 /// Given a register class constraint, like 'r', if this corresponds directly
2945 /// to an LLVM register class, return a register of 0 and the register class
2947 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2948 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2950 if (Constraint.size() == 1) {
2951 switch (Constraint[0]) {
2952 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2953 case 'y': // Same as 'r'. Exists for compatibility.
2955 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2956 if (Subtarget->inMips16Mode())
2957 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2958 return std::make_pair(0U, &Mips::GPR32RegClass);
2960 if (VT == MVT::i64 && !isGP64bit())
2961 return std::make_pair(0U, &Mips::GPR32RegClass);
2962 if (VT == MVT::i64 && isGP64bit())
2963 return std::make_pair(0U, &Mips::GPR64RegClass);
2964 // This will generate an error message
2965 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2966 case 'f': // FPU or MSA register
2967 if (VT == MVT::v16i8)
2968 return std::make_pair(0U, &Mips::MSA128BRegClass);
2969 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
2970 return std::make_pair(0U, &Mips::MSA128HRegClass);
2971 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2972 return std::make_pair(0U, &Mips::MSA128WRegClass);
2973 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2974 return std::make_pair(0U, &Mips::MSA128DRegClass);
2975 else if (VT == MVT::f32)
2976 return std::make_pair(0U, &Mips::FGR32RegClass);
2977 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2978 if (Subtarget->isFP64bit())
2979 return std::make_pair(0U, &Mips::FGR64RegClass);
2980 return std::make_pair(0U, &Mips::AFGR64RegClass);
2983 case 'c': // register suitable for indirect jump
2985 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2986 assert(VT == MVT::i64 && "Unexpected type.");
2987 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2988 case 'l': // register suitable for indirect jump
2990 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2991 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2992 case 'x': // register suitable for indirect jump
2993 // Fixme: Not triggering the use of both hi and low
2994 // This will generate an error message
2995 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2999 std::pair<unsigned, const TargetRegisterClass *> R;
3000 R = parseRegForInlineAsmConstraint(Constraint, VT);
3005 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3008 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3009 /// vector. If it is invalid, don't add anything to Ops.
3010 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3011 std::string &Constraint,
3012 std::vector<SDValue>&Ops,
3013 SelectionDAG &DAG) const {
3014 SDValue Result(0, 0);
3016 // Only support length 1 constraints for now.
3017 if (Constraint.length() > 1) return;
3019 char ConstraintLetter = Constraint[0];
3020 switch (ConstraintLetter) {
3021 default: break; // This will fall through to the generic implementation
3022 case 'I': // Signed 16 bit constant
3023 // If this fails, the parent routine will give an error
3024 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3025 EVT Type = Op.getValueType();
3026 int64_t Val = C->getSExtValue();
3027 if (isInt<16>(Val)) {
3028 Result = DAG.getTargetConstant(Val, Type);
3033 case 'J': // integer zero
3034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3035 EVT Type = Op.getValueType();
3036 int64_t Val = C->getZExtValue();
3038 Result = DAG.getTargetConstant(0, Type);
3043 case 'K': // unsigned 16 bit immediate
3044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3045 EVT Type = Op.getValueType();
3046 uint64_t Val = (uint64_t)C->getZExtValue();
3047 if (isUInt<16>(Val)) {
3048 Result = DAG.getTargetConstant(Val, Type);
3053 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3055 EVT Type = Op.getValueType();
3056 int64_t Val = C->getSExtValue();
3057 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3058 Result = DAG.getTargetConstant(Val, Type);
3063 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3065 EVT Type = Op.getValueType();
3066 int64_t Val = C->getSExtValue();
3067 if ((Val >= -65535) && (Val <= -1)) {
3068 Result = DAG.getTargetConstant(Val, Type);
3073 case 'O': // signed 15 bit immediate
3074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3075 EVT Type = Op.getValueType();
3076 int64_t Val = C->getSExtValue();
3077 if ((isInt<15>(Val))) {
3078 Result = DAG.getTargetConstant(Val, Type);
3083 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3084 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3085 EVT Type = Op.getValueType();
3086 int64_t Val = C->getSExtValue();
3087 if ((Val <= 65535) && (Val >= 1)) {
3088 Result = DAG.getTargetConstant(Val, Type);
3095 if (Result.getNode()) {
3096 Ops.push_back(Result);
3100 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3103 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3105 // No global is ever allowed as a base.
3110 case 0: // "r+i" or just "i", depending on HasBaseReg.
3113 if (!AM.HasBaseReg) // allow "r+i".
3115 return false; // disallow "r+r" or "r+r+i".
3124 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3125 // The Mips target isn't yet aware of offsets.
3129 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3131 bool IsMemset, bool ZeroMemset,
3133 MachineFunction &MF) const {
3134 if (Subtarget->hasMips64())
3140 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3141 if (VT != MVT::f32 && VT != MVT::f64)
3143 if (Imm.isNegZero())
3145 return Imm.isZero();
3148 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3150 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3152 return TargetLowering::getJumpTableEncoding();
3155 /// This function returns true if CallSym is a long double emulation routine.
3156 static bool isF128SoftLibCall(const char *CallSym) {
3157 const char *const LibCalls[] =
3158 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3159 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3160 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3161 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3162 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3163 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3164 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3165 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3168 const char *const *End = LibCalls + array_lengthof(LibCalls);
3170 // Check that LibCalls is sorted alphabetically.
3171 MipsTargetLowering::LTStr Comp;
3174 for (const char *const *I = LibCalls; I < End - 1; ++I)
3175 assert(Comp(*I, *(I + 1)));
3178 return std::binary_search(LibCalls, End, CallSym, Comp);
3181 /// This function returns true if Ty is fp128 or i128 which was originally a
3183 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3184 if (Ty->isFP128Ty())
3187 const ExternalSymbolSDNode *ES =
3188 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3190 // If the Ty is i128 and the function being called is a long double emulation
3191 // routine, then the original type is f128.
3192 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3195 MipsTargetLowering::MipsCC::SpecialCallingConvType
3196 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3197 MipsCC::SpecialCallingConvType SpecialCallingConv =
3198 MipsCC::NoSpecialCallingConv;;
3199 if (Subtarget->inMips16HardFloat()) {
3200 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3201 llvm::StringRef Sym = G->getGlobal()->getName();
3202 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3203 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3204 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3208 return SpecialCallingConv;
3211 MipsTargetLowering::MipsCC::MipsCC(
3212 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3213 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3214 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3215 SpecialCallingConv(SpecialCallingConv_){
3216 // Pre-allocate reserved argument area.
3217 CCInfo.AllocateStack(reservedArgArea(), 1);
3221 void MipsTargetLowering::MipsCC::
3222 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3223 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3224 std::vector<ArgListEntry> &FuncArgs) {
3225 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3226 "CallingConv::Fast shouldn't be used for vararg functions.");
3228 unsigned NumOpnds = Args.size();
3229 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3231 for (unsigned I = 0; I != NumOpnds; ++I) {
3232 MVT ArgVT = Args[I].VT;
3233 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3236 if (ArgFlags.isByVal()) {
3237 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3241 if (IsVarArg && !Args[I].IsFixed)
3242 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3244 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3246 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3251 dbgs() << "Call operand #" << I << " has unhandled type "
3252 << EVT(ArgVT).getEVTString();
3254 llvm_unreachable(0);
3259 void MipsTargetLowering::MipsCC::
3260 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3261 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3262 unsigned NumArgs = Args.size();
3263 llvm::CCAssignFn *FixedFn = fixedArgFn();
3264 unsigned CurArgIdx = 0;
3266 for (unsigned I = 0; I != NumArgs; ++I) {
3267 MVT ArgVT = Args[I].VT;
3268 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3269 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3270 CurArgIdx = Args[I].OrigArgIndex;
3272 if (ArgFlags.isByVal()) {
3273 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3277 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3279 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3283 dbgs() << "Formal Arg #" << I << " has unhandled type "
3284 << EVT(ArgVT).getEVTString();
3286 llvm_unreachable(0);
3290 template<typename Ty>
3291 void MipsTargetLowering::MipsCC::
3292 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3293 const SDNode *CallNode, const Type *RetTy) const {
3296 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3297 Fn = RetCC_F128Soft;
3301 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3302 MVT VT = RetVals[I].VT;
3303 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3304 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3306 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3308 dbgs() << "Call result #" << I << " has unhandled type "
3309 << EVT(VT).getEVTString() << '\n';
3311 llvm_unreachable(0);
3316 void MipsTargetLowering::MipsCC::
3317 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3318 const SDNode *CallNode, const Type *RetTy) const {
3319 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3322 void MipsTargetLowering::MipsCC::
3323 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3324 const Type *RetTy) const {
3325 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3328 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3330 CCValAssign::LocInfo LocInfo,
3331 ISD::ArgFlagsTy ArgFlags) {
3332 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3334 struct ByValArgInfo ByVal;
3335 unsigned RegSize = regSize();
3336 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3337 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3340 if (useRegsForByval())
3341 allocateRegs(ByVal, ByValSize, Align);
3343 // Allocate space on caller's stack.
3344 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3346 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3348 ByValArgs.push_back(ByVal);
3351 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3352 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3355 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3356 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3359 const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
3360 return IsO32 ? O32IntRegs : Mips64IntRegs;
3363 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3364 if (CallConv == CallingConv::Fast)
3365 return CC_Mips_FastCC;
3367 if (SpecialCallingConv == Mips16RetHelperConv)
3368 return CC_Mips16RetHelper;
3369 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3372 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3373 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3376 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3377 return IsO32 ? O32IntRegs : Mips64DPRegs;
3380 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3383 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3384 const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3385 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3386 "Byval argument's size and alignment should be a multiple of"
3389 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3391 // If Align > RegSize, the first arg register must be even.
3392 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3393 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3397 // Mark the registers allocated.
3398 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3399 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3400 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3403 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3404 const SDNode *CallNode,
3405 bool IsSoftFloat) const {
3406 if (IsSoftFloat || IsO32)
3409 // Check if the original type was fp128.
3410 if (originalTypeIsF128(OrigTy, CallNode)) {
3411 assert(VT == MVT::i64);
3418 void MipsTargetLowering::
3419 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3420 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3421 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3422 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3423 MachineFunction &MF = DAG.getMachineFunction();
3424 MachineFrameInfo *MFI = MF.getFrameInfo();
3425 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3426 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3430 FrameObjOffset = (int)CC.reservedArgArea() -
3431 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3433 FrameObjOffset = ByVal.Address;
3435 // Create frame object.
3436 EVT PtrTy = getPointerTy();
3437 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3438 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3439 InVals.push_back(FIN);
3444 // Copy arg registers.
3445 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3446 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3448 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3449 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3450 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3451 unsigned Offset = I * CC.regSize();
3452 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3453 DAG.getConstant(Offset, PtrTy));
3454 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3455 StorePtr, MachinePointerInfo(FuncArg, Offset),
3457 OutChains.push_back(Store);
3461 // Copy byVal arg to registers and stack.
3462 void MipsTargetLowering::
3463 passByValArg(SDValue Chain, SDLoc DL,
3464 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3465 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3466 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3467 const MipsCC &CC, const ByValArgInfo &ByVal,
3468 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3469 unsigned ByValSize = Flags.getByValSize();
3470 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3471 unsigned RegSize = CC.regSize();
3472 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3473 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3475 if (ByVal.NumRegs) {
3476 const MCPhysReg *ArgRegs = CC.intArgRegs();
3477 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3480 // Copy words to registers.
3481 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3482 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3483 DAG.getConstant(Offset, PtrTy));
3484 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3485 MachinePointerInfo(), false, false, false,
3487 MemOpChains.push_back(LoadVal.getValue(1));
3488 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3489 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3492 // Return if the struct has been fully copied.
3493 if (ByValSize == Offset)
3496 // Copy the remainder of the byval argument with sub-word loads and shifts.
3497 if (LeftoverBytes) {
3498 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3499 "Size of the remainder should be smaller than RegSize.");
3502 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3503 Offset < ByValSize; LoadSize /= 2) {
3504 unsigned RemSize = ByValSize - Offset;
3506 if (RemSize < LoadSize)
3510 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3511 DAG.getConstant(Offset, PtrTy));
3513 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3514 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3515 false, false, Alignment);
3516 MemOpChains.push_back(LoadVal.getValue(1));
3518 // Shift the loaded value.
3522 Shamt = TotalSizeLoaded;
3524 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3526 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3527 DAG.getConstant(Shamt, MVT::i32));
3530 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3535 TotalSizeLoaded += LoadSize;
3536 Alignment = std::min(Alignment, LoadSize);
3539 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3540 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3545 // Copy remainder of byval arg to it with memcpy.
3546 unsigned MemCpySize = ByValSize - Offset;
3547 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3548 DAG.getConstant(Offset, PtrTy));
3549 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3550 DAG.getIntPtrConstant(ByVal.Address));
3551 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3552 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3553 MachinePointerInfo(), MachinePointerInfo());
3554 MemOpChains.push_back(Chain);
3557 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3558 const MipsCC &CC, SDValue Chain,
3559 SDLoc DL, SelectionDAG &DAG) const {
3560 unsigned NumRegs = CC.numIntArgRegs();
3561 const MCPhysReg *ArgRegs = CC.intArgRegs();
3562 const CCState &CCInfo = CC.getCCInfo();
3563 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3564 unsigned RegSize = CC.regSize();
3565 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3566 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3567 MachineFunction &MF = DAG.getMachineFunction();
3568 MachineFrameInfo *MFI = MF.getFrameInfo();
3569 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3571 // Offset of the first variable argument from stack pointer.
3575 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3577 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3579 // Record the frame index of the first variable argument
3580 // which is a value necessary to VASTART.
3581 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3582 MipsFI->setVarArgsFrameIndex(FI);
3584 // Copy the integer registers that have not been used for argument passing
3585 // to the argument register save area. For O32, the save area is allocated
3586 // in the caller's stack frame, while for N32/64, it is allocated in the
3587 // callee's stack frame.
3588 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3589 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3590 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3591 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3592 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3593 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3594 MachinePointerInfo(), false, false, 0);
3595 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue((Value*)0);
3596 OutChains.push_back(Store);