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/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
40 STATISTIC(NumTailCalls, "Number of tail calls");
43 LargeGOT("mxgot", cl::Hidden,
44 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
47 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
48 cl::desc("MIPS: Don't trap on integer division by zero."),
51 static const uint16_t O32IntRegs[4] = {
52 Mips::A0, Mips::A1, Mips::A2, Mips::A3
55 static const uint16_t Mips64IntRegs[8] = {
56 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
57 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
60 static const uint16_t Mips64DPRegs[8] = {
61 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
62 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
65 // If I is a shifted mask, set the size (Size) and the first bit of the
66 // mask (Pos), and return true.
67 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
68 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
69 if (!isShiftedMask_64(I))
72 Size = CountPopulation_64(I);
73 Pos = countTrailingZeros(I);
77 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
78 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
79 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
82 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
83 EVT Ty = Op.getValueType();
85 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(Op), Ty, 0,
88 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
89 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
90 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
91 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
92 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
93 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
94 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
95 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
96 N->getOffset(), Flag);
98 llvm_unreachable("Unexpected node type.");
102 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
104 EVT Ty = Op.getValueType();
105 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
106 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
107 return DAG.getNode(ISD::ADD, DL, Ty,
108 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
109 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
112 SDValue MipsTargetLowering::getAddrLocal(SDValue Op, SelectionDAG &DAG,
113 bool HasMips64) const {
115 EVT Ty = Op.getValueType();
116 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
117 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
118 getTargetNode(Op, DAG, GOTFlag));
119 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
120 MachinePointerInfo::getGOT(), false, false, false,
122 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
123 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
124 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
127 SDValue MipsTargetLowering::getAddrGlobal(SDValue Op, SelectionDAG &DAG,
128 unsigned Flag) const {
130 EVT Ty = Op.getValueType();
131 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
132 getTargetNode(Op, DAG, Flag));
133 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
134 MachinePointerInfo::getGOT(), false, false, false, 0);
137 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
139 unsigned LoFlag) const {
141 EVT Ty = Op.getValueType();
142 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
143 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
144 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
145 getTargetNode(Op, DAG, LoFlag));
146 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
147 MachinePointerInfo::getGOT(), false, false, false, 0);
150 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
152 case MipsISD::JmpLink: return "MipsISD::JmpLink";
153 case MipsISD::TailCall: return "MipsISD::TailCall";
154 case MipsISD::Hi: return "MipsISD::Hi";
155 case MipsISD::Lo: return "MipsISD::Lo";
156 case MipsISD::GPRel: return "MipsISD::GPRel";
157 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
158 case MipsISD::Ret: return "MipsISD::Ret";
159 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
160 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
161 case MipsISD::FPCmp: return "MipsISD::FPCmp";
162 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
163 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
164 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
165 case MipsISD::ExtractLOHI: return "MipsISD::ExtractLOHI";
166 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
167 case MipsISD::Mult: return "MipsISD::Mult";
168 case MipsISD::Multu: return "MipsISD::Multu";
169 case MipsISD::MAdd: return "MipsISD::MAdd";
170 case MipsISD::MAddu: return "MipsISD::MAddu";
171 case MipsISD::MSub: return "MipsISD::MSub";
172 case MipsISD::MSubu: return "MipsISD::MSubu";
173 case MipsISD::DivRem: return "MipsISD::DivRem";
174 case MipsISD::DivRemU: return "MipsISD::DivRemU";
175 case MipsISD::DivRem16: return "MipsISD::DivRem16";
176 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
177 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
178 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
179 case MipsISD::Wrapper: return "MipsISD::Wrapper";
180 case MipsISD::Sync: return "MipsISD::Sync";
181 case MipsISD::Ext: return "MipsISD::Ext";
182 case MipsISD::Ins: return "MipsISD::Ins";
183 case MipsISD::LWL: return "MipsISD::LWL";
184 case MipsISD::LWR: return "MipsISD::LWR";
185 case MipsISD::SWL: return "MipsISD::SWL";
186 case MipsISD::SWR: return "MipsISD::SWR";
187 case MipsISD::LDL: return "MipsISD::LDL";
188 case MipsISD::LDR: return "MipsISD::LDR";
189 case MipsISD::SDL: return "MipsISD::SDL";
190 case MipsISD::SDR: return "MipsISD::SDR";
191 case MipsISD::EXTP: return "MipsISD::EXTP";
192 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
193 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
194 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
195 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
196 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
197 case MipsISD::SHILO: return "MipsISD::SHILO";
198 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
199 case MipsISD::MULT: return "MipsISD::MULT";
200 case MipsISD::MULTU: return "MipsISD::MULTU";
201 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
202 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
203 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
204 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
205 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
206 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
207 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
208 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
209 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
210 default: return NULL;
215 MipsTargetLowering(MipsTargetMachine &TM)
216 : TargetLowering(TM, new MipsTargetObjectFile()),
217 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
218 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
219 IsO32(Subtarget->isABI_O32()) {
220 // Mips does not have i1 type, so use i32 for
221 // setcc operations results (slt, sgt, ...).
222 setBooleanContents(ZeroOrOneBooleanContent);
223 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
225 // Load extented operations for i1 types must be promoted
226 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
227 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
228 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
230 // MIPS doesn't have extending float->double load/store
231 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
232 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
234 // Used by legalize types to correctly generate the setcc result.
235 // Without this, every float setcc comes with a AND/OR with the result,
236 // we don't want this, since the fpcmp result goes to a flag register,
237 // which is used implicitly by brcond and select operations.
238 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
240 // Mips Custom Operations
241 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
242 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
243 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
244 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
245 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
246 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
247 setOperationAction(ISD::SELECT, MVT::f32, Custom);
248 setOperationAction(ISD::SELECT, MVT::f64, Custom);
249 setOperationAction(ISD::SELECT, MVT::i32, Custom);
250 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
251 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
252 setOperationAction(ISD::SETCC, MVT::f32, Custom);
253 setOperationAction(ISD::SETCC, MVT::f64, Custom);
254 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
255 setOperationAction(ISD::VASTART, MVT::Other, Custom);
256 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
257 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
258 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
260 if (!TM.Options.NoNaNsFPMath) {
261 setOperationAction(ISD::FABS, MVT::f32, Custom);
262 setOperationAction(ISD::FABS, MVT::f64, Custom);
266 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
267 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
268 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
269 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
270 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
271 setOperationAction(ISD::SELECT, MVT::i64, Custom);
272 setOperationAction(ISD::LOAD, MVT::i64, Custom);
273 setOperationAction(ISD::STORE, MVT::i64, Custom);
274 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
278 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
279 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
280 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
283 setOperationAction(ISD::ADD, MVT::i32, Custom);
285 setOperationAction(ISD::ADD, MVT::i64, Custom);
287 setOperationAction(ISD::SDIV, MVT::i32, Expand);
288 setOperationAction(ISD::SREM, MVT::i32, Expand);
289 setOperationAction(ISD::UDIV, MVT::i32, Expand);
290 setOperationAction(ISD::UREM, MVT::i32, Expand);
291 setOperationAction(ISD::SDIV, MVT::i64, Expand);
292 setOperationAction(ISD::SREM, MVT::i64, Expand);
293 setOperationAction(ISD::UDIV, MVT::i64, Expand);
294 setOperationAction(ISD::UREM, MVT::i64, Expand);
296 // Operations not directly supported by Mips.
297 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
298 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
299 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
300 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
301 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
302 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
303 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
304 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
305 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
306 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
307 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
308 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
309 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
310 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
311 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
312 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
313 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
314 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
315 setOperationAction(ISD::ROTL, MVT::i32, Expand);
316 setOperationAction(ISD::ROTL, MVT::i64, Expand);
317 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
318 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
320 if (!Subtarget->hasMips32r2())
321 setOperationAction(ISD::ROTR, MVT::i32, Expand);
323 if (!Subtarget->hasMips64r2())
324 setOperationAction(ISD::ROTR, MVT::i64, Expand);
326 setOperationAction(ISD::FSIN, MVT::f32, Expand);
327 setOperationAction(ISD::FSIN, MVT::f64, Expand);
328 setOperationAction(ISD::FCOS, MVT::f32, Expand);
329 setOperationAction(ISD::FCOS, MVT::f64, Expand);
330 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
331 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
332 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
333 setOperationAction(ISD::FPOW, MVT::f32, Expand);
334 setOperationAction(ISD::FPOW, MVT::f64, Expand);
335 setOperationAction(ISD::FLOG, MVT::f32, Expand);
336 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
337 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
338 setOperationAction(ISD::FEXP, MVT::f32, Expand);
339 setOperationAction(ISD::FMA, MVT::f32, Expand);
340 setOperationAction(ISD::FMA, MVT::f64, Expand);
341 setOperationAction(ISD::FREM, MVT::f32, Expand);
342 setOperationAction(ISD::FREM, MVT::f64, Expand);
344 if (!TM.Options.NoNaNsFPMath) {
345 setOperationAction(ISD::FNEG, MVT::f32, Expand);
346 setOperationAction(ISD::FNEG, MVT::f64, Expand);
349 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
350 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
351 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
352 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
354 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
356 setOperationAction(ISD::VAARG, MVT::Other, Expand);
357 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
358 setOperationAction(ISD::VAEND, MVT::Other, Expand);
360 // Use the default for now
361 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
362 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
364 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
365 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
366 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
367 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
369 setInsertFencesForAtomic(true);
371 if (!Subtarget->hasSEInReg()) {
372 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
373 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
376 if (!Subtarget->hasBitCount()) {
377 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
378 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
381 if (!Subtarget->hasSwap()) {
382 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
383 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
387 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
388 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
389 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
390 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
393 setTargetDAGCombine(ISD::SDIVREM);
394 setTargetDAGCombine(ISD::UDIVREM);
395 setTargetDAGCombine(ISD::SELECT);
396 setTargetDAGCombine(ISD::AND);
397 setTargetDAGCombine(ISD::OR);
398 setTargetDAGCombine(ISD::ADD);
400 setMinFunctionAlignment(HasMips64 ? 3 : 2);
402 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
404 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
405 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
407 MaxStoresPerMemcpy = 16;
410 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
411 if (TM.getSubtargetImpl()->inMips16Mode())
412 return llvm::createMips16TargetLowering(TM);
414 return llvm::createMipsSETargetLowering(TM);
417 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
420 return VT.changeVectorElementTypeToInteger();
423 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
424 TargetLowering::DAGCombinerInfo &DCI,
425 const MipsSubtarget *Subtarget) {
426 if (DCI.isBeforeLegalizeOps())
429 EVT Ty = N->getValueType(0);
430 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
431 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
432 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
436 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
437 N->getOperand(0), N->getOperand(1));
438 SDValue InChain = DAG.getEntryNode();
439 SDValue InGlue = DivRem;
442 if (N->hasAnyUseOfValue(0)) {
443 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
446 InChain = CopyFromLo.getValue(1);
447 InGlue = CopyFromLo.getValue(2);
451 if (N->hasAnyUseOfValue(1)) {
452 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
454 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
460 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
462 default: llvm_unreachable("Unknown fp condition code!");
464 case ISD::SETOEQ: return Mips::FCOND_OEQ;
465 case ISD::SETUNE: return Mips::FCOND_UNE;
467 case ISD::SETOLT: return Mips::FCOND_OLT;
469 case ISD::SETOGT: return Mips::FCOND_OGT;
471 case ISD::SETOLE: return Mips::FCOND_OLE;
473 case ISD::SETOGE: return Mips::FCOND_OGE;
474 case ISD::SETULT: return Mips::FCOND_ULT;
475 case ISD::SETULE: return Mips::FCOND_ULE;
476 case ISD::SETUGT: return Mips::FCOND_UGT;
477 case ISD::SETUGE: return Mips::FCOND_UGE;
478 case ISD::SETUO: return Mips::FCOND_UN;
479 case ISD::SETO: return Mips::FCOND_OR;
481 case ISD::SETONE: return Mips::FCOND_ONE;
482 case ISD::SETUEQ: return Mips::FCOND_UEQ;
487 /// This function returns true if the floating point conditional branches and
488 /// conditional moves which use condition code CC should be inverted.
489 static bool invertFPCondCodeUser(Mips::CondCode CC) {
490 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
493 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
494 "Illegal Condition Code");
499 // Creates and returns an FPCmp node from a setcc node.
500 // Returns Op if setcc is not a floating point comparison.
501 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
502 // must be a SETCC node
503 if (Op.getOpcode() != ISD::SETCC)
506 SDValue LHS = Op.getOperand(0);
508 if (!LHS.getValueType().isFloatingPoint())
511 SDValue RHS = Op.getOperand(1);
514 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
515 // node if necessary.
516 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
518 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
519 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
522 // Creates and returns a CMovFPT/F node.
523 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
524 SDValue False, SDLoc DL) {
525 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
526 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
528 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
529 True.getValueType(), True, False, Cond);
532 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
533 TargetLowering::DAGCombinerInfo &DCI,
534 const MipsSubtarget *Subtarget) {
535 if (DCI.isBeforeLegalizeOps())
538 SDValue SetCC = N->getOperand(0);
540 if ((SetCC.getOpcode() != ISD::SETCC) ||
541 !SetCC.getOperand(0).getValueType().isInteger())
544 SDValue False = N->getOperand(2);
545 EVT FalseTy = False.getValueType();
547 if (!FalseTy.isInteger())
550 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
552 if (!CN || CN->getZExtValue())
556 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
557 SDValue True = N->getOperand(1);
559 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
560 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
562 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
565 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
566 TargetLowering::DAGCombinerInfo &DCI,
567 const MipsSubtarget *Subtarget) {
568 // Pattern match EXT.
569 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
570 // => ext $dst, $src, size, pos
571 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
574 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
575 unsigned ShiftRightOpc = ShiftRight.getOpcode();
577 // Op's first operand must be a shift right.
578 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
581 // The second operand of the shift must be an immediate.
583 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
586 uint64_t Pos = CN->getZExtValue();
587 uint64_t SMPos, SMSize;
589 // Op's second operand must be a shifted mask.
590 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
591 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
594 // Return if the shifted mask does not start at bit 0 or the sum of its size
595 // and Pos exceeds the word's size.
596 EVT ValTy = N->getValueType(0);
597 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
600 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
601 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
602 DAG.getConstant(SMSize, MVT::i32));
605 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
606 TargetLowering::DAGCombinerInfo &DCI,
607 const MipsSubtarget *Subtarget) {
608 // Pattern match INS.
609 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
610 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
611 // => ins $dst, $src, size, pos, $src1
612 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
615 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
616 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
619 // See if Op's first operand matches (and $src1 , mask0).
620 if (And0.getOpcode() != ISD::AND)
623 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
624 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
627 // See if Op's second operand matches (and (shl $src, pos), mask1).
628 if (And1.getOpcode() != ISD::AND)
631 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
632 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
635 // The shift masks must have the same position and size.
636 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
639 SDValue Shl = And1.getOperand(0);
640 if (Shl.getOpcode() != ISD::SHL)
643 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
646 unsigned Shamt = CN->getZExtValue();
648 // Return if the shift amount and the first bit position of mask are not the
650 EVT ValTy = N->getValueType(0);
651 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
654 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
655 DAG.getConstant(SMPos0, MVT::i32),
656 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
659 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
660 TargetLowering::DAGCombinerInfo &DCI,
661 const MipsSubtarget *Subtarget) {
662 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
664 if (DCI.isBeforeLegalizeOps())
667 SDValue Add = N->getOperand(1);
669 if (Add.getOpcode() != ISD::ADD)
672 SDValue Lo = Add.getOperand(1);
674 if ((Lo.getOpcode() != MipsISD::Lo) ||
675 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
678 EVT ValTy = N->getValueType(0);
681 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
683 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
686 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
688 SelectionDAG &DAG = DCI.DAG;
689 unsigned Opc = N->getOpcode();
695 return performDivRemCombine(N, DAG, DCI, Subtarget);
697 return performSELECTCombine(N, DAG, DCI, Subtarget);
699 return performANDCombine(N, DAG, DCI, Subtarget);
701 return performORCombine(N, DAG, DCI, Subtarget);
703 return performADDCombine(N, DAG, DCI, Subtarget);
710 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
711 SmallVectorImpl<SDValue> &Results,
712 SelectionDAG &DAG) const {
713 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
715 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
716 Results.push_back(Res.getValue(I));
720 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
721 SmallVectorImpl<SDValue> &Results,
722 SelectionDAG &DAG) const {
723 return LowerOperationWrapper(N, Results, DAG);
726 SDValue MipsTargetLowering::
727 LowerOperation(SDValue Op, SelectionDAG &DAG) const
729 switch (Op.getOpcode())
731 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
732 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
733 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
734 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
735 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
736 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
737 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
738 case ISD::SELECT: return lowerSELECT(Op, DAG);
739 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
740 case ISD::SETCC: return lowerSETCC(Op, DAG);
741 case ISD::VASTART: return lowerVASTART(Op, DAG);
742 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
743 case ISD::FABS: return lowerFABS(Op, DAG);
744 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
745 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
746 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
747 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
748 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
749 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
750 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
751 case ISD::LOAD: return lowerLOAD(Op, DAG);
752 case ISD::STORE: return lowerSTORE(Op, DAG);
753 case ISD::ADD: return lowerADD(Op, DAG);
754 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
759 //===----------------------------------------------------------------------===//
760 // Lower helper functions
761 //===----------------------------------------------------------------------===//
763 // addLiveIn - This helper function adds the specified physical register to the
764 // MachineFunction as a live in value. It also creates a corresponding
765 // virtual register for it.
767 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
769 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
770 MF.getRegInfo().addLiveIn(PReg, VReg);
774 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
775 MachineBasicBlock &MBB,
776 const TargetInstrInfo &TII,
781 // Insert instruction "teq $divisor_reg, $zero, 7".
782 MachineBasicBlock::iterator I(MI);
783 MachineInstrBuilder MIB;
784 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
785 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
787 // Use the 32-bit sub-register if this is a 64-bit division.
789 MIB->getOperand(0).setSubReg(Mips::sub_32);
795 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
796 MachineBasicBlock *BB) const {
797 switch (MI->getOpcode()) {
799 llvm_unreachable("Unexpected instr type to insert");
800 case Mips::ATOMIC_LOAD_ADD_I8:
801 case Mips::ATOMIC_LOAD_ADD_I8_P8:
802 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
803 case Mips::ATOMIC_LOAD_ADD_I16:
804 case Mips::ATOMIC_LOAD_ADD_I16_P8:
805 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
806 case Mips::ATOMIC_LOAD_ADD_I32:
807 case Mips::ATOMIC_LOAD_ADD_I32_P8:
808 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
809 case Mips::ATOMIC_LOAD_ADD_I64:
810 case Mips::ATOMIC_LOAD_ADD_I64_P8:
811 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
813 case Mips::ATOMIC_LOAD_AND_I8:
814 case Mips::ATOMIC_LOAD_AND_I8_P8:
815 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
816 case Mips::ATOMIC_LOAD_AND_I16:
817 case Mips::ATOMIC_LOAD_AND_I16_P8:
818 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
819 case Mips::ATOMIC_LOAD_AND_I32:
820 case Mips::ATOMIC_LOAD_AND_I32_P8:
821 return emitAtomicBinary(MI, BB, 4, Mips::AND);
822 case Mips::ATOMIC_LOAD_AND_I64:
823 case Mips::ATOMIC_LOAD_AND_I64_P8:
824 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
826 case Mips::ATOMIC_LOAD_OR_I8:
827 case Mips::ATOMIC_LOAD_OR_I8_P8:
828 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
829 case Mips::ATOMIC_LOAD_OR_I16:
830 case Mips::ATOMIC_LOAD_OR_I16_P8:
831 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
832 case Mips::ATOMIC_LOAD_OR_I32:
833 case Mips::ATOMIC_LOAD_OR_I32_P8:
834 return emitAtomicBinary(MI, BB, 4, Mips::OR);
835 case Mips::ATOMIC_LOAD_OR_I64:
836 case Mips::ATOMIC_LOAD_OR_I64_P8:
837 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
839 case Mips::ATOMIC_LOAD_XOR_I8:
840 case Mips::ATOMIC_LOAD_XOR_I8_P8:
841 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
842 case Mips::ATOMIC_LOAD_XOR_I16:
843 case Mips::ATOMIC_LOAD_XOR_I16_P8:
844 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
845 case Mips::ATOMIC_LOAD_XOR_I32:
846 case Mips::ATOMIC_LOAD_XOR_I32_P8:
847 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
848 case Mips::ATOMIC_LOAD_XOR_I64:
849 case Mips::ATOMIC_LOAD_XOR_I64_P8:
850 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
852 case Mips::ATOMIC_LOAD_NAND_I8:
853 case Mips::ATOMIC_LOAD_NAND_I8_P8:
854 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
855 case Mips::ATOMIC_LOAD_NAND_I16:
856 case Mips::ATOMIC_LOAD_NAND_I16_P8:
857 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
858 case Mips::ATOMIC_LOAD_NAND_I32:
859 case Mips::ATOMIC_LOAD_NAND_I32_P8:
860 return emitAtomicBinary(MI, BB, 4, 0, true);
861 case Mips::ATOMIC_LOAD_NAND_I64:
862 case Mips::ATOMIC_LOAD_NAND_I64_P8:
863 return emitAtomicBinary(MI, BB, 8, 0, true);
865 case Mips::ATOMIC_LOAD_SUB_I8:
866 case Mips::ATOMIC_LOAD_SUB_I8_P8:
867 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
868 case Mips::ATOMIC_LOAD_SUB_I16:
869 case Mips::ATOMIC_LOAD_SUB_I16_P8:
870 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
871 case Mips::ATOMIC_LOAD_SUB_I32:
872 case Mips::ATOMIC_LOAD_SUB_I32_P8:
873 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
874 case Mips::ATOMIC_LOAD_SUB_I64:
875 case Mips::ATOMIC_LOAD_SUB_I64_P8:
876 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
878 case Mips::ATOMIC_SWAP_I8:
879 case Mips::ATOMIC_SWAP_I8_P8:
880 return emitAtomicBinaryPartword(MI, BB, 1, 0);
881 case Mips::ATOMIC_SWAP_I16:
882 case Mips::ATOMIC_SWAP_I16_P8:
883 return emitAtomicBinaryPartword(MI, BB, 2, 0);
884 case Mips::ATOMIC_SWAP_I32:
885 case Mips::ATOMIC_SWAP_I32_P8:
886 return emitAtomicBinary(MI, BB, 4, 0);
887 case Mips::ATOMIC_SWAP_I64:
888 case Mips::ATOMIC_SWAP_I64_P8:
889 return emitAtomicBinary(MI, BB, 8, 0);
891 case Mips::ATOMIC_CMP_SWAP_I8:
892 case Mips::ATOMIC_CMP_SWAP_I8_P8:
893 return emitAtomicCmpSwapPartword(MI, BB, 1);
894 case Mips::ATOMIC_CMP_SWAP_I16:
895 case Mips::ATOMIC_CMP_SWAP_I16_P8:
896 return emitAtomicCmpSwapPartword(MI, BB, 2);
897 case Mips::ATOMIC_CMP_SWAP_I32:
898 case Mips::ATOMIC_CMP_SWAP_I32_P8:
899 return emitAtomicCmpSwap(MI, BB, 4);
900 case Mips::ATOMIC_CMP_SWAP_I64:
901 case Mips::ATOMIC_CMP_SWAP_I64_P8:
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 = IsN64 ? Mips::LL_P8 : Mips::LL;
929 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
936 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
937 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
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 llvm::next(MachineBasicBlock::iterator(MI)),
965 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
969 // fallthrough --> loopMBB
970 BB->addSuccessor(loopMBB);
971 loopMBB->addSuccessor(loopMBB);
972 loopMBB->addSuccessor(exitMBB);
976 // <binop> storeval, oldval, incr
977 // sc success, storeval, 0(ptr)
978 // beq success, $0, loopMBB
980 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
982 // and andres, oldval, incr
983 // nor storeval, $0, andres
984 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
985 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
986 } else if (BinOpcode) {
987 // <binop> storeval, oldval, incr
988 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
992 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
993 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
995 MI->eraseFromParent(); // The instruction is gone now.
1001 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1002 MachineBasicBlock *BB,
1003 unsigned Size, unsigned BinOpcode,
1005 assert((Size == 1 || Size == 2) &&
1006 "Unsupported size for EmitAtomicBinaryPartial.");
1008 MachineFunction *MF = BB->getParent();
1009 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1010 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1011 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1012 DebugLoc DL = MI->getDebugLoc();
1013 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1014 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1016 unsigned Dest = MI->getOperand(0).getReg();
1017 unsigned Ptr = MI->getOperand(1).getReg();
1018 unsigned Incr = MI->getOperand(2).getReg();
1020 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1021 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1022 unsigned Mask = RegInfo.createVirtualRegister(RC);
1023 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1024 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1025 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1026 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1027 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1028 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1029 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1030 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1031 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1032 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1033 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1034 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1035 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1036 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1037 unsigned Success = RegInfo.createVirtualRegister(RC);
1039 // insert new blocks after the current block
1040 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1041 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1042 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1043 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1044 MachineFunction::iterator It = BB;
1046 MF->insert(It, loopMBB);
1047 MF->insert(It, sinkMBB);
1048 MF->insert(It, exitMBB);
1050 // Transfer the remainder of BB and its successor edges to exitMBB.
1051 exitMBB->splice(exitMBB->begin(), BB,
1052 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1053 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1055 BB->addSuccessor(loopMBB);
1056 loopMBB->addSuccessor(loopMBB);
1057 loopMBB->addSuccessor(sinkMBB);
1058 sinkMBB->addSuccessor(exitMBB);
1061 // addiu masklsb2,$0,-4 # 0xfffffffc
1062 // and alignedaddr,ptr,masklsb2
1063 // andi ptrlsb2,ptr,3
1064 // sll shiftamt,ptrlsb2,3
1065 // ori maskupper,$0,255 # 0xff
1066 // sll mask,maskupper,shiftamt
1067 // nor mask2,$0,mask
1068 // sll incr2,incr,shiftamt
1070 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1071 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1072 .addReg(Mips::ZERO).addImm(-4);
1073 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1074 .addReg(Ptr).addReg(MaskLSB2);
1075 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1076 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1077 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1078 .addReg(Mips::ZERO).addImm(MaskImm);
1079 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1080 .addReg(ShiftAmt).addReg(MaskUpper);
1081 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1082 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1084 // atomic.load.binop
1086 // ll oldval,0(alignedaddr)
1087 // binop binopres,oldval,incr2
1088 // and newval,binopres,mask
1089 // and maskedoldval0,oldval,mask2
1090 // or storeval,maskedoldval0,newval
1091 // sc success,storeval,0(alignedaddr)
1092 // beq success,$0,loopMBB
1096 // ll oldval,0(alignedaddr)
1097 // and newval,incr2,mask
1098 // and maskedoldval0,oldval,mask2
1099 // or storeval,maskedoldval0,newval
1100 // sc success,storeval,0(alignedaddr)
1101 // beq success,$0,loopMBB
1104 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1106 // and andres, oldval, incr2
1107 // nor binopres, $0, andres
1108 // and newval, binopres, mask
1109 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1110 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1111 .addReg(Mips::ZERO).addReg(AndRes);
1112 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1113 } else if (BinOpcode) {
1114 // <binop> binopres, oldval, incr2
1115 // and newval, binopres, mask
1116 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1117 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1118 } else {// atomic.swap
1119 // and newval, incr2, mask
1120 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1123 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1124 .addReg(OldVal).addReg(Mask2);
1125 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1126 .addReg(MaskedOldVal0).addReg(NewVal);
1127 BuildMI(BB, DL, TII->get(SC), Success)
1128 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1129 BuildMI(BB, DL, TII->get(Mips::BEQ))
1130 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1133 // and maskedoldval1,oldval,mask
1134 // srl srlres,maskedoldval1,shiftamt
1135 // sll sllres,srlres,24
1136 // sra dest,sllres,24
1138 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1140 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1141 .addReg(OldVal).addReg(Mask);
1142 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1143 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1144 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1145 .addReg(SrlRes).addImm(ShiftImm);
1146 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1147 .addReg(SllRes).addImm(ShiftImm);
1149 MI->eraseFromParent(); // The instruction is gone now.
1155 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1156 MachineBasicBlock *BB,
1157 unsigned Size) const {
1158 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1160 MachineFunction *MF = BB->getParent();
1161 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1162 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1163 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1164 DebugLoc DL = MI->getDebugLoc();
1165 unsigned LL, SC, ZERO, BNE, BEQ;
1168 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1169 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1175 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1176 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1177 ZERO = Mips::ZERO_64;
1182 unsigned Dest = MI->getOperand(0).getReg();
1183 unsigned Ptr = MI->getOperand(1).getReg();
1184 unsigned OldVal = MI->getOperand(2).getReg();
1185 unsigned NewVal = MI->getOperand(3).getReg();
1187 unsigned Success = RegInfo.createVirtualRegister(RC);
1189 // insert new blocks after the current block
1190 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1191 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1192 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1193 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1194 MachineFunction::iterator It = BB;
1196 MF->insert(It, loop1MBB);
1197 MF->insert(It, loop2MBB);
1198 MF->insert(It, exitMBB);
1200 // Transfer the remainder of BB and its successor edges to exitMBB.
1201 exitMBB->splice(exitMBB->begin(), BB,
1202 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1203 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1207 // fallthrough --> loop1MBB
1208 BB->addSuccessor(loop1MBB);
1209 loop1MBB->addSuccessor(exitMBB);
1210 loop1MBB->addSuccessor(loop2MBB);
1211 loop2MBB->addSuccessor(loop1MBB);
1212 loop2MBB->addSuccessor(exitMBB);
1216 // bne dest, oldval, exitMBB
1218 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1219 BuildMI(BB, DL, TII->get(BNE))
1220 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1223 // sc success, newval, 0(ptr)
1224 // beq success, $0, loop1MBB
1226 BuildMI(BB, DL, TII->get(SC), Success)
1227 .addReg(NewVal).addReg(Ptr).addImm(0);
1228 BuildMI(BB, DL, TII->get(BEQ))
1229 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1231 MI->eraseFromParent(); // The instruction is gone now.
1237 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1238 MachineBasicBlock *BB,
1239 unsigned Size) const {
1240 assert((Size == 1 || Size == 2) &&
1241 "Unsupported size for EmitAtomicCmpSwapPartial.");
1243 MachineFunction *MF = BB->getParent();
1244 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1245 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1246 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1247 DebugLoc DL = MI->getDebugLoc();
1248 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1249 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
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 llvm::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 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1320 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1321 .addReg(Mips::ZERO).addImm(MaskImm);
1322 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1323 .addReg(ShiftAmt).addReg(MaskUpper);
1324 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1325 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1326 .addReg(CmpVal).addImm(MaskImm);
1327 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1328 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1329 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1330 .addReg(NewVal).addImm(MaskImm);
1331 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1332 .addReg(ShiftAmt).addReg(MaskedNewVal);
1335 // ll oldval,0(alginedaddr)
1336 // and maskedoldval0,oldval,mask
1337 // bne maskedoldval0,shiftedcmpval,sinkMBB
1339 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1340 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1341 .addReg(OldVal).addReg(Mask);
1342 BuildMI(BB, DL, TII->get(Mips::BNE))
1343 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1346 // and maskedoldval1,oldval,mask2
1347 // or storeval,maskedoldval1,shiftednewval
1348 // sc success,storeval,0(alignedaddr)
1349 // beq success,$0,loop1MBB
1351 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1352 .addReg(OldVal).addReg(Mask2);
1353 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1354 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1355 BuildMI(BB, DL, TII->get(SC), Success)
1356 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1357 BuildMI(BB, DL, TII->get(Mips::BEQ))
1358 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1361 // srl srlres,maskedoldval0,shiftamt
1362 // sll sllres,srlres,24
1363 // sra dest,sllres,24
1365 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1367 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1368 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1369 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1370 .addReg(SrlRes).addImm(ShiftImm);
1371 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1372 .addReg(SllRes).addImm(ShiftImm);
1374 MI->eraseFromParent(); // The instruction is gone now.
1379 //===----------------------------------------------------------------------===//
1380 // Misc Lower Operation implementation
1381 //===----------------------------------------------------------------------===//
1382 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1383 SDValue Chain = Op.getOperand(0);
1384 SDValue Table = Op.getOperand(1);
1385 SDValue Index = Op.getOperand(2);
1387 EVT PTy = getPointerTy();
1388 unsigned EntrySize =
1389 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1391 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1392 DAG.getConstant(EntrySize, PTy));
1393 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1395 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1396 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1397 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1399 Chain = Addr.getValue(1);
1401 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1402 // For PIC, the sequence is:
1403 // BRIND(load(Jumptable + index) + RelocBase)
1404 // RelocBase can be JumpTable, GOT or some sort of global base.
1405 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1406 getPICJumpTableRelocBase(Table, DAG));
1409 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1412 SDValue MipsTargetLowering::
1413 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1415 // The first operand is the chain, the second is the condition, the third is
1416 // the block to branch to if the condition is true.
1417 SDValue Chain = Op.getOperand(0);
1418 SDValue Dest = Op.getOperand(2);
1421 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1423 // Return if flag is not set by a floating point comparison.
1424 if (CondRes.getOpcode() != MipsISD::FPCmp)
1427 SDValue CCNode = CondRes.getOperand(2);
1429 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1430 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1431 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1432 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1436 SDValue MipsTargetLowering::
1437 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1439 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1441 // Return if flag is not set by a floating point comparison.
1442 if (Cond.getOpcode() != MipsISD::FPCmp)
1445 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1449 SDValue MipsTargetLowering::
1450 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1453 EVT Ty = Op.getOperand(0).getValueType();
1454 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1455 getSetCCResultType(*DAG.getContext(), Ty),
1456 Op.getOperand(0), Op.getOperand(1),
1459 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1463 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1464 SDValue Cond = createFPCmp(DAG, Op);
1466 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1467 "Floating point operand expected.");
1469 SDValue True = DAG.getConstant(1, MVT::i32);
1470 SDValue False = DAG.getConstant(0, MVT::i32);
1472 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1475 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1476 SelectionDAG &DAG) const {
1477 // FIXME there isn't actually debug info here
1479 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1481 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1482 const MipsTargetObjectFile &TLOF =
1483 (const MipsTargetObjectFile&)getObjFileLowering();
1485 // %gp_rel relocation
1486 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1487 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1489 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1490 DAG.getVTList(MVT::i32), &GA, 1);
1491 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1492 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1495 // %hi/%lo relocation
1496 return getAddrNonPIC(Op, DAG);
1499 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1500 return getAddrLocal(Op, DAG, HasMips64);
1503 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1504 MipsII::MO_GOT_LO16);
1506 return getAddrGlobal(Op, DAG,
1507 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1510 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1511 SelectionDAG &DAG) const {
1512 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1513 return getAddrNonPIC(Op, DAG);
1515 return getAddrLocal(Op, DAG, HasMips64);
1518 SDValue MipsTargetLowering::
1519 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1521 // If the relocation model is PIC, use the General Dynamic TLS Model or
1522 // Local Dynamic TLS model, otherwise use the Initial Exec or
1523 // Local Exec TLS Model.
1525 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1527 const GlobalValue *GV = GA->getGlobal();
1528 EVT PtrVT = getPointerTy();
1530 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1532 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1533 // General Dynamic and Local Dynamic TLS Model.
1534 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1537 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1538 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1539 getGlobalReg(DAG, PtrVT), TGA);
1540 unsigned PtrSize = PtrVT.getSizeInBits();
1541 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1543 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1547 Entry.Node = Argument;
1549 Args.push_back(Entry);
1551 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1552 false, false, false, false, 0, CallingConv::C,
1553 /*IsTailCall=*/false, /*doesNotRet=*/false,
1554 /*isReturnValueUsed=*/true,
1555 TlsGetAddr, Args, DAG, DL);
1556 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1558 SDValue Ret = CallResult.first;
1560 if (model != TLSModel::LocalDynamic)
1563 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1564 MipsII::MO_DTPREL_HI);
1565 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1566 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1567 MipsII::MO_DTPREL_LO);
1568 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1569 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1570 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1574 if (model == TLSModel::InitialExec) {
1575 // Initial Exec TLS Model
1576 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1577 MipsII::MO_GOTTPREL);
1578 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1580 Offset = DAG.getLoad(PtrVT, DL,
1581 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1582 false, false, false, 0);
1584 // Local Exec TLS Model
1585 assert(model == TLSModel::LocalExec);
1586 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1587 MipsII::MO_TPREL_HI);
1588 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1589 MipsII::MO_TPREL_LO);
1590 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1591 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1592 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1595 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1596 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1599 SDValue MipsTargetLowering::
1600 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1602 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1603 return getAddrNonPIC(Op, DAG);
1605 return getAddrLocal(Op, DAG, HasMips64);
1608 SDValue MipsTargetLowering::
1609 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1611 // gp_rel relocation
1612 // FIXME: we should reference the constant pool using small data sections,
1613 // but the asm printer currently doesn't support this feature without
1614 // hacking it. This feature should come soon so we can uncomment the
1616 //if (IsInSmallSection(C->getType())) {
1617 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1618 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1619 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1621 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1622 return getAddrNonPIC(Op, DAG);
1624 return getAddrLocal(Op, DAG, HasMips64);
1627 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1628 MachineFunction &MF = DAG.getMachineFunction();
1629 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1632 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1635 // vastart just stores the address of the VarArgsFrameIndex slot into the
1636 // memory location argument.
1637 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1638 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1639 MachinePointerInfo(SV), false, false, 0);
1642 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1643 EVT TyX = Op.getOperand(0).getValueType();
1644 EVT TyY = Op.getOperand(1).getValueType();
1645 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1646 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1650 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1652 SDValue X = (TyX == MVT::f32) ?
1653 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1654 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1656 SDValue Y = (TyY == MVT::f32) ?
1657 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1658 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1662 // ext E, Y, 31, 1 ; extract bit31 of Y
1663 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1664 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1665 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1668 // srl SrlX, SllX, 1
1670 // sll SllY, SrlX, 31
1671 // or Or, SrlX, SllY
1672 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1673 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1674 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1675 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1676 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1679 if (TyX == MVT::f32)
1680 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1682 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1683 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1684 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1687 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1688 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1689 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1690 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1691 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1694 // Bitcast to integer nodes.
1695 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1696 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1699 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1700 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1701 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1702 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1704 if (WidthX > WidthY)
1705 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1706 else if (WidthY > WidthX)
1707 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1709 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1710 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1711 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1714 // (d)sll SllX, X, 1
1715 // (d)srl SrlX, SllX, 1
1716 // (d)srl SrlY, Y, width(Y)-1
1717 // (d)sll SllY, SrlX, width(Y)-1
1718 // or Or, SrlX, SllY
1719 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1720 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1721 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1722 DAG.getConstant(WidthY - 1, MVT::i32));
1724 if (WidthX > WidthY)
1725 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1726 else if (WidthY > WidthX)
1727 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1729 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1730 DAG.getConstant(WidthX - 1, MVT::i32));
1731 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1732 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1736 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1737 if (Subtarget->hasMips64())
1738 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1740 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1743 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1744 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1747 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1749 SDValue X = (Op.getValueType() == MVT::f32) ?
1750 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1751 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1756 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1757 DAG.getRegister(Mips::ZERO, MVT::i32),
1758 DAG.getConstant(31, MVT::i32), Const1, X);
1760 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1761 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1764 if (Op.getValueType() == MVT::f32)
1765 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1767 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1768 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1769 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1772 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1773 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1776 // Bitcast to integer node.
1777 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1781 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1782 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1783 DAG.getConstant(63, MVT::i32), Const1, X);
1785 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1786 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1789 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1793 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1794 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1795 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1797 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1800 SDValue MipsTargetLowering::
1801 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1803 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1804 "Frame address can only be determined for current frame.");
1806 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1807 MFI->setFrameAddressIsTaken(true);
1808 EVT VT = Op.getValueType();
1810 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1811 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1815 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1816 SelectionDAG &DAG) const {
1818 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1819 "Return address can be determined only for current frame.");
1821 MachineFunction &MF = DAG.getMachineFunction();
1822 MachineFrameInfo *MFI = MF.getFrameInfo();
1823 MVT VT = Op.getSimpleValueType();
1824 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1825 MFI->setReturnAddressIsTaken(true);
1827 // Return RA, which contains the return address. Mark it an implicit live-in.
1828 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1829 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1832 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1833 // generated from __builtin_eh_return (offset, handler)
1834 // The effect of this is to adjust the stack pointer by "offset"
1835 // and then branch to "handler".
1836 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1838 MachineFunction &MF = DAG.getMachineFunction();
1839 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1841 MipsFI->setCallsEhReturn();
1842 SDValue Chain = Op.getOperand(0);
1843 SDValue Offset = Op.getOperand(1);
1844 SDValue Handler = Op.getOperand(2);
1846 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1848 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1849 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1850 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1851 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1852 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1853 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1854 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1855 DAG.getRegister(OffsetReg, Ty),
1856 DAG.getRegister(AddrReg, getPointerTy()),
1860 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1861 SelectionDAG &DAG) const {
1862 // FIXME: Need pseudo-fence for 'singlethread' fences
1863 // FIXME: Set SType for weaker fences where supported/appropriate.
1866 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1867 DAG.getConstant(SType, MVT::i32));
1870 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1871 SelectionDAG &DAG) const {
1873 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1874 SDValue Shamt = Op.getOperand(2);
1877 // lo = (shl lo, shamt)
1878 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1881 // hi = (shl lo, shamt[4:0])
1882 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1883 DAG.getConstant(-1, MVT::i32));
1884 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1885 DAG.getConstant(1, MVT::i32));
1886 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1888 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1889 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1890 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1891 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1892 DAG.getConstant(0x20, MVT::i32));
1893 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1894 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1895 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1897 SDValue Ops[2] = {Lo, Hi};
1898 return DAG.getMergeValues(Ops, 2, DL);
1901 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1904 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1905 SDValue Shamt = Op.getOperand(2);
1908 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1910 // hi = (sra hi, shamt)
1912 // hi = (srl hi, shamt)
1915 // lo = (sra hi, shamt[4:0])
1916 // hi = (sra hi, 31)
1918 // lo = (srl hi, shamt[4:0])
1920 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1921 DAG.getConstant(-1, MVT::i32));
1922 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1923 DAG.getConstant(1, MVT::i32));
1924 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1925 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1926 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1927 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1929 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1930 DAG.getConstant(0x20, MVT::i32));
1931 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1932 DAG.getConstant(31, MVT::i32));
1933 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1934 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1935 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1938 SDValue Ops[2] = {Lo, Hi};
1939 return DAG.getMergeValues(Ops, 2, DL);
1942 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1943 SDValue Chain, SDValue Src, unsigned Offset) {
1944 SDValue Ptr = LD->getBasePtr();
1945 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1946 EVT BasePtrVT = Ptr.getValueType();
1948 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1951 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1952 DAG.getConstant(Offset, BasePtrVT));
1954 SDValue Ops[] = { Chain, Ptr, Src };
1955 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1956 LD->getMemOperand());
1959 // Expand an unaligned 32 or 64-bit integer load node.
1960 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1961 LoadSDNode *LD = cast<LoadSDNode>(Op);
1962 EVT MemVT = LD->getMemoryVT();
1964 // Return if load is aligned or if MemVT is neither i32 nor i64.
1965 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1966 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1969 bool IsLittle = Subtarget->isLittle();
1970 EVT VT = Op.getValueType();
1971 ISD::LoadExtType ExtType = LD->getExtensionType();
1972 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1974 assert((VT == MVT::i32) || (VT == MVT::i64));
1977 // (set dst, (i64 (load baseptr)))
1979 // (set tmp, (ldl (add baseptr, 7), undef))
1980 // (set dst, (ldr baseptr, tmp))
1981 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1982 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1984 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1988 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1990 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1994 // (set dst, (i32 (load baseptr))) or
1995 // (set dst, (i64 (sextload baseptr))) or
1996 // (set dst, (i64 (extload baseptr)))
1998 // (set tmp, (lwl (add baseptr, 3), undef))
1999 // (set dst, (lwr baseptr, tmp))
2000 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2001 (ExtType == ISD::EXTLOAD))
2004 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2007 // (set dst, (i64 (zextload baseptr)))
2009 // (set tmp0, (lwl (add baseptr, 3), undef))
2010 // (set tmp1, (lwr baseptr, tmp0))
2011 // (set tmp2, (shl tmp1, 32))
2012 // (set dst, (srl tmp2, 32))
2014 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2015 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2016 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2017 SDValue Ops[] = { SRL, LWR.getValue(1) };
2018 return DAG.getMergeValues(Ops, 2, DL);
2021 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2022 SDValue Chain, unsigned Offset) {
2023 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2024 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2026 SDVTList VTList = DAG.getVTList(MVT::Other);
2029 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2030 DAG.getConstant(Offset, BasePtrVT));
2032 SDValue Ops[] = { Chain, Value, Ptr };
2033 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2034 SD->getMemOperand());
2037 // Expand an unaligned 32 or 64-bit integer store node.
2038 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2040 SDValue Value = SD->getValue(), Chain = SD->getChain();
2041 EVT VT = Value.getValueType();
2044 // (store val, baseptr) or
2045 // (truncstore val, baseptr)
2047 // (swl val, (add baseptr, 3))
2048 // (swr val, baseptr)
2049 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2050 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2052 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2055 assert(VT == MVT::i64);
2058 // (store val, baseptr)
2060 // (sdl val, (add baseptr, 7))
2061 // (sdr val, baseptr)
2062 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2063 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2066 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2067 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2068 SDValue Val = SD->getValue();
2070 if (Val.getOpcode() != ISD::FP_TO_SINT)
2073 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2074 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2077 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2078 SD->getPointerInfo(), SD->isVolatile(),
2079 SD->isNonTemporal(), SD->getAlignment());
2082 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2083 StoreSDNode *SD = cast<StoreSDNode>(Op);
2084 EVT MemVT = SD->getMemoryVT();
2086 // Lower unaligned integer stores.
2087 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2088 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2089 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2091 return lowerFP_TO_SINT_STORE(SD, DAG);
2094 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2095 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2096 || cast<ConstantSDNode>
2097 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2098 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2102 // (add (frameaddr 0), (frame_to_args_offset))
2103 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2104 // (add FrameObject, 0)
2105 // where FrameObject is a fixed StackObject with offset 0 which points to
2106 // the old stack pointer.
2107 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2108 EVT ValTy = Op->getValueType(0);
2109 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2110 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2111 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2112 DAG.getConstant(0, ValTy));
2115 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2116 SelectionDAG &DAG) const {
2117 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2118 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2120 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2123 //===----------------------------------------------------------------------===//
2124 // Calling Convention Implementation
2125 //===----------------------------------------------------------------------===//
2127 //===----------------------------------------------------------------------===//
2128 // TODO: Implement a generic logic using tblgen that can support this.
2129 // Mips O32 ABI rules:
2131 // i32 - Passed in A0, A1, A2, A3 and stack
2132 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2133 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2134 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2135 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2136 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2139 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2140 //===----------------------------------------------------------------------===//
2142 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2143 MVT LocVT, CCValAssign::LocInfo LocInfo,
2144 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2146 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2148 static const uint16_t IntRegs[] = {
2149 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2151 static const uint16_t F32Regs[] = {
2152 Mips::F12, Mips::F14
2154 static const uint16_t F64Regs[] = {
2158 // Do not process byval args here.
2159 if (ArgFlags.isByVal())
2162 // Promote i8 and i16
2163 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2165 if (ArgFlags.isSExt())
2166 LocInfo = CCValAssign::SExt;
2167 else if (ArgFlags.isZExt())
2168 LocInfo = CCValAssign::ZExt;
2170 LocInfo = CCValAssign::AExt;
2175 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2176 // is true: function is vararg, argument is 3rd or higher, there is previous
2177 // argument which is not f32 or f64.
2178 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2179 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2180 unsigned OrigAlign = ArgFlags.getOrigAlign();
2181 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2183 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2184 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2185 // If this is the first part of an i64 arg,
2186 // the allocated register must be either A0 or A2.
2187 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2188 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2190 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2191 // Allocate int register and shadow next int register. If first
2192 // available register is Mips::A1 or Mips::A3, shadow it too.
2193 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2194 if (Reg == Mips::A1 || Reg == Mips::A3)
2195 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2196 State.AllocateReg(IntRegs, IntRegsSize);
2198 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2199 // we are guaranteed to find an available float register
2200 if (ValVT == MVT::f32) {
2201 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2202 // Shadow int register
2203 State.AllocateReg(IntRegs, IntRegsSize);
2205 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2206 // Shadow int registers
2207 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2208 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2209 State.AllocateReg(IntRegs, IntRegsSize);
2210 State.AllocateReg(IntRegs, IntRegsSize);
2213 llvm_unreachable("Cannot handle this ValVT.");
2216 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2218 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2220 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2225 #include "MipsGenCallingConv.inc"
2227 //===----------------------------------------------------------------------===//
2228 // Call Calling Convention Implementation
2229 //===----------------------------------------------------------------------===//
2231 static const unsigned O32IntRegsSize = 4;
2233 // Return next O32 integer argument register.
2234 static unsigned getNextIntArgReg(unsigned Reg) {
2235 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2236 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2240 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2241 SDValue Chain, SDValue Arg, SDLoc DL,
2242 bool IsTailCall, SelectionDAG &DAG) const {
2244 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2245 DAG.getIntPtrConstant(Offset));
2246 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2250 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2251 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2252 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2253 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2254 /*isVolatile=*/ true, false, 0);
2257 void MipsTargetLowering::
2258 getOpndList(SmallVectorImpl<SDValue> &Ops,
2259 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2260 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2261 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2262 // Insert node "GP copy globalreg" before call to function.
2264 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2265 // in PIC mode) allow symbols to be resolved via lazy binding.
2266 // The lazy binding stub requires GP to point to the GOT.
2267 if (IsPICCall && !InternalLinkage) {
2268 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2269 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2270 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2273 // Build a sequence of copy-to-reg nodes chained together with token
2274 // chain and flag operands which copy the outgoing args into registers.
2275 // The InFlag in necessary since all emitted instructions must be
2279 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2280 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2281 RegsToPass[i].second, InFlag);
2282 InFlag = Chain.getValue(1);
2285 // Add argument registers to the end of the list so that they are
2286 // known live into the call.
2287 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2288 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2289 RegsToPass[i].second.getValueType()));
2291 // Add a register mask operand representing the call-preserved registers.
2292 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2293 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2294 assert(Mask && "Missing call preserved mask for calling convention");
2295 if (Subtarget->inMips16HardFloat()) {
2296 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2297 llvm::StringRef Sym = G->getGlobal()->getName();
2298 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2299 if (F->hasFnAttribute("__Mips16RetHelper")) {
2300 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2304 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2306 if (InFlag.getNode())
2307 Ops.push_back(InFlag);
2310 /// LowerCall - functions arguments are copied from virtual regs to
2311 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2313 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2314 SmallVectorImpl<SDValue> &InVals) const {
2315 SelectionDAG &DAG = CLI.DAG;
2317 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2318 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2319 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2320 SDValue Chain = CLI.Chain;
2321 SDValue Callee = CLI.Callee;
2322 bool &IsTailCall = CLI.IsTailCall;
2323 CallingConv::ID CallConv = CLI.CallConv;
2324 bool IsVarArg = CLI.IsVarArg;
2326 MachineFunction &MF = DAG.getMachineFunction();
2327 MachineFrameInfo *MFI = MF.getFrameInfo();
2328 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2329 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2331 // Analyze operands of the call, assigning locations to each operand.
2332 SmallVector<CCValAssign, 16> ArgLocs;
2333 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2334 getTargetMachine(), ArgLocs, *DAG.getContext());
2335 MipsCC::SpecialCallingConvType SpecialCallingConv =
2336 getSpecialCallingConv(Callee);
2337 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo, SpecialCallingConv);
2339 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2340 getTargetMachine().Options.UseSoftFloat,
2341 Callee.getNode(), CLI.Args);
2343 // Get a count of how many bytes are to be pushed on the stack.
2344 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2346 // Check if it's really possible to do a tail call.
2349 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2350 *MF.getInfo<MipsFunctionInfo>());
2355 // Chain is the output chain of the last Load/Store or CopyToReg node.
2356 // ByValChain is the output chain of the last Memcpy node created for copying
2357 // byval arguments to the stack.
2358 unsigned StackAlignment = TFL->getStackAlignment();
2359 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2360 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2363 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2365 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2366 IsN64 ? Mips::SP_64 : Mips::SP,
2369 // With EABI is it possible to have 16 args on registers.
2370 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2371 SmallVector<SDValue, 8> MemOpChains;
2372 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2374 // Walk the register/memloc assignments, inserting copies/loads.
2375 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2376 SDValue Arg = OutVals[i];
2377 CCValAssign &VA = ArgLocs[i];
2378 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2379 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2382 if (Flags.isByVal()) {
2383 assert(Flags.getByValSize() &&
2384 "ByVal args of size 0 should have been ignored by front-end.");
2385 assert(ByValArg != MipsCCInfo.byval_end());
2386 assert(!IsTailCall &&
2387 "Do not tail-call optimize if there is a byval argument.");
2388 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2389 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2394 // Promote the value if needed.
2395 switch (VA.getLocInfo()) {
2396 default: llvm_unreachable("Unknown loc info!");
2397 case CCValAssign::Full:
2398 if (VA.isRegLoc()) {
2399 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2400 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2401 (ValVT == MVT::i64 && LocVT == MVT::f64))
2402 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2403 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2404 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2405 Arg, DAG.getConstant(0, MVT::i32));
2406 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2407 Arg, DAG.getConstant(1, MVT::i32));
2408 if (!Subtarget->isLittle())
2410 unsigned LocRegLo = VA.getLocReg();
2411 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2412 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2413 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2418 case CCValAssign::SExt:
2419 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2421 case CCValAssign::ZExt:
2422 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2424 case CCValAssign::AExt:
2425 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2429 // Arguments that can be passed on register must be kept at
2430 // RegsToPass vector
2431 if (VA.isRegLoc()) {
2432 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2436 // Register can't get to this point...
2437 assert(VA.isMemLoc());
2439 // emit ISD::STORE whichs stores the
2440 // parameter value to a stack Location
2441 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2442 Chain, Arg, DL, IsTailCall, DAG));
2445 // Transform all store nodes into one single node because all store
2446 // nodes are independent of each other.
2447 if (!MemOpChains.empty())
2448 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2449 &MemOpChains[0], MemOpChains.size());
2451 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2452 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2453 // node so that legalize doesn't hack it.
2454 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2455 bool GlobalOrExternal = false, InternalLinkage = false;
2458 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2460 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2462 if (InternalLinkage)
2463 Callee = getAddrLocal(Callee, DAG, HasMips64);
2465 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2466 MipsII::MO_CALL_LO16);
2468 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2470 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2471 MipsII::MO_NO_FLAG);
2472 GlobalOrExternal = true;
2474 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2475 if (!IsN64 && !IsPIC) // !N64 && static
2476 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2477 MipsII::MO_NO_FLAG);
2479 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2480 MipsII::MO_CALL_LO16);
2482 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2484 GlobalOrExternal = true;
2487 SmallVector<SDValue, 8> Ops(1, Chain);
2488 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2490 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2491 CLI, Callee, Chain);
2494 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2496 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2497 SDValue InFlag = Chain.getValue(1);
2499 // Create the CALLSEQ_END node.
2500 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2501 DAG.getIntPtrConstant(0, true), InFlag, DL);
2502 InFlag = Chain.getValue(1);
2504 // Handle result values, copying them out of physregs into vregs that we
2506 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2507 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2510 /// LowerCallResult - Lower the result values of a call into the
2511 /// appropriate copies out of appropriate physical registers.
2513 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2514 CallingConv::ID CallConv, bool IsVarArg,
2515 const SmallVectorImpl<ISD::InputArg> &Ins,
2516 SDLoc DL, SelectionDAG &DAG,
2517 SmallVectorImpl<SDValue> &InVals,
2518 const SDNode *CallNode,
2519 const Type *RetTy) const {
2520 // Assign locations to each value returned by this call.
2521 SmallVector<CCValAssign, 16> RVLocs;
2522 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2523 getTargetMachine(), RVLocs, *DAG.getContext());
2524 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2526 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2529 // Copy all of the result registers out of their specified physreg.
2530 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2531 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2532 RVLocs[i].getLocVT(), InFlag);
2533 Chain = Val.getValue(1);
2534 InFlag = Val.getValue(2);
2536 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2537 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2539 InVals.push_back(Val);
2545 //===----------------------------------------------------------------------===//
2546 // Formal Arguments Calling Convention Implementation
2547 //===----------------------------------------------------------------------===//
2548 /// LowerFormalArguments - transform physical registers into virtual registers
2549 /// and generate load operations for arguments places on the stack.
2551 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2552 CallingConv::ID CallConv,
2554 const SmallVectorImpl<ISD::InputArg> &Ins,
2555 SDLoc DL, SelectionDAG &DAG,
2556 SmallVectorImpl<SDValue> &InVals)
2558 MachineFunction &MF = DAG.getMachineFunction();
2559 MachineFrameInfo *MFI = MF.getFrameInfo();
2560 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2562 MipsFI->setVarArgsFrameIndex(0);
2564 // Used with vargs to acumulate store chains.
2565 std::vector<SDValue> OutChains;
2567 // Assign locations to all of the incoming arguments.
2568 SmallVector<CCValAssign, 16> ArgLocs;
2569 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2570 getTargetMachine(), ArgLocs, *DAG.getContext());
2571 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2572 Function::const_arg_iterator FuncArg =
2573 DAG.getMachineFunction().getFunction()->arg_begin();
2574 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2576 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2577 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2578 MipsCCInfo.hasByValArg());
2580 unsigned CurArgIdx = 0;
2581 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2583 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2584 CCValAssign &VA = ArgLocs[i];
2585 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2586 CurArgIdx = Ins[i].OrigArgIndex;
2587 EVT ValVT = VA.getValVT();
2588 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2589 bool IsRegLoc = VA.isRegLoc();
2591 if (Flags.isByVal()) {
2592 assert(Flags.getByValSize() &&
2593 "ByVal args of size 0 should have been ignored by front-end.");
2594 assert(ByValArg != MipsCCInfo.byval_end());
2595 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2596 MipsCCInfo, *ByValArg);
2601 // Arguments stored on registers
2603 EVT RegVT = VA.getLocVT();
2604 unsigned ArgReg = VA.getLocReg();
2605 const TargetRegisterClass *RC;
2607 if (RegVT == MVT::i32)
2608 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2609 &Mips::CPURegsRegClass;
2610 else if (RegVT == MVT::i64)
2611 RC = &Mips::CPU64RegsRegClass;
2612 else if (RegVT == MVT::f32)
2613 RC = &Mips::FGR32RegClass;
2614 else if (RegVT == MVT::f64)
2615 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2617 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2619 // Transform the arguments stored on
2620 // physical registers into virtual ones
2621 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2622 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2624 // If this is an 8 or 16-bit value, it has been passed promoted
2625 // to 32 bits. Insert an assert[sz]ext to capture this, then
2626 // truncate to the right size.
2627 if (VA.getLocInfo() != CCValAssign::Full) {
2628 unsigned Opcode = 0;
2629 if (VA.getLocInfo() == CCValAssign::SExt)
2630 Opcode = ISD::AssertSext;
2631 else if (VA.getLocInfo() == CCValAssign::ZExt)
2632 Opcode = ISD::AssertZext;
2634 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2635 DAG.getValueType(ValVT));
2636 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2639 // Handle floating point arguments passed in integer registers and
2640 // long double arguments passed in floating point registers.
2641 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2642 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2643 (RegVT == MVT::f64 && ValVT == MVT::i64))
2644 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2645 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2646 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2647 getNextIntArgReg(ArgReg), RC);
2648 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2649 if (!Subtarget->isLittle())
2650 std::swap(ArgValue, ArgValue2);
2651 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2652 ArgValue, ArgValue2);
2655 InVals.push_back(ArgValue);
2656 } else { // VA.isRegLoc()
2659 assert(VA.isMemLoc());
2661 // The stack pointer offset is relative to the caller stack frame.
2662 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2663 VA.getLocMemOffset(), true);
2665 // Create load nodes to retrieve arguments from the stack
2666 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2667 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2668 MachinePointerInfo::getFixedStack(FI),
2669 false, false, false, 0));
2673 // The mips ABIs for returning structs by value requires that we copy
2674 // the sret argument into $v0 for the return. Save the argument into
2675 // a virtual register so that we can access it from the return points.
2676 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2677 unsigned Reg = MipsFI->getSRetReturnReg();
2679 Reg = MF.getRegInfo().
2680 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2681 MipsFI->setSRetReturnReg(Reg);
2683 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2684 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2688 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2690 // All stores are grouped in one node to allow the matching between
2691 // the size of Ins and InVals. This only happens when on varg functions
2692 if (!OutChains.empty()) {
2693 OutChains.push_back(Chain);
2694 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2695 &OutChains[0], OutChains.size());
2701 //===----------------------------------------------------------------------===//
2702 // Return Value Calling Convention Implementation
2703 //===----------------------------------------------------------------------===//
2706 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2707 MachineFunction &MF, bool IsVarArg,
2708 const SmallVectorImpl<ISD::OutputArg> &Outs,
2709 LLVMContext &Context) const {
2710 SmallVector<CCValAssign, 16> RVLocs;
2711 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2713 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2717 MipsTargetLowering::LowerReturn(SDValue Chain,
2718 CallingConv::ID CallConv, bool IsVarArg,
2719 const SmallVectorImpl<ISD::OutputArg> &Outs,
2720 const SmallVectorImpl<SDValue> &OutVals,
2721 SDLoc DL, SelectionDAG &DAG) const {
2722 // CCValAssign - represent the assignment of
2723 // the return value to a location
2724 SmallVector<CCValAssign, 16> RVLocs;
2725 MachineFunction &MF = DAG.getMachineFunction();
2727 // CCState - Info about the registers and stack slot.
2728 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2730 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2732 // Analyze return values.
2733 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2734 MF.getFunction()->getReturnType());
2737 SmallVector<SDValue, 4> RetOps(1, Chain);
2739 // Copy the result values into the output registers.
2740 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2741 SDValue Val = OutVals[i];
2742 CCValAssign &VA = RVLocs[i];
2743 assert(VA.isRegLoc() && "Can only return in registers!");
2745 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2746 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2748 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2750 // Guarantee that all emitted copies are stuck together with flags.
2751 Flag = Chain.getValue(1);
2752 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2755 // The mips ABIs for returning structs by value requires that we copy
2756 // the sret argument into $v0 for the return. We saved the argument into
2757 // a virtual register in the entry block, so now we copy the value out
2759 if (MF.getFunction()->hasStructRetAttr()) {
2760 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2761 unsigned Reg = MipsFI->getSRetReturnReg();
2764 llvm_unreachable("sret virtual register not created in the entry block");
2765 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2766 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2768 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2769 Flag = Chain.getValue(1);
2770 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2773 RetOps[0] = Chain; // Update chain.
2775 // Add the flag if we have it.
2777 RetOps.push_back(Flag);
2779 // Return on Mips is always a "jr $ra"
2780 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2783 //===----------------------------------------------------------------------===//
2784 // Mips Inline Assembly Support
2785 //===----------------------------------------------------------------------===//
2787 /// getConstraintType - Given a constraint letter, return the type of
2788 /// constraint it is for this target.
2789 MipsTargetLowering::ConstraintType MipsTargetLowering::
2790 getConstraintType(const std::string &Constraint) const
2792 // Mips specific constrainy
2793 // GCC config/mips/constraints.md
2795 // 'd' : An address register. Equivalent to r
2796 // unless generating MIPS16 code.
2797 // 'y' : Equivalent to r; retained for
2798 // backwards compatibility.
2799 // 'c' : A register suitable for use in an indirect
2800 // jump. This will always be $25 for -mabicalls.
2801 // 'l' : The lo register. 1 word storage.
2802 // 'x' : The hilo register pair. Double word storage.
2803 if (Constraint.size() == 1) {
2804 switch (Constraint[0]) {
2812 return C_RegisterClass;
2817 return TargetLowering::getConstraintType(Constraint);
2820 /// Examine constraint type and operand type and determine a weight value.
2821 /// This object must already have been set up with the operand type
2822 /// and the current alternative constraint selected.
2823 TargetLowering::ConstraintWeight
2824 MipsTargetLowering::getSingleConstraintMatchWeight(
2825 AsmOperandInfo &info, const char *constraint) const {
2826 ConstraintWeight weight = CW_Invalid;
2827 Value *CallOperandVal = info.CallOperandVal;
2828 // If we don't have a value, we can't do a match,
2829 // but allow it at the lowest weight.
2830 if (CallOperandVal == NULL)
2832 Type *type = CallOperandVal->getType();
2833 // Look at the constraint type.
2834 switch (*constraint) {
2836 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2840 if (type->isIntegerTy())
2841 weight = CW_Register;
2844 if (type->isFloatTy())
2845 weight = CW_Register;
2847 case 'c': // $25 for indirect jumps
2848 case 'l': // lo register
2849 case 'x': // hilo register pair
2850 if (type->isIntegerTy())
2851 weight = CW_SpecificReg;
2853 case 'I': // signed 16 bit immediate
2854 case 'J': // integer zero
2855 case 'K': // unsigned 16 bit immediate
2856 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2857 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2858 case 'O': // signed 15 bit immediate (+- 16383)
2859 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2860 if (isa<ConstantInt>(CallOperandVal))
2861 weight = CW_Constant;
2870 /// Given a register class constraint, like 'r', if this corresponds directly
2871 /// to an LLVM register class, return a register of 0 and the register class
2873 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2874 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2876 if (Constraint.size() == 1) {
2877 switch (Constraint[0]) {
2878 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2879 case 'y': // Same as 'r'. Exists for compatibility.
2881 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2882 if (Subtarget->inMips16Mode())
2883 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2884 return std::make_pair(0U, &Mips::CPURegsRegClass);
2886 if (VT == MVT::i64 && !HasMips64)
2887 return std::make_pair(0U, &Mips::CPURegsRegClass);
2888 if (VT == MVT::i64 && HasMips64)
2889 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
2890 // This will generate an error message
2891 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2894 return std::make_pair(0U, &Mips::FGR32RegClass);
2895 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2896 if (Subtarget->isFP64bit())
2897 return std::make_pair(0U, &Mips::FGR64RegClass);
2898 return std::make_pair(0U, &Mips::AFGR64RegClass);
2901 case 'c': // register suitable for indirect jump
2903 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
2904 assert(VT == MVT::i64 && "Unexpected type.");
2905 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
2906 case 'l': // register suitable for indirect jump
2908 return std::make_pair((unsigned)Mips::LO, &Mips::LORegsRegClass);
2909 return std::make_pair((unsigned)Mips::LO64, &Mips::LORegs64RegClass);
2910 case 'x': // register suitable for indirect jump
2911 // Fixme: Not triggering the use of both hi and low
2912 // This will generate an error message
2913 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2916 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2919 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2920 /// vector. If it is invalid, don't add anything to Ops.
2921 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2922 std::string &Constraint,
2923 std::vector<SDValue>&Ops,
2924 SelectionDAG &DAG) const {
2925 SDValue Result(0, 0);
2927 // Only support length 1 constraints for now.
2928 if (Constraint.length() > 1) return;
2930 char ConstraintLetter = Constraint[0];
2931 switch (ConstraintLetter) {
2932 default: break; // This will fall through to the generic implementation
2933 case 'I': // Signed 16 bit constant
2934 // If this fails, the parent routine will give an error
2935 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2936 EVT Type = Op.getValueType();
2937 int64_t Val = C->getSExtValue();
2938 if (isInt<16>(Val)) {
2939 Result = DAG.getTargetConstant(Val, Type);
2944 case 'J': // integer zero
2945 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2946 EVT Type = Op.getValueType();
2947 int64_t Val = C->getZExtValue();
2949 Result = DAG.getTargetConstant(0, Type);
2954 case 'K': // unsigned 16 bit immediate
2955 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2956 EVT Type = Op.getValueType();
2957 uint64_t Val = (uint64_t)C->getZExtValue();
2958 if (isUInt<16>(Val)) {
2959 Result = DAG.getTargetConstant(Val, Type);
2964 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2965 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2966 EVT Type = Op.getValueType();
2967 int64_t Val = C->getSExtValue();
2968 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
2969 Result = DAG.getTargetConstant(Val, Type);
2974 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2975 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2976 EVT Type = Op.getValueType();
2977 int64_t Val = C->getSExtValue();
2978 if ((Val >= -65535) && (Val <= -1)) {
2979 Result = DAG.getTargetConstant(Val, Type);
2984 case 'O': // signed 15 bit immediate
2985 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2986 EVT Type = Op.getValueType();
2987 int64_t Val = C->getSExtValue();
2988 if ((isInt<15>(Val))) {
2989 Result = DAG.getTargetConstant(Val, Type);
2994 case 'P': // immediate in the range of 1 to 65535 (inclusive)
2995 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2996 EVT Type = Op.getValueType();
2997 int64_t Val = C->getSExtValue();
2998 if ((Val <= 65535) && (Val >= 1)) {
2999 Result = DAG.getTargetConstant(Val, Type);
3006 if (Result.getNode()) {
3007 Ops.push_back(Result);
3011 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3015 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3016 // No global is ever allowed as a base.
3021 case 0: // "r+i" or just "i", depending on HasBaseReg.
3024 if (!AM.HasBaseReg) // allow "r+i".
3026 return false; // disallow "r+r" or "r+r+i".
3035 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3036 // The Mips target isn't yet aware of offsets.
3040 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3042 bool IsMemset, bool ZeroMemset,
3044 MachineFunction &MF) const {
3045 if (Subtarget->hasMips64())
3051 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3052 if (VT != MVT::f32 && VT != MVT::f64)
3054 if (Imm.isNegZero())
3056 return Imm.isZero();
3059 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3061 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3063 return TargetLowering::getJumpTableEncoding();
3066 /// This function returns true if CallSym is a long double emulation routine.
3067 static bool isF128SoftLibCall(const char *CallSym) {
3068 const char *const LibCalls[] =
3069 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3070 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3071 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3072 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3073 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3074 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3075 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3076 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3079 const char * const *End = LibCalls + array_lengthof(LibCalls);
3081 // Check that LibCalls is sorted alphabetically.
3082 MipsTargetLowering::LTStr Comp;
3085 for (const char * const *I = LibCalls; I < End - 1; ++I)
3086 assert(Comp(*I, *(I + 1)));
3089 return std::binary_search(LibCalls, End, CallSym, Comp);
3092 /// This function returns true if Ty is fp128 or i128 which was originally a
3094 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3095 if (Ty->isFP128Ty())
3098 const ExternalSymbolSDNode *ES =
3099 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3101 // If the Ty is i128 and the function being called is a long double emulation
3102 // routine, then the original type is f128.
3103 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3106 MipsTargetLowering::MipsCC::SpecialCallingConvType
3107 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3108 MipsCC::SpecialCallingConvType SpecialCallingConv =
3109 MipsCC::NoSpecialCallingConv;;
3110 if (Subtarget->inMips16HardFloat()) {
3111 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3112 llvm::StringRef Sym = G->getGlobal()->getName();
3113 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3114 if (F->hasFnAttribute("__Mips16RetHelper")) {
3115 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3119 return SpecialCallingConv;
3122 MipsTargetLowering::MipsCC::MipsCC(
3123 CallingConv::ID CC, bool IsO32_, CCState &Info,
3124 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3125 : CCInfo(Info), CallConv(CC), IsO32(IsO32_),
3126 SpecialCallingConv(SpecialCallingConv_){
3127 // Pre-allocate reserved argument area.
3128 CCInfo.AllocateStack(reservedArgArea(), 1);
3132 void MipsTargetLowering::MipsCC::
3133 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3134 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3135 std::vector<ArgListEntry> &FuncArgs) {
3136 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3137 "CallingConv::Fast shouldn't be used for vararg functions.");
3139 unsigned NumOpnds = Args.size();
3140 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3142 for (unsigned I = 0; I != NumOpnds; ++I) {
3143 MVT ArgVT = Args[I].VT;
3144 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3147 if (ArgFlags.isByVal()) {
3148 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3152 if (IsVarArg && !Args[I].IsFixed)
3153 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3155 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3157 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3162 dbgs() << "Call operand #" << I << " has unhandled type "
3163 << EVT(ArgVT).getEVTString();
3165 llvm_unreachable(0);
3170 void MipsTargetLowering::MipsCC::
3171 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3172 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3173 unsigned NumArgs = Args.size();
3174 llvm::CCAssignFn *FixedFn = fixedArgFn();
3175 unsigned CurArgIdx = 0;
3177 for (unsigned I = 0; I != NumArgs; ++I) {
3178 MVT ArgVT = Args[I].VT;
3179 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3180 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3181 CurArgIdx = Args[I].OrigArgIndex;
3183 if (ArgFlags.isByVal()) {
3184 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3188 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3190 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3194 dbgs() << "Formal Arg #" << I << " has unhandled type "
3195 << EVT(ArgVT).getEVTString();
3197 llvm_unreachable(0);
3201 template<typename Ty>
3202 void MipsTargetLowering::MipsCC::
3203 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3204 const SDNode *CallNode, const Type *RetTy) const {
3207 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3208 Fn = RetCC_F128Soft;
3212 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3213 MVT VT = RetVals[I].VT;
3214 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3215 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3217 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3219 dbgs() << "Call result #" << I << " has unhandled type "
3220 << EVT(VT).getEVTString() << '\n';
3222 llvm_unreachable(0);
3227 void MipsTargetLowering::MipsCC::
3228 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3229 const SDNode *CallNode, const Type *RetTy) const {
3230 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3233 void MipsTargetLowering::MipsCC::
3234 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3235 const Type *RetTy) const {
3236 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3240 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3242 CCValAssign::LocInfo LocInfo,
3243 ISD::ArgFlagsTy ArgFlags) {
3244 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3246 struct ByValArgInfo ByVal;
3247 unsigned RegSize = regSize();
3248 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3249 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3252 if (useRegsForByval())
3253 allocateRegs(ByVal, ByValSize, Align);
3255 // Allocate space on caller's stack.
3256 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3258 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3260 ByValArgs.push_back(ByVal);
3263 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3264 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3267 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3268 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3271 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3272 return IsO32 ? O32IntRegs : Mips64IntRegs;
3275 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3276 if (CallConv == CallingConv::Fast)
3277 return CC_Mips_FastCC;
3279 if (SpecialCallingConv == Mips16RetHelperConv)
3280 return CC_Mips16RetHelper;
3281 return IsO32 ? CC_MipsO32 : CC_MipsN;
3284 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3285 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
3288 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3289 return IsO32 ? O32IntRegs : Mips64DPRegs;
3292 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3295 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3296 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3297 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3298 "Byval argument's size and alignment should be a multiple of"
3301 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3303 // If Align > RegSize, the first arg register must be even.
3304 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3305 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3309 // Mark the registers allocated.
3310 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3311 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3312 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3315 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3316 const SDNode *CallNode,
3317 bool IsSoftFloat) const {
3318 if (IsSoftFloat || IsO32)
3321 // Check if the original type was fp128.
3322 if (originalTypeIsF128(OrigTy, CallNode)) {
3323 assert(VT == MVT::i64);
3330 void MipsTargetLowering::
3331 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3332 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3333 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3334 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3335 MachineFunction &MF = DAG.getMachineFunction();
3336 MachineFrameInfo *MFI = MF.getFrameInfo();
3337 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3338 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3342 FrameObjOffset = (int)CC.reservedArgArea() -
3343 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3345 FrameObjOffset = ByVal.Address;
3347 // Create frame object.
3348 EVT PtrTy = getPointerTy();
3349 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3350 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3351 InVals.push_back(FIN);
3356 // Copy arg registers.
3357 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3358 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3360 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3361 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3362 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3363 unsigned Offset = I * CC.regSize();
3364 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3365 DAG.getConstant(Offset, PtrTy));
3366 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3367 StorePtr, MachinePointerInfo(FuncArg, Offset),
3369 OutChains.push_back(Store);
3373 // Copy byVal arg to registers and stack.
3374 void MipsTargetLowering::
3375 passByValArg(SDValue Chain, SDLoc DL,
3376 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3377 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3378 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3379 const MipsCC &CC, const ByValArgInfo &ByVal,
3380 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3381 unsigned ByValSize = Flags.getByValSize();
3382 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3383 unsigned RegSize = CC.regSize();
3384 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3385 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3387 if (ByVal.NumRegs) {
3388 const uint16_t *ArgRegs = CC.intArgRegs();
3389 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3392 // Copy words to registers.
3393 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3394 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3395 DAG.getConstant(Offset, PtrTy));
3396 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3397 MachinePointerInfo(), false, false, false,
3399 MemOpChains.push_back(LoadVal.getValue(1));
3400 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3401 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3404 // Return if the struct has been fully copied.
3405 if (ByValSize == Offset)
3408 // Copy the remainder of the byval argument with sub-word loads and shifts.
3409 if (LeftoverBytes) {
3410 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3411 "Size of the remainder should be smaller than RegSize.");
3414 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3415 Offset < ByValSize; LoadSize /= 2) {
3416 unsigned RemSize = ByValSize - Offset;
3418 if (RemSize < LoadSize)
3422 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3423 DAG.getConstant(Offset, PtrTy));
3425 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3426 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3427 false, false, Alignment);
3428 MemOpChains.push_back(LoadVal.getValue(1));
3430 // Shift the loaded value.
3434 Shamt = TotalSizeLoaded;
3436 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3438 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3439 DAG.getConstant(Shamt, MVT::i32));
3442 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3447 TotalSizeLoaded += LoadSize;
3448 Alignment = std::min(Alignment, LoadSize);
3451 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3452 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3457 // Copy remainder of byval arg to it with memcpy.
3458 unsigned MemCpySize = ByValSize - Offset;
3459 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3460 DAG.getConstant(Offset, PtrTy));
3461 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3462 DAG.getIntPtrConstant(ByVal.Address));
3463 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3464 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3465 /*isVolatile=*/false, /*AlwaysInline=*/false,
3466 MachinePointerInfo(0), MachinePointerInfo(0));
3467 MemOpChains.push_back(Chain);
3471 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3472 const MipsCC &CC, SDValue Chain,
3473 SDLoc DL, SelectionDAG &DAG) const {
3474 unsigned NumRegs = CC.numIntArgRegs();
3475 const uint16_t *ArgRegs = CC.intArgRegs();
3476 const CCState &CCInfo = CC.getCCInfo();
3477 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3478 unsigned RegSize = CC.regSize();
3479 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3480 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3481 MachineFunction &MF = DAG.getMachineFunction();
3482 MachineFrameInfo *MFI = MF.getFrameInfo();
3483 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3485 // Offset of the first variable argument from stack pointer.
3489 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3492 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3494 // Record the frame index of the first variable argument
3495 // which is a value necessary to VASTART.
3496 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3497 MipsFI->setVarArgsFrameIndex(FI);
3499 // Copy the integer registers that have not been used for argument passing
3500 // to the argument register save area. For O32, the save area is allocated
3501 // in the caller's stack frame, while for N32/64, it is allocated in the
3502 // callee's stack frame.
3503 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3504 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3505 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3506 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3507 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3508 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3509 MachinePointerInfo(), false, false, 0);
3510 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3511 OutChains.push_back(Store);