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::EH_RETURN, MVT::Other, Custom);
351 setOperationAction(ISD::VAARG, MVT::Other, Expand);
352 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
353 setOperationAction(ISD::VAEND, MVT::Other, Expand);
355 // Use the default for now
356 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
357 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
359 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
360 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
361 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
362 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
364 setInsertFencesForAtomic(true);
366 if (!Subtarget->hasSEInReg()) {
367 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
368 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
371 if (!Subtarget->hasBitCount()) {
372 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
373 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
376 if (!Subtarget->hasSwap()) {
377 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
378 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
382 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
383 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
384 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
385 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
388 setTargetDAGCombine(ISD::SDIVREM);
389 setTargetDAGCombine(ISD::UDIVREM);
390 setTargetDAGCombine(ISD::SELECT);
391 setTargetDAGCombine(ISD::AND);
392 setTargetDAGCombine(ISD::OR);
393 setTargetDAGCombine(ISD::ADD);
395 setMinFunctionAlignment(HasMips64 ? 3 : 2);
397 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
399 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
400 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
402 MaxStoresPerMemcpy = 16;
405 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
406 if (TM.getSubtargetImpl()->inMips16Mode())
407 return llvm::createMips16TargetLowering(TM);
409 return llvm::createMipsSETargetLowering(TM);
412 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
415 return VT.changeVectorElementTypeToInteger();
418 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
419 TargetLowering::DAGCombinerInfo &DCI,
420 const MipsSubtarget *Subtarget) {
421 if (DCI.isBeforeLegalizeOps())
424 EVT Ty = N->getValueType(0);
425 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
426 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
427 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
431 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
432 N->getOperand(0), N->getOperand(1));
433 SDValue InChain = DAG.getEntryNode();
434 SDValue InGlue = DivRem;
437 if (N->hasAnyUseOfValue(0)) {
438 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
440 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
441 InChain = CopyFromLo.getValue(1);
442 InGlue = CopyFromLo.getValue(2);
446 if (N->hasAnyUseOfValue(1)) {
447 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
449 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
455 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
457 default: llvm_unreachable("Unknown fp condition code!");
459 case ISD::SETOEQ: return Mips::FCOND_OEQ;
460 case ISD::SETUNE: return Mips::FCOND_UNE;
462 case ISD::SETOLT: return Mips::FCOND_OLT;
464 case ISD::SETOGT: return Mips::FCOND_OGT;
466 case ISD::SETOLE: return Mips::FCOND_OLE;
468 case ISD::SETOGE: return Mips::FCOND_OGE;
469 case ISD::SETULT: return Mips::FCOND_ULT;
470 case ISD::SETULE: return Mips::FCOND_ULE;
471 case ISD::SETUGT: return Mips::FCOND_UGT;
472 case ISD::SETUGE: return Mips::FCOND_UGE;
473 case ISD::SETUO: return Mips::FCOND_UN;
474 case ISD::SETO: return Mips::FCOND_OR;
476 case ISD::SETONE: return Mips::FCOND_ONE;
477 case ISD::SETUEQ: return Mips::FCOND_UEQ;
482 /// This function returns true if the floating point conditional branches and
483 /// conditional moves which use condition code CC should be inverted.
484 static bool invertFPCondCodeUser(Mips::CondCode CC) {
485 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
488 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
489 "Illegal Condition Code");
494 // Creates and returns an FPCmp node from a setcc node.
495 // Returns Op if setcc is not a floating point comparison.
496 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
497 // must be a SETCC node
498 if (Op.getOpcode() != ISD::SETCC)
501 SDValue LHS = Op.getOperand(0);
503 if (!LHS.getValueType().isFloatingPoint())
506 SDValue RHS = Op.getOperand(1);
509 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
510 // node if necessary.
511 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
513 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
514 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
517 // Creates and returns a CMovFPT/F node.
518 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
519 SDValue False, SDLoc DL) {
520 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
521 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
522 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
524 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
525 True.getValueType(), True, FCC0, False, Cond);
528 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
529 TargetLowering::DAGCombinerInfo &DCI,
530 const MipsSubtarget *Subtarget) {
531 if (DCI.isBeforeLegalizeOps())
534 SDValue SetCC = N->getOperand(0);
536 if ((SetCC.getOpcode() != ISD::SETCC) ||
537 !SetCC.getOperand(0).getValueType().isInteger())
540 SDValue False = N->getOperand(2);
541 EVT FalseTy = False.getValueType();
543 if (!FalseTy.isInteger())
546 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
548 if (!CN || CN->getZExtValue())
552 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
553 SDValue True = N->getOperand(1);
555 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
556 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
558 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
561 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
562 TargetLowering::DAGCombinerInfo &DCI,
563 const MipsSubtarget *Subtarget) {
564 // Pattern match EXT.
565 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
566 // => ext $dst, $src, size, pos
567 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
570 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
571 unsigned ShiftRightOpc = ShiftRight.getOpcode();
573 // Op's first operand must be a shift right.
574 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
577 // The second operand of the shift must be an immediate.
579 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
582 uint64_t Pos = CN->getZExtValue();
583 uint64_t SMPos, SMSize;
585 // Op's second operand must be a shifted mask.
586 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
587 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
590 // Return if the shifted mask does not start at bit 0 or the sum of its size
591 // and Pos exceeds the word's size.
592 EVT ValTy = N->getValueType(0);
593 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
596 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
597 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
598 DAG.getConstant(SMSize, MVT::i32));
601 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
602 TargetLowering::DAGCombinerInfo &DCI,
603 const MipsSubtarget *Subtarget) {
604 // Pattern match INS.
605 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
606 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
607 // => ins $dst, $src, size, pos, $src1
608 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
611 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
612 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
615 // See if Op's first operand matches (and $src1 , mask0).
616 if (And0.getOpcode() != ISD::AND)
619 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
620 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
623 // See if Op's second operand matches (and (shl $src, pos), mask1).
624 if (And1.getOpcode() != ISD::AND)
627 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
628 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
631 // The shift masks must have the same position and size.
632 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
635 SDValue Shl = And1.getOperand(0);
636 if (Shl.getOpcode() != ISD::SHL)
639 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
642 unsigned Shamt = CN->getZExtValue();
644 // Return if the shift amount and the first bit position of mask are not the
646 EVT ValTy = N->getValueType(0);
647 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
650 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
651 DAG.getConstant(SMPos0, MVT::i32),
652 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
655 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
656 TargetLowering::DAGCombinerInfo &DCI,
657 const MipsSubtarget *Subtarget) {
658 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
660 if (DCI.isBeforeLegalizeOps())
663 SDValue Add = N->getOperand(1);
665 if (Add.getOpcode() != ISD::ADD)
668 SDValue Lo = Add.getOperand(1);
670 if ((Lo.getOpcode() != MipsISD::Lo) ||
671 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
674 EVT ValTy = N->getValueType(0);
677 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
679 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
682 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
684 SelectionDAG &DAG = DCI.DAG;
685 unsigned Opc = N->getOpcode();
691 return performDivRemCombine(N, DAG, DCI, Subtarget);
693 return performSELECTCombine(N, DAG, DCI, Subtarget);
695 return performANDCombine(N, DAG, DCI, Subtarget);
697 return performORCombine(N, DAG, DCI, Subtarget);
699 return performADDCombine(N, DAG, DCI, Subtarget);
706 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
707 SmallVectorImpl<SDValue> &Results,
708 SelectionDAG &DAG) const {
709 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
711 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
712 Results.push_back(Res.getValue(I));
716 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
717 SmallVectorImpl<SDValue> &Results,
718 SelectionDAG &DAG) const {
719 return LowerOperationWrapper(N, Results, DAG);
722 SDValue MipsTargetLowering::
723 LowerOperation(SDValue Op, SelectionDAG &DAG) const
725 switch (Op.getOpcode())
727 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
728 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
729 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
730 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
731 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
732 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
733 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
734 case ISD::SELECT: return lowerSELECT(Op, DAG);
735 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
736 case ISD::SETCC: return lowerSETCC(Op, DAG);
737 case ISD::VASTART: return lowerVASTART(Op, DAG);
738 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
739 case ISD::FABS: return lowerFABS(Op, DAG);
740 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
741 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
742 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
743 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
744 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
745 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
746 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
747 case ISD::LOAD: return lowerLOAD(Op, DAG);
748 case ISD::STORE: return lowerSTORE(Op, DAG);
749 case ISD::ADD: return lowerADD(Op, DAG);
750 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
755 //===----------------------------------------------------------------------===//
756 // Lower helper functions
757 //===----------------------------------------------------------------------===//
759 // addLiveIn - This helper function adds the specified physical register to the
760 // MachineFunction as a live in value. It also creates a corresponding
761 // virtual register for it.
763 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
765 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
766 MF.getRegInfo().addLiveIn(PReg, VReg);
770 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
771 MachineBasicBlock &MBB,
772 const TargetInstrInfo &TII,
777 // Insert instruction "teq $divisor_reg, $zero, 7".
778 MachineBasicBlock::iterator I(MI);
779 MachineInstrBuilder MIB;
780 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
781 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
783 // Use the 32-bit sub-register if this is a 64-bit division.
785 MIB->getOperand(0).setSubReg(Mips::sub_32);
791 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
792 MachineBasicBlock *BB) const {
793 switch (MI->getOpcode()) {
795 llvm_unreachable("Unexpected instr type to insert");
796 case Mips::ATOMIC_LOAD_ADD_I8:
797 case Mips::ATOMIC_LOAD_ADD_I8_P8:
798 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
799 case Mips::ATOMIC_LOAD_ADD_I16:
800 case Mips::ATOMIC_LOAD_ADD_I16_P8:
801 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
802 case Mips::ATOMIC_LOAD_ADD_I32:
803 case Mips::ATOMIC_LOAD_ADD_I32_P8:
804 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
805 case Mips::ATOMIC_LOAD_ADD_I64:
806 case Mips::ATOMIC_LOAD_ADD_I64_P8:
807 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
809 case Mips::ATOMIC_LOAD_AND_I8:
810 case Mips::ATOMIC_LOAD_AND_I8_P8:
811 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
812 case Mips::ATOMIC_LOAD_AND_I16:
813 case Mips::ATOMIC_LOAD_AND_I16_P8:
814 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
815 case Mips::ATOMIC_LOAD_AND_I32:
816 case Mips::ATOMIC_LOAD_AND_I32_P8:
817 return emitAtomicBinary(MI, BB, 4, Mips::AND);
818 case Mips::ATOMIC_LOAD_AND_I64:
819 case Mips::ATOMIC_LOAD_AND_I64_P8:
820 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
822 case Mips::ATOMIC_LOAD_OR_I8:
823 case Mips::ATOMIC_LOAD_OR_I8_P8:
824 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
825 case Mips::ATOMIC_LOAD_OR_I16:
826 case Mips::ATOMIC_LOAD_OR_I16_P8:
827 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
828 case Mips::ATOMIC_LOAD_OR_I32:
829 case Mips::ATOMIC_LOAD_OR_I32_P8:
830 return emitAtomicBinary(MI, BB, 4, Mips::OR);
831 case Mips::ATOMIC_LOAD_OR_I64:
832 case Mips::ATOMIC_LOAD_OR_I64_P8:
833 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
835 case Mips::ATOMIC_LOAD_XOR_I8:
836 case Mips::ATOMIC_LOAD_XOR_I8_P8:
837 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
838 case Mips::ATOMIC_LOAD_XOR_I16:
839 case Mips::ATOMIC_LOAD_XOR_I16_P8:
840 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
841 case Mips::ATOMIC_LOAD_XOR_I32:
842 case Mips::ATOMIC_LOAD_XOR_I32_P8:
843 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
844 case Mips::ATOMIC_LOAD_XOR_I64:
845 case Mips::ATOMIC_LOAD_XOR_I64_P8:
846 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
848 case Mips::ATOMIC_LOAD_NAND_I8:
849 case Mips::ATOMIC_LOAD_NAND_I8_P8:
850 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
851 case Mips::ATOMIC_LOAD_NAND_I16:
852 case Mips::ATOMIC_LOAD_NAND_I16_P8:
853 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
854 case Mips::ATOMIC_LOAD_NAND_I32:
855 case Mips::ATOMIC_LOAD_NAND_I32_P8:
856 return emitAtomicBinary(MI, BB, 4, 0, true);
857 case Mips::ATOMIC_LOAD_NAND_I64:
858 case Mips::ATOMIC_LOAD_NAND_I64_P8:
859 return emitAtomicBinary(MI, BB, 8, 0, true);
861 case Mips::ATOMIC_LOAD_SUB_I8:
862 case Mips::ATOMIC_LOAD_SUB_I8_P8:
863 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
864 case Mips::ATOMIC_LOAD_SUB_I16:
865 case Mips::ATOMIC_LOAD_SUB_I16_P8:
866 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
867 case Mips::ATOMIC_LOAD_SUB_I32:
868 case Mips::ATOMIC_LOAD_SUB_I32_P8:
869 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
870 case Mips::ATOMIC_LOAD_SUB_I64:
871 case Mips::ATOMIC_LOAD_SUB_I64_P8:
872 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
874 case Mips::ATOMIC_SWAP_I8:
875 case Mips::ATOMIC_SWAP_I8_P8:
876 return emitAtomicBinaryPartword(MI, BB, 1, 0);
877 case Mips::ATOMIC_SWAP_I16:
878 case Mips::ATOMIC_SWAP_I16_P8:
879 return emitAtomicBinaryPartword(MI, BB, 2, 0);
880 case Mips::ATOMIC_SWAP_I32:
881 case Mips::ATOMIC_SWAP_I32_P8:
882 return emitAtomicBinary(MI, BB, 4, 0);
883 case Mips::ATOMIC_SWAP_I64:
884 case Mips::ATOMIC_SWAP_I64_P8:
885 return emitAtomicBinary(MI, BB, 8, 0);
887 case Mips::ATOMIC_CMP_SWAP_I8:
888 case Mips::ATOMIC_CMP_SWAP_I8_P8:
889 return emitAtomicCmpSwapPartword(MI, BB, 1);
890 case Mips::ATOMIC_CMP_SWAP_I16:
891 case Mips::ATOMIC_CMP_SWAP_I16_P8:
892 return emitAtomicCmpSwapPartword(MI, BB, 2);
893 case Mips::ATOMIC_CMP_SWAP_I32:
894 case Mips::ATOMIC_CMP_SWAP_I32_P8:
895 return emitAtomicCmpSwap(MI, BB, 4);
896 case Mips::ATOMIC_CMP_SWAP_I64:
897 case Mips::ATOMIC_CMP_SWAP_I64_P8:
898 return emitAtomicCmpSwap(MI, BB, 8);
899 case Mips::PseudoSDIV:
900 case Mips::PseudoUDIV:
901 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
902 case Mips::PseudoDSDIV:
903 case Mips::PseudoDUDIV:
904 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
908 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
909 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
911 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
912 unsigned Size, unsigned BinOpcode,
914 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
916 MachineFunction *MF = BB->getParent();
917 MachineRegisterInfo &RegInfo = MF->getRegInfo();
918 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
919 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
920 DebugLoc DL = MI->getDebugLoc();
921 unsigned LL, SC, AND, NOR, ZERO, BEQ;
924 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
925 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
932 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
933 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
936 ZERO = Mips::ZERO_64;
940 unsigned OldVal = MI->getOperand(0).getReg();
941 unsigned Ptr = MI->getOperand(1).getReg();
942 unsigned Incr = MI->getOperand(2).getReg();
944 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
945 unsigned AndRes = RegInfo.createVirtualRegister(RC);
946 unsigned Success = RegInfo.createVirtualRegister(RC);
948 // insert new blocks after the current block
949 const BasicBlock *LLVM_BB = BB->getBasicBlock();
950 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
951 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
952 MachineFunction::iterator It = BB;
954 MF->insert(It, loopMBB);
955 MF->insert(It, exitMBB);
957 // Transfer the remainder of BB and its successor edges to exitMBB.
958 exitMBB->splice(exitMBB->begin(), BB,
959 llvm::next(MachineBasicBlock::iterator(MI)),
961 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
965 // fallthrough --> loopMBB
966 BB->addSuccessor(loopMBB);
967 loopMBB->addSuccessor(loopMBB);
968 loopMBB->addSuccessor(exitMBB);
972 // <binop> storeval, oldval, incr
973 // sc success, storeval, 0(ptr)
974 // beq success, $0, loopMBB
976 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
978 // and andres, oldval, incr
979 // nor storeval, $0, andres
980 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
981 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
982 } else if (BinOpcode) {
983 // <binop> storeval, oldval, incr
984 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
988 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
989 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
991 MI->eraseFromParent(); // The instruction is gone now.
997 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
998 MachineBasicBlock *BB,
999 unsigned Size, unsigned BinOpcode,
1001 assert((Size == 1 || Size == 2) &&
1002 "Unsupported size for EmitAtomicBinaryPartial.");
1004 MachineFunction *MF = BB->getParent();
1005 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1006 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1007 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1008 DebugLoc DL = MI->getDebugLoc();
1009 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1010 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1012 unsigned Dest = MI->getOperand(0).getReg();
1013 unsigned Ptr = MI->getOperand(1).getReg();
1014 unsigned Incr = MI->getOperand(2).getReg();
1016 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1017 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1018 unsigned Mask = RegInfo.createVirtualRegister(RC);
1019 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1020 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1021 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1022 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1023 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1024 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1025 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1026 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1027 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1028 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1029 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1030 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1031 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1032 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1033 unsigned Success = RegInfo.createVirtualRegister(RC);
1035 // insert new blocks after the current block
1036 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1037 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1038 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1039 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1040 MachineFunction::iterator It = BB;
1042 MF->insert(It, loopMBB);
1043 MF->insert(It, sinkMBB);
1044 MF->insert(It, exitMBB);
1046 // Transfer the remainder of BB and its successor edges to exitMBB.
1047 exitMBB->splice(exitMBB->begin(), BB,
1048 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1049 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1051 BB->addSuccessor(loopMBB);
1052 loopMBB->addSuccessor(loopMBB);
1053 loopMBB->addSuccessor(sinkMBB);
1054 sinkMBB->addSuccessor(exitMBB);
1057 // addiu masklsb2,$0,-4 # 0xfffffffc
1058 // and alignedaddr,ptr,masklsb2
1059 // andi ptrlsb2,ptr,3
1060 // sll shiftamt,ptrlsb2,3
1061 // ori maskupper,$0,255 # 0xff
1062 // sll mask,maskupper,shiftamt
1063 // nor mask2,$0,mask
1064 // sll incr2,incr,shiftamt
1066 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1067 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1068 .addReg(Mips::ZERO).addImm(-4);
1069 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1070 .addReg(Ptr).addReg(MaskLSB2);
1071 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1072 if (Subtarget->isLittle()) {
1073 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1075 unsigned Off = RegInfo.createVirtualRegister(RC);
1076 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1077 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1078 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1080 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1081 .addReg(Mips::ZERO).addImm(MaskImm);
1082 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1083 .addReg(MaskUpper).addReg(ShiftAmt);
1084 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1085 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1087 // atomic.load.binop
1089 // ll oldval,0(alignedaddr)
1090 // binop binopres,oldval,incr2
1091 // and newval,binopres,mask
1092 // and maskedoldval0,oldval,mask2
1093 // or storeval,maskedoldval0,newval
1094 // sc success,storeval,0(alignedaddr)
1095 // beq success,$0,loopMBB
1099 // ll oldval,0(alignedaddr)
1100 // and newval,incr2,mask
1101 // and maskedoldval0,oldval,mask2
1102 // or storeval,maskedoldval0,newval
1103 // sc success,storeval,0(alignedaddr)
1104 // beq success,$0,loopMBB
1107 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1109 // and andres, oldval, incr2
1110 // nor binopres, $0, andres
1111 // and newval, binopres, mask
1112 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1113 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1114 .addReg(Mips::ZERO).addReg(AndRes);
1115 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1116 } else if (BinOpcode) {
1117 // <binop> binopres, oldval, incr2
1118 // and newval, binopres, mask
1119 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1120 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1121 } else {// atomic.swap
1122 // and newval, incr2, mask
1123 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1126 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1127 .addReg(OldVal).addReg(Mask2);
1128 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1129 .addReg(MaskedOldVal0).addReg(NewVal);
1130 BuildMI(BB, DL, TII->get(SC), Success)
1131 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1132 BuildMI(BB, DL, TII->get(Mips::BEQ))
1133 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1136 // and maskedoldval1,oldval,mask
1137 // srl srlres,maskedoldval1,shiftamt
1138 // sll sllres,srlres,24
1139 // sra dest,sllres,24
1141 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1143 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1144 .addReg(OldVal).addReg(Mask);
1145 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1146 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1147 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1148 .addReg(SrlRes).addImm(ShiftImm);
1149 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1150 .addReg(SllRes).addImm(ShiftImm);
1152 MI->eraseFromParent(); // The instruction is gone now.
1158 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1159 MachineBasicBlock *BB,
1160 unsigned Size) const {
1161 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1163 MachineFunction *MF = BB->getParent();
1164 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1165 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1166 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1167 DebugLoc DL = MI->getDebugLoc();
1168 unsigned LL, SC, ZERO, BNE, BEQ;
1171 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1172 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1178 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1179 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1180 ZERO = Mips::ZERO_64;
1185 unsigned Dest = MI->getOperand(0).getReg();
1186 unsigned Ptr = MI->getOperand(1).getReg();
1187 unsigned OldVal = MI->getOperand(2).getReg();
1188 unsigned NewVal = MI->getOperand(3).getReg();
1190 unsigned Success = RegInfo.createVirtualRegister(RC);
1192 // insert new blocks after the current block
1193 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1194 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1195 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1196 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1197 MachineFunction::iterator It = BB;
1199 MF->insert(It, loop1MBB);
1200 MF->insert(It, loop2MBB);
1201 MF->insert(It, exitMBB);
1203 // Transfer the remainder of BB and its successor edges to exitMBB.
1204 exitMBB->splice(exitMBB->begin(), BB,
1205 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1206 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1210 // fallthrough --> loop1MBB
1211 BB->addSuccessor(loop1MBB);
1212 loop1MBB->addSuccessor(exitMBB);
1213 loop1MBB->addSuccessor(loop2MBB);
1214 loop2MBB->addSuccessor(loop1MBB);
1215 loop2MBB->addSuccessor(exitMBB);
1219 // bne dest, oldval, exitMBB
1221 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1222 BuildMI(BB, DL, TII->get(BNE))
1223 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1226 // sc success, newval, 0(ptr)
1227 // beq success, $0, loop1MBB
1229 BuildMI(BB, DL, TII->get(SC), Success)
1230 .addReg(NewVal).addReg(Ptr).addImm(0);
1231 BuildMI(BB, DL, TII->get(BEQ))
1232 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1234 MI->eraseFromParent(); // The instruction is gone now.
1240 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1241 MachineBasicBlock *BB,
1242 unsigned Size) const {
1243 assert((Size == 1 || Size == 2) &&
1244 "Unsupported size for EmitAtomicCmpSwapPartial.");
1246 MachineFunction *MF = BB->getParent();
1247 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1248 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1249 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1250 DebugLoc DL = MI->getDebugLoc();
1251 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1252 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1254 unsigned Dest = MI->getOperand(0).getReg();
1255 unsigned Ptr = MI->getOperand(1).getReg();
1256 unsigned CmpVal = MI->getOperand(2).getReg();
1257 unsigned NewVal = MI->getOperand(3).getReg();
1259 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1260 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1261 unsigned Mask = RegInfo.createVirtualRegister(RC);
1262 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1263 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1264 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1265 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1266 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1267 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1268 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1269 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1270 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1271 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1272 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1273 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1274 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1275 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1276 unsigned Success = RegInfo.createVirtualRegister(RC);
1278 // insert new blocks after the current block
1279 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1280 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1281 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1282 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1283 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1284 MachineFunction::iterator It = BB;
1286 MF->insert(It, loop1MBB);
1287 MF->insert(It, loop2MBB);
1288 MF->insert(It, sinkMBB);
1289 MF->insert(It, exitMBB);
1291 // Transfer the remainder of BB and its successor edges to exitMBB.
1292 exitMBB->splice(exitMBB->begin(), BB,
1293 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1294 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1296 BB->addSuccessor(loop1MBB);
1297 loop1MBB->addSuccessor(sinkMBB);
1298 loop1MBB->addSuccessor(loop2MBB);
1299 loop2MBB->addSuccessor(loop1MBB);
1300 loop2MBB->addSuccessor(sinkMBB);
1301 sinkMBB->addSuccessor(exitMBB);
1303 // FIXME: computation of newval2 can be moved to loop2MBB.
1305 // addiu masklsb2,$0,-4 # 0xfffffffc
1306 // and alignedaddr,ptr,masklsb2
1307 // andi ptrlsb2,ptr,3
1308 // sll shiftamt,ptrlsb2,3
1309 // ori maskupper,$0,255 # 0xff
1310 // sll mask,maskupper,shiftamt
1311 // nor mask2,$0,mask
1312 // andi maskedcmpval,cmpval,255
1313 // sll shiftedcmpval,maskedcmpval,shiftamt
1314 // andi maskednewval,newval,255
1315 // sll shiftednewval,maskednewval,shiftamt
1316 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1317 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1318 .addReg(Mips::ZERO).addImm(-4);
1319 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1320 .addReg(Ptr).addReg(MaskLSB2);
1321 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1322 if (Subtarget->isLittle()) {
1323 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1325 unsigned Off = RegInfo.createVirtualRegister(RC);
1326 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1327 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1328 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1330 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1331 .addReg(Mips::ZERO).addImm(MaskImm);
1332 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1333 .addReg(MaskUpper).addReg(ShiftAmt);
1334 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1335 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1336 .addReg(CmpVal).addImm(MaskImm);
1337 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1338 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1339 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1340 .addReg(NewVal).addImm(MaskImm);
1341 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1342 .addReg(MaskedNewVal).addReg(ShiftAmt);
1345 // ll oldval,0(alginedaddr)
1346 // and maskedoldval0,oldval,mask
1347 // bne maskedoldval0,shiftedcmpval,sinkMBB
1349 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1350 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1351 .addReg(OldVal).addReg(Mask);
1352 BuildMI(BB, DL, TII->get(Mips::BNE))
1353 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1356 // and maskedoldval1,oldval,mask2
1357 // or storeval,maskedoldval1,shiftednewval
1358 // sc success,storeval,0(alignedaddr)
1359 // beq success,$0,loop1MBB
1361 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1362 .addReg(OldVal).addReg(Mask2);
1363 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1364 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1365 BuildMI(BB, DL, TII->get(SC), Success)
1366 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1367 BuildMI(BB, DL, TII->get(Mips::BEQ))
1368 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1371 // srl srlres,maskedoldval0,shiftamt
1372 // sll sllres,srlres,24
1373 // sra dest,sllres,24
1375 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1377 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1378 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1379 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1380 .addReg(SrlRes).addImm(ShiftImm);
1381 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1382 .addReg(SllRes).addImm(ShiftImm);
1384 MI->eraseFromParent(); // The instruction is gone now.
1389 //===----------------------------------------------------------------------===//
1390 // Misc Lower Operation implementation
1391 //===----------------------------------------------------------------------===//
1392 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1393 SDValue Chain = Op.getOperand(0);
1394 SDValue Table = Op.getOperand(1);
1395 SDValue Index = Op.getOperand(2);
1397 EVT PTy = getPointerTy();
1398 unsigned EntrySize =
1399 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1401 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1402 DAG.getConstant(EntrySize, PTy));
1403 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1405 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1406 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1407 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1409 Chain = Addr.getValue(1);
1411 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1412 // For PIC, the sequence is:
1413 // BRIND(load(Jumptable + index) + RelocBase)
1414 // RelocBase can be JumpTable, GOT or some sort of global base.
1415 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1416 getPICJumpTableRelocBase(Table, DAG));
1419 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1422 SDValue MipsTargetLowering::
1423 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1425 // The first operand is the chain, the second is the condition, the third is
1426 // the block to branch to if the condition is true.
1427 SDValue Chain = Op.getOperand(0);
1428 SDValue Dest = Op.getOperand(2);
1431 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1433 // Return if flag is not set by a floating point comparison.
1434 if (CondRes.getOpcode() != MipsISD::FPCmp)
1437 SDValue CCNode = CondRes.getOperand(2);
1439 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1440 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1441 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1442 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1443 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1444 FCC0, Dest, CondRes);
1447 SDValue MipsTargetLowering::
1448 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1450 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1452 // Return if flag is not set by a floating point comparison.
1453 if (Cond.getOpcode() != MipsISD::FPCmp)
1456 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1460 SDValue MipsTargetLowering::
1461 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1464 EVT Ty = Op.getOperand(0).getValueType();
1465 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1466 getSetCCResultType(*DAG.getContext(), Ty),
1467 Op.getOperand(0), Op.getOperand(1),
1470 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1474 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1475 SDValue Cond = createFPCmp(DAG, Op);
1477 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1478 "Floating point operand expected.");
1480 SDValue True = DAG.getConstant(1, MVT::i32);
1481 SDValue False = DAG.getConstant(0, MVT::i32);
1483 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1486 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1487 SelectionDAG &DAG) const {
1488 // FIXME there isn't actually debug info here
1490 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1492 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1493 const MipsTargetObjectFile &TLOF =
1494 (const MipsTargetObjectFile&)getObjFileLowering();
1496 // %gp_rel relocation
1497 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1498 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1500 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1501 DAG.getVTList(MVT::i32), &GA, 1);
1502 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1503 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1506 // %hi/%lo relocation
1507 return getAddrNonPIC(Op, DAG);
1510 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1511 return getAddrLocal(Op, DAG, HasMips64);
1514 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1515 MipsII::MO_GOT_LO16);
1517 return getAddrGlobal(Op, DAG,
1518 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1521 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1522 SelectionDAG &DAG) const {
1523 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1524 return getAddrNonPIC(Op, DAG);
1526 return getAddrLocal(Op, DAG, HasMips64);
1529 SDValue MipsTargetLowering::
1530 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1532 // If the relocation model is PIC, use the General Dynamic TLS Model or
1533 // Local Dynamic TLS model, otherwise use the Initial Exec or
1534 // Local Exec TLS Model.
1536 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1538 const GlobalValue *GV = GA->getGlobal();
1539 EVT PtrVT = getPointerTy();
1541 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1543 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1544 // General Dynamic and Local Dynamic TLS Model.
1545 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1548 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1549 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1550 getGlobalReg(DAG, PtrVT), TGA);
1551 unsigned PtrSize = PtrVT.getSizeInBits();
1552 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1554 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1558 Entry.Node = Argument;
1560 Args.push_back(Entry);
1562 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1563 false, false, false, false, 0, CallingConv::C,
1564 /*IsTailCall=*/false, /*doesNotRet=*/false,
1565 /*isReturnValueUsed=*/true,
1566 TlsGetAddr, Args, DAG, DL);
1567 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1569 SDValue Ret = CallResult.first;
1571 if (model != TLSModel::LocalDynamic)
1574 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1575 MipsII::MO_DTPREL_HI);
1576 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1577 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1578 MipsII::MO_DTPREL_LO);
1579 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1580 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1581 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1585 if (model == TLSModel::InitialExec) {
1586 // Initial Exec TLS Model
1587 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1588 MipsII::MO_GOTTPREL);
1589 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1591 Offset = DAG.getLoad(PtrVT, DL,
1592 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1593 false, false, false, 0);
1595 // Local Exec TLS Model
1596 assert(model == TLSModel::LocalExec);
1597 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1598 MipsII::MO_TPREL_HI);
1599 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1600 MipsII::MO_TPREL_LO);
1601 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1602 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1603 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1606 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1607 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1610 SDValue MipsTargetLowering::
1611 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1613 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1614 return getAddrNonPIC(Op, DAG);
1616 return getAddrLocal(Op, DAG, HasMips64);
1619 SDValue MipsTargetLowering::
1620 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1622 // gp_rel relocation
1623 // FIXME: we should reference the constant pool using small data sections,
1624 // but the asm printer currently doesn't support this feature without
1625 // hacking it. This feature should come soon so we can uncomment the
1627 //if (IsInSmallSection(C->getType())) {
1628 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1629 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1630 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1632 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1633 return getAddrNonPIC(Op, DAG);
1635 return getAddrLocal(Op, DAG, HasMips64);
1638 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1639 MachineFunction &MF = DAG.getMachineFunction();
1640 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1643 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1646 // vastart just stores the address of the VarArgsFrameIndex slot into the
1647 // memory location argument.
1648 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1649 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1650 MachinePointerInfo(SV), false, false, 0);
1653 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1654 EVT TyX = Op.getOperand(0).getValueType();
1655 EVT TyY = Op.getOperand(1).getValueType();
1656 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1657 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1661 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1663 SDValue X = (TyX == MVT::f32) ?
1664 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1665 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1667 SDValue Y = (TyY == MVT::f32) ?
1668 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1669 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1673 // ext E, Y, 31, 1 ; extract bit31 of Y
1674 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1675 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1676 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1679 // srl SrlX, SllX, 1
1681 // sll SllY, SrlX, 31
1682 // or Or, SrlX, SllY
1683 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1684 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1685 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1686 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1687 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1690 if (TyX == MVT::f32)
1691 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1693 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1694 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1695 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1698 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1699 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1700 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1701 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1702 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1705 // Bitcast to integer nodes.
1706 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1707 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1710 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1711 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1712 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1713 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1715 if (WidthX > WidthY)
1716 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1717 else if (WidthY > WidthX)
1718 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1720 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1721 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1722 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1725 // (d)sll SllX, X, 1
1726 // (d)srl SrlX, SllX, 1
1727 // (d)srl SrlY, Y, width(Y)-1
1728 // (d)sll SllY, SrlX, width(Y)-1
1729 // or Or, SrlX, SllY
1730 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1731 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1732 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1733 DAG.getConstant(WidthY - 1, MVT::i32));
1735 if (WidthX > WidthY)
1736 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1737 else if (WidthY > WidthX)
1738 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1740 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1741 DAG.getConstant(WidthX - 1, MVT::i32));
1742 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1743 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1747 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1748 if (Subtarget->hasMips64())
1749 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1751 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1754 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1755 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1758 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1760 SDValue X = (Op.getValueType() == MVT::f32) ?
1761 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1762 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1767 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1768 DAG.getRegister(Mips::ZERO, MVT::i32),
1769 DAG.getConstant(31, MVT::i32), Const1, X);
1771 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1772 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1775 if (Op.getValueType() == MVT::f32)
1776 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1778 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1779 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1780 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1783 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1784 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1787 // Bitcast to integer node.
1788 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1792 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1793 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1794 DAG.getConstant(63, MVT::i32), Const1, X);
1796 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1797 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1800 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1804 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1805 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1806 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1808 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1811 SDValue MipsTargetLowering::
1812 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1814 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1815 "Frame address can only be determined for current frame.");
1817 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1818 MFI->setFrameAddressIsTaken(true);
1819 EVT VT = Op.getValueType();
1821 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1822 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1826 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1827 SelectionDAG &DAG) const {
1829 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1830 "Return address can be determined only for current frame.");
1832 MachineFunction &MF = DAG.getMachineFunction();
1833 MachineFrameInfo *MFI = MF.getFrameInfo();
1834 MVT VT = Op.getSimpleValueType();
1835 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1836 MFI->setReturnAddressIsTaken(true);
1838 // Return RA, which contains the return address. Mark it an implicit live-in.
1839 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1840 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1843 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1844 // generated from __builtin_eh_return (offset, handler)
1845 // The effect of this is to adjust the stack pointer by "offset"
1846 // and then branch to "handler".
1847 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1849 MachineFunction &MF = DAG.getMachineFunction();
1850 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1852 MipsFI->setCallsEhReturn();
1853 SDValue Chain = Op.getOperand(0);
1854 SDValue Offset = Op.getOperand(1);
1855 SDValue Handler = Op.getOperand(2);
1857 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1859 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1860 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1861 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1862 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1863 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1864 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1865 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1866 DAG.getRegister(OffsetReg, Ty),
1867 DAG.getRegister(AddrReg, getPointerTy()),
1871 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1872 SelectionDAG &DAG) const {
1873 // FIXME: Need pseudo-fence for 'singlethread' fences
1874 // FIXME: Set SType for weaker fences where supported/appropriate.
1877 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1878 DAG.getConstant(SType, MVT::i32));
1881 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1882 SelectionDAG &DAG) const {
1884 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1885 SDValue Shamt = Op.getOperand(2);
1888 // lo = (shl lo, shamt)
1889 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1892 // hi = (shl lo, shamt[4:0])
1893 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1894 DAG.getConstant(-1, MVT::i32));
1895 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1896 DAG.getConstant(1, MVT::i32));
1897 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1899 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1900 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1901 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1902 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1903 DAG.getConstant(0x20, MVT::i32));
1904 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1905 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1906 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1908 SDValue Ops[2] = {Lo, Hi};
1909 return DAG.getMergeValues(Ops, 2, DL);
1912 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1915 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1916 SDValue Shamt = Op.getOperand(2);
1919 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1921 // hi = (sra hi, shamt)
1923 // hi = (srl hi, shamt)
1926 // lo = (sra hi, shamt[4:0])
1927 // hi = (sra hi, 31)
1929 // lo = (srl hi, shamt[4:0])
1931 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1932 DAG.getConstant(-1, MVT::i32));
1933 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1934 DAG.getConstant(1, MVT::i32));
1935 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1936 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1937 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1938 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1940 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1941 DAG.getConstant(0x20, MVT::i32));
1942 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1943 DAG.getConstant(31, MVT::i32));
1944 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1945 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1946 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1949 SDValue Ops[2] = {Lo, Hi};
1950 return DAG.getMergeValues(Ops, 2, DL);
1953 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1954 SDValue Chain, SDValue Src, unsigned Offset) {
1955 SDValue Ptr = LD->getBasePtr();
1956 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1957 EVT BasePtrVT = Ptr.getValueType();
1959 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1962 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1963 DAG.getConstant(Offset, BasePtrVT));
1965 SDValue Ops[] = { Chain, Ptr, Src };
1966 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1967 LD->getMemOperand());
1970 // Expand an unaligned 32 or 64-bit integer load node.
1971 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1972 LoadSDNode *LD = cast<LoadSDNode>(Op);
1973 EVT MemVT = LD->getMemoryVT();
1975 // Return if load is aligned or if MemVT is neither i32 nor i64.
1976 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1977 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1980 bool IsLittle = Subtarget->isLittle();
1981 EVT VT = Op.getValueType();
1982 ISD::LoadExtType ExtType = LD->getExtensionType();
1983 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1985 assert((VT == MVT::i32) || (VT == MVT::i64));
1988 // (set dst, (i64 (load baseptr)))
1990 // (set tmp, (ldl (add baseptr, 7), undef))
1991 // (set dst, (ldr baseptr, tmp))
1992 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1993 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1995 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1999 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2001 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2005 // (set dst, (i32 (load baseptr))) or
2006 // (set dst, (i64 (sextload baseptr))) or
2007 // (set dst, (i64 (extload baseptr)))
2009 // (set tmp, (lwl (add baseptr, 3), undef))
2010 // (set dst, (lwr baseptr, tmp))
2011 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2012 (ExtType == ISD::EXTLOAD))
2015 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2018 // (set dst, (i64 (zextload baseptr)))
2020 // (set tmp0, (lwl (add baseptr, 3), undef))
2021 // (set tmp1, (lwr baseptr, tmp0))
2022 // (set tmp2, (shl tmp1, 32))
2023 // (set dst, (srl tmp2, 32))
2025 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2026 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2027 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2028 SDValue Ops[] = { SRL, LWR.getValue(1) };
2029 return DAG.getMergeValues(Ops, 2, DL);
2032 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2033 SDValue Chain, unsigned Offset) {
2034 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2035 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2037 SDVTList VTList = DAG.getVTList(MVT::Other);
2040 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2041 DAG.getConstant(Offset, BasePtrVT));
2043 SDValue Ops[] = { Chain, Value, Ptr };
2044 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2045 SD->getMemOperand());
2048 // Expand an unaligned 32 or 64-bit integer store node.
2049 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2051 SDValue Value = SD->getValue(), Chain = SD->getChain();
2052 EVT VT = Value.getValueType();
2055 // (store val, baseptr) or
2056 // (truncstore val, baseptr)
2058 // (swl val, (add baseptr, 3))
2059 // (swr val, baseptr)
2060 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2061 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2063 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2066 assert(VT == MVT::i64);
2069 // (store val, baseptr)
2071 // (sdl val, (add baseptr, 7))
2072 // (sdr val, baseptr)
2073 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2074 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2077 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2078 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2079 SDValue Val = SD->getValue();
2081 if (Val.getOpcode() != ISD::FP_TO_SINT)
2084 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2085 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2088 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2089 SD->getPointerInfo(), SD->isVolatile(),
2090 SD->isNonTemporal(), SD->getAlignment());
2093 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2094 StoreSDNode *SD = cast<StoreSDNode>(Op);
2095 EVT MemVT = SD->getMemoryVT();
2097 // Lower unaligned integer stores.
2098 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2099 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2100 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2102 return lowerFP_TO_SINT_STORE(SD, DAG);
2105 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2106 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2107 || cast<ConstantSDNode>
2108 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2109 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2113 // (add (frameaddr 0), (frame_to_args_offset))
2114 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2115 // (add FrameObject, 0)
2116 // where FrameObject is a fixed StackObject with offset 0 which points to
2117 // the old stack pointer.
2118 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2119 EVT ValTy = Op->getValueType(0);
2120 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2121 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2122 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2123 DAG.getConstant(0, ValTy));
2126 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2127 SelectionDAG &DAG) const {
2128 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2129 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2131 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2134 //===----------------------------------------------------------------------===//
2135 // Calling Convention Implementation
2136 //===----------------------------------------------------------------------===//
2138 //===----------------------------------------------------------------------===//
2139 // TODO: Implement a generic logic using tblgen that can support this.
2140 // Mips O32 ABI rules:
2142 // i32 - Passed in A0, A1, A2, A3 and stack
2143 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2144 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2145 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2146 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2147 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2150 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2151 //===----------------------------------------------------------------------===//
2153 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2154 MVT LocVT, CCValAssign::LocInfo LocInfo,
2155 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2157 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2159 static const uint16_t IntRegs[] = {
2160 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2162 static const uint16_t F32Regs[] = {
2163 Mips::F12, Mips::F14
2165 static const uint16_t F64Regs[] = {
2169 // Do not process byval args here.
2170 if (ArgFlags.isByVal())
2173 // Promote i8 and i16
2174 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2176 if (ArgFlags.isSExt())
2177 LocInfo = CCValAssign::SExt;
2178 else if (ArgFlags.isZExt())
2179 LocInfo = CCValAssign::ZExt;
2181 LocInfo = CCValAssign::AExt;
2186 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2187 // is true: function is vararg, argument is 3rd or higher, there is previous
2188 // argument which is not f32 or f64.
2189 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2190 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2191 unsigned OrigAlign = ArgFlags.getOrigAlign();
2192 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2194 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2195 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2196 // If this is the first part of an i64 arg,
2197 // the allocated register must be either A0 or A2.
2198 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2199 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2201 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2202 // Allocate int register and shadow next int register. If first
2203 // available register is Mips::A1 or Mips::A3, shadow it too.
2204 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2205 if (Reg == Mips::A1 || Reg == Mips::A3)
2206 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2207 State.AllocateReg(IntRegs, IntRegsSize);
2209 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2210 // we are guaranteed to find an available float register
2211 if (ValVT == MVT::f32) {
2212 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2213 // Shadow int register
2214 State.AllocateReg(IntRegs, IntRegsSize);
2216 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2217 // Shadow int registers
2218 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2219 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2220 State.AllocateReg(IntRegs, IntRegsSize);
2221 State.AllocateReg(IntRegs, IntRegsSize);
2224 llvm_unreachable("Cannot handle this ValVT.");
2227 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2229 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2231 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2236 #include "MipsGenCallingConv.inc"
2238 //===----------------------------------------------------------------------===//
2239 // Call Calling Convention Implementation
2240 //===----------------------------------------------------------------------===//
2242 static const unsigned O32IntRegsSize = 4;
2244 // Return next O32 integer argument register.
2245 static unsigned getNextIntArgReg(unsigned Reg) {
2246 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2247 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2251 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2252 SDValue Chain, SDValue Arg, SDLoc DL,
2253 bool IsTailCall, SelectionDAG &DAG) const {
2255 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2256 DAG.getIntPtrConstant(Offset));
2257 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2261 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2262 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2263 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2264 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2265 /*isVolatile=*/ true, false, 0);
2268 void MipsTargetLowering::
2269 getOpndList(SmallVectorImpl<SDValue> &Ops,
2270 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2271 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2272 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2273 // Insert node "GP copy globalreg" before call to function.
2275 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2276 // in PIC mode) allow symbols to be resolved via lazy binding.
2277 // The lazy binding stub requires GP to point to the GOT.
2278 if (IsPICCall && !InternalLinkage) {
2279 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2280 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2281 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2284 // Build a sequence of copy-to-reg nodes chained together with token
2285 // chain and flag operands which copy the outgoing args into registers.
2286 // The InFlag in necessary since all emitted instructions must be
2290 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2291 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2292 RegsToPass[i].second, InFlag);
2293 InFlag = Chain.getValue(1);
2296 // Add argument registers to the end of the list so that they are
2297 // known live into the call.
2298 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2299 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2300 RegsToPass[i].second.getValueType()));
2302 // Add a register mask operand representing the call-preserved registers.
2303 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2304 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2305 assert(Mask && "Missing call preserved mask for calling convention");
2306 if (Subtarget->inMips16HardFloat()) {
2307 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2308 llvm::StringRef Sym = G->getGlobal()->getName();
2309 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2310 if (F->hasFnAttribute("__Mips16RetHelper")) {
2311 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2315 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2317 if (InFlag.getNode())
2318 Ops.push_back(InFlag);
2321 /// LowerCall - functions arguments are copied from virtual regs to
2322 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2324 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2325 SmallVectorImpl<SDValue> &InVals) const {
2326 SelectionDAG &DAG = CLI.DAG;
2328 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2329 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2330 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2331 SDValue Chain = CLI.Chain;
2332 SDValue Callee = CLI.Callee;
2333 bool &IsTailCall = CLI.IsTailCall;
2334 CallingConv::ID CallConv = CLI.CallConv;
2335 bool IsVarArg = CLI.IsVarArg;
2337 MachineFunction &MF = DAG.getMachineFunction();
2338 MachineFrameInfo *MFI = MF.getFrameInfo();
2339 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2340 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2342 // Analyze operands of the call, assigning locations to each operand.
2343 SmallVector<CCValAssign, 16> ArgLocs;
2344 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2345 getTargetMachine(), ArgLocs, *DAG.getContext());
2346 MipsCC::SpecialCallingConvType SpecialCallingConv =
2347 getSpecialCallingConv(Callee);
2348 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo, SpecialCallingConv);
2350 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2351 getTargetMachine().Options.UseSoftFloat,
2352 Callee.getNode(), CLI.Args);
2354 // Get a count of how many bytes are to be pushed on the stack.
2355 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2357 // Check if it's really possible to do a tail call.
2360 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2361 *MF.getInfo<MipsFunctionInfo>());
2366 // Chain is the output chain of the last Load/Store or CopyToReg node.
2367 // ByValChain is the output chain of the last Memcpy node created for copying
2368 // byval arguments to the stack.
2369 unsigned StackAlignment = TFL->getStackAlignment();
2370 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2371 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2374 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2376 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2377 IsN64 ? Mips::SP_64 : Mips::SP,
2380 // With EABI is it possible to have 16 args on registers.
2381 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2382 SmallVector<SDValue, 8> MemOpChains;
2383 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2385 // Walk the register/memloc assignments, inserting copies/loads.
2386 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2387 SDValue Arg = OutVals[i];
2388 CCValAssign &VA = ArgLocs[i];
2389 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2390 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2393 if (Flags.isByVal()) {
2394 assert(Flags.getByValSize() &&
2395 "ByVal args of size 0 should have been ignored by front-end.");
2396 assert(ByValArg != MipsCCInfo.byval_end());
2397 assert(!IsTailCall &&
2398 "Do not tail-call optimize if there is a byval argument.");
2399 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2400 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2405 // Promote the value if needed.
2406 switch (VA.getLocInfo()) {
2407 default: llvm_unreachable("Unknown loc info!");
2408 case CCValAssign::Full:
2409 if (VA.isRegLoc()) {
2410 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2411 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2412 (ValVT == MVT::i64 && LocVT == MVT::f64))
2413 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2414 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2415 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2416 Arg, DAG.getConstant(0, MVT::i32));
2417 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2418 Arg, DAG.getConstant(1, MVT::i32));
2419 if (!Subtarget->isLittle())
2421 unsigned LocRegLo = VA.getLocReg();
2422 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2423 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2424 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2429 case CCValAssign::SExt:
2430 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2432 case CCValAssign::ZExt:
2433 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2435 case CCValAssign::AExt:
2436 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2440 // Arguments that can be passed on register must be kept at
2441 // RegsToPass vector
2442 if (VA.isRegLoc()) {
2443 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2447 // Register can't get to this point...
2448 assert(VA.isMemLoc());
2450 // emit ISD::STORE whichs stores the
2451 // parameter value to a stack Location
2452 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2453 Chain, Arg, DL, IsTailCall, DAG));
2456 // Transform all store nodes into one single node because all store
2457 // nodes are independent of each other.
2458 if (!MemOpChains.empty())
2459 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2460 &MemOpChains[0], MemOpChains.size());
2462 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2463 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2464 // node so that legalize doesn't hack it.
2465 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2466 bool GlobalOrExternal = false, InternalLinkage = false;
2469 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2471 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2473 if (InternalLinkage)
2474 Callee = getAddrLocal(Callee, DAG, HasMips64);
2476 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2477 MipsII::MO_CALL_LO16);
2479 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2481 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2482 MipsII::MO_NO_FLAG);
2483 GlobalOrExternal = true;
2485 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2486 if (!IsN64 && !IsPIC) // !N64 && static
2487 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2488 MipsII::MO_NO_FLAG);
2490 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2491 MipsII::MO_CALL_LO16);
2493 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2495 GlobalOrExternal = true;
2498 SmallVector<SDValue, 8> Ops(1, Chain);
2499 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2501 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2502 CLI, Callee, Chain);
2505 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2507 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2508 SDValue InFlag = Chain.getValue(1);
2510 // Create the CALLSEQ_END node.
2511 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2512 DAG.getIntPtrConstant(0, true), InFlag, DL);
2513 InFlag = Chain.getValue(1);
2515 // Handle result values, copying them out of physregs into vregs that we
2517 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2518 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2521 /// LowerCallResult - Lower the result values of a call into the
2522 /// appropriate copies out of appropriate physical registers.
2524 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2525 CallingConv::ID CallConv, bool IsVarArg,
2526 const SmallVectorImpl<ISD::InputArg> &Ins,
2527 SDLoc DL, SelectionDAG &DAG,
2528 SmallVectorImpl<SDValue> &InVals,
2529 const SDNode *CallNode,
2530 const Type *RetTy) const {
2531 // Assign locations to each value returned by this call.
2532 SmallVector<CCValAssign, 16> RVLocs;
2533 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2534 getTargetMachine(), RVLocs, *DAG.getContext());
2535 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2537 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2540 // Copy all of the result registers out of their specified physreg.
2541 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2542 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2543 RVLocs[i].getLocVT(), InFlag);
2544 Chain = Val.getValue(1);
2545 InFlag = Val.getValue(2);
2547 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2548 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2550 InVals.push_back(Val);
2556 //===----------------------------------------------------------------------===//
2557 // Formal Arguments Calling Convention Implementation
2558 //===----------------------------------------------------------------------===//
2559 /// LowerFormalArguments - transform physical registers into virtual registers
2560 /// and generate load operations for arguments places on the stack.
2562 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2563 CallingConv::ID CallConv,
2565 const SmallVectorImpl<ISD::InputArg> &Ins,
2566 SDLoc DL, SelectionDAG &DAG,
2567 SmallVectorImpl<SDValue> &InVals)
2569 MachineFunction &MF = DAG.getMachineFunction();
2570 MachineFrameInfo *MFI = MF.getFrameInfo();
2571 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2573 MipsFI->setVarArgsFrameIndex(0);
2575 // Used with vargs to acumulate store chains.
2576 std::vector<SDValue> OutChains;
2578 // Assign locations to all of the incoming arguments.
2579 SmallVector<CCValAssign, 16> ArgLocs;
2580 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2581 getTargetMachine(), ArgLocs, *DAG.getContext());
2582 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2583 Function::const_arg_iterator FuncArg =
2584 DAG.getMachineFunction().getFunction()->arg_begin();
2585 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2587 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2588 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2589 MipsCCInfo.hasByValArg());
2591 unsigned CurArgIdx = 0;
2592 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2594 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2595 CCValAssign &VA = ArgLocs[i];
2596 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2597 CurArgIdx = Ins[i].OrigArgIndex;
2598 EVT ValVT = VA.getValVT();
2599 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2600 bool IsRegLoc = VA.isRegLoc();
2602 if (Flags.isByVal()) {
2603 assert(Flags.getByValSize() &&
2604 "ByVal args of size 0 should have been ignored by front-end.");
2605 assert(ByValArg != MipsCCInfo.byval_end());
2606 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2607 MipsCCInfo, *ByValArg);
2612 // Arguments stored on registers
2614 EVT RegVT = VA.getLocVT();
2615 unsigned ArgReg = VA.getLocReg();
2616 const TargetRegisterClass *RC;
2618 if (RegVT == MVT::i32)
2619 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2620 &Mips::CPURegsRegClass;
2621 else if (RegVT == MVT::i64)
2622 RC = &Mips::CPU64RegsRegClass;
2623 else if (RegVT == MVT::f32)
2624 RC = &Mips::FGR32RegClass;
2625 else if (RegVT == MVT::f64)
2626 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2628 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2630 // Transform the arguments stored on
2631 // physical registers into virtual ones
2632 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2633 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2635 // If this is an 8 or 16-bit value, it has been passed promoted
2636 // to 32 bits. Insert an assert[sz]ext to capture this, then
2637 // truncate to the right size.
2638 if (VA.getLocInfo() != CCValAssign::Full) {
2639 unsigned Opcode = 0;
2640 if (VA.getLocInfo() == CCValAssign::SExt)
2641 Opcode = ISD::AssertSext;
2642 else if (VA.getLocInfo() == CCValAssign::ZExt)
2643 Opcode = ISD::AssertZext;
2645 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2646 DAG.getValueType(ValVT));
2647 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2650 // Handle floating point arguments passed in integer registers and
2651 // long double arguments passed in floating point registers.
2652 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2653 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2654 (RegVT == MVT::f64 && ValVT == MVT::i64))
2655 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2656 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2657 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2658 getNextIntArgReg(ArgReg), RC);
2659 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2660 if (!Subtarget->isLittle())
2661 std::swap(ArgValue, ArgValue2);
2662 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2663 ArgValue, ArgValue2);
2666 InVals.push_back(ArgValue);
2667 } else { // VA.isRegLoc()
2670 assert(VA.isMemLoc());
2672 // The stack pointer offset is relative to the caller stack frame.
2673 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2674 VA.getLocMemOffset(), true);
2676 // Create load nodes to retrieve arguments from the stack
2677 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2678 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2679 MachinePointerInfo::getFixedStack(FI),
2680 false, false, false, 0));
2684 // The mips ABIs for returning structs by value requires that we copy
2685 // the sret argument into $v0 for the return. Save the argument into
2686 // a virtual register so that we can access it from the return points.
2687 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2688 unsigned Reg = MipsFI->getSRetReturnReg();
2690 Reg = MF.getRegInfo().
2691 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2692 MipsFI->setSRetReturnReg(Reg);
2694 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2695 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2699 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2701 // All stores are grouped in one node to allow the matching between
2702 // the size of Ins and InVals. This only happens when on varg functions
2703 if (!OutChains.empty()) {
2704 OutChains.push_back(Chain);
2705 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2706 &OutChains[0], OutChains.size());
2712 //===----------------------------------------------------------------------===//
2713 // Return Value Calling Convention Implementation
2714 //===----------------------------------------------------------------------===//
2717 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2718 MachineFunction &MF, bool IsVarArg,
2719 const SmallVectorImpl<ISD::OutputArg> &Outs,
2720 LLVMContext &Context) const {
2721 SmallVector<CCValAssign, 16> RVLocs;
2722 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2724 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2728 MipsTargetLowering::LowerReturn(SDValue Chain,
2729 CallingConv::ID CallConv, bool IsVarArg,
2730 const SmallVectorImpl<ISD::OutputArg> &Outs,
2731 const SmallVectorImpl<SDValue> &OutVals,
2732 SDLoc DL, SelectionDAG &DAG) const {
2733 // CCValAssign - represent the assignment of
2734 // the return value to a location
2735 SmallVector<CCValAssign, 16> RVLocs;
2736 MachineFunction &MF = DAG.getMachineFunction();
2738 // CCState - Info about the registers and stack slot.
2739 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2741 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2743 // Analyze return values.
2744 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2745 MF.getFunction()->getReturnType());
2748 SmallVector<SDValue, 4> RetOps(1, Chain);
2750 // Copy the result values into the output registers.
2751 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2752 SDValue Val = OutVals[i];
2753 CCValAssign &VA = RVLocs[i];
2754 assert(VA.isRegLoc() && "Can only return in registers!");
2756 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2757 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2759 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2761 // Guarantee that all emitted copies are stuck together with flags.
2762 Flag = Chain.getValue(1);
2763 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2766 // The mips ABIs for returning structs by value requires that we copy
2767 // the sret argument into $v0 for the return. We saved the argument into
2768 // a virtual register in the entry block, so now we copy the value out
2770 if (MF.getFunction()->hasStructRetAttr()) {
2771 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2772 unsigned Reg = MipsFI->getSRetReturnReg();
2775 llvm_unreachable("sret virtual register not created in the entry block");
2776 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2777 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2779 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2780 Flag = Chain.getValue(1);
2781 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2784 RetOps[0] = Chain; // Update chain.
2786 // Add the flag if we have it.
2788 RetOps.push_back(Flag);
2790 // Return on Mips is always a "jr $ra"
2791 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2794 //===----------------------------------------------------------------------===//
2795 // Mips Inline Assembly Support
2796 //===----------------------------------------------------------------------===//
2798 /// getConstraintType - Given a constraint letter, return the type of
2799 /// constraint it is for this target.
2800 MipsTargetLowering::ConstraintType MipsTargetLowering::
2801 getConstraintType(const std::string &Constraint) const
2803 // Mips specific constrainy
2804 // GCC config/mips/constraints.md
2806 // 'd' : An address register. Equivalent to r
2807 // unless generating MIPS16 code.
2808 // 'y' : Equivalent to r; retained for
2809 // backwards compatibility.
2810 // 'c' : A register suitable for use in an indirect
2811 // jump. This will always be $25 for -mabicalls.
2812 // 'l' : The lo register. 1 word storage.
2813 // 'x' : The hilo register pair. Double word storage.
2814 if (Constraint.size() == 1) {
2815 switch (Constraint[0]) {
2823 return C_RegisterClass;
2828 return TargetLowering::getConstraintType(Constraint);
2831 /// Examine constraint type and operand type and determine a weight value.
2832 /// This object must already have been set up with the operand type
2833 /// and the current alternative constraint selected.
2834 TargetLowering::ConstraintWeight
2835 MipsTargetLowering::getSingleConstraintMatchWeight(
2836 AsmOperandInfo &info, const char *constraint) const {
2837 ConstraintWeight weight = CW_Invalid;
2838 Value *CallOperandVal = info.CallOperandVal;
2839 // If we don't have a value, we can't do a match,
2840 // but allow it at the lowest weight.
2841 if (CallOperandVal == NULL)
2843 Type *type = CallOperandVal->getType();
2844 // Look at the constraint type.
2845 switch (*constraint) {
2847 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2851 if (type->isIntegerTy())
2852 weight = CW_Register;
2855 if (type->isFloatTy())
2856 weight = CW_Register;
2858 case 'c': // $25 for indirect jumps
2859 case 'l': // lo register
2860 case 'x': // hilo register pair
2861 if (type->isIntegerTy())
2862 weight = CW_SpecificReg;
2864 case 'I': // signed 16 bit immediate
2865 case 'J': // integer zero
2866 case 'K': // unsigned 16 bit immediate
2867 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2868 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2869 case 'O': // signed 15 bit immediate (+- 16383)
2870 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2871 if (isa<ConstantInt>(CallOperandVal))
2872 weight = CW_Constant;
2881 /// Given a register class constraint, like 'r', if this corresponds directly
2882 /// to an LLVM register class, return a register of 0 and the register class
2884 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2885 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2887 if (Constraint.size() == 1) {
2888 switch (Constraint[0]) {
2889 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2890 case 'y': // Same as 'r'. Exists for compatibility.
2892 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2893 if (Subtarget->inMips16Mode())
2894 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2895 return std::make_pair(0U, &Mips::CPURegsRegClass);
2897 if (VT == MVT::i64 && !HasMips64)
2898 return std::make_pair(0U, &Mips::CPURegsRegClass);
2899 if (VT == MVT::i64 && HasMips64)
2900 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
2901 // This will generate an error message
2902 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2905 return std::make_pair(0U, &Mips::FGR32RegClass);
2906 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2907 if (Subtarget->isFP64bit())
2908 return std::make_pair(0U, &Mips::FGR64RegClass);
2909 return std::make_pair(0U, &Mips::AFGR64RegClass);
2912 case 'c': // register suitable for indirect jump
2914 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
2915 assert(VT == MVT::i64 && "Unexpected type.");
2916 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
2917 case 'l': // register suitable for indirect jump
2919 return std::make_pair((unsigned)Mips::LO, &Mips::LORegsRegClass);
2920 return std::make_pair((unsigned)Mips::LO64, &Mips::LORegs64RegClass);
2921 case 'x': // register suitable for indirect jump
2922 // Fixme: Not triggering the use of both hi and low
2923 // This will generate an error message
2924 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2927 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2930 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2931 /// vector. If it is invalid, don't add anything to Ops.
2932 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2933 std::string &Constraint,
2934 std::vector<SDValue>&Ops,
2935 SelectionDAG &DAG) const {
2936 SDValue Result(0, 0);
2938 // Only support length 1 constraints for now.
2939 if (Constraint.length() > 1) return;
2941 char ConstraintLetter = Constraint[0];
2942 switch (ConstraintLetter) {
2943 default: break; // This will fall through to the generic implementation
2944 case 'I': // Signed 16 bit constant
2945 // If this fails, the parent routine will give an error
2946 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2947 EVT Type = Op.getValueType();
2948 int64_t Val = C->getSExtValue();
2949 if (isInt<16>(Val)) {
2950 Result = DAG.getTargetConstant(Val, Type);
2955 case 'J': // integer zero
2956 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2957 EVT Type = Op.getValueType();
2958 int64_t Val = C->getZExtValue();
2960 Result = DAG.getTargetConstant(0, Type);
2965 case 'K': // unsigned 16 bit immediate
2966 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2967 EVT Type = Op.getValueType();
2968 uint64_t Val = (uint64_t)C->getZExtValue();
2969 if (isUInt<16>(Val)) {
2970 Result = DAG.getTargetConstant(Val, Type);
2975 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2976 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2977 EVT Type = Op.getValueType();
2978 int64_t Val = C->getSExtValue();
2979 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
2980 Result = DAG.getTargetConstant(Val, Type);
2985 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2986 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2987 EVT Type = Op.getValueType();
2988 int64_t Val = C->getSExtValue();
2989 if ((Val >= -65535) && (Val <= -1)) {
2990 Result = DAG.getTargetConstant(Val, Type);
2995 case 'O': // signed 15 bit immediate
2996 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2997 EVT Type = Op.getValueType();
2998 int64_t Val = C->getSExtValue();
2999 if ((isInt<15>(Val))) {
3000 Result = DAG.getTargetConstant(Val, Type);
3005 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3007 EVT Type = Op.getValueType();
3008 int64_t Val = C->getSExtValue();
3009 if ((Val <= 65535) && (Val >= 1)) {
3010 Result = DAG.getTargetConstant(Val, Type);
3017 if (Result.getNode()) {
3018 Ops.push_back(Result);
3022 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3026 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3027 // No global is ever allowed as a base.
3032 case 0: // "r+i" or just "i", depending on HasBaseReg.
3035 if (!AM.HasBaseReg) // allow "r+i".
3037 return false; // disallow "r+r" or "r+r+i".
3046 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3047 // The Mips target isn't yet aware of offsets.
3051 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3053 bool IsMemset, bool ZeroMemset,
3055 MachineFunction &MF) const {
3056 if (Subtarget->hasMips64())
3062 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3063 if (VT != MVT::f32 && VT != MVT::f64)
3065 if (Imm.isNegZero())
3067 return Imm.isZero();
3070 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3072 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3074 return TargetLowering::getJumpTableEncoding();
3077 /// This function returns true if CallSym is a long double emulation routine.
3078 static bool isF128SoftLibCall(const char *CallSym) {
3079 const char *const LibCalls[] =
3080 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3081 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3082 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3083 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3084 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3085 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3086 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3087 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3090 const char * const *End = LibCalls + array_lengthof(LibCalls);
3092 // Check that LibCalls is sorted alphabetically.
3093 MipsTargetLowering::LTStr Comp;
3096 for (const char * const *I = LibCalls; I < End - 1; ++I)
3097 assert(Comp(*I, *(I + 1)));
3100 return std::binary_search(LibCalls, End, CallSym, Comp);
3103 /// This function returns true if Ty is fp128 or i128 which was originally a
3105 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3106 if (Ty->isFP128Ty())
3109 const ExternalSymbolSDNode *ES =
3110 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3112 // If the Ty is i128 and the function being called is a long double emulation
3113 // routine, then the original type is f128.
3114 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3117 MipsTargetLowering::MipsCC::SpecialCallingConvType
3118 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3119 MipsCC::SpecialCallingConvType SpecialCallingConv =
3120 MipsCC::NoSpecialCallingConv;;
3121 if (Subtarget->inMips16HardFloat()) {
3122 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3123 llvm::StringRef Sym = G->getGlobal()->getName();
3124 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3125 if (F->hasFnAttribute("__Mips16RetHelper")) {
3126 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3130 return SpecialCallingConv;
3133 MipsTargetLowering::MipsCC::MipsCC(
3134 CallingConv::ID CC, bool IsO32_, CCState &Info,
3135 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3136 : CCInfo(Info), CallConv(CC), IsO32(IsO32_),
3137 SpecialCallingConv(SpecialCallingConv_){
3138 // Pre-allocate reserved argument area.
3139 CCInfo.AllocateStack(reservedArgArea(), 1);
3143 void MipsTargetLowering::MipsCC::
3144 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3145 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3146 std::vector<ArgListEntry> &FuncArgs) {
3147 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3148 "CallingConv::Fast shouldn't be used for vararg functions.");
3150 unsigned NumOpnds = Args.size();
3151 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3153 for (unsigned I = 0; I != NumOpnds; ++I) {
3154 MVT ArgVT = Args[I].VT;
3155 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3158 if (ArgFlags.isByVal()) {
3159 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3163 if (IsVarArg && !Args[I].IsFixed)
3164 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3166 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3168 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3173 dbgs() << "Call operand #" << I << " has unhandled type "
3174 << EVT(ArgVT).getEVTString();
3176 llvm_unreachable(0);
3181 void MipsTargetLowering::MipsCC::
3182 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3183 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3184 unsigned NumArgs = Args.size();
3185 llvm::CCAssignFn *FixedFn = fixedArgFn();
3186 unsigned CurArgIdx = 0;
3188 for (unsigned I = 0; I != NumArgs; ++I) {
3189 MVT ArgVT = Args[I].VT;
3190 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3191 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3192 CurArgIdx = Args[I].OrigArgIndex;
3194 if (ArgFlags.isByVal()) {
3195 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3199 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3201 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3205 dbgs() << "Formal Arg #" << I << " has unhandled type "
3206 << EVT(ArgVT).getEVTString();
3208 llvm_unreachable(0);
3212 template<typename Ty>
3213 void MipsTargetLowering::MipsCC::
3214 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3215 const SDNode *CallNode, const Type *RetTy) const {
3218 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3219 Fn = RetCC_F128Soft;
3223 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3224 MVT VT = RetVals[I].VT;
3225 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3226 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3228 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3230 dbgs() << "Call result #" << I << " has unhandled type "
3231 << EVT(VT).getEVTString() << '\n';
3233 llvm_unreachable(0);
3238 void MipsTargetLowering::MipsCC::
3239 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3240 const SDNode *CallNode, const Type *RetTy) const {
3241 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3244 void MipsTargetLowering::MipsCC::
3245 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3246 const Type *RetTy) const {
3247 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3251 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3253 CCValAssign::LocInfo LocInfo,
3254 ISD::ArgFlagsTy ArgFlags) {
3255 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3257 struct ByValArgInfo ByVal;
3258 unsigned RegSize = regSize();
3259 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3260 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3263 if (useRegsForByval())
3264 allocateRegs(ByVal, ByValSize, Align);
3266 // Allocate space on caller's stack.
3267 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3269 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3271 ByValArgs.push_back(ByVal);
3274 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3275 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3278 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3279 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3282 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3283 return IsO32 ? O32IntRegs : Mips64IntRegs;
3286 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3287 if (CallConv == CallingConv::Fast)
3288 return CC_Mips_FastCC;
3290 if (SpecialCallingConv == Mips16RetHelperConv)
3291 return CC_Mips16RetHelper;
3292 return IsO32 ? CC_MipsO32 : CC_MipsN;
3295 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3296 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
3299 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3300 return IsO32 ? O32IntRegs : Mips64DPRegs;
3303 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3306 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3307 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3308 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3309 "Byval argument's size and alignment should be a multiple of"
3312 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3314 // If Align > RegSize, the first arg register must be even.
3315 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3316 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3320 // Mark the registers allocated.
3321 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3322 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3323 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3326 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3327 const SDNode *CallNode,
3328 bool IsSoftFloat) const {
3329 if (IsSoftFloat || IsO32)
3332 // Check if the original type was fp128.
3333 if (originalTypeIsF128(OrigTy, CallNode)) {
3334 assert(VT == MVT::i64);
3341 void MipsTargetLowering::
3342 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3343 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3344 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3345 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3346 MachineFunction &MF = DAG.getMachineFunction();
3347 MachineFrameInfo *MFI = MF.getFrameInfo();
3348 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3349 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3353 FrameObjOffset = (int)CC.reservedArgArea() -
3354 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3356 FrameObjOffset = ByVal.Address;
3358 // Create frame object.
3359 EVT PtrTy = getPointerTy();
3360 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3361 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3362 InVals.push_back(FIN);
3367 // Copy arg registers.
3368 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3369 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3371 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3372 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3373 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3374 unsigned Offset = I * CC.regSize();
3375 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3376 DAG.getConstant(Offset, PtrTy));
3377 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3378 StorePtr, MachinePointerInfo(FuncArg, Offset),
3380 OutChains.push_back(Store);
3384 // Copy byVal arg to registers and stack.
3385 void MipsTargetLowering::
3386 passByValArg(SDValue Chain, SDLoc DL,
3387 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3388 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3389 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3390 const MipsCC &CC, const ByValArgInfo &ByVal,
3391 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3392 unsigned ByValSize = Flags.getByValSize();
3393 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3394 unsigned RegSize = CC.regSize();
3395 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3396 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3398 if (ByVal.NumRegs) {
3399 const uint16_t *ArgRegs = CC.intArgRegs();
3400 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3403 // Copy words to registers.
3404 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3405 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3406 DAG.getConstant(Offset, PtrTy));
3407 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3408 MachinePointerInfo(), false, false, false,
3410 MemOpChains.push_back(LoadVal.getValue(1));
3411 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3412 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3415 // Return if the struct has been fully copied.
3416 if (ByValSize == Offset)
3419 // Copy the remainder of the byval argument with sub-word loads and shifts.
3420 if (LeftoverBytes) {
3421 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3422 "Size of the remainder should be smaller than RegSize.");
3425 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3426 Offset < ByValSize; LoadSize /= 2) {
3427 unsigned RemSize = ByValSize - Offset;
3429 if (RemSize < LoadSize)
3433 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3434 DAG.getConstant(Offset, PtrTy));
3436 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3437 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3438 false, false, Alignment);
3439 MemOpChains.push_back(LoadVal.getValue(1));
3441 // Shift the loaded value.
3445 Shamt = TotalSizeLoaded;
3447 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3449 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3450 DAG.getConstant(Shamt, MVT::i32));
3453 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3458 TotalSizeLoaded += LoadSize;
3459 Alignment = std::min(Alignment, LoadSize);
3462 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3463 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3468 // Copy remainder of byval arg to it with memcpy.
3469 unsigned MemCpySize = ByValSize - Offset;
3470 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3471 DAG.getConstant(Offset, PtrTy));
3472 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3473 DAG.getIntPtrConstant(ByVal.Address));
3474 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3475 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3476 /*isVolatile=*/false, /*AlwaysInline=*/false,
3477 MachinePointerInfo(0), MachinePointerInfo(0));
3478 MemOpChains.push_back(Chain);
3482 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3483 const MipsCC &CC, SDValue Chain,
3484 SDLoc DL, SelectionDAG &DAG) const {
3485 unsigned NumRegs = CC.numIntArgRegs();
3486 const uint16_t *ArgRegs = CC.intArgRegs();
3487 const CCState &CCInfo = CC.getCCInfo();
3488 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3489 unsigned RegSize = CC.regSize();
3490 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3491 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3492 MachineFunction &MF = DAG.getMachineFunction();
3493 MachineFrameInfo *MFI = MF.getFrameInfo();
3494 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3496 // Offset of the first variable argument from stack pointer.
3500 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3503 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3505 // Record the frame index of the first variable argument
3506 // which is a value necessary to VASTART.
3507 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3508 MipsFI->setVarArgsFrameIndex(FI);
3510 // Copy the integer registers that have not been used for argument passing
3511 // to the argument register save area. For O32, the save area is allocated
3512 // in the caller's stack frame, while for N32/64, it is allocated in the
3513 // callee's stack frame.
3514 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3515 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3516 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3517 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3518 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3519 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3520 MachinePointerInfo(), false, false, 0);
3521 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3522 OutChains.push_back(Store);