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));
46 static const uint16_t O32IntRegs[4] = {
47 Mips::A0, Mips::A1, Mips::A2, Mips::A3
50 static const uint16_t Mips64IntRegs[8] = {
51 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
52 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
55 static const uint16_t Mips64DPRegs[8] = {
56 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
57 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
60 // If I is a shifted mask, set the size (Size) and the first bit of the
61 // mask (Pos), and return true.
62 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
63 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
64 if (!isShiftedMask_64(I))
67 Size = CountPopulation_64(I);
68 Pos = CountTrailingZeros_64(I);
72 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
73 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
74 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
77 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
78 EVT Ty = Op.getValueType();
80 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
81 return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
83 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
84 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
85 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
86 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
87 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
88 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
89 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
90 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
91 N->getOffset(), Flag);
93 llvm_unreachable("Unexpected node type.");
97 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
98 DebugLoc DL = Op.getDebugLoc();
99 EVT Ty = Op.getValueType();
100 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
101 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
102 return DAG.getNode(ISD::ADD, DL, Ty,
103 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
104 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
107 SDValue MipsTargetLowering::getAddrLocal(SDValue Op, SelectionDAG &DAG,
108 bool HasMips64) const {
109 DebugLoc DL = Op.getDebugLoc();
110 EVT Ty = Op.getValueType();
111 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
112 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
113 getTargetNode(Op, DAG, GOTFlag));
114 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
115 MachinePointerInfo::getGOT(), false, false, false,
117 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
118 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
119 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
122 SDValue MipsTargetLowering::getAddrGlobal(SDValue Op, SelectionDAG &DAG,
123 unsigned Flag) const {
124 DebugLoc DL = Op.getDebugLoc();
125 EVT Ty = Op.getValueType();
126 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
127 getTargetNode(Op, DAG, Flag));
128 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
129 MachinePointerInfo::getGOT(), false, false, false, 0);
132 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
134 unsigned LoFlag) const {
135 DebugLoc DL = Op.getDebugLoc();
136 EVT Ty = Op.getValueType();
137 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
138 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
139 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
140 getTargetNode(Op, DAG, LoFlag));
141 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
142 MachinePointerInfo::getGOT(), false, false, false, 0);
145 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
147 case MipsISD::JmpLink: return "MipsISD::JmpLink";
148 case MipsISD::TailCall: return "MipsISD::TailCall";
149 case MipsISD::Hi: return "MipsISD::Hi";
150 case MipsISD::Lo: return "MipsISD::Lo";
151 case MipsISD::GPRel: return "MipsISD::GPRel";
152 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
153 case MipsISD::Ret: return "MipsISD::Ret";
154 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
155 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
156 case MipsISD::FPCmp: return "MipsISD::FPCmp";
157 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
158 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
159 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
160 case MipsISD::ExtractLOHI: return "MipsISD::ExtractLOHI";
161 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
162 case MipsISD::Mult: return "MipsISD::Mult";
163 case MipsISD::Multu: return "MipsISD::Multu";
164 case MipsISD::MAdd: return "MipsISD::MAdd";
165 case MipsISD::MAddu: return "MipsISD::MAddu";
166 case MipsISD::MSub: return "MipsISD::MSub";
167 case MipsISD::MSubu: return "MipsISD::MSubu";
168 case MipsISD::DivRem: return "MipsISD::DivRem";
169 case MipsISD::DivRemU: return "MipsISD::DivRemU";
170 case MipsISD::DivRem16: return "MipsISD::DivRem16";
171 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
172 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
173 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
174 case MipsISD::Wrapper: return "MipsISD::Wrapper";
175 case MipsISD::Sync: return "MipsISD::Sync";
176 case MipsISD::Ext: return "MipsISD::Ext";
177 case MipsISD::Ins: return "MipsISD::Ins";
178 case MipsISD::LWL: return "MipsISD::LWL";
179 case MipsISD::LWR: return "MipsISD::LWR";
180 case MipsISD::SWL: return "MipsISD::SWL";
181 case MipsISD::SWR: return "MipsISD::SWR";
182 case MipsISD::LDL: return "MipsISD::LDL";
183 case MipsISD::LDR: return "MipsISD::LDR";
184 case MipsISD::SDL: return "MipsISD::SDL";
185 case MipsISD::SDR: return "MipsISD::SDR";
186 case MipsISD::EXTP: return "MipsISD::EXTP";
187 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
188 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
189 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
190 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
191 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
192 case MipsISD::SHILO: return "MipsISD::SHILO";
193 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
194 case MipsISD::MULT: return "MipsISD::MULT";
195 case MipsISD::MULTU: return "MipsISD::MULTU";
196 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
197 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
198 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
199 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
200 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
201 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
202 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
203 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
204 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
205 default: return NULL;
210 MipsTargetLowering(MipsTargetMachine &TM)
211 : TargetLowering(TM, new MipsTargetObjectFile()),
212 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
213 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
214 IsO32(Subtarget->isABI_O32()) {
215 // Mips does not have i1 type, so use i32 for
216 // setcc operations results (slt, sgt, ...).
217 setBooleanContents(ZeroOrOneBooleanContent);
218 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
220 // Load extented operations for i1 types must be promoted
221 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
222 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
223 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
225 // MIPS doesn't have extending float->double load/store
226 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
227 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
229 // Used by legalize types to correctly generate the setcc result.
230 // Without this, every float setcc comes with a AND/OR with the result,
231 // we don't want this, since the fpcmp result goes to a flag register,
232 // which is used implicitly by brcond and select operations.
233 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
235 // Mips Custom Operations
236 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
237 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
238 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
239 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
240 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
241 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
242 setOperationAction(ISD::SELECT, MVT::f32, Custom);
243 setOperationAction(ISD::SELECT, MVT::f64, Custom);
244 setOperationAction(ISD::SELECT, MVT::i32, Custom);
245 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
246 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
247 setOperationAction(ISD::SETCC, MVT::f32, Custom);
248 setOperationAction(ISD::SETCC, MVT::f64, Custom);
249 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
250 setOperationAction(ISD::VASTART, MVT::Other, Custom);
251 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
252 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
253 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 if (!TM.Options.NoNaNsFPMath) {
256 setOperationAction(ISD::FABS, MVT::f32, Custom);
257 setOperationAction(ISD::FABS, MVT::f64, Custom);
261 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
262 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
263 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
264 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
265 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
266 setOperationAction(ISD::SELECT, MVT::i64, Custom);
267 setOperationAction(ISD::LOAD, MVT::i64, Custom);
268 setOperationAction(ISD::STORE, MVT::i64, Custom);
269 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
273 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
274 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
275 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
278 setOperationAction(ISD::ADD, MVT::i32, Custom);
280 setOperationAction(ISD::ADD, MVT::i64, Custom);
282 setOperationAction(ISD::SDIV, MVT::i32, Expand);
283 setOperationAction(ISD::SREM, MVT::i32, Expand);
284 setOperationAction(ISD::UDIV, MVT::i32, Expand);
285 setOperationAction(ISD::UREM, MVT::i32, Expand);
286 setOperationAction(ISD::SDIV, MVT::i64, Expand);
287 setOperationAction(ISD::SREM, MVT::i64, Expand);
288 setOperationAction(ISD::UDIV, MVT::i64, Expand);
289 setOperationAction(ISD::UREM, MVT::i64, Expand);
291 // Operations not directly supported by Mips.
292 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
293 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
294 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
295 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
296 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
297 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
298 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
299 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
300 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
301 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
302 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
303 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
304 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
305 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
306 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
307 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
308 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
309 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
310 setOperationAction(ISD::ROTL, MVT::i32, Expand);
311 setOperationAction(ISD::ROTL, MVT::i64, Expand);
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
313 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
315 if (!Subtarget->hasMips32r2())
316 setOperationAction(ISD::ROTR, MVT::i32, Expand);
318 if (!Subtarget->hasMips64r2())
319 setOperationAction(ISD::ROTR, MVT::i64, Expand);
321 setOperationAction(ISD::FSIN, MVT::f32, Expand);
322 setOperationAction(ISD::FSIN, MVT::f64, Expand);
323 setOperationAction(ISD::FCOS, MVT::f32, Expand);
324 setOperationAction(ISD::FCOS, MVT::f64, Expand);
325 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
326 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
327 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
328 setOperationAction(ISD::FPOW, MVT::f32, Expand);
329 setOperationAction(ISD::FPOW, MVT::f64, Expand);
330 setOperationAction(ISD::FLOG, MVT::f32, Expand);
331 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
332 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
333 setOperationAction(ISD::FEXP, MVT::f32, Expand);
334 setOperationAction(ISD::FMA, MVT::f32, Expand);
335 setOperationAction(ISD::FMA, MVT::f64, Expand);
336 setOperationAction(ISD::FREM, MVT::f32, Expand);
337 setOperationAction(ISD::FREM, MVT::f64, Expand);
339 if (!TM.Options.NoNaNsFPMath) {
340 setOperationAction(ISD::FNEG, MVT::f32, Expand);
341 setOperationAction(ISD::FNEG, MVT::f64, Expand);
344 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
345 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
346 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
347 setOperationAction(ISD::EHSELECTION, MVT::i64, 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 :
429 DebugLoc DL = N->getDebugLoc();
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);
507 DebugLoc DL = Op.getDebugLoc();
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, DebugLoc DL) {
520 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
521 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
523 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
524 True.getValueType(), True, False, Cond);
527 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
528 TargetLowering::DAGCombinerInfo &DCI,
529 const MipsSubtarget *Subtarget) {
530 if (DCI.isBeforeLegalizeOps())
533 SDValue SetCC = N->getOperand(0);
535 if ((SetCC.getOpcode() != ISD::SETCC) ||
536 !SetCC.getOperand(0).getValueType().isInteger())
539 SDValue False = N->getOperand(2);
540 EVT FalseTy = False.getValueType();
542 if (!FalseTy.isInteger())
545 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
547 if (!CN || CN->getZExtValue())
550 const DebugLoc DL = N->getDebugLoc();
551 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
552 SDValue True = N->getOperand(1);
554 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
555 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
557 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
560 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
561 TargetLowering::DAGCombinerInfo &DCI,
562 const MipsSubtarget *Subtarget) {
563 // Pattern match EXT.
564 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
565 // => ext $dst, $src, size, pos
566 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
569 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
570 unsigned ShiftRightOpc = ShiftRight.getOpcode();
572 // Op's first operand must be a shift right.
573 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
576 // The second operand of the shift must be an immediate.
578 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
581 uint64_t Pos = CN->getZExtValue();
582 uint64_t SMPos, SMSize;
584 // Op's second operand must be a shifted mask.
585 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
586 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
589 // Return if the shifted mask does not start at bit 0 or the sum of its size
590 // and Pos exceeds the word's size.
591 EVT ValTy = N->getValueType(0);
592 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
595 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
596 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
597 DAG.getConstant(SMSize, MVT::i32));
600 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
601 TargetLowering::DAGCombinerInfo &DCI,
602 const MipsSubtarget *Subtarget) {
603 // Pattern match INS.
604 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
605 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
606 // => ins $dst, $src, size, pos, $src1
607 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
610 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
611 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
614 // See if Op's first operand matches (and $src1 , mask0).
615 if (And0.getOpcode() != ISD::AND)
618 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
619 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
622 // See if Op's second operand matches (and (shl $src, pos), mask1).
623 if (And1.getOpcode() != ISD::AND)
626 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
627 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
630 // The shift masks must have the same position and size.
631 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
634 SDValue Shl = And1.getOperand(0);
635 if (Shl.getOpcode() != ISD::SHL)
638 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
641 unsigned Shamt = CN->getZExtValue();
643 // Return if the shift amount and the first bit position of mask are not the
645 EVT ValTy = N->getValueType(0);
646 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
649 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
650 DAG.getConstant(SMPos0, MVT::i32),
651 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
654 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
655 TargetLowering::DAGCombinerInfo &DCI,
656 const MipsSubtarget *Subtarget) {
657 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
659 if (DCI.isBeforeLegalizeOps())
662 SDValue Add = N->getOperand(1);
664 if (Add.getOpcode() != ISD::ADD)
667 SDValue Lo = Add.getOperand(1);
669 if ((Lo.getOpcode() != MipsISD::Lo) ||
670 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
673 EVT ValTy = N->getValueType(0);
674 DebugLoc DL = N->getDebugLoc();
676 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
678 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
681 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
683 SelectionDAG &DAG = DCI.DAG;
684 unsigned Opc = N->getOpcode();
690 return performDivRemCombine(N, DAG, DCI, Subtarget);
692 return performSELECTCombine(N, DAG, DCI, Subtarget);
694 return performANDCombine(N, DAG, DCI, Subtarget);
696 return performORCombine(N, DAG, DCI, Subtarget);
698 return performADDCombine(N, DAG, DCI, Subtarget);
705 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
706 SmallVectorImpl<SDValue> &Results,
707 SelectionDAG &DAG) const {
708 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
710 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
711 Results.push_back(Res.getValue(I));
715 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
716 SmallVectorImpl<SDValue> &Results,
717 SelectionDAG &DAG) const {
718 return LowerOperationWrapper(N, Results, DAG);
721 SDValue MipsTargetLowering::
722 LowerOperation(SDValue Op, SelectionDAG &DAG) const
724 switch (Op.getOpcode())
726 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
727 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
728 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
729 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
730 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
731 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
732 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
733 case ISD::SELECT: return lowerSELECT(Op, DAG);
734 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
735 case ISD::SETCC: return lowerSETCC(Op, DAG);
736 case ISD::VASTART: return lowerVASTART(Op, DAG);
737 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
738 case ISD::FABS: return lowerFABS(Op, DAG);
739 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
740 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
741 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
742 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
743 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
744 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
745 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
746 case ISD::LOAD: return lowerLOAD(Op, DAG);
747 case ISD::STORE: return lowerSTORE(Op, DAG);
748 case ISD::ADD: return lowerADD(Op, DAG);
749 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
754 //===----------------------------------------------------------------------===//
755 // Lower helper functions
756 //===----------------------------------------------------------------------===//
758 // addLiveIn - This helper function adds the specified physical register to the
759 // MachineFunction as a live in value. It also creates a corresponding
760 // virtual register for it.
762 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
764 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
765 MF.getRegInfo().addLiveIn(PReg, VReg);
770 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
771 MachineBasicBlock *BB) const {
772 switch (MI->getOpcode()) {
774 llvm_unreachable("Unexpected instr type to insert");
775 case Mips::ATOMIC_LOAD_ADD_I8:
776 case Mips::ATOMIC_LOAD_ADD_I8_P8:
777 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
778 case Mips::ATOMIC_LOAD_ADD_I16:
779 case Mips::ATOMIC_LOAD_ADD_I16_P8:
780 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
781 case Mips::ATOMIC_LOAD_ADD_I32:
782 case Mips::ATOMIC_LOAD_ADD_I32_P8:
783 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
784 case Mips::ATOMIC_LOAD_ADD_I64:
785 case Mips::ATOMIC_LOAD_ADD_I64_P8:
786 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
788 case Mips::ATOMIC_LOAD_AND_I8:
789 case Mips::ATOMIC_LOAD_AND_I8_P8:
790 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
791 case Mips::ATOMIC_LOAD_AND_I16:
792 case Mips::ATOMIC_LOAD_AND_I16_P8:
793 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
794 case Mips::ATOMIC_LOAD_AND_I32:
795 case Mips::ATOMIC_LOAD_AND_I32_P8:
796 return emitAtomicBinary(MI, BB, 4, Mips::AND);
797 case Mips::ATOMIC_LOAD_AND_I64:
798 case Mips::ATOMIC_LOAD_AND_I64_P8:
799 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
801 case Mips::ATOMIC_LOAD_OR_I8:
802 case Mips::ATOMIC_LOAD_OR_I8_P8:
803 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
804 case Mips::ATOMIC_LOAD_OR_I16:
805 case Mips::ATOMIC_LOAD_OR_I16_P8:
806 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
807 case Mips::ATOMIC_LOAD_OR_I32:
808 case Mips::ATOMIC_LOAD_OR_I32_P8:
809 return emitAtomicBinary(MI, BB, 4, Mips::OR);
810 case Mips::ATOMIC_LOAD_OR_I64:
811 case Mips::ATOMIC_LOAD_OR_I64_P8:
812 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
814 case Mips::ATOMIC_LOAD_XOR_I8:
815 case Mips::ATOMIC_LOAD_XOR_I8_P8:
816 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
817 case Mips::ATOMIC_LOAD_XOR_I16:
818 case Mips::ATOMIC_LOAD_XOR_I16_P8:
819 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
820 case Mips::ATOMIC_LOAD_XOR_I32:
821 case Mips::ATOMIC_LOAD_XOR_I32_P8:
822 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
823 case Mips::ATOMIC_LOAD_XOR_I64:
824 case Mips::ATOMIC_LOAD_XOR_I64_P8:
825 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
827 case Mips::ATOMIC_LOAD_NAND_I8:
828 case Mips::ATOMIC_LOAD_NAND_I8_P8:
829 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
830 case Mips::ATOMIC_LOAD_NAND_I16:
831 case Mips::ATOMIC_LOAD_NAND_I16_P8:
832 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
833 case Mips::ATOMIC_LOAD_NAND_I32:
834 case Mips::ATOMIC_LOAD_NAND_I32_P8:
835 return emitAtomicBinary(MI, BB, 4, 0, true);
836 case Mips::ATOMIC_LOAD_NAND_I64:
837 case Mips::ATOMIC_LOAD_NAND_I64_P8:
838 return emitAtomicBinary(MI, BB, 8, 0, true);
840 case Mips::ATOMIC_LOAD_SUB_I8:
841 case Mips::ATOMIC_LOAD_SUB_I8_P8:
842 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
843 case Mips::ATOMIC_LOAD_SUB_I16:
844 case Mips::ATOMIC_LOAD_SUB_I16_P8:
845 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
846 case Mips::ATOMIC_LOAD_SUB_I32:
847 case Mips::ATOMIC_LOAD_SUB_I32_P8:
848 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
849 case Mips::ATOMIC_LOAD_SUB_I64:
850 case Mips::ATOMIC_LOAD_SUB_I64_P8:
851 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
853 case Mips::ATOMIC_SWAP_I8:
854 case Mips::ATOMIC_SWAP_I8_P8:
855 return emitAtomicBinaryPartword(MI, BB, 1, 0);
856 case Mips::ATOMIC_SWAP_I16:
857 case Mips::ATOMIC_SWAP_I16_P8:
858 return emitAtomicBinaryPartword(MI, BB, 2, 0);
859 case Mips::ATOMIC_SWAP_I32:
860 case Mips::ATOMIC_SWAP_I32_P8:
861 return emitAtomicBinary(MI, BB, 4, 0);
862 case Mips::ATOMIC_SWAP_I64:
863 case Mips::ATOMIC_SWAP_I64_P8:
864 return emitAtomicBinary(MI, BB, 8, 0);
866 case Mips::ATOMIC_CMP_SWAP_I8:
867 case Mips::ATOMIC_CMP_SWAP_I8_P8:
868 return emitAtomicCmpSwapPartword(MI, BB, 1);
869 case Mips::ATOMIC_CMP_SWAP_I16:
870 case Mips::ATOMIC_CMP_SWAP_I16_P8:
871 return emitAtomicCmpSwapPartword(MI, BB, 2);
872 case Mips::ATOMIC_CMP_SWAP_I32:
873 case Mips::ATOMIC_CMP_SWAP_I32_P8:
874 return emitAtomicCmpSwap(MI, BB, 4);
875 case Mips::ATOMIC_CMP_SWAP_I64:
876 case Mips::ATOMIC_CMP_SWAP_I64_P8:
877 return emitAtomicCmpSwap(MI, BB, 8);
881 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
882 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
884 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
885 unsigned Size, unsigned BinOpcode,
887 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
889 MachineFunction *MF = BB->getParent();
890 MachineRegisterInfo &RegInfo = MF->getRegInfo();
891 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
892 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
893 DebugLoc DL = MI->getDebugLoc();
894 unsigned LL, SC, AND, NOR, ZERO, BEQ;
897 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
898 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
905 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
906 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
909 ZERO = Mips::ZERO_64;
913 unsigned OldVal = MI->getOperand(0).getReg();
914 unsigned Ptr = MI->getOperand(1).getReg();
915 unsigned Incr = MI->getOperand(2).getReg();
917 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
918 unsigned AndRes = RegInfo.createVirtualRegister(RC);
919 unsigned Success = RegInfo.createVirtualRegister(RC);
921 // insert new blocks after the current block
922 const BasicBlock *LLVM_BB = BB->getBasicBlock();
923 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
924 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
925 MachineFunction::iterator It = BB;
927 MF->insert(It, loopMBB);
928 MF->insert(It, exitMBB);
930 // Transfer the remainder of BB and its successor edges to exitMBB.
931 exitMBB->splice(exitMBB->begin(), BB,
932 llvm::next(MachineBasicBlock::iterator(MI)),
934 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
938 // fallthrough --> loopMBB
939 BB->addSuccessor(loopMBB);
940 loopMBB->addSuccessor(loopMBB);
941 loopMBB->addSuccessor(exitMBB);
945 // <binop> storeval, oldval, incr
946 // sc success, storeval, 0(ptr)
947 // beq success, $0, loopMBB
949 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
951 // and andres, oldval, incr
952 // nor storeval, $0, andres
953 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
954 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
955 } else if (BinOpcode) {
956 // <binop> storeval, oldval, incr
957 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
961 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
962 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
964 MI->eraseFromParent(); // The instruction is gone now.
970 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
971 MachineBasicBlock *BB,
972 unsigned Size, unsigned BinOpcode,
974 assert((Size == 1 || Size == 2) &&
975 "Unsupported size for EmitAtomicBinaryPartial.");
977 MachineFunction *MF = BB->getParent();
978 MachineRegisterInfo &RegInfo = MF->getRegInfo();
979 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
980 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
981 DebugLoc DL = MI->getDebugLoc();
982 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
983 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
985 unsigned Dest = MI->getOperand(0).getReg();
986 unsigned Ptr = MI->getOperand(1).getReg();
987 unsigned Incr = MI->getOperand(2).getReg();
989 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
990 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
991 unsigned Mask = RegInfo.createVirtualRegister(RC);
992 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
993 unsigned NewVal = RegInfo.createVirtualRegister(RC);
994 unsigned OldVal = RegInfo.createVirtualRegister(RC);
995 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
996 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
997 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
998 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
999 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1000 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1001 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1002 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1003 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1004 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1005 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1006 unsigned Success = RegInfo.createVirtualRegister(RC);
1008 // insert new blocks after the current block
1009 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1010 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1011 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1012 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1013 MachineFunction::iterator It = BB;
1015 MF->insert(It, loopMBB);
1016 MF->insert(It, sinkMBB);
1017 MF->insert(It, exitMBB);
1019 // Transfer the remainder of BB and its successor edges to exitMBB.
1020 exitMBB->splice(exitMBB->begin(), BB,
1021 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1022 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1024 BB->addSuccessor(loopMBB);
1025 loopMBB->addSuccessor(loopMBB);
1026 loopMBB->addSuccessor(sinkMBB);
1027 sinkMBB->addSuccessor(exitMBB);
1030 // addiu masklsb2,$0,-4 # 0xfffffffc
1031 // and alignedaddr,ptr,masklsb2
1032 // andi ptrlsb2,ptr,3
1033 // sll shiftamt,ptrlsb2,3
1034 // ori maskupper,$0,255 # 0xff
1035 // sll mask,maskupper,shiftamt
1036 // nor mask2,$0,mask
1037 // sll incr2,incr,shiftamt
1039 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1040 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1041 .addReg(Mips::ZERO).addImm(-4);
1042 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1043 .addReg(Ptr).addReg(MaskLSB2);
1044 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1045 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1046 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1047 .addReg(Mips::ZERO).addImm(MaskImm);
1048 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1049 .addReg(ShiftAmt).addReg(MaskUpper);
1050 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1051 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1053 // atomic.load.binop
1055 // ll oldval,0(alignedaddr)
1056 // binop binopres,oldval,incr2
1057 // and newval,binopres,mask
1058 // and maskedoldval0,oldval,mask2
1059 // or storeval,maskedoldval0,newval
1060 // sc success,storeval,0(alignedaddr)
1061 // beq success,$0,loopMBB
1065 // ll oldval,0(alignedaddr)
1066 // and newval,incr2,mask
1067 // and maskedoldval0,oldval,mask2
1068 // or storeval,maskedoldval0,newval
1069 // sc success,storeval,0(alignedaddr)
1070 // beq success,$0,loopMBB
1073 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1075 // and andres, oldval, incr2
1076 // nor binopres, $0, andres
1077 // and newval, binopres, mask
1078 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1079 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1080 .addReg(Mips::ZERO).addReg(AndRes);
1081 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1082 } else if (BinOpcode) {
1083 // <binop> binopres, oldval, incr2
1084 // and newval, binopres, mask
1085 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1086 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1087 } else {// atomic.swap
1088 // and newval, incr2, mask
1089 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1092 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1093 .addReg(OldVal).addReg(Mask2);
1094 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1095 .addReg(MaskedOldVal0).addReg(NewVal);
1096 BuildMI(BB, DL, TII->get(SC), Success)
1097 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1098 BuildMI(BB, DL, TII->get(Mips::BEQ))
1099 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1102 // and maskedoldval1,oldval,mask
1103 // srl srlres,maskedoldval1,shiftamt
1104 // sll sllres,srlres,24
1105 // sra dest,sllres,24
1107 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1109 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1110 .addReg(OldVal).addReg(Mask);
1111 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1112 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1113 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1114 .addReg(SrlRes).addImm(ShiftImm);
1115 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1116 .addReg(SllRes).addImm(ShiftImm);
1118 MI->eraseFromParent(); // The instruction is gone now.
1124 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1125 MachineBasicBlock *BB,
1126 unsigned Size) const {
1127 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1129 MachineFunction *MF = BB->getParent();
1130 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1131 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1132 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1133 DebugLoc DL = MI->getDebugLoc();
1134 unsigned LL, SC, ZERO, BNE, BEQ;
1137 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1138 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1144 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1145 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1146 ZERO = Mips::ZERO_64;
1151 unsigned Dest = MI->getOperand(0).getReg();
1152 unsigned Ptr = MI->getOperand(1).getReg();
1153 unsigned OldVal = MI->getOperand(2).getReg();
1154 unsigned NewVal = MI->getOperand(3).getReg();
1156 unsigned Success = RegInfo.createVirtualRegister(RC);
1158 // insert new blocks after the current block
1159 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1160 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1161 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1162 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1163 MachineFunction::iterator It = BB;
1165 MF->insert(It, loop1MBB);
1166 MF->insert(It, loop2MBB);
1167 MF->insert(It, exitMBB);
1169 // Transfer the remainder of BB and its successor edges to exitMBB.
1170 exitMBB->splice(exitMBB->begin(), BB,
1171 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1172 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1176 // fallthrough --> loop1MBB
1177 BB->addSuccessor(loop1MBB);
1178 loop1MBB->addSuccessor(exitMBB);
1179 loop1MBB->addSuccessor(loop2MBB);
1180 loop2MBB->addSuccessor(loop1MBB);
1181 loop2MBB->addSuccessor(exitMBB);
1185 // bne dest, oldval, exitMBB
1187 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1188 BuildMI(BB, DL, TII->get(BNE))
1189 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1192 // sc success, newval, 0(ptr)
1193 // beq success, $0, loop1MBB
1195 BuildMI(BB, DL, TII->get(SC), Success)
1196 .addReg(NewVal).addReg(Ptr).addImm(0);
1197 BuildMI(BB, DL, TII->get(BEQ))
1198 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1200 MI->eraseFromParent(); // The instruction is gone now.
1206 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1207 MachineBasicBlock *BB,
1208 unsigned Size) const {
1209 assert((Size == 1 || Size == 2) &&
1210 "Unsupported size for EmitAtomicCmpSwapPartial.");
1212 MachineFunction *MF = BB->getParent();
1213 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1214 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1215 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1216 DebugLoc DL = MI->getDebugLoc();
1217 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1218 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1220 unsigned Dest = MI->getOperand(0).getReg();
1221 unsigned Ptr = MI->getOperand(1).getReg();
1222 unsigned CmpVal = MI->getOperand(2).getReg();
1223 unsigned NewVal = MI->getOperand(3).getReg();
1225 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1226 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1227 unsigned Mask = RegInfo.createVirtualRegister(RC);
1228 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1229 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1230 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1231 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1232 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1233 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1234 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1235 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1236 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1237 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1238 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1239 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1240 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1241 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1242 unsigned Success = RegInfo.createVirtualRegister(RC);
1244 // insert new blocks after the current block
1245 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1246 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1247 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1248 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1249 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1250 MachineFunction::iterator It = BB;
1252 MF->insert(It, loop1MBB);
1253 MF->insert(It, loop2MBB);
1254 MF->insert(It, sinkMBB);
1255 MF->insert(It, exitMBB);
1257 // Transfer the remainder of BB and its successor edges to exitMBB.
1258 exitMBB->splice(exitMBB->begin(), BB,
1259 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1260 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1262 BB->addSuccessor(loop1MBB);
1263 loop1MBB->addSuccessor(sinkMBB);
1264 loop1MBB->addSuccessor(loop2MBB);
1265 loop2MBB->addSuccessor(loop1MBB);
1266 loop2MBB->addSuccessor(sinkMBB);
1267 sinkMBB->addSuccessor(exitMBB);
1269 // FIXME: computation of newval2 can be moved to loop2MBB.
1271 // addiu masklsb2,$0,-4 # 0xfffffffc
1272 // and alignedaddr,ptr,masklsb2
1273 // andi ptrlsb2,ptr,3
1274 // sll shiftamt,ptrlsb2,3
1275 // ori maskupper,$0,255 # 0xff
1276 // sll mask,maskupper,shiftamt
1277 // nor mask2,$0,mask
1278 // andi maskedcmpval,cmpval,255
1279 // sll shiftedcmpval,maskedcmpval,shiftamt
1280 // andi maskednewval,newval,255
1281 // sll shiftednewval,maskednewval,shiftamt
1282 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1283 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1284 .addReg(Mips::ZERO).addImm(-4);
1285 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1286 .addReg(Ptr).addReg(MaskLSB2);
1287 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1288 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1289 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1290 .addReg(Mips::ZERO).addImm(MaskImm);
1291 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1292 .addReg(ShiftAmt).addReg(MaskUpper);
1293 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1294 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1295 .addReg(CmpVal).addImm(MaskImm);
1296 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1297 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1298 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1299 .addReg(NewVal).addImm(MaskImm);
1300 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1301 .addReg(ShiftAmt).addReg(MaskedNewVal);
1304 // ll oldval,0(alginedaddr)
1305 // and maskedoldval0,oldval,mask
1306 // bne maskedoldval0,shiftedcmpval,sinkMBB
1308 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1309 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1310 .addReg(OldVal).addReg(Mask);
1311 BuildMI(BB, DL, TII->get(Mips::BNE))
1312 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1315 // and maskedoldval1,oldval,mask2
1316 // or storeval,maskedoldval1,shiftednewval
1317 // sc success,storeval,0(alignedaddr)
1318 // beq success,$0,loop1MBB
1320 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1321 .addReg(OldVal).addReg(Mask2);
1322 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1323 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1324 BuildMI(BB, DL, TII->get(SC), Success)
1325 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1326 BuildMI(BB, DL, TII->get(Mips::BEQ))
1327 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1330 // srl srlres,maskedoldval0,shiftamt
1331 // sll sllres,srlres,24
1332 // sra dest,sllres,24
1334 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1336 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1337 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1338 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1339 .addReg(SrlRes).addImm(ShiftImm);
1340 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1341 .addReg(SllRes).addImm(ShiftImm);
1343 MI->eraseFromParent(); // The instruction is gone now.
1348 //===----------------------------------------------------------------------===//
1349 // Misc Lower Operation implementation
1350 //===----------------------------------------------------------------------===//
1351 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1352 SDValue Chain = Op.getOperand(0);
1353 SDValue Table = Op.getOperand(1);
1354 SDValue Index = Op.getOperand(2);
1355 DebugLoc DL = Op.getDebugLoc();
1356 EVT PTy = getPointerTy();
1357 unsigned EntrySize =
1358 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1360 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1361 DAG.getConstant(EntrySize, PTy));
1362 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1364 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1365 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1366 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1368 Chain = Addr.getValue(1);
1370 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1371 // For PIC, the sequence is:
1372 // BRIND(load(Jumptable + index) + RelocBase)
1373 // RelocBase can be JumpTable, GOT or some sort of global base.
1374 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1375 getPICJumpTableRelocBase(Table, DAG));
1378 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1381 SDValue MipsTargetLowering::
1382 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1384 // The first operand is the chain, the second is the condition, the third is
1385 // the block to branch to if the condition is true.
1386 SDValue Chain = Op.getOperand(0);
1387 SDValue Dest = Op.getOperand(2);
1388 DebugLoc DL = Op.getDebugLoc();
1390 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1392 // Return if flag is not set by a floating point comparison.
1393 if (CondRes.getOpcode() != MipsISD::FPCmp)
1396 SDValue CCNode = CondRes.getOperand(2);
1398 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1399 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1400 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1401 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1405 SDValue MipsTargetLowering::
1406 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1408 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1410 // Return if flag is not set by a floating point comparison.
1411 if (Cond.getOpcode() != MipsISD::FPCmp)
1414 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1418 SDValue MipsTargetLowering::
1419 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1421 DebugLoc DL = Op.getDebugLoc();
1422 EVT Ty = Op.getOperand(0).getValueType();
1423 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1424 getSetCCResultType(*DAG.getContext(), Ty),
1425 Op.getOperand(0), Op.getOperand(1),
1428 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1432 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1433 SDValue Cond = createFPCmp(DAG, Op);
1435 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1436 "Floating point operand expected.");
1438 SDValue True = DAG.getConstant(1, MVT::i32);
1439 SDValue False = DAG.getConstant(0, MVT::i32);
1441 return createCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1444 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1445 SelectionDAG &DAG) const {
1446 // FIXME there isn't actually debug info here
1447 DebugLoc DL = Op.getDebugLoc();
1448 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1450 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1451 const MipsTargetObjectFile &TLOF =
1452 (const MipsTargetObjectFile&)getObjFileLowering();
1454 // %gp_rel relocation
1455 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1456 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1458 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1459 DAG.getVTList(MVT::i32), &GA, 1);
1460 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1461 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1464 // %hi/%lo relocation
1465 return getAddrNonPIC(Op, DAG);
1468 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1469 return getAddrLocal(Op, DAG, HasMips64);
1472 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1473 MipsII::MO_GOT_LO16);
1475 return getAddrGlobal(Op, DAG,
1476 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1479 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1480 SelectionDAG &DAG) const {
1481 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1482 return getAddrNonPIC(Op, DAG);
1484 return getAddrLocal(Op, DAG, HasMips64);
1487 SDValue MipsTargetLowering::
1488 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1490 // If the relocation model is PIC, use the General Dynamic TLS Model or
1491 // Local Dynamic TLS model, otherwise use the Initial Exec or
1492 // Local Exec TLS Model.
1494 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1495 DebugLoc DL = GA->getDebugLoc();
1496 const GlobalValue *GV = GA->getGlobal();
1497 EVT PtrVT = getPointerTy();
1499 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1501 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1502 // General Dynamic and Local Dynamic TLS Model.
1503 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1506 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1507 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1508 getGlobalReg(DAG, PtrVT), TGA);
1509 unsigned PtrSize = PtrVT.getSizeInBits();
1510 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1512 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1516 Entry.Node = Argument;
1518 Args.push_back(Entry);
1520 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1521 false, false, false, false, 0, CallingConv::C,
1522 /*IsTailCall=*/false, /*doesNotRet=*/false,
1523 /*isReturnValueUsed=*/true,
1524 TlsGetAddr, Args, DAG, DL);
1525 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1527 SDValue Ret = CallResult.first;
1529 if (model != TLSModel::LocalDynamic)
1532 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1533 MipsII::MO_DTPREL_HI);
1534 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1535 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1536 MipsII::MO_DTPREL_LO);
1537 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1538 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1539 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1543 if (model == TLSModel::InitialExec) {
1544 // Initial Exec TLS Model
1545 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1546 MipsII::MO_GOTTPREL);
1547 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1549 Offset = DAG.getLoad(PtrVT, DL,
1550 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1551 false, false, false, 0);
1553 // Local Exec TLS Model
1554 assert(model == TLSModel::LocalExec);
1555 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1556 MipsII::MO_TPREL_HI);
1557 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1558 MipsII::MO_TPREL_LO);
1559 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1560 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1561 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1564 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1565 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1568 SDValue MipsTargetLowering::
1569 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1571 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1572 return getAddrNonPIC(Op, DAG);
1574 return getAddrLocal(Op, DAG, HasMips64);
1577 SDValue MipsTargetLowering::
1578 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1580 // gp_rel relocation
1581 // FIXME: we should reference the constant pool using small data sections,
1582 // but the asm printer currently doesn't support this feature without
1583 // hacking it. This feature should come soon so we can uncomment the
1585 //if (IsInSmallSection(C->getType())) {
1586 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1587 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1588 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1590 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1591 return getAddrNonPIC(Op, DAG);
1593 return getAddrLocal(Op, DAG, HasMips64);
1596 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1597 MachineFunction &MF = DAG.getMachineFunction();
1598 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1600 DebugLoc DL = Op.getDebugLoc();
1601 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1604 // vastart just stores the address of the VarArgsFrameIndex slot into the
1605 // memory location argument.
1606 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1607 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1608 MachinePointerInfo(SV), false, false, 0);
1611 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1612 EVT TyX = Op.getOperand(0).getValueType();
1613 EVT TyY = Op.getOperand(1).getValueType();
1614 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1615 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1616 DebugLoc DL = Op.getDebugLoc();
1619 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1621 SDValue X = (TyX == MVT::f32) ?
1622 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1623 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1625 SDValue Y = (TyY == MVT::f32) ?
1626 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1627 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1631 // ext E, Y, 31, 1 ; extract bit31 of Y
1632 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1633 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1634 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1637 // srl SrlX, SllX, 1
1639 // sll SllY, SrlX, 31
1640 // or Or, SrlX, SllY
1641 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1642 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1643 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1644 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1645 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1648 if (TyX == MVT::f32)
1649 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1651 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1652 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1653 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1656 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1657 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1658 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1659 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1660 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1661 DebugLoc DL = Op.getDebugLoc();
1663 // Bitcast to integer nodes.
1664 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1665 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1668 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1669 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1670 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1671 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1673 if (WidthX > WidthY)
1674 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1675 else if (WidthY > WidthX)
1676 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1678 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1679 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1680 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1683 // (d)sll SllX, X, 1
1684 // (d)srl SrlX, SllX, 1
1685 // (d)srl SrlY, Y, width(Y)-1
1686 // (d)sll SllY, SrlX, width(Y)-1
1687 // or Or, SrlX, SllY
1688 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1689 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1690 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1691 DAG.getConstant(WidthY - 1, MVT::i32));
1693 if (WidthX > WidthY)
1694 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1695 else if (WidthY > WidthX)
1696 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1698 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1699 DAG.getConstant(WidthX - 1, MVT::i32));
1700 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1701 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1705 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1706 if (Subtarget->hasMips64())
1707 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1709 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1712 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1713 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1714 DebugLoc DL = Op.getDebugLoc();
1716 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1718 SDValue X = (Op.getValueType() == MVT::f32) ?
1719 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1720 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1725 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1726 DAG.getRegister(Mips::ZERO, MVT::i32),
1727 DAG.getConstant(31, MVT::i32), Const1, X);
1729 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1730 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1733 if (Op.getValueType() == MVT::f32)
1734 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1736 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1737 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1738 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1741 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1742 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1743 DebugLoc DL = Op.getDebugLoc();
1745 // Bitcast to integer node.
1746 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1750 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1751 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1752 DAG.getConstant(63, MVT::i32), Const1, X);
1754 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1755 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1758 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1762 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1763 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1764 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1766 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1769 SDValue MipsTargetLowering::
1770 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1772 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1773 "Frame address can only be determined for current frame.");
1775 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1776 MFI->setFrameAddressIsTaken(true);
1777 EVT VT = Op.getValueType();
1778 DebugLoc DL = Op.getDebugLoc();
1779 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1780 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1784 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1785 SelectionDAG &DAG) const {
1787 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1788 "Return address can be determined only for current frame.");
1790 MachineFunction &MF = DAG.getMachineFunction();
1791 MachineFrameInfo *MFI = MF.getFrameInfo();
1792 MVT VT = Op.getSimpleValueType();
1793 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1794 MFI->setReturnAddressIsTaken(true);
1796 // Return RA, which contains the return address. Mark it an implicit live-in.
1797 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1798 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
1801 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1802 // generated from __builtin_eh_return (offset, handler)
1803 // The effect of this is to adjust the stack pointer by "offset"
1804 // and then branch to "handler".
1805 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1807 MachineFunction &MF = DAG.getMachineFunction();
1808 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1810 MipsFI->setCallsEhReturn();
1811 SDValue Chain = Op.getOperand(0);
1812 SDValue Offset = Op.getOperand(1);
1813 SDValue Handler = Op.getOperand(2);
1814 DebugLoc DL = Op.getDebugLoc();
1815 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1817 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1818 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1819 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1820 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1821 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1822 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1823 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1824 DAG.getRegister(OffsetReg, Ty),
1825 DAG.getRegister(AddrReg, getPointerTy()),
1829 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1830 SelectionDAG &DAG) const {
1831 // FIXME: Need pseudo-fence for 'singlethread' fences
1832 // FIXME: Set SType for weaker fences where supported/appropriate.
1834 DebugLoc DL = Op.getDebugLoc();
1835 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1836 DAG.getConstant(SType, MVT::i32));
1839 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1840 SelectionDAG &DAG) const {
1841 DebugLoc DL = Op.getDebugLoc();
1842 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1843 SDValue Shamt = Op.getOperand(2);
1846 // lo = (shl lo, shamt)
1847 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1850 // hi = (shl lo, shamt[4:0])
1851 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1852 DAG.getConstant(-1, MVT::i32));
1853 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1854 DAG.getConstant(1, MVT::i32));
1855 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1857 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1858 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1859 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1860 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1861 DAG.getConstant(0x20, MVT::i32));
1862 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1863 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1864 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1866 SDValue Ops[2] = {Lo, Hi};
1867 return DAG.getMergeValues(Ops, 2, DL);
1870 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1872 DebugLoc DL = Op.getDebugLoc();
1873 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1874 SDValue Shamt = Op.getOperand(2);
1877 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1879 // hi = (sra hi, shamt)
1881 // hi = (srl hi, shamt)
1884 // lo = (sra hi, shamt[4:0])
1885 // hi = (sra hi, 31)
1887 // lo = (srl hi, shamt[4:0])
1889 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1890 DAG.getConstant(-1, MVT::i32));
1891 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1892 DAG.getConstant(1, MVT::i32));
1893 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1894 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1895 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1896 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1898 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1899 DAG.getConstant(0x20, MVT::i32));
1900 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1901 DAG.getConstant(31, MVT::i32));
1902 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1903 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1904 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1907 SDValue Ops[2] = {Lo, Hi};
1908 return DAG.getMergeValues(Ops, 2, DL);
1911 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1912 SDValue Chain, SDValue Src, unsigned Offset) {
1913 SDValue Ptr = LD->getBasePtr();
1914 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1915 EVT BasePtrVT = Ptr.getValueType();
1916 DebugLoc DL = LD->getDebugLoc();
1917 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1920 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1921 DAG.getConstant(Offset, BasePtrVT));
1923 SDValue Ops[] = { Chain, Ptr, Src };
1924 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1925 LD->getMemOperand());
1928 // Expand an unaligned 32 or 64-bit integer load node.
1929 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1930 LoadSDNode *LD = cast<LoadSDNode>(Op);
1931 EVT MemVT = LD->getMemoryVT();
1933 // Return if load is aligned or if MemVT is neither i32 nor i64.
1934 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1935 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1938 bool IsLittle = Subtarget->isLittle();
1939 EVT VT = Op.getValueType();
1940 ISD::LoadExtType ExtType = LD->getExtensionType();
1941 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1943 assert((VT == MVT::i32) || (VT == MVT::i64));
1946 // (set dst, (i64 (load baseptr)))
1948 // (set tmp, (ldl (add baseptr, 7), undef))
1949 // (set dst, (ldr baseptr, tmp))
1950 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1951 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1953 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1957 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1959 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1963 // (set dst, (i32 (load baseptr))) or
1964 // (set dst, (i64 (sextload baseptr))) or
1965 // (set dst, (i64 (extload baseptr)))
1967 // (set tmp, (lwl (add baseptr, 3), undef))
1968 // (set dst, (lwr baseptr, tmp))
1969 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1970 (ExtType == ISD::EXTLOAD))
1973 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1976 // (set dst, (i64 (zextload baseptr)))
1978 // (set tmp0, (lwl (add baseptr, 3), undef))
1979 // (set tmp1, (lwr baseptr, tmp0))
1980 // (set tmp2, (shl tmp1, 32))
1981 // (set dst, (srl tmp2, 32))
1982 DebugLoc DL = LD->getDebugLoc();
1983 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1984 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1985 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1986 SDValue Ops[] = { SRL, LWR.getValue(1) };
1987 return DAG.getMergeValues(Ops, 2, DL);
1990 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
1991 SDValue Chain, unsigned Offset) {
1992 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
1993 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
1994 DebugLoc DL = SD->getDebugLoc();
1995 SDVTList VTList = DAG.getVTList(MVT::Other);
1998 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1999 DAG.getConstant(Offset, BasePtrVT));
2001 SDValue Ops[] = { Chain, Value, Ptr };
2002 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2003 SD->getMemOperand());
2006 // Expand an unaligned 32 or 64-bit integer store node.
2007 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2009 SDValue Value = SD->getValue(), Chain = SD->getChain();
2010 EVT VT = Value.getValueType();
2013 // (store val, baseptr) or
2014 // (truncstore val, baseptr)
2016 // (swl val, (add baseptr, 3))
2017 // (swr val, baseptr)
2018 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2019 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2021 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2024 assert(VT == MVT::i64);
2027 // (store val, baseptr)
2029 // (sdl val, (add baseptr, 7))
2030 // (sdr val, baseptr)
2031 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2032 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2035 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2036 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2037 SDValue Val = SD->getValue();
2039 if (Val.getOpcode() != ISD::FP_TO_SINT)
2042 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2043 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, Val.getDebugLoc(), FPTy,
2046 return DAG.getStore(SD->getChain(), SD->getDebugLoc(), Tr, SD->getBasePtr(),
2047 SD->getPointerInfo(), SD->isVolatile(),
2048 SD->isNonTemporal(), SD->getAlignment());
2051 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2052 StoreSDNode *SD = cast<StoreSDNode>(Op);
2053 EVT MemVT = SD->getMemoryVT();
2055 // Lower unaligned integer stores.
2056 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2057 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2058 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2060 return lowerFP_TO_SINT_STORE(SD, DAG);
2063 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2064 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2065 || cast<ConstantSDNode>
2066 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2067 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2071 // (add (frameaddr 0), (frame_to_args_offset))
2072 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2073 // (add FrameObject, 0)
2074 // where FrameObject is a fixed StackObject with offset 0 which points to
2075 // the old stack pointer.
2076 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2077 EVT ValTy = Op->getValueType(0);
2078 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2079 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2080 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2081 DAG.getConstant(0, ValTy));
2084 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2085 SelectionDAG &DAG) const {
2086 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2087 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, Op.getDebugLoc(), FPTy,
2089 return DAG.getNode(ISD::BITCAST, Op.getDebugLoc(), Op.getValueType(), Trunc);
2092 //===----------------------------------------------------------------------===//
2093 // Calling Convention Implementation
2094 //===----------------------------------------------------------------------===//
2096 //===----------------------------------------------------------------------===//
2097 // TODO: Implement a generic logic using tblgen that can support this.
2098 // Mips O32 ABI rules:
2100 // i32 - Passed in A0, A1, A2, A3 and stack
2101 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2102 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2103 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2104 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2105 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2108 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2109 //===----------------------------------------------------------------------===//
2111 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2112 MVT LocVT, CCValAssign::LocInfo LocInfo,
2113 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2115 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2117 static const uint16_t IntRegs[] = {
2118 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2120 static const uint16_t F32Regs[] = {
2121 Mips::F12, Mips::F14
2123 static const uint16_t F64Regs[] = {
2127 // Do not process byval args here.
2128 if (ArgFlags.isByVal())
2131 // Promote i8 and i16
2132 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2134 if (ArgFlags.isSExt())
2135 LocInfo = CCValAssign::SExt;
2136 else if (ArgFlags.isZExt())
2137 LocInfo = CCValAssign::ZExt;
2139 LocInfo = CCValAssign::AExt;
2144 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2145 // is true: function is vararg, argument is 3rd or higher, there is previous
2146 // argument which is not f32 or f64.
2147 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2148 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2149 unsigned OrigAlign = ArgFlags.getOrigAlign();
2150 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2152 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2153 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2154 // If this is the first part of an i64 arg,
2155 // the allocated register must be either A0 or A2.
2156 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2157 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2159 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2160 // Allocate int register and shadow next int register. If first
2161 // available register is Mips::A1 or Mips::A3, shadow it too.
2162 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2163 if (Reg == Mips::A1 || Reg == Mips::A3)
2164 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2165 State.AllocateReg(IntRegs, IntRegsSize);
2167 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2168 // we are guaranteed to find an available float register
2169 if (ValVT == MVT::f32) {
2170 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2171 // Shadow int register
2172 State.AllocateReg(IntRegs, IntRegsSize);
2174 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2175 // Shadow int registers
2176 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2177 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2178 State.AllocateReg(IntRegs, IntRegsSize);
2179 State.AllocateReg(IntRegs, IntRegsSize);
2182 llvm_unreachable("Cannot handle this ValVT.");
2185 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2187 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2189 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2194 #include "MipsGenCallingConv.inc"
2196 //===----------------------------------------------------------------------===//
2197 // Call Calling Convention Implementation
2198 //===----------------------------------------------------------------------===//
2200 static const unsigned O32IntRegsSize = 4;
2202 // Return next O32 integer argument register.
2203 static unsigned getNextIntArgReg(unsigned Reg) {
2204 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2205 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2209 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2210 SDValue Chain, SDValue Arg, DebugLoc DL,
2211 bool IsTailCall, SelectionDAG &DAG) const {
2213 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2214 DAG.getIntPtrConstant(Offset));
2215 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2219 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2220 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2221 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2222 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2223 /*isVolatile=*/ true, false, 0);
2226 void MipsTargetLowering::
2227 getOpndList(SmallVectorImpl<SDValue> &Ops,
2228 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2229 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2230 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2231 // Insert node "GP copy globalreg" before call to function.
2233 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2234 // in PIC mode) allow symbols to be resolved via lazy binding.
2235 // The lazy binding stub requires GP to point to the GOT.
2236 if (IsPICCall && !InternalLinkage) {
2237 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2238 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2239 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2242 // Build a sequence of copy-to-reg nodes chained together with token
2243 // chain and flag operands which copy the outgoing args into registers.
2244 // The InFlag in necessary since all emitted instructions must be
2248 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2249 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2250 RegsToPass[i].second, InFlag);
2251 InFlag = Chain.getValue(1);
2254 // Add argument registers to the end of the list so that they are
2255 // known live into the call.
2256 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2257 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2258 RegsToPass[i].second.getValueType()));
2260 // Add a register mask operand representing the call-preserved registers.
2261 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2262 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2263 assert(Mask && "Missing call preserved mask for calling convention");
2264 if (Subtarget->inMips16HardFloat()) {
2265 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2266 llvm::StringRef Sym = G->getGlobal()->getName();
2267 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2268 if (F->hasFnAttribute("__Mips16RetHelper")) {
2269 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2273 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2275 if (InFlag.getNode())
2276 Ops.push_back(InFlag);
2279 /// LowerCall - functions arguments are copied from virtual regs to
2280 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2282 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2283 SmallVectorImpl<SDValue> &InVals) const {
2284 SelectionDAG &DAG = CLI.DAG;
2285 DebugLoc &DL = CLI.DL;
2286 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2287 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2288 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2289 SDValue Chain = CLI.Chain;
2290 SDValue Callee = CLI.Callee;
2291 bool &IsTailCall = CLI.IsTailCall;
2292 CallingConv::ID CallConv = CLI.CallConv;
2293 bool IsVarArg = CLI.IsVarArg;
2295 MachineFunction &MF = DAG.getMachineFunction();
2296 MachineFrameInfo *MFI = MF.getFrameInfo();
2297 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2298 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2300 // Analyze operands of the call, assigning locations to each operand.
2301 SmallVector<CCValAssign, 16> ArgLocs;
2302 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2303 getTargetMachine(), ArgLocs, *DAG.getContext());
2304 MipsCC::SpecialCallingConvType SpecialCallingConv =
2305 getSpecialCallingConv(Callee);
2306 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo, SpecialCallingConv);
2308 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2309 getTargetMachine().Options.UseSoftFloat,
2310 Callee.getNode(), CLI.Args);
2312 // Get a count of how many bytes are to be pushed on the stack.
2313 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2315 // Check if it's really possible to do a tail call.
2318 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2319 *MF.getInfo<MipsFunctionInfo>());
2324 // Chain is the output chain of the last Load/Store or CopyToReg node.
2325 // ByValChain is the output chain of the last Memcpy node created for copying
2326 // byval arguments to the stack.
2327 unsigned StackAlignment = TFL->getStackAlignment();
2328 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2329 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2332 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
2334 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2335 IsN64 ? Mips::SP_64 : Mips::SP,
2338 // With EABI is it possible to have 16 args on registers.
2339 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2340 SmallVector<SDValue, 8> MemOpChains;
2341 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2343 // Walk the register/memloc assignments, inserting copies/loads.
2344 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2345 SDValue Arg = OutVals[i];
2346 CCValAssign &VA = ArgLocs[i];
2347 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2348 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2351 if (Flags.isByVal()) {
2352 assert(Flags.getByValSize() &&
2353 "ByVal args of size 0 should have been ignored by front-end.");
2354 assert(ByValArg != MipsCCInfo.byval_end());
2355 assert(!IsTailCall &&
2356 "Do not tail-call optimize if there is a byval argument.");
2357 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2358 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2363 // Promote the value if needed.
2364 switch (VA.getLocInfo()) {
2365 default: llvm_unreachable("Unknown loc info!");
2366 case CCValAssign::Full:
2367 if (VA.isRegLoc()) {
2368 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2369 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2370 (ValVT == MVT::i64 && LocVT == MVT::f64))
2371 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2372 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2373 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2374 Arg, DAG.getConstant(0, MVT::i32));
2375 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2376 Arg, DAG.getConstant(1, MVT::i32));
2377 if (!Subtarget->isLittle())
2379 unsigned LocRegLo = VA.getLocReg();
2380 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2381 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2382 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2387 case CCValAssign::SExt:
2388 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2390 case CCValAssign::ZExt:
2391 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2393 case CCValAssign::AExt:
2394 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2398 // Arguments that can be passed on register must be kept at
2399 // RegsToPass vector
2400 if (VA.isRegLoc()) {
2401 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2405 // Register can't get to this point...
2406 assert(VA.isMemLoc());
2408 // emit ISD::STORE whichs stores the
2409 // parameter value to a stack Location
2410 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2411 Chain, Arg, DL, IsTailCall, DAG));
2414 // Transform all store nodes into one single node because all store
2415 // nodes are independent of each other.
2416 if (!MemOpChains.empty())
2417 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2418 &MemOpChains[0], MemOpChains.size());
2420 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2421 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2422 // node so that legalize doesn't hack it.
2423 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2424 bool GlobalOrExternal = false, InternalLinkage = false;
2427 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2429 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2431 if (InternalLinkage)
2432 Callee = getAddrLocal(Callee, DAG, HasMips64);
2434 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2435 MipsII::MO_CALL_LO16);
2437 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2439 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2440 MipsII::MO_NO_FLAG);
2441 GlobalOrExternal = true;
2443 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2444 if (!IsN64 && !IsPIC) // !N64 && static
2445 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2446 MipsII::MO_NO_FLAG);
2448 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2449 MipsII::MO_CALL_LO16);
2451 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2453 GlobalOrExternal = true;
2456 SmallVector<SDValue, 8> Ops(1, Chain);
2457 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2459 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2460 CLI, Callee, Chain);
2463 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2465 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2466 SDValue InFlag = Chain.getValue(1);
2468 // Create the CALLSEQ_END node.
2469 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2470 DAG.getIntPtrConstant(0, true), InFlag);
2471 InFlag = Chain.getValue(1);
2473 // Handle result values, copying them out of physregs into vregs that we
2475 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2476 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2479 /// LowerCallResult - Lower the result values of a call into the
2480 /// appropriate copies out of appropriate physical registers.
2482 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2483 CallingConv::ID CallConv, bool IsVarArg,
2484 const SmallVectorImpl<ISD::InputArg> &Ins,
2485 DebugLoc DL, SelectionDAG &DAG,
2486 SmallVectorImpl<SDValue> &InVals,
2487 const SDNode *CallNode,
2488 const Type *RetTy) const {
2489 // Assign locations to each value returned by this call.
2490 SmallVector<CCValAssign, 16> RVLocs;
2491 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2492 getTargetMachine(), RVLocs, *DAG.getContext());
2493 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2495 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2498 // Copy all of the result registers out of their specified physreg.
2499 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2500 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2501 RVLocs[i].getLocVT(), InFlag);
2502 Chain = Val.getValue(1);
2503 InFlag = Val.getValue(2);
2505 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2506 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2508 InVals.push_back(Val);
2514 //===----------------------------------------------------------------------===//
2515 // Formal Arguments Calling Convention Implementation
2516 //===----------------------------------------------------------------------===//
2517 /// LowerFormalArguments - transform physical registers into virtual registers
2518 /// and generate load operations for arguments places on the stack.
2520 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2521 CallingConv::ID CallConv,
2523 const SmallVectorImpl<ISD::InputArg> &Ins,
2524 DebugLoc DL, SelectionDAG &DAG,
2525 SmallVectorImpl<SDValue> &InVals)
2527 MachineFunction &MF = DAG.getMachineFunction();
2528 MachineFrameInfo *MFI = MF.getFrameInfo();
2529 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2531 MipsFI->setVarArgsFrameIndex(0);
2533 // Used with vargs to acumulate store chains.
2534 std::vector<SDValue> OutChains;
2536 // Assign locations to all of the incoming arguments.
2537 SmallVector<CCValAssign, 16> ArgLocs;
2538 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2539 getTargetMachine(), ArgLocs, *DAG.getContext());
2540 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2541 Function::const_arg_iterator FuncArg =
2542 DAG.getMachineFunction().getFunction()->arg_begin();
2543 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2545 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2546 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2547 MipsCCInfo.hasByValArg());
2549 unsigned CurArgIdx = 0;
2550 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2552 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2553 CCValAssign &VA = ArgLocs[i];
2554 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2555 CurArgIdx = Ins[i].OrigArgIndex;
2556 EVT ValVT = VA.getValVT();
2557 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2558 bool IsRegLoc = VA.isRegLoc();
2560 if (Flags.isByVal()) {
2561 assert(Flags.getByValSize() &&
2562 "ByVal args of size 0 should have been ignored by front-end.");
2563 assert(ByValArg != MipsCCInfo.byval_end());
2564 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2565 MipsCCInfo, *ByValArg);
2570 // Arguments stored on registers
2572 EVT RegVT = VA.getLocVT();
2573 unsigned ArgReg = VA.getLocReg();
2574 const TargetRegisterClass *RC;
2576 if (RegVT == MVT::i32)
2577 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2578 &Mips::CPURegsRegClass;
2579 else if (RegVT == MVT::i64)
2580 RC = &Mips::CPU64RegsRegClass;
2581 else if (RegVT == MVT::f32)
2582 RC = &Mips::FGR32RegClass;
2583 else if (RegVT == MVT::f64)
2584 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2586 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2588 // Transform the arguments stored on
2589 // physical registers into virtual ones
2590 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2591 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2593 // If this is an 8 or 16-bit value, it has been passed promoted
2594 // to 32 bits. Insert an assert[sz]ext to capture this, then
2595 // truncate to the right size.
2596 if (VA.getLocInfo() != CCValAssign::Full) {
2597 unsigned Opcode = 0;
2598 if (VA.getLocInfo() == CCValAssign::SExt)
2599 Opcode = ISD::AssertSext;
2600 else if (VA.getLocInfo() == CCValAssign::ZExt)
2601 Opcode = ISD::AssertZext;
2603 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2604 DAG.getValueType(ValVT));
2605 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2608 // Handle floating point arguments passed in integer registers and
2609 // long double arguments passed in floating point registers.
2610 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2611 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2612 (RegVT == MVT::f64 && ValVT == MVT::i64))
2613 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2614 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2615 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2616 getNextIntArgReg(ArgReg), RC);
2617 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2618 if (!Subtarget->isLittle())
2619 std::swap(ArgValue, ArgValue2);
2620 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2621 ArgValue, ArgValue2);
2624 InVals.push_back(ArgValue);
2625 } else { // VA.isRegLoc()
2628 assert(VA.isMemLoc());
2630 // The stack pointer offset is relative to the caller stack frame.
2631 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2632 VA.getLocMemOffset(), true);
2634 // Create load nodes to retrieve arguments from the stack
2635 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2636 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2637 MachinePointerInfo::getFixedStack(FI),
2638 false, false, false, 0));
2642 // The mips ABIs for returning structs by value requires that we copy
2643 // the sret argument into $v0 for the return. Save the argument into
2644 // a virtual register so that we can access it from the return points.
2645 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2646 unsigned Reg = MipsFI->getSRetReturnReg();
2648 Reg = MF.getRegInfo().
2649 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2650 MipsFI->setSRetReturnReg(Reg);
2652 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2653 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2657 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2659 // All stores are grouped in one node to allow the matching between
2660 // the size of Ins and InVals. This only happens when on varg functions
2661 if (!OutChains.empty()) {
2662 OutChains.push_back(Chain);
2663 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2664 &OutChains[0], OutChains.size());
2670 //===----------------------------------------------------------------------===//
2671 // Return Value Calling Convention Implementation
2672 //===----------------------------------------------------------------------===//
2675 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2676 MachineFunction &MF, bool IsVarArg,
2677 const SmallVectorImpl<ISD::OutputArg> &Outs,
2678 LLVMContext &Context) const {
2679 SmallVector<CCValAssign, 16> RVLocs;
2680 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2682 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2686 MipsTargetLowering::LowerReturn(SDValue Chain,
2687 CallingConv::ID CallConv, bool IsVarArg,
2688 const SmallVectorImpl<ISD::OutputArg> &Outs,
2689 const SmallVectorImpl<SDValue> &OutVals,
2690 DebugLoc DL, SelectionDAG &DAG) const {
2691 // CCValAssign - represent the assignment of
2692 // the return value to a location
2693 SmallVector<CCValAssign, 16> RVLocs;
2694 MachineFunction &MF = DAG.getMachineFunction();
2696 // CCState - Info about the registers and stack slot.
2697 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2699 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2701 // Analyze return values.
2702 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2703 MF.getFunction()->getReturnType());
2706 SmallVector<SDValue, 4> RetOps(1, Chain);
2708 // Copy the result values into the output registers.
2709 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2710 SDValue Val = OutVals[i];
2711 CCValAssign &VA = RVLocs[i];
2712 assert(VA.isRegLoc() && "Can only return in registers!");
2714 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2715 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2717 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2719 // Guarantee that all emitted copies are stuck together with flags.
2720 Flag = Chain.getValue(1);
2721 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2724 // The mips ABIs for returning structs by value requires that we copy
2725 // the sret argument into $v0 for the return. We saved the argument into
2726 // a virtual register in the entry block, so now we copy the value out
2728 if (MF.getFunction()->hasStructRetAttr()) {
2729 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2730 unsigned Reg = MipsFI->getSRetReturnReg();
2733 llvm_unreachable("sret virtual register not created in the entry block");
2734 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2735 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2737 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2738 Flag = Chain.getValue(1);
2739 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2742 RetOps[0] = Chain; // Update chain.
2744 // Add the flag if we have it.
2746 RetOps.push_back(Flag);
2748 // Return on Mips is always a "jr $ra"
2749 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2752 //===----------------------------------------------------------------------===//
2753 // Mips Inline Assembly Support
2754 //===----------------------------------------------------------------------===//
2756 /// getConstraintType - Given a constraint letter, return the type of
2757 /// constraint it is for this target.
2758 MipsTargetLowering::ConstraintType MipsTargetLowering::
2759 getConstraintType(const std::string &Constraint) const
2761 // Mips specific constrainy
2762 // GCC config/mips/constraints.md
2764 // 'd' : An address register. Equivalent to r
2765 // unless generating MIPS16 code.
2766 // 'y' : Equivalent to r; retained for
2767 // backwards compatibility.
2768 // 'c' : A register suitable for use in an indirect
2769 // jump. This will always be $25 for -mabicalls.
2770 // 'l' : The lo register. 1 word storage.
2771 // 'x' : The hilo register pair. Double word storage.
2772 if (Constraint.size() == 1) {
2773 switch (Constraint[0]) {
2781 return C_RegisterClass;
2786 return TargetLowering::getConstraintType(Constraint);
2789 /// Examine constraint type and operand type and determine a weight value.
2790 /// This object must already have been set up with the operand type
2791 /// and the current alternative constraint selected.
2792 TargetLowering::ConstraintWeight
2793 MipsTargetLowering::getSingleConstraintMatchWeight(
2794 AsmOperandInfo &info, const char *constraint) const {
2795 ConstraintWeight weight = CW_Invalid;
2796 Value *CallOperandVal = info.CallOperandVal;
2797 // If we don't have a value, we can't do a match,
2798 // but allow it at the lowest weight.
2799 if (CallOperandVal == NULL)
2801 Type *type = CallOperandVal->getType();
2802 // Look at the constraint type.
2803 switch (*constraint) {
2805 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2809 if (type->isIntegerTy())
2810 weight = CW_Register;
2813 if (type->isFloatTy())
2814 weight = CW_Register;
2816 case 'c': // $25 for indirect jumps
2817 case 'l': // lo register
2818 case 'x': // hilo register pair
2819 if (type->isIntegerTy())
2820 weight = CW_SpecificReg;
2822 case 'I': // signed 16 bit immediate
2823 case 'J': // integer zero
2824 case 'K': // unsigned 16 bit immediate
2825 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2826 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2827 case 'O': // signed 15 bit immediate (+- 16383)
2828 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2829 if (isa<ConstantInt>(CallOperandVal))
2830 weight = CW_Constant;
2839 /// Given a register class constraint, like 'r', if this corresponds directly
2840 /// to an LLVM register class, return a register of 0 and the register class
2842 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2843 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2845 if (Constraint.size() == 1) {
2846 switch (Constraint[0]) {
2847 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2848 case 'y': // Same as 'r'. Exists for compatibility.
2850 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2851 if (Subtarget->inMips16Mode())
2852 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2853 return std::make_pair(0U, &Mips::CPURegsRegClass);
2855 if (VT == MVT::i64 && !HasMips64)
2856 return std::make_pair(0U, &Mips::CPURegsRegClass);
2857 if (VT == MVT::i64 && HasMips64)
2858 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
2859 // This will generate an error message
2860 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2863 return std::make_pair(0U, &Mips::FGR32RegClass);
2864 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2865 if (Subtarget->isFP64bit())
2866 return std::make_pair(0U, &Mips::FGR64RegClass);
2867 return std::make_pair(0U, &Mips::AFGR64RegClass);
2870 case 'c': // register suitable for indirect jump
2872 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
2873 assert(VT == MVT::i64 && "Unexpected type.");
2874 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
2875 case 'l': // register suitable for indirect jump
2877 return std::make_pair((unsigned)Mips::LO, &Mips::LORegsRegClass);
2878 return std::make_pair((unsigned)Mips::LO64, &Mips::LORegs64RegClass);
2879 case 'x': // register suitable for indirect jump
2880 // Fixme: Not triggering the use of both hi and low
2881 // This will generate an error message
2882 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2885 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2888 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2889 /// vector. If it is invalid, don't add anything to Ops.
2890 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2891 std::string &Constraint,
2892 std::vector<SDValue>&Ops,
2893 SelectionDAG &DAG) const {
2894 SDValue Result(0, 0);
2896 // Only support length 1 constraints for now.
2897 if (Constraint.length() > 1) return;
2899 char ConstraintLetter = Constraint[0];
2900 switch (ConstraintLetter) {
2901 default: break; // This will fall through to the generic implementation
2902 case 'I': // Signed 16 bit constant
2903 // If this fails, the parent routine will give an error
2904 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2905 EVT Type = Op.getValueType();
2906 int64_t Val = C->getSExtValue();
2907 if (isInt<16>(Val)) {
2908 Result = DAG.getTargetConstant(Val, Type);
2913 case 'J': // integer zero
2914 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2915 EVT Type = Op.getValueType();
2916 int64_t Val = C->getZExtValue();
2918 Result = DAG.getTargetConstant(0, Type);
2923 case 'K': // unsigned 16 bit immediate
2924 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2925 EVT Type = Op.getValueType();
2926 uint64_t Val = (uint64_t)C->getZExtValue();
2927 if (isUInt<16>(Val)) {
2928 Result = DAG.getTargetConstant(Val, Type);
2933 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2934 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2935 EVT Type = Op.getValueType();
2936 int64_t Val = C->getSExtValue();
2937 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
2938 Result = DAG.getTargetConstant(Val, Type);
2943 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2944 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2945 EVT Type = Op.getValueType();
2946 int64_t Val = C->getSExtValue();
2947 if ((Val >= -65535) && (Val <= -1)) {
2948 Result = DAG.getTargetConstant(Val, Type);
2953 case 'O': // signed 15 bit immediate
2954 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2955 EVT Type = Op.getValueType();
2956 int64_t Val = C->getSExtValue();
2957 if ((isInt<15>(Val))) {
2958 Result = DAG.getTargetConstant(Val, Type);
2963 case 'P': // immediate in the range of 1 to 65535 (inclusive)
2964 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2965 EVT Type = Op.getValueType();
2966 int64_t Val = C->getSExtValue();
2967 if ((Val <= 65535) && (Val >= 1)) {
2968 Result = DAG.getTargetConstant(Val, Type);
2975 if (Result.getNode()) {
2976 Ops.push_back(Result);
2980 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2984 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
2985 // No global is ever allowed as a base.
2990 case 0: // "r+i" or just "i", depending on HasBaseReg.
2993 if (!AM.HasBaseReg) // allow "r+i".
2995 return false; // disallow "r+r" or "r+r+i".
3004 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3005 // The Mips target isn't yet aware of offsets.
3009 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3011 bool IsMemset, bool ZeroMemset,
3013 MachineFunction &MF) const {
3014 if (Subtarget->hasMips64())
3020 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3021 if (VT != MVT::f32 && VT != MVT::f64)
3023 if (Imm.isNegZero())
3025 return Imm.isZero();
3028 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3030 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3032 return TargetLowering::getJumpTableEncoding();
3035 /// This function returns true if CallSym is a long double emulation routine.
3036 static bool isF128SoftLibCall(const char *CallSym) {
3037 const char *const LibCalls[] =
3038 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3039 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3040 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3041 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3042 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3043 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3044 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3045 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3048 const char * const *End = LibCalls + array_lengthof(LibCalls);
3050 // Check that LibCalls is sorted alphabetically.
3051 MipsTargetLowering::LTStr Comp;
3054 for (const char * const *I = LibCalls; I < End - 1; ++I)
3055 assert(Comp(*I, *(I + 1)));
3058 return std::binary_search(LibCalls, End, CallSym, Comp);
3061 /// This function returns true if Ty is fp128 or i128 which was originally a
3063 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3064 if (Ty->isFP128Ty())
3067 const ExternalSymbolSDNode *ES =
3068 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3070 // If the Ty is i128 and the function being called is a long double emulation
3071 // routine, then the original type is f128.
3072 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3075 MipsTargetLowering::MipsCC::SpecialCallingConvType
3076 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3077 MipsCC::SpecialCallingConvType SpecialCallingConv =
3078 MipsCC::NoSpecialCallingConv;;
3079 if (Subtarget->inMips16HardFloat()) {
3080 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3081 llvm::StringRef Sym = G->getGlobal()->getName();
3082 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3083 if (F->hasFnAttribute("__Mips16RetHelper")) {
3084 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3088 return SpecialCallingConv;
3091 MipsTargetLowering::MipsCC::MipsCC(
3092 CallingConv::ID CC, bool IsO32_, CCState &Info,
3093 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3094 : CCInfo(Info), CallConv(CC), IsO32(IsO32_),
3095 SpecialCallingConv(SpecialCallingConv_){
3096 // Pre-allocate reserved argument area.
3097 CCInfo.AllocateStack(reservedArgArea(), 1);
3101 void MipsTargetLowering::MipsCC::
3102 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3103 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3104 std::vector<ArgListEntry> &FuncArgs) {
3105 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3106 "CallingConv::Fast shouldn't be used for vararg functions.");
3108 unsigned NumOpnds = Args.size();
3109 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3111 for (unsigned I = 0; I != NumOpnds; ++I) {
3112 MVT ArgVT = Args[I].VT;
3113 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3116 if (ArgFlags.isByVal()) {
3117 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3121 if (IsVarArg && !Args[I].IsFixed)
3122 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3124 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3126 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3131 dbgs() << "Call operand #" << I << " has unhandled type "
3132 << EVT(ArgVT).getEVTString();
3134 llvm_unreachable(0);
3139 void MipsTargetLowering::MipsCC::
3140 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3141 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3142 unsigned NumArgs = Args.size();
3143 llvm::CCAssignFn *FixedFn = fixedArgFn();
3144 unsigned CurArgIdx = 0;
3146 for (unsigned I = 0; I != NumArgs; ++I) {
3147 MVT ArgVT = Args[I].VT;
3148 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3149 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3150 CurArgIdx = Args[I].OrigArgIndex;
3152 if (ArgFlags.isByVal()) {
3153 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3157 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3159 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3163 dbgs() << "Formal Arg #" << I << " has unhandled type "
3164 << EVT(ArgVT).getEVTString();
3166 llvm_unreachable(0);
3170 template<typename Ty>
3171 void MipsTargetLowering::MipsCC::
3172 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3173 const SDNode *CallNode, const Type *RetTy) const {
3176 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3177 Fn = RetCC_F128Soft;
3181 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3182 MVT VT = RetVals[I].VT;
3183 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3184 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3186 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3188 dbgs() << "Call result #" << I << " has unhandled type "
3189 << EVT(VT).getEVTString() << '\n';
3191 llvm_unreachable(0);
3196 void MipsTargetLowering::MipsCC::
3197 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3198 const SDNode *CallNode, const Type *RetTy) const {
3199 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3202 void MipsTargetLowering::MipsCC::
3203 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3204 const Type *RetTy) const {
3205 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3209 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3211 CCValAssign::LocInfo LocInfo,
3212 ISD::ArgFlagsTy ArgFlags) {
3213 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3215 struct ByValArgInfo ByVal;
3216 unsigned RegSize = regSize();
3217 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3218 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3221 if (useRegsForByval())
3222 allocateRegs(ByVal, ByValSize, Align);
3224 // Allocate space on caller's stack.
3225 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3227 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3229 ByValArgs.push_back(ByVal);
3232 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3233 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3236 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3237 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3240 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3241 return IsO32 ? O32IntRegs : Mips64IntRegs;
3244 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3245 if (CallConv == CallingConv::Fast)
3246 return CC_Mips_FastCC;
3248 if (SpecialCallingConv == Mips16RetHelperConv)
3249 return CC_Mips16RetHelper;
3250 return IsO32 ? CC_MipsO32 : CC_MipsN;
3253 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3254 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
3257 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3258 return IsO32 ? O32IntRegs : Mips64DPRegs;
3261 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3264 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3265 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3266 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3267 "Byval argument's size and alignment should be a multiple of"
3270 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3272 // If Align > RegSize, the first arg register must be even.
3273 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3274 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3278 // Mark the registers allocated.
3279 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3280 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3281 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3284 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3285 const SDNode *CallNode,
3286 bool IsSoftFloat) const {
3287 if (IsSoftFloat || IsO32)
3290 // Check if the original type was fp128.
3291 if (originalTypeIsF128(OrigTy, CallNode)) {
3292 assert(VT == MVT::i64);
3299 void MipsTargetLowering::
3300 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3301 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3302 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3303 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3304 MachineFunction &MF = DAG.getMachineFunction();
3305 MachineFrameInfo *MFI = MF.getFrameInfo();
3306 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3307 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3311 FrameObjOffset = (int)CC.reservedArgArea() -
3312 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3314 FrameObjOffset = ByVal.Address;
3316 // Create frame object.
3317 EVT PtrTy = getPointerTy();
3318 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3319 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3320 InVals.push_back(FIN);
3325 // Copy arg registers.
3326 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3327 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3329 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3330 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3331 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3332 unsigned Offset = I * CC.regSize();
3333 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3334 DAG.getConstant(Offset, PtrTy));
3335 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3336 StorePtr, MachinePointerInfo(FuncArg, Offset),
3338 OutChains.push_back(Store);
3342 // Copy byVal arg to registers and stack.
3343 void MipsTargetLowering::
3344 passByValArg(SDValue Chain, DebugLoc DL,
3345 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3346 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3347 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3348 const MipsCC &CC, const ByValArgInfo &ByVal,
3349 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3350 unsigned ByValSize = Flags.getByValSize();
3351 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3352 unsigned RegSize = CC.regSize();
3353 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3354 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3356 if (ByVal.NumRegs) {
3357 const uint16_t *ArgRegs = CC.intArgRegs();
3358 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3361 // Copy words to registers.
3362 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3363 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3364 DAG.getConstant(Offset, PtrTy));
3365 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3366 MachinePointerInfo(), false, false, false,
3368 MemOpChains.push_back(LoadVal.getValue(1));
3369 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3370 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3373 // Return if the struct has been fully copied.
3374 if (ByValSize == Offset)
3377 // Copy the remainder of the byval argument with sub-word loads and shifts.
3378 if (LeftoverBytes) {
3379 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3380 "Size of the remainder should be smaller than RegSize.");
3383 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3384 Offset < ByValSize; LoadSize /= 2) {
3385 unsigned RemSize = ByValSize - Offset;
3387 if (RemSize < LoadSize)
3391 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3392 DAG.getConstant(Offset, PtrTy));
3394 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3395 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3396 false, false, Alignment);
3397 MemOpChains.push_back(LoadVal.getValue(1));
3399 // Shift the loaded value.
3403 Shamt = TotalSizeLoaded;
3405 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3407 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3408 DAG.getConstant(Shamt, MVT::i32));
3411 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3416 TotalSizeLoaded += LoadSize;
3417 Alignment = std::min(Alignment, LoadSize);
3420 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3421 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3426 // Copy remainder of byval arg to it with memcpy.
3427 unsigned MemCpySize = ByValSize - Offset;
3428 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3429 DAG.getConstant(Offset, PtrTy));
3430 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3431 DAG.getIntPtrConstant(ByVal.Address));
3432 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3433 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3434 /*isVolatile=*/false, /*AlwaysInline=*/false,
3435 MachinePointerInfo(0), MachinePointerInfo(0));
3436 MemOpChains.push_back(Chain);
3440 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3441 const MipsCC &CC, SDValue Chain,
3442 DebugLoc DL, SelectionDAG &DAG) const {
3443 unsigned NumRegs = CC.numIntArgRegs();
3444 const uint16_t *ArgRegs = CC.intArgRegs();
3445 const CCState &CCInfo = CC.getCCInfo();
3446 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3447 unsigned RegSize = CC.regSize();
3448 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3449 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3450 MachineFunction &MF = DAG.getMachineFunction();
3451 MachineFrameInfo *MFI = MF.getFrameInfo();
3452 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3454 // Offset of the first variable argument from stack pointer.
3458 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3461 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3463 // Record the frame index of the first variable argument
3464 // which is a value necessary to VASTART.
3465 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3466 MipsFI->setVarArgsFrameIndex(FI);
3468 // Copy the integer registers that have not been used for argument passing
3469 // to the argument register save area. For O32, the save area is allocated
3470 // in the caller's stack frame, while for N32/64, it is allocated in the
3471 // callee's stack frame.
3472 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3473 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3474 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3475 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3476 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3477 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3478 MachinePointerInfo(), false, false, 0);
3479 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3480 OutChains.push_back(Store);