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::FPRound: return "MipsISD::FPRound";
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);
254 if (!TM.Options.NoNaNsFPMath) {
255 setOperationAction(ISD::FABS, MVT::f32, Custom);
256 setOperationAction(ISD::FABS, MVT::f64, Custom);
260 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
261 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
262 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
263 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
264 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
265 setOperationAction(ISD::SELECT, MVT::i64, Custom);
266 setOperationAction(ISD::LOAD, MVT::i64, Custom);
267 setOperationAction(ISD::STORE, MVT::i64, Custom);
271 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
273 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
276 setOperationAction(ISD::ADD, MVT::i32, Custom);
278 setOperationAction(ISD::ADD, MVT::i64, Custom);
280 setOperationAction(ISD::SDIV, MVT::i32, Expand);
281 setOperationAction(ISD::SREM, MVT::i32, Expand);
282 setOperationAction(ISD::UDIV, MVT::i32, Expand);
283 setOperationAction(ISD::UREM, MVT::i32, Expand);
284 setOperationAction(ISD::SDIV, MVT::i64, Expand);
285 setOperationAction(ISD::SREM, MVT::i64, Expand);
286 setOperationAction(ISD::UDIV, MVT::i64, Expand);
287 setOperationAction(ISD::UREM, MVT::i64, Expand);
289 // Operations not directly supported by Mips.
290 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
291 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
292 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
293 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
294 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
295 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
296 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
297 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
298 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
299 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
300 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
301 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
302 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
303 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
304 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
305 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
306 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
307 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
308 setOperationAction(ISD::ROTL, MVT::i32, Expand);
309 setOperationAction(ISD::ROTL, MVT::i64, Expand);
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
313 if (!Subtarget->hasMips32r2())
314 setOperationAction(ISD::ROTR, MVT::i32, Expand);
316 if (!Subtarget->hasMips64r2())
317 setOperationAction(ISD::ROTR, MVT::i64, Expand);
319 setOperationAction(ISD::FSIN, MVT::f32, Expand);
320 setOperationAction(ISD::FSIN, MVT::f64, Expand);
321 setOperationAction(ISD::FCOS, MVT::f32, Expand);
322 setOperationAction(ISD::FCOS, MVT::f64, Expand);
323 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
324 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
325 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
326 setOperationAction(ISD::FPOW, MVT::f32, Expand);
327 setOperationAction(ISD::FPOW, MVT::f64, Expand);
328 setOperationAction(ISD::FLOG, MVT::f32, Expand);
329 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
330 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
331 setOperationAction(ISD::FEXP, MVT::f32, Expand);
332 setOperationAction(ISD::FMA, MVT::f32, Expand);
333 setOperationAction(ISD::FMA, MVT::f64, Expand);
334 setOperationAction(ISD::FREM, MVT::f32, Expand);
335 setOperationAction(ISD::FREM, MVT::f64, Expand);
337 if (!TM.Options.NoNaNsFPMath) {
338 setOperationAction(ISD::FNEG, MVT::f32, Expand);
339 setOperationAction(ISD::FNEG, MVT::f64, Expand);
342 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
343 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
344 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
345 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
347 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
349 setOperationAction(ISD::VAARG, MVT::Other, Expand);
350 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
351 setOperationAction(ISD::VAEND, MVT::Other, Expand);
353 // Use the default for now
354 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
355 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
357 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
358 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
359 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
360 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
362 setInsertFencesForAtomic(true);
364 if (!Subtarget->hasSEInReg()) {
365 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
366 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
369 if (!Subtarget->hasBitCount()) {
370 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
371 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
374 if (!Subtarget->hasSwap()) {
375 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
376 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
380 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
381 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
382 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
383 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
386 setTargetDAGCombine(ISD::SDIVREM);
387 setTargetDAGCombine(ISD::UDIVREM);
388 setTargetDAGCombine(ISD::SELECT);
389 setTargetDAGCombine(ISD::AND);
390 setTargetDAGCombine(ISD::OR);
391 setTargetDAGCombine(ISD::ADD);
393 setMinFunctionAlignment(HasMips64 ? 3 : 2);
395 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
397 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
398 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
400 MaxStoresPerMemcpy = 16;
403 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
404 if (TM.getSubtargetImpl()->inMips16Mode())
405 return llvm::createMips16TargetLowering(TM);
407 return llvm::createMipsSETargetLowering(TM);
410 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
413 return VT.changeVectorElementTypeToInteger();
416 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
417 TargetLowering::DAGCombinerInfo &DCI,
418 const MipsSubtarget *Subtarget) {
419 if (DCI.isBeforeLegalizeOps())
422 EVT Ty = N->getValueType(0);
423 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
424 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
425 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
427 DebugLoc DL = N->getDebugLoc();
429 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
430 N->getOperand(0), N->getOperand(1));
431 SDValue InChain = DAG.getEntryNode();
432 SDValue InGlue = DivRem;
435 if (N->hasAnyUseOfValue(0)) {
436 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
438 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
439 InChain = CopyFromLo.getValue(1);
440 InGlue = CopyFromLo.getValue(2);
444 if (N->hasAnyUseOfValue(1)) {
445 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
447 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
453 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
455 default: llvm_unreachable("Unknown fp condition code!");
457 case ISD::SETOEQ: return Mips::FCOND_OEQ;
458 case ISD::SETUNE: return Mips::FCOND_UNE;
460 case ISD::SETOLT: return Mips::FCOND_OLT;
462 case ISD::SETOGT: return Mips::FCOND_OGT;
464 case ISD::SETOLE: return Mips::FCOND_OLE;
466 case ISD::SETOGE: return Mips::FCOND_OGE;
467 case ISD::SETULT: return Mips::FCOND_ULT;
468 case ISD::SETULE: return Mips::FCOND_ULE;
469 case ISD::SETUGT: return Mips::FCOND_UGT;
470 case ISD::SETUGE: return Mips::FCOND_UGE;
471 case ISD::SETUO: return Mips::FCOND_UN;
472 case ISD::SETO: return Mips::FCOND_OR;
474 case ISD::SETONE: return Mips::FCOND_ONE;
475 case ISD::SETUEQ: return Mips::FCOND_UEQ;
480 /// This function returns true if the floating point conditional branches and
481 /// conditional moves which use condition code CC should be inverted.
482 static bool invertFPCondCodeUser(Mips::CondCode CC) {
483 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
486 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
487 "Illegal Condition Code");
492 // Creates and returns an FPCmp node from a setcc node.
493 // Returns Op if setcc is not a floating point comparison.
494 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
495 // must be a SETCC node
496 if (Op.getOpcode() != ISD::SETCC)
499 SDValue LHS = Op.getOperand(0);
501 if (!LHS.getValueType().isFloatingPoint())
504 SDValue RHS = Op.getOperand(1);
505 DebugLoc DL = Op.getDebugLoc();
507 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
508 // node if necessary.
509 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
511 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
512 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
515 // Creates and returns a CMovFPT/F node.
516 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
517 SDValue False, DebugLoc DL) {
518 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
519 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
521 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
522 True.getValueType(), True, False, Cond);
525 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
526 TargetLowering::DAGCombinerInfo &DCI,
527 const MipsSubtarget *Subtarget) {
528 if (DCI.isBeforeLegalizeOps())
531 SDValue SetCC = N->getOperand(0);
533 if ((SetCC.getOpcode() != ISD::SETCC) ||
534 !SetCC.getOperand(0).getValueType().isInteger())
537 SDValue False = N->getOperand(2);
538 EVT FalseTy = False.getValueType();
540 if (!FalseTy.isInteger())
543 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
545 if (!CN || CN->getZExtValue())
548 const DebugLoc DL = N->getDebugLoc();
549 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
550 SDValue True = N->getOperand(1);
552 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
553 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
555 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
558 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
559 TargetLowering::DAGCombinerInfo &DCI,
560 const MipsSubtarget *Subtarget) {
561 // Pattern match EXT.
562 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
563 // => ext $dst, $src, size, pos
564 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
567 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
568 unsigned ShiftRightOpc = ShiftRight.getOpcode();
570 // Op's first operand must be a shift right.
571 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
574 // The second operand of the shift must be an immediate.
576 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
579 uint64_t Pos = CN->getZExtValue();
580 uint64_t SMPos, SMSize;
582 // Op's second operand must be a shifted mask.
583 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
584 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
587 // Return if the shifted mask does not start at bit 0 or the sum of its size
588 // and Pos exceeds the word's size.
589 EVT ValTy = N->getValueType(0);
590 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
593 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
594 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
595 DAG.getConstant(SMSize, MVT::i32));
598 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
599 TargetLowering::DAGCombinerInfo &DCI,
600 const MipsSubtarget *Subtarget) {
601 // Pattern match INS.
602 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
603 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
604 // => ins $dst, $src, size, pos, $src1
605 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
608 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
609 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
612 // See if Op's first operand matches (and $src1 , mask0).
613 if (And0.getOpcode() != ISD::AND)
616 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
617 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
620 // See if Op's second operand matches (and (shl $src, pos), mask1).
621 if (And1.getOpcode() != ISD::AND)
624 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
625 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
628 // The shift masks must have the same position and size.
629 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
632 SDValue Shl = And1.getOperand(0);
633 if (Shl.getOpcode() != ISD::SHL)
636 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
639 unsigned Shamt = CN->getZExtValue();
641 // Return if the shift amount and the first bit position of mask are not the
643 EVT ValTy = N->getValueType(0);
644 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
647 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
648 DAG.getConstant(SMPos0, MVT::i32),
649 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
652 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
653 TargetLowering::DAGCombinerInfo &DCI,
654 const MipsSubtarget *Subtarget) {
655 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
657 if (DCI.isBeforeLegalizeOps())
660 SDValue Add = N->getOperand(1);
662 if (Add.getOpcode() != ISD::ADD)
665 SDValue Lo = Add.getOperand(1);
667 if ((Lo.getOpcode() != MipsISD::Lo) ||
668 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
671 EVT ValTy = N->getValueType(0);
672 DebugLoc DL = N->getDebugLoc();
674 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
676 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
679 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
681 SelectionDAG &DAG = DCI.DAG;
682 unsigned Opc = N->getOpcode();
688 return performDivRemCombine(N, DAG, DCI, Subtarget);
690 return performSELECTCombine(N, DAG, DCI, Subtarget);
692 return performANDCombine(N, DAG, DCI, Subtarget);
694 return performORCombine(N, DAG, DCI, Subtarget);
696 return performADDCombine(N, DAG, DCI, Subtarget);
703 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
704 SmallVectorImpl<SDValue> &Results,
705 SelectionDAG &DAG) const {
706 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
708 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
709 Results.push_back(Res.getValue(I));
713 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
714 SmallVectorImpl<SDValue> &Results,
715 SelectionDAG &DAG) const {
716 return LowerOperationWrapper(N, Results, DAG);
719 SDValue MipsTargetLowering::
720 LowerOperation(SDValue Op, SelectionDAG &DAG) const
722 switch (Op.getOpcode())
724 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
725 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
726 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
727 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
728 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
729 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
730 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
731 case ISD::SELECT: return lowerSELECT(Op, DAG);
732 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
733 case ISD::SETCC: return lowerSETCC(Op, DAG);
734 case ISD::VASTART: return lowerVASTART(Op, DAG);
735 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
736 case ISD::FABS: return lowerFABS(Op, DAG);
737 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
738 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
739 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
740 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
741 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
742 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
743 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
744 case ISD::LOAD: return lowerLOAD(Op, DAG);
745 case ISD::STORE: return lowerSTORE(Op, DAG);
746 case ISD::ADD: return lowerADD(Op, DAG);
751 //===----------------------------------------------------------------------===//
752 // Lower helper functions
753 //===----------------------------------------------------------------------===//
755 // addLiveIn - This helper function adds the specified physical register to the
756 // MachineFunction as a live in value. It also creates a corresponding
757 // virtual register for it.
759 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
761 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
762 MF.getRegInfo().addLiveIn(PReg, VReg);
767 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
768 MachineBasicBlock *BB) const {
769 switch (MI->getOpcode()) {
771 llvm_unreachable("Unexpected instr type to insert");
772 case Mips::ATOMIC_LOAD_ADD_I8:
773 case Mips::ATOMIC_LOAD_ADD_I8_P8:
774 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
775 case Mips::ATOMIC_LOAD_ADD_I16:
776 case Mips::ATOMIC_LOAD_ADD_I16_P8:
777 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
778 case Mips::ATOMIC_LOAD_ADD_I32:
779 case Mips::ATOMIC_LOAD_ADD_I32_P8:
780 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
781 case Mips::ATOMIC_LOAD_ADD_I64:
782 case Mips::ATOMIC_LOAD_ADD_I64_P8:
783 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
785 case Mips::ATOMIC_LOAD_AND_I8:
786 case Mips::ATOMIC_LOAD_AND_I8_P8:
787 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
788 case Mips::ATOMIC_LOAD_AND_I16:
789 case Mips::ATOMIC_LOAD_AND_I16_P8:
790 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
791 case Mips::ATOMIC_LOAD_AND_I32:
792 case Mips::ATOMIC_LOAD_AND_I32_P8:
793 return emitAtomicBinary(MI, BB, 4, Mips::AND);
794 case Mips::ATOMIC_LOAD_AND_I64:
795 case Mips::ATOMIC_LOAD_AND_I64_P8:
796 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
798 case Mips::ATOMIC_LOAD_OR_I8:
799 case Mips::ATOMIC_LOAD_OR_I8_P8:
800 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
801 case Mips::ATOMIC_LOAD_OR_I16:
802 case Mips::ATOMIC_LOAD_OR_I16_P8:
803 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
804 case Mips::ATOMIC_LOAD_OR_I32:
805 case Mips::ATOMIC_LOAD_OR_I32_P8:
806 return emitAtomicBinary(MI, BB, 4, Mips::OR);
807 case Mips::ATOMIC_LOAD_OR_I64:
808 case Mips::ATOMIC_LOAD_OR_I64_P8:
809 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
811 case Mips::ATOMIC_LOAD_XOR_I8:
812 case Mips::ATOMIC_LOAD_XOR_I8_P8:
813 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
814 case Mips::ATOMIC_LOAD_XOR_I16:
815 case Mips::ATOMIC_LOAD_XOR_I16_P8:
816 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
817 case Mips::ATOMIC_LOAD_XOR_I32:
818 case Mips::ATOMIC_LOAD_XOR_I32_P8:
819 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
820 case Mips::ATOMIC_LOAD_XOR_I64:
821 case Mips::ATOMIC_LOAD_XOR_I64_P8:
822 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
824 case Mips::ATOMIC_LOAD_NAND_I8:
825 case Mips::ATOMIC_LOAD_NAND_I8_P8:
826 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
827 case Mips::ATOMIC_LOAD_NAND_I16:
828 case Mips::ATOMIC_LOAD_NAND_I16_P8:
829 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
830 case Mips::ATOMIC_LOAD_NAND_I32:
831 case Mips::ATOMIC_LOAD_NAND_I32_P8:
832 return emitAtomicBinary(MI, BB, 4, 0, true);
833 case Mips::ATOMIC_LOAD_NAND_I64:
834 case Mips::ATOMIC_LOAD_NAND_I64_P8:
835 return emitAtomicBinary(MI, BB, 8, 0, true);
837 case Mips::ATOMIC_LOAD_SUB_I8:
838 case Mips::ATOMIC_LOAD_SUB_I8_P8:
839 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
840 case Mips::ATOMIC_LOAD_SUB_I16:
841 case Mips::ATOMIC_LOAD_SUB_I16_P8:
842 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
843 case Mips::ATOMIC_LOAD_SUB_I32:
844 case Mips::ATOMIC_LOAD_SUB_I32_P8:
845 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
846 case Mips::ATOMIC_LOAD_SUB_I64:
847 case Mips::ATOMIC_LOAD_SUB_I64_P8:
848 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
850 case Mips::ATOMIC_SWAP_I8:
851 case Mips::ATOMIC_SWAP_I8_P8:
852 return emitAtomicBinaryPartword(MI, BB, 1, 0);
853 case Mips::ATOMIC_SWAP_I16:
854 case Mips::ATOMIC_SWAP_I16_P8:
855 return emitAtomicBinaryPartword(MI, BB, 2, 0);
856 case Mips::ATOMIC_SWAP_I32:
857 case Mips::ATOMIC_SWAP_I32_P8:
858 return emitAtomicBinary(MI, BB, 4, 0);
859 case Mips::ATOMIC_SWAP_I64:
860 case Mips::ATOMIC_SWAP_I64_P8:
861 return emitAtomicBinary(MI, BB, 8, 0);
863 case Mips::ATOMIC_CMP_SWAP_I8:
864 case Mips::ATOMIC_CMP_SWAP_I8_P8:
865 return emitAtomicCmpSwapPartword(MI, BB, 1);
866 case Mips::ATOMIC_CMP_SWAP_I16:
867 case Mips::ATOMIC_CMP_SWAP_I16_P8:
868 return emitAtomicCmpSwapPartword(MI, BB, 2);
869 case Mips::ATOMIC_CMP_SWAP_I32:
870 case Mips::ATOMIC_CMP_SWAP_I32_P8:
871 return emitAtomicCmpSwap(MI, BB, 4);
872 case Mips::ATOMIC_CMP_SWAP_I64:
873 case Mips::ATOMIC_CMP_SWAP_I64_P8:
874 return emitAtomicCmpSwap(MI, BB, 8);
878 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
879 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
881 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
882 unsigned Size, unsigned BinOpcode,
884 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
886 MachineFunction *MF = BB->getParent();
887 MachineRegisterInfo &RegInfo = MF->getRegInfo();
888 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
889 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
890 DebugLoc DL = MI->getDebugLoc();
891 unsigned LL, SC, AND, NOR, ZERO, BEQ;
894 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
895 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
902 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
903 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
906 ZERO = Mips::ZERO_64;
910 unsigned OldVal = MI->getOperand(0).getReg();
911 unsigned Ptr = MI->getOperand(1).getReg();
912 unsigned Incr = MI->getOperand(2).getReg();
914 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
915 unsigned AndRes = RegInfo.createVirtualRegister(RC);
916 unsigned Success = RegInfo.createVirtualRegister(RC);
918 // insert new blocks after the current block
919 const BasicBlock *LLVM_BB = BB->getBasicBlock();
920 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
921 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
922 MachineFunction::iterator It = BB;
924 MF->insert(It, loopMBB);
925 MF->insert(It, exitMBB);
927 // Transfer the remainder of BB and its successor edges to exitMBB.
928 exitMBB->splice(exitMBB->begin(), BB,
929 llvm::next(MachineBasicBlock::iterator(MI)),
931 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
935 // fallthrough --> loopMBB
936 BB->addSuccessor(loopMBB);
937 loopMBB->addSuccessor(loopMBB);
938 loopMBB->addSuccessor(exitMBB);
942 // <binop> storeval, oldval, incr
943 // sc success, storeval, 0(ptr)
944 // beq success, $0, loopMBB
946 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
948 // and andres, oldval, incr
949 // nor storeval, $0, andres
950 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
951 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
952 } else if (BinOpcode) {
953 // <binop> storeval, oldval, incr
954 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
958 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
959 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
961 MI->eraseFromParent(); // The instruction is gone now.
967 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
968 MachineBasicBlock *BB,
969 unsigned Size, unsigned BinOpcode,
971 assert((Size == 1 || Size == 2) &&
972 "Unsupported size for EmitAtomicBinaryPartial.");
974 MachineFunction *MF = BB->getParent();
975 MachineRegisterInfo &RegInfo = MF->getRegInfo();
976 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
977 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
978 DebugLoc DL = MI->getDebugLoc();
979 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
980 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
982 unsigned Dest = MI->getOperand(0).getReg();
983 unsigned Ptr = MI->getOperand(1).getReg();
984 unsigned Incr = MI->getOperand(2).getReg();
986 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
987 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
988 unsigned Mask = RegInfo.createVirtualRegister(RC);
989 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
990 unsigned NewVal = RegInfo.createVirtualRegister(RC);
991 unsigned OldVal = RegInfo.createVirtualRegister(RC);
992 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
993 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
994 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
995 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
996 unsigned AndRes = RegInfo.createVirtualRegister(RC);
997 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
998 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
999 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1000 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1001 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1002 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1003 unsigned Success = RegInfo.createVirtualRegister(RC);
1005 // insert new blocks after the current block
1006 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1007 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1008 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1009 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1010 MachineFunction::iterator It = BB;
1012 MF->insert(It, loopMBB);
1013 MF->insert(It, sinkMBB);
1014 MF->insert(It, exitMBB);
1016 // Transfer the remainder of BB and its successor edges to exitMBB.
1017 exitMBB->splice(exitMBB->begin(), BB,
1018 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1019 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1021 BB->addSuccessor(loopMBB);
1022 loopMBB->addSuccessor(loopMBB);
1023 loopMBB->addSuccessor(sinkMBB);
1024 sinkMBB->addSuccessor(exitMBB);
1027 // addiu masklsb2,$0,-4 # 0xfffffffc
1028 // and alignedaddr,ptr,masklsb2
1029 // andi ptrlsb2,ptr,3
1030 // sll shiftamt,ptrlsb2,3
1031 // ori maskupper,$0,255 # 0xff
1032 // sll mask,maskupper,shiftamt
1033 // nor mask2,$0,mask
1034 // sll incr2,incr,shiftamt
1036 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1037 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1038 .addReg(Mips::ZERO).addImm(-4);
1039 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1040 .addReg(Ptr).addReg(MaskLSB2);
1041 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1042 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1043 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1044 .addReg(Mips::ZERO).addImm(MaskImm);
1045 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1046 .addReg(ShiftAmt).addReg(MaskUpper);
1047 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1048 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1050 // atomic.load.binop
1052 // ll oldval,0(alignedaddr)
1053 // binop binopres,oldval,incr2
1054 // and newval,binopres,mask
1055 // and maskedoldval0,oldval,mask2
1056 // or storeval,maskedoldval0,newval
1057 // sc success,storeval,0(alignedaddr)
1058 // beq success,$0,loopMBB
1062 // ll oldval,0(alignedaddr)
1063 // and newval,incr2,mask
1064 // and maskedoldval0,oldval,mask2
1065 // or storeval,maskedoldval0,newval
1066 // sc success,storeval,0(alignedaddr)
1067 // beq success,$0,loopMBB
1070 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1072 // and andres, oldval, incr2
1073 // nor binopres, $0, andres
1074 // and newval, binopres, mask
1075 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1076 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1077 .addReg(Mips::ZERO).addReg(AndRes);
1078 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1079 } else if (BinOpcode) {
1080 // <binop> binopres, oldval, incr2
1081 // and newval, binopres, mask
1082 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1083 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1084 } else {// atomic.swap
1085 // and newval, incr2, mask
1086 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1089 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1090 .addReg(OldVal).addReg(Mask2);
1091 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1092 .addReg(MaskedOldVal0).addReg(NewVal);
1093 BuildMI(BB, DL, TII->get(SC), Success)
1094 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1095 BuildMI(BB, DL, TII->get(Mips::BEQ))
1096 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1099 // and maskedoldval1,oldval,mask
1100 // srl srlres,maskedoldval1,shiftamt
1101 // sll sllres,srlres,24
1102 // sra dest,sllres,24
1104 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1106 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1107 .addReg(OldVal).addReg(Mask);
1108 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1109 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1110 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1111 .addReg(SrlRes).addImm(ShiftImm);
1112 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1113 .addReg(SllRes).addImm(ShiftImm);
1115 MI->eraseFromParent(); // The instruction is gone now.
1121 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1122 MachineBasicBlock *BB,
1123 unsigned Size) const {
1124 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1126 MachineFunction *MF = BB->getParent();
1127 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1128 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1129 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1130 DebugLoc DL = MI->getDebugLoc();
1131 unsigned LL, SC, ZERO, BNE, BEQ;
1134 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1135 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1141 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1142 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1143 ZERO = Mips::ZERO_64;
1148 unsigned Dest = MI->getOperand(0).getReg();
1149 unsigned Ptr = MI->getOperand(1).getReg();
1150 unsigned OldVal = MI->getOperand(2).getReg();
1151 unsigned NewVal = MI->getOperand(3).getReg();
1153 unsigned Success = RegInfo.createVirtualRegister(RC);
1155 // insert new blocks after the current block
1156 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1157 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1158 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1159 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1160 MachineFunction::iterator It = BB;
1162 MF->insert(It, loop1MBB);
1163 MF->insert(It, loop2MBB);
1164 MF->insert(It, exitMBB);
1166 // Transfer the remainder of BB and its successor edges to exitMBB.
1167 exitMBB->splice(exitMBB->begin(), BB,
1168 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1169 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1173 // fallthrough --> loop1MBB
1174 BB->addSuccessor(loop1MBB);
1175 loop1MBB->addSuccessor(exitMBB);
1176 loop1MBB->addSuccessor(loop2MBB);
1177 loop2MBB->addSuccessor(loop1MBB);
1178 loop2MBB->addSuccessor(exitMBB);
1182 // bne dest, oldval, exitMBB
1184 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1185 BuildMI(BB, DL, TII->get(BNE))
1186 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1189 // sc success, newval, 0(ptr)
1190 // beq success, $0, loop1MBB
1192 BuildMI(BB, DL, TII->get(SC), Success)
1193 .addReg(NewVal).addReg(Ptr).addImm(0);
1194 BuildMI(BB, DL, TII->get(BEQ))
1195 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1197 MI->eraseFromParent(); // The instruction is gone now.
1203 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1204 MachineBasicBlock *BB,
1205 unsigned Size) const {
1206 assert((Size == 1 || Size == 2) &&
1207 "Unsupported size for EmitAtomicCmpSwapPartial.");
1209 MachineFunction *MF = BB->getParent();
1210 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1211 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1212 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1213 DebugLoc DL = MI->getDebugLoc();
1214 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1215 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1217 unsigned Dest = MI->getOperand(0).getReg();
1218 unsigned Ptr = MI->getOperand(1).getReg();
1219 unsigned CmpVal = MI->getOperand(2).getReg();
1220 unsigned NewVal = MI->getOperand(3).getReg();
1222 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1223 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1224 unsigned Mask = RegInfo.createVirtualRegister(RC);
1225 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1226 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1227 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1228 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1229 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1230 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1231 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1232 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1233 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1234 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1235 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1236 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1237 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1238 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1239 unsigned Success = RegInfo.createVirtualRegister(RC);
1241 // insert new blocks after the current block
1242 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1243 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1246 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1247 MachineFunction::iterator It = BB;
1249 MF->insert(It, loop1MBB);
1250 MF->insert(It, loop2MBB);
1251 MF->insert(It, sinkMBB);
1252 MF->insert(It, exitMBB);
1254 // Transfer the remainder of BB and its successor edges to exitMBB.
1255 exitMBB->splice(exitMBB->begin(), BB,
1256 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1257 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1259 BB->addSuccessor(loop1MBB);
1260 loop1MBB->addSuccessor(sinkMBB);
1261 loop1MBB->addSuccessor(loop2MBB);
1262 loop2MBB->addSuccessor(loop1MBB);
1263 loop2MBB->addSuccessor(sinkMBB);
1264 sinkMBB->addSuccessor(exitMBB);
1266 // FIXME: computation of newval2 can be moved to loop2MBB.
1268 // addiu masklsb2,$0,-4 # 0xfffffffc
1269 // and alignedaddr,ptr,masklsb2
1270 // andi ptrlsb2,ptr,3
1271 // sll shiftamt,ptrlsb2,3
1272 // ori maskupper,$0,255 # 0xff
1273 // sll mask,maskupper,shiftamt
1274 // nor mask2,$0,mask
1275 // andi maskedcmpval,cmpval,255
1276 // sll shiftedcmpval,maskedcmpval,shiftamt
1277 // andi maskednewval,newval,255
1278 // sll shiftednewval,maskednewval,shiftamt
1279 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1280 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1281 .addReg(Mips::ZERO).addImm(-4);
1282 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1283 .addReg(Ptr).addReg(MaskLSB2);
1284 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1285 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1286 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1287 .addReg(Mips::ZERO).addImm(MaskImm);
1288 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1289 .addReg(ShiftAmt).addReg(MaskUpper);
1290 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1291 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1292 .addReg(CmpVal).addImm(MaskImm);
1293 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1294 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1295 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1296 .addReg(NewVal).addImm(MaskImm);
1297 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1298 .addReg(ShiftAmt).addReg(MaskedNewVal);
1301 // ll oldval,0(alginedaddr)
1302 // and maskedoldval0,oldval,mask
1303 // bne maskedoldval0,shiftedcmpval,sinkMBB
1305 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1306 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1307 .addReg(OldVal).addReg(Mask);
1308 BuildMI(BB, DL, TII->get(Mips::BNE))
1309 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1312 // and maskedoldval1,oldval,mask2
1313 // or storeval,maskedoldval1,shiftednewval
1314 // sc success,storeval,0(alignedaddr)
1315 // beq success,$0,loop1MBB
1317 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1318 .addReg(OldVal).addReg(Mask2);
1319 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1320 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1321 BuildMI(BB, DL, TII->get(SC), Success)
1322 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1323 BuildMI(BB, DL, TII->get(Mips::BEQ))
1324 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1327 // srl srlres,maskedoldval0,shiftamt
1328 // sll sllres,srlres,24
1329 // sra dest,sllres,24
1331 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1333 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1334 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1335 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1336 .addReg(SrlRes).addImm(ShiftImm);
1337 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1338 .addReg(SllRes).addImm(ShiftImm);
1340 MI->eraseFromParent(); // The instruction is gone now.
1345 //===----------------------------------------------------------------------===//
1346 // Misc Lower Operation implementation
1347 //===----------------------------------------------------------------------===//
1348 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1349 SDValue Chain = Op.getOperand(0);
1350 SDValue Table = Op.getOperand(1);
1351 SDValue Index = Op.getOperand(2);
1352 DebugLoc DL = Op.getDebugLoc();
1353 EVT PTy = getPointerTy();
1354 unsigned EntrySize =
1355 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1357 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1358 DAG.getConstant(EntrySize, PTy));
1359 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1361 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1362 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1363 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1365 Chain = Addr.getValue(1);
1367 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1368 // For PIC, the sequence is:
1369 // BRIND(load(Jumptable + index) + RelocBase)
1370 // RelocBase can be JumpTable, GOT or some sort of global base.
1371 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1372 getPICJumpTableRelocBase(Table, DAG));
1375 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1378 SDValue MipsTargetLowering::
1379 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1381 // The first operand is the chain, the second is the condition, the third is
1382 // the block to branch to if the condition is true.
1383 SDValue Chain = Op.getOperand(0);
1384 SDValue Dest = Op.getOperand(2);
1385 DebugLoc DL = Op.getDebugLoc();
1387 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1389 // Return if flag is not set by a floating point comparison.
1390 if (CondRes.getOpcode() != MipsISD::FPCmp)
1393 SDValue CCNode = CondRes.getOperand(2);
1395 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1396 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1397 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1398 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1402 SDValue MipsTargetLowering::
1403 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1405 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1407 // Return if flag is not set by a floating point comparison.
1408 if (Cond.getOpcode() != MipsISD::FPCmp)
1411 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1415 SDValue MipsTargetLowering::
1416 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1418 DebugLoc DL = Op.getDebugLoc();
1419 EVT Ty = Op.getOperand(0).getValueType();
1420 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1421 Op.getOperand(0), Op.getOperand(1),
1424 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1428 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1429 SDValue Cond = createFPCmp(DAG, Op);
1431 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1432 "Floating point operand expected.");
1434 SDValue True = DAG.getConstant(1, MVT::i32);
1435 SDValue False = DAG.getConstant(0, MVT::i32);
1437 return createCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1440 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1441 SelectionDAG &DAG) const {
1442 // FIXME there isn't actually debug info here
1443 DebugLoc DL = Op.getDebugLoc();
1444 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1446 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1447 const MipsTargetObjectFile &TLOF =
1448 (const MipsTargetObjectFile&)getObjFileLowering();
1450 // %gp_rel relocation
1451 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1452 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1454 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1455 DAG.getVTList(MVT::i32), &GA, 1);
1456 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1457 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1460 // %hi/%lo relocation
1461 return getAddrNonPIC(Op, DAG);
1464 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1465 return getAddrLocal(Op, DAG, HasMips64);
1468 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1469 MipsII::MO_GOT_LO16);
1471 return getAddrGlobal(Op, DAG,
1472 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1475 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1476 SelectionDAG &DAG) const {
1477 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1478 return getAddrNonPIC(Op, DAG);
1480 return getAddrLocal(Op, DAG, HasMips64);
1483 SDValue MipsTargetLowering::
1484 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1486 // If the relocation model is PIC, use the General Dynamic TLS Model or
1487 // Local Dynamic TLS model, otherwise use the Initial Exec or
1488 // Local Exec TLS Model.
1490 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1491 DebugLoc DL = GA->getDebugLoc();
1492 const GlobalValue *GV = GA->getGlobal();
1493 EVT PtrVT = getPointerTy();
1495 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1497 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1498 // General Dynamic and Local Dynamic TLS Model.
1499 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1502 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1503 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1504 getGlobalReg(DAG, PtrVT), TGA);
1505 unsigned PtrSize = PtrVT.getSizeInBits();
1506 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1508 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1512 Entry.Node = Argument;
1514 Args.push_back(Entry);
1516 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1517 false, false, false, false, 0, CallingConv::C,
1518 /*IsTailCall=*/false, /*doesNotRet=*/false,
1519 /*isReturnValueUsed=*/true,
1520 TlsGetAddr, Args, DAG, DL);
1521 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1523 SDValue Ret = CallResult.first;
1525 if (model != TLSModel::LocalDynamic)
1528 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1529 MipsII::MO_DTPREL_HI);
1530 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1531 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1532 MipsII::MO_DTPREL_LO);
1533 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1534 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1535 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1539 if (model == TLSModel::InitialExec) {
1540 // Initial Exec TLS Model
1541 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1542 MipsII::MO_GOTTPREL);
1543 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1545 Offset = DAG.getLoad(PtrVT, DL,
1546 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1547 false, false, false, 0);
1549 // Local Exec TLS Model
1550 assert(model == TLSModel::LocalExec);
1551 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1552 MipsII::MO_TPREL_HI);
1553 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1554 MipsII::MO_TPREL_LO);
1555 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1556 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1557 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1560 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1561 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1564 SDValue MipsTargetLowering::
1565 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1567 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1568 return getAddrNonPIC(Op, DAG);
1570 return getAddrLocal(Op, DAG, HasMips64);
1573 SDValue MipsTargetLowering::
1574 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1576 // gp_rel relocation
1577 // FIXME: we should reference the constant pool using small data sections,
1578 // but the asm printer currently doesn't support this feature without
1579 // hacking it. This feature should come soon so we can uncomment the
1581 //if (IsInSmallSection(C->getType())) {
1582 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1583 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1584 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1586 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1587 return getAddrNonPIC(Op, DAG);
1589 return getAddrLocal(Op, DAG, HasMips64);
1592 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1593 MachineFunction &MF = DAG.getMachineFunction();
1594 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1596 DebugLoc DL = Op.getDebugLoc();
1597 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1600 // vastart just stores the address of the VarArgsFrameIndex slot into the
1601 // memory location argument.
1602 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1603 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1604 MachinePointerInfo(SV), false, false, 0);
1607 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1608 EVT TyX = Op.getOperand(0).getValueType();
1609 EVT TyY = Op.getOperand(1).getValueType();
1610 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1611 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1612 DebugLoc DL = Op.getDebugLoc();
1615 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1617 SDValue X = (TyX == MVT::f32) ?
1618 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1619 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1621 SDValue Y = (TyY == MVT::f32) ?
1622 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1623 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1627 // ext E, Y, 31, 1 ; extract bit31 of Y
1628 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1629 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1630 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1633 // srl SrlX, SllX, 1
1635 // sll SllY, SrlX, 31
1636 // or Or, SrlX, SllY
1637 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1638 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1639 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1640 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1641 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1644 if (TyX == MVT::f32)
1645 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1647 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1648 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1649 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1652 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1653 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1654 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1655 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1656 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1657 DebugLoc DL = Op.getDebugLoc();
1659 // Bitcast to integer nodes.
1660 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1661 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1664 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1665 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1666 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1667 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1669 if (WidthX > WidthY)
1670 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1671 else if (WidthY > WidthX)
1672 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1674 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1675 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1676 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1679 // (d)sll SllX, X, 1
1680 // (d)srl SrlX, SllX, 1
1681 // (d)srl SrlY, Y, width(Y)-1
1682 // (d)sll SllY, SrlX, width(Y)-1
1683 // or Or, SrlX, SllY
1684 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1685 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1686 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1687 DAG.getConstant(WidthY - 1, MVT::i32));
1689 if (WidthX > WidthY)
1690 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1691 else if (WidthY > WidthX)
1692 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1694 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1695 DAG.getConstant(WidthX - 1, MVT::i32));
1696 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1697 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1701 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1702 if (Subtarget->hasMips64())
1703 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1705 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1708 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1709 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1710 DebugLoc DL = Op.getDebugLoc();
1712 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1714 SDValue X = (Op.getValueType() == MVT::f32) ?
1715 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1716 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1721 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1722 DAG.getRegister(Mips::ZERO, MVT::i32),
1723 DAG.getConstant(31, MVT::i32), Const1, X);
1725 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1726 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1729 if (Op.getValueType() == MVT::f32)
1730 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1732 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1733 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1734 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1737 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1738 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1739 DebugLoc DL = Op.getDebugLoc();
1741 // Bitcast to integer node.
1742 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1746 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1747 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1748 DAG.getConstant(63, MVT::i32), Const1, X);
1750 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1751 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1754 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1758 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1759 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1760 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1762 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1765 SDValue MipsTargetLowering::
1766 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1768 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1769 "Frame address can only be determined for current frame.");
1771 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1772 MFI->setFrameAddressIsTaken(true);
1773 EVT VT = Op.getValueType();
1774 DebugLoc DL = Op.getDebugLoc();
1775 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1776 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1780 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1781 SelectionDAG &DAG) const {
1783 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1784 "Return address can be determined only for current frame.");
1786 MachineFunction &MF = DAG.getMachineFunction();
1787 MachineFrameInfo *MFI = MF.getFrameInfo();
1788 MVT VT = Op.getSimpleValueType();
1789 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1790 MFI->setReturnAddressIsTaken(true);
1792 // Return RA, which contains the return address. Mark it an implicit live-in.
1793 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1794 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
1797 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1798 // generated from __builtin_eh_return (offset, handler)
1799 // The effect of this is to adjust the stack pointer by "offset"
1800 // and then branch to "handler".
1801 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1803 MachineFunction &MF = DAG.getMachineFunction();
1804 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1806 MipsFI->setCallsEhReturn();
1807 SDValue Chain = Op.getOperand(0);
1808 SDValue Offset = Op.getOperand(1);
1809 SDValue Handler = Op.getOperand(2);
1810 DebugLoc DL = Op.getDebugLoc();
1811 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1813 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1814 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1815 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1816 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1817 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1818 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1819 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1820 DAG.getRegister(OffsetReg, Ty),
1821 DAG.getRegister(AddrReg, getPointerTy()),
1825 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1826 SelectionDAG &DAG) const {
1827 // FIXME: Need pseudo-fence for 'singlethread' fences
1828 // FIXME: Set SType for weaker fences where supported/appropriate.
1830 DebugLoc DL = Op.getDebugLoc();
1831 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1832 DAG.getConstant(SType, MVT::i32));
1835 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1836 SelectionDAG &DAG) const {
1837 DebugLoc DL = Op.getDebugLoc();
1838 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1839 SDValue Shamt = Op.getOperand(2);
1842 // lo = (shl lo, shamt)
1843 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1846 // hi = (shl lo, shamt[4:0])
1847 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1848 DAG.getConstant(-1, MVT::i32));
1849 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1850 DAG.getConstant(1, MVT::i32));
1851 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1853 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1854 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1855 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1856 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1857 DAG.getConstant(0x20, MVT::i32));
1858 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1859 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1860 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1862 SDValue Ops[2] = {Lo, Hi};
1863 return DAG.getMergeValues(Ops, 2, DL);
1866 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1868 DebugLoc DL = Op.getDebugLoc();
1869 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1870 SDValue Shamt = Op.getOperand(2);
1873 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1875 // hi = (sra hi, shamt)
1877 // hi = (srl hi, shamt)
1880 // lo = (sra hi, shamt[4:0])
1881 // hi = (sra hi, 31)
1883 // lo = (srl hi, shamt[4:0])
1885 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1886 DAG.getConstant(-1, MVT::i32));
1887 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1888 DAG.getConstant(1, MVT::i32));
1889 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1890 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1891 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1892 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1894 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1895 DAG.getConstant(0x20, MVT::i32));
1896 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1897 DAG.getConstant(31, MVT::i32));
1898 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1899 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1900 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1903 SDValue Ops[2] = {Lo, Hi};
1904 return DAG.getMergeValues(Ops, 2, DL);
1907 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1908 SDValue Chain, SDValue Src, unsigned Offset) {
1909 SDValue Ptr = LD->getBasePtr();
1910 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1911 EVT BasePtrVT = Ptr.getValueType();
1912 DebugLoc DL = LD->getDebugLoc();
1913 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1916 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1917 DAG.getConstant(Offset, BasePtrVT));
1919 SDValue Ops[] = { Chain, Ptr, Src };
1920 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1921 LD->getMemOperand());
1924 // Expand an unaligned 32 or 64-bit integer load node.
1925 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1926 LoadSDNode *LD = cast<LoadSDNode>(Op);
1927 EVT MemVT = LD->getMemoryVT();
1929 // Return if load is aligned or if MemVT is neither i32 nor i64.
1930 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1931 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1934 bool IsLittle = Subtarget->isLittle();
1935 EVT VT = Op.getValueType();
1936 ISD::LoadExtType ExtType = LD->getExtensionType();
1937 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1939 assert((VT == MVT::i32) || (VT == MVT::i64));
1942 // (set dst, (i64 (load baseptr)))
1944 // (set tmp, (ldl (add baseptr, 7), undef))
1945 // (set dst, (ldr baseptr, tmp))
1946 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1947 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1949 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1953 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1955 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1959 // (set dst, (i32 (load baseptr))) or
1960 // (set dst, (i64 (sextload baseptr))) or
1961 // (set dst, (i64 (extload baseptr)))
1963 // (set tmp, (lwl (add baseptr, 3), undef))
1964 // (set dst, (lwr baseptr, tmp))
1965 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1966 (ExtType == ISD::EXTLOAD))
1969 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1972 // (set dst, (i64 (zextload baseptr)))
1974 // (set tmp0, (lwl (add baseptr, 3), undef))
1975 // (set tmp1, (lwr baseptr, tmp0))
1976 // (set tmp2, (shl tmp1, 32))
1977 // (set dst, (srl tmp2, 32))
1978 DebugLoc DL = LD->getDebugLoc();
1979 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1980 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1981 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1982 SDValue Ops[] = { SRL, LWR.getValue(1) };
1983 return DAG.getMergeValues(Ops, 2, DL);
1986 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
1987 SDValue Chain, unsigned Offset) {
1988 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
1989 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
1990 DebugLoc DL = SD->getDebugLoc();
1991 SDVTList VTList = DAG.getVTList(MVT::Other);
1994 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1995 DAG.getConstant(Offset, BasePtrVT));
1997 SDValue Ops[] = { Chain, Value, Ptr };
1998 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1999 SD->getMemOperand());
2002 // Expand an unaligned 32 or 64-bit integer store node.
2003 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2004 StoreSDNode *SD = cast<StoreSDNode>(Op);
2005 EVT MemVT = SD->getMemoryVT();
2007 // Return if store is aligned or if MemVT is neither i32 nor i64.
2008 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2009 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2012 bool IsLittle = Subtarget->isLittle();
2013 SDValue Value = SD->getValue(), Chain = SD->getChain();
2014 EVT VT = Value.getValueType();
2017 // (store val, baseptr) or
2018 // (truncstore val, baseptr)
2020 // (swl val, (add baseptr, 3))
2021 // (swr val, baseptr)
2022 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2023 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2025 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2028 assert(VT == MVT::i64);
2031 // (store val, baseptr)
2033 // (sdl val, (add baseptr, 7))
2034 // (sdr val, baseptr)
2035 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2036 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2039 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2040 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2041 || cast<ConstantSDNode>
2042 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2043 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2047 // (add (frameaddr 0), (frame_to_args_offset))
2048 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2049 // (add FrameObject, 0)
2050 // where FrameObject is a fixed StackObject with offset 0 which points to
2051 // the old stack pointer.
2052 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2053 EVT ValTy = Op->getValueType(0);
2054 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2055 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2056 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2057 DAG.getConstant(0, ValTy));
2060 //===----------------------------------------------------------------------===//
2061 // Calling Convention Implementation
2062 //===----------------------------------------------------------------------===//
2064 //===----------------------------------------------------------------------===//
2065 // TODO: Implement a generic logic using tblgen that can support this.
2066 // Mips O32 ABI rules:
2068 // i32 - Passed in A0, A1, A2, A3 and stack
2069 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2070 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2071 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2072 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2073 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2076 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2077 //===----------------------------------------------------------------------===//
2079 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2080 MVT LocVT, CCValAssign::LocInfo LocInfo,
2081 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2083 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2085 static const uint16_t IntRegs[] = {
2086 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2088 static const uint16_t F32Regs[] = {
2089 Mips::F12, Mips::F14
2091 static const uint16_t F64Regs[] = {
2095 // Do not process byval args here.
2096 if (ArgFlags.isByVal())
2099 // Promote i8 and i16
2100 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2102 if (ArgFlags.isSExt())
2103 LocInfo = CCValAssign::SExt;
2104 else if (ArgFlags.isZExt())
2105 LocInfo = CCValAssign::ZExt;
2107 LocInfo = CCValAssign::AExt;
2112 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2113 // is true: function is vararg, argument is 3rd or higher, there is previous
2114 // argument which is not f32 or f64.
2115 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2116 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2117 unsigned OrigAlign = ArgFlags.getOrigAlign();
2118 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2120 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2121 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2122 // If this is the first part of an i64 arg,
2123 // the allocated register must be either A0 or A2.
2124 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2125 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2127 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2128 // Allocate int register and shadow next int register. If first
2129 // available register is Mips::A1 or Mips::A3, shadow it too.
2130 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2131 if (Reg == Mips::A1 || Reg == Mips::A3)
2132 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2133 State.AllocateReg(IntRegs, IntRegsSize);
2135 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2136 // we are guaranteed to find an available float register
2137 if (ValVT == MVT::f32) {
2138 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2139 // Shadow int register
2140 State.AllocateReg(IntRegs, IntRegsSize);
2142 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2143 // Shadow int registers
2144 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2145 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2146 State.AllocateReg(IntRegs, IntRegsSize);
2147 State.AllocateReg(IntRegs, IntRegsSize);
2150 llvm_unreachable("Cannot handle this ValVT.");
2153 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2155 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2157 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2162 #include "MipsGenCallingConv.inc"
2164 //===----------------------------------------------------------------------===//
2165 // Call Calling Convention Implementation
2166 //===----------------------------------------------------------------------===//
2168 static const unsigned O32IntRegsSize = 4;
2170 // Return next O32 integer argument register.
2171 static unsigned getNextIntArgReg(unsigned Reg) {
2172 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2173 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2177 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2178 SDValue Chain, SDValue Arg, DebugLoc DL,
2179 bool IsTailCall, SelectionDAG &DAG) const {
2181 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2182 DAG.getIntPtrConstant(Offset));
2183 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2187 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2188 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2189 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2190 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2191 /*isVolatile=*/ true, false, 0);
2194 void MipsTargetLowering::
2195 getOpndList(SmallVectorImpl<SDValue> &Ops,
2196 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2197 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2198 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2199 // Insert node "GP copy globalreg" before call to function.
2201 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2202 // in PIC mode) allow symbols to be resolved via lazy binding.
2203 // The lazy binding stub requires GP to point to the GOT.
2204 if (IsPICCall && !InternalLinkage) {
2205 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2206 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2207 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2210 // Build a sequence of copy-to-reg nodes chained together with token
2211 // chain and flag operands which copy the outgoing args into registers.
2212 // The InFlag in necessary since all emitted instructions must be
2216 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2217 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2218 RegsToPass[i].second, InFlag);
2219 InFlag = Chain.getValue(1);
2222 // Add argument registers to the end of the list so that they are
2223 // known live into the call.
2224 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2225 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2226 RegsToPass[i].second.getValueType()));
2228 // Add a register mask operand representing the call-preserved registers.
2229 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2230 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2231 assert(Mask && "Missing call preserved mask for calling convention");
2232 if (Subtarget->inMips16HardFloat()) {
2233 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2234 llvm::StringRef Sym = G->getGlobal()->getName();
2235 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2236 if (F->hasFnAttribute("__Mips16RetHelper")) {
2237 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2241 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2243 if (InFlag.getNode())
2244 Ops.push_back(InFlag);
2247 /// LowerCall - functions arguments are copied from virtual regs to
2248 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2250 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2251 SmallVectorImpl<SDValue> &InVals) const {
2252 SelectionDAG &DAG = CLI.DAG;
2253 DebugLoc &DL = CLI.DL;
2254 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2255 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2256 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2257 SDValue Chain = CLI.Chain;
2258 SDValue Callee = CLI.Callee;
2259 bool &IsTailCall = CLI.IsTailCall;
2260 CallingConv::ID CallConv = CLI.CallConv;
2261 bool IsVarArg = CLI.IsVarArg;
2263 MachineFunction &MF = DAG.getMachineFunction();
2264 MachineFrameInfo *MFI = MF.getFrameInfo();
2265 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2266 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2268 // Analyze operands of the call, assigning locations to each operand.
2269 SmallVector<CCValAssign, 16> ArgLocs;
2270 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2271 getTargetMachine(), ArgLocs, *DAG.getContext());
2272 MipsCC::SpecialCallingConvType SpecialCallingConv =
2273 getSpecialCallingConv(Callee);
2274 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo, SpecialCallingConv);
2276 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2277 getTargetMachine().Options.UseSoftFloat,
2278 Callee.getNode(), CLI.Args);
2280 // Get a count of how many bytes are to be pushed on the stack.
2281 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2283 // Check if it's really possible to do a tail call.
2286 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2287 *MF.getInfo<MipsFunctionInfo>());
2292 // Chain is the output chain of the last Load/Store or CopyToReg node.
2293 // ByValChain is the output chain of the last Memcpy node created for copying
2294 // byval arguments to the stack.
2295 unsigned StackAlignment = TFL->getStackAlignment();
2296 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2297 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2300 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
2302 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2303 IsN64 ? Mips::SP_64 : Mips::SP,
2306 // With EABI is it possible to have 16 args on registers.
2307 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2308 SmallVector<SDValue, 8> MemOpChains;
2309 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2311 // Walk the register/memloc assignments, inserting copies/loads.
2312 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2313 SDValue Arg = OutVals[i];
2314 CCValAssign &VA = ArgLocs[i];
2315 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2316 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2319 if (Flags.isByVal()) {
2320 assert(Flags.getByValSize() &&
2321 "ByVal args of size 0 should have been ignored by front-end.");
2322 assert(ByValArg != MipsCCInfo.byval_end());
2323 assert(!IsTailCall &&
2324 "Do not tail-call optimize if there is a byval argument.");
2325 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2326 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2331 // Promote the value if needed.
2332 switch (VA.getLocInfo()) {
2333 default: llvm_unreachable("Unknown loc info!");
2334 case CCValAssign::Full:
2335 if (VA.isRegLoc()) {
2336 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2337 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2338 (ValVT == MVT::i64 && LocVT == MVT::f64))
2339 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2340 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2341 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2342 Arg, DAG.getConstant(0, MVT::i32));
2343 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2344 Arg, DAG.getConstant(1, MVT::i32));
2345 if (!Subtarget->isLittle())
2347 unsigned LocRegLo = VA.getLocReg();
2348 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2349 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2350 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2355 case CCValAssign::SExt:
2356 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2358 case CCValAssign::ZExt:
2359 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2361 case CCValAssign::AExt:
2362 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2366 // Arguments that can be passed on register must be kept at
2367 // RegsToPass vector
2368 if (VA.isRegLoc()) {
2369 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2373 // Register can't get to this point...
2374 assert(VA.isMemLoc());
2376 // emit ISD::STORE whichs stores the
2377 // parameter value to a stack Location
2378 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2379 Chain, Arg, DL, IsTailCall, DAG));
2382 // Transform all store nodes into one single node because all store
2383 // nodes are independent of each other.
2384 if (!MemOpChains.empty())
2385 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2386 &MemOpChains[0], MemOpChains.size());
2388 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2389 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2390 // node so that legalize doesn't hack it.
2391 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2392 bool GlobalOrExternal = false, InternalLinkage = false;
2395 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2397 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2399 if (InternalLinkage)
2400 Callee = getAddrLocal(Callee, DAG, HasMips64);
2402 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2403 MipsII::MO_CALL_LO16);
2405 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2407 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2408 MipsII::MO_NO_FLAG);
2409 GlobalOrExternal = true;
2411 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2412 if (!IsN64 && !IsPIC) // !N64 && static
2413 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2414 MipsII::MO_NO_FLAG);
2416 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2417 MipsII::MO_CALL_LO16);
2419 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2421 GlobalOrExternal = true;
2424 SmallVector<SDValue, 8> Ops(1, Chain);
2425 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2427 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2428 CLI, Callee, Chain);
2431 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2433 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2434 SDValue InFlag = Chain.getValue(1);
2436 // Create the CALLSEQ_END node.
2437 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2438 DAG.getIntPtrConstant(0, true), InFlag);
2439 InFlag = Chain.getValue(1);
2441 // Handle result values, copying them out of physregs into vregs that we
2443 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2444 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2447 /// LowerCallResult - Lower the result values of a call into the
2448 /// appropriate copies out of appropriate physical registers.
2450 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2451 CallingConv::ID CallConv, bool IsVarArg,
2452 const SmallVectorImpl<ISD::InputArg> &Ins,
2453 DebugLoc DL, SelectionDAG &DAG,
2454 SmallVectorImpl<SDValue> &InVals,
2455 const SDNode *CallNode,
2456 const Type *RetTy) const {
2457 // Assign locations to each value returned by this call.
2458 SmallVector<CCValAssign, 16> RVLocs;
2459 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2460 getTargetMachine(), RVLocs, *DAG.getContext());
2461 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2463 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2466 // Copy all of the result registers out of their specified physreg.
2467 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2468 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2469 RVLocs[i].getLocVT(), InFlag);
2470 Chain = Val.getValue(1);
2471 InFlag = Val.getValue(2);
2473 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2474 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2476 InVals.push_back(Val);
2482 //===----------------------------------------------------------------------===//
2483 // Formal Arguments Calling Convention Implementation
2484 //===----------------------------------------------------------------------===//
2485 /// LowerFormalArguments - transform physical registers into virtual registers
2486 /// and generate load operations for arguments places on the stack.
2488 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2489 CallingConv::ID CallConv,
2491 const SmallVectorImpl<ISD::InputArg> &Ins,
2492 DebugLoc DL, SelectionDAG &DAG,
2493 SmallVectorImpl<SDValue> &InVals)
2495 MachineFunction &MF = DAG.getMachineFunction();
2496 MachineFrameInfo *MFI = MF.getFrameInfo();
2497 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2499 MipsFI->setVarArgsFrameIndex(0);
2501 // Used with vargs to acumulate store chains.
2502 std::vector<SDValue> OutChains;
2504 // Assign locations to all of the incoming arguments.
2505 SmallVector<CCValAssign, 16> ArgLocs;
2506 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2507 getTargetMachine(), ArgLocs, *DAG.getContext());
2508 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2509 Function::const_arg_iterator FuncArg =
2510 DAG.getMachineFunction().getFunction()->arg_begin();
2511 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2513 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2514 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2515 MipsCCInfo.hasByValArg());
2517 unsigned CurArgIdx = 0;
2518 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2520 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2521 CCValAssign &VA = ArgLocs[i];
2522 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2523 CurArgIdx = Ins[i].OrigArgIndex;
2524 EVT ValVT = VA.getValVT();
2525 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2526 bool IsRegLoc = VA.isRegLoc();
2528 if (Flags.isByVal()) {
2529 assert(Flags.getByValSize() &&
2530 "ByVal args of size 0 should have been ignored by front-end.");
2531 assert(ByValArg != MipsCCInfo.byval_end());
2532 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2533 MipsCCInfo, *ByValArg);
2538 // Arguments stored on registers
2540 EVT RegVT = VA.getLocVT();
2541 unsigned ArgReg = VA.getLocReg();
2542 const TargetRegisterClass *RC;
2544 if (RegVT == MVT::i32)
2545 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2546 &Mips::CPURegsRegClass;
2547 else if (RegVT == MVT::i64)
2548 RC = &Mips::CPU64RegsRegClass;
2549 else if (RegVT == MVT::f32)
2550 RC = &Mips::FGR32RegClass;
2551 else if (RegVT == MVT::f64)
2552 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2554 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2556 // Transform the arguments stored on
2557 // physical registers into virtual ones
2558 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2559 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2561 // If this is an 8 or 16-bit value, it has been passed promoted
2562 // to 32 bits. Insert an assert[sz]ext to capture this, then
2563 // truncate to the right size.
2564 if (VA.getLocInfo() != CCValAssign::Full) {
2565 unsigned Opcode = 0;
2566 if (VA.getLocInfo() == CCValAssign::SExt)
2567 Opcode = ISD::AssertSext;
2568 else if (VA.getLocInfo() == CCValAssign::ZExt)
2569 Opcode = ISD::AssertZext;
2571 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2572 DAG.getValueType(ValVT));
2573 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2576 // Handle floating point arguments passed in integer registers and
2577 // long double arguments passed in floating point registers.
2578 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2579 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2580 (RegVT == MVT::f64 && ValVT == MVT::i64))
2581 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2582 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2583 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2584 getNextIntArgReg(ArgReg), RC);
2585 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2586 if (!Subtarget->isLittle())
2587 std::swap(ArgValue, ArgValue2);
2588 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2589 ArgValue, ArgValue2);
2592 InVals.push_back(ArgValue);
2593 } else { // VA.isRegLoc()
2596 assert(VA.isMemLoc());
2598 // The stack pointer offset is relative to the caller stack frame.
2599 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2600 VA.getLocMemOffset(), true);
2602 // Create load nodes to retrieve arguments from the stack
2603 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2604 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2605 MachinePointerInfo::getFixedStack(FI),
2606 false, false, false, 0));
2610 // The mips ABIs for returning structs by value requires that we copy
2611 // the sret argument into $v0 for the return. Save the argument into
2612 // a virtual register so that we can access it from the return points.
2613 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2614 unsigned Reg = MipsFI->getSRetReturnReg();
2616 Reg = MF.getRegInfo().
2617 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2618 MipsFI->setSRetReturnReg(Reg);
2620 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2621 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2625 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2627 // All stores are grouped in one node to allow the matching between
2628 // the size of Ins and InVals. This only happens when on varg functions
2629 if (!OutChains.empty()) {
2630 OutChains.push_back(Chain);
2631 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2632 &OutChains[0], OutChains.size());
2638 //===----------------------------------------------------------------------===//
2639 // Return Value Calling Convention Implementation
2640 //===----------------------------------------------------------------------===//
2643 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2644 MachineFunction &MF, bool IsVarArg,
2645 const SmallVectorImpl<ISD::OutputArg> &Outs,
2646 LLVMContext &Context) const {
2647 SmallVector<CCValAssign, 16> RVLocs;
2648 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2650 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2654 MipsTargetLowering::LowerReturn(SDValue Chain,
2655 CallingConv::ID CallConv, bool IsVarArg,
2656 const SmallVectorImpl<ISD::OutputArg> &Outs,
2657 const SmallVectorImpl<SDValue> &OutVals,
2658 DebugLoc DL, SelectionDAG &DAG) const {
2659 // CCValAssign - represent the assignment of
2660 // the return value to a location
2661 SmallVector<CCValAssign, 16> RVLocs;
2662 MachineFunction &MF = DAG.getMachineFunction();
2664 // CCState - Info about the registers and stack slot.
2665 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2667 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2669 // Analyze return values.
2670 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2671 MF.getFunction()->getReturnType());
2674 SmallVector<SDValue, 4> RetOps(1, Chain);
2676 // Copy the result values into the output registers.
2677 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2678 SDValue Val = OutVals[i];
2679 CCValAssign &VA = RVLocs[i];
2680 assert(VA.isRegLoc() && "Can only return in registers!");
2682 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2683 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2685 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2687 // Guarantee that all emitted copies are stuck together with flags.
2688 Flag = Chain.getValue(1);
2689 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2692 // The mips ABIs for returning structs by value requires that we copy
2693 // the sret argument into $v0 for the return. We saved the argument into
2694 // a virtual register in the entry block, so now we copy the value out
2696 if (MF.getFunction()->hasStructRetAttr()) {
2697 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2698 unsigned Reg = MipsFI->getSRetReturnReg();
2701 llvm_unreachable("sret virtual register not created in the entry block");
2702 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2703 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2705 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2706 Flag = Chain.getValue(1);
2707 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2710 RetOps[0] = Chain; // Update chain.
2712 // Add the flag if we have it.
2714 RetOps.push_back(Flag);
2716 // Return on Mips is always a "jr $ra"
2717 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2720 //===----------------------------------------------------------------------===//
2721 // Mips Inline Assembly Support
2722 //===----------------------------------------------------------------------===//
2724 /// getConstraintType - Given a constraint letter, return the type of
2725 /// constraint it is for this target.
2726 MipsTargetLowering::ConstraintType MipsTargetLowering::
2727 getConstraintType(const std::string &Constraint) const
2729 // Mips specific constrainy
2730 // GCC config/mips/constraints.md
2732 // 'd' : An address register. Equivalent to r
2733 // unless generating MIPS16 code.
2734 // 'y' : Equivalent to r; retained for
2735 // backwards compatibility.
2736 // 'c' : A register suitable for use in an indirect
2737 // jump. This will always be $25 for -mabicalls.
2738 // 'l' : The lo register. 1 word storage.
2739 // 'x' : The hilo register pair. Double word storage.
2740 if (Constraint.size() == 1) {
2741 switch (Constraint[0]) {
2749 return C_RegisterClass;
2754 return TargetLowering::getConstraintType(Constraint);
2757 /// Examine constraint type and operand type and determine a weight value.
2758 /// This object must already have been set up with the operand type
2759 /// and the current alternative constraint selected.
2760 TargetLowering::ConstraintWeight
2761 MipsTargetLowering::getSingleConstraintMatchWeight(
2762 AsmOperandInfo &info, const char *constraint) const {
2763 ConstraintWeight weight = CW_Invalid;
2764 Value *CallOperandVal = info.CallOperandVal;
2765 // If we don't have a value, we can't do a match,
2766 // but allow it at the lowest weight.
2767 if (CallOperandVal == NULL)
2769 Type *type = CallOperandVal->getType();
2770 // Look at the constraint type.
2771 switch (*constraint) {
2773 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2777 if (type->isIntegerTy())
2778 weight = CW_Register;
2781 if (type->isFloatTy())
2782 weight = CW_Register;
2784 case 'c': // $25 for indirect jumps
2785 case 'l': // lo register
2786 case 'x': // hilo register pair
2787 if (type->isIntegerTy())
2788 weight = CW_SpecificReg;
2790 case 'I': // signed 16 bit immediate
2791 case 'J': // integer zero
2792 case 'K': // unsigned 16 bit immediate
2793 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2794 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2795 case 'O': // signed 15 bit immediate (+- 16383)
2796 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2797 if (isa<ConstantInt>(CallOperandVal))
2798 weight = CW_Constant;
2807 /// Given a register class constraint, like 'r', if this corresponds directly
2808 /// to an LLVM register class, return a register of 0 and the register class
2810 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2811 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2813 if (Constraint.size() == 1) {
2814 switch (Constraint[0]) {
2815 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2816 case 'y': // Same as 'r'. Exists for compatibility.
2818 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2819 if (Subtarget->inMips16Mode())
2820 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2821 return std::make_pair(0U, &Mips::CPURegsRegClass);
2823 if (VT == MVT::i64 && !HasMips64)
2824 return std::make_pair(0U, &Mips::CPURegsRegClass);
2825 if (VT == MVT::i64 && HasMips64)
2826 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
2827 // This will generate an error message
2828 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2831 return std::make_pair(0U, &Mips::FGR32RegClass);
2832 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2833 if (Subtarget->isFP64bit())
2834 return std::make_pair(0U, &Mips::FGR64RegClass);
2835 return std::make_pair(0U, &Mips::AFGR64RegClass);
2838 case 'c': // register suitable for indirect jump
2840 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
2841 assert(VT == MVT::i64 && "Unexpected type.");
2842 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
2843 case 'l': // register suitable for indirect jump
2845 return std::make_pair((unsigned)Mips::LO, &Mips::LORegsRegClass);
2846 return std::make_pair((unsigned)Mips::LO64, &Mips::LORegs64RegClass);
2847 case 'x': // register suitable for indirect jump
2848 // Fixme: Not triggering the use of both hi and low
2849 // This will generate an error message
2850 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2853 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2856 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2857 /// vector. If it is invalid, don't add anything to Ops.
2858 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2859 std::string &Constraint,
2860 std::vector<SDValue>&Ops,
2861 SelectionDAG &DAG) const {
2862 SDValue Result(0, 0);
2864 // Only support length 1 constraints for now.
2865 if (Constraint.length() > 1) return;
2867 char ConstraintLetter = Constraint[0];
2868 switch (ConstraintLetter) {
2869 default: break; // This will fall through to the generic implementation
2870 case 'I': // Signed 16 bit constant
2871 // If this fails, the parent routine will give an error
2872 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2873 EVT Type = Op.getValueType();
2874 int64_t Val = C->getSExtValue();
2875 if (isInt<16>(Val)) {
2876 Result = DAG.getTargetConstant(Val, Type);
2881 case 'J': // integer zero
2882 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2883 EVT Type = Op.getValueType();
2884 int64_t Val = C->getZExtValue();
2886 Result = DAG.getTargetConstant(0, Type);
2891 case 'K': // unsigned 16 bit immediate
2892 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2893 EVT Type = Op.getValueType();
2894 uint64_t Val = (uint64_t)C->getZExtValue();
2895 if (isUInt<16>(Val)) {
2896 Result = DAG.getTargetConstant(Val, Type);
2901 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2902 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2903 EVT Type = Op.getValueType();
2904 int64_t Val = C->getSExtValue();
2905 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
2906 Result = DAG.getTargetConstant(Val, Type);
2911 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2912 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2913 EVT Type = Op.getValueType();
2914 int64_t Val = C->getSExtValue();
2915 if ((Val >= -65535) && (Val <= -1)) {
2916 Result = DAG.getTargetConstant(Val, Type);
2921 case 'O': // signed 15 bit immediate
2922 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2923 EVT Type = Op.getValueType();
2924 int64_t Val = C->getSExtValue();
2925 if ((isInt<15>(Val))) {
2926 Result = DAG.getTargetConstant(Val, Type);
2931 case 'P': // immediate in the range of 1 to 65535 (inclusive)
2932 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2933 EVT Type = Op.getValueType();
2934 int64_t Val = C->getSExtValue();
2935 if ((Val <= 65535) && (Val >= 1)) {
2936 Result = DAG.getTargetConstant(Val, Type);
2943 if (Result.getNode()) {
2944 Ops.push_back(Result);
2948 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2952 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
2953 // No global is ever allowed as a base.
2958 case 0: // "r+i" or just "i", depending on HasBaseReg.
2961 if (!AM.HasBaseReg) // allow "r+i".
2963 return false; // disallow "r+r" or "r+r+i".
2972 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2973 // The Mips target isn't yet aware of offsets.
2977 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
2979 bool IsMemset, bool ZeroMemset,
2981 MachineFunction &MF) const {
2982 if (Subtarget->hasMips64())
2988 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2989 if (VT != MVT::f32 && VT != MVT::f64)
2991 if (Imm.isNegZero())
2993 return Imm.isZero();
2996 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2998 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3000 return TargetLowering::getJumpTableEncoding();
3003 /// This function returns true if CallSym is a long double emulation routine.
3004 static bool isF128SoftLibCall(const char *CallSym) {
3005 const char *const LibCalls[] =
3006 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3007 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3008 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3009 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3010 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3011 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3012 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3013 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3016 const char * const *End = LibCalls + array_lengthof(LibCalls);
3018 // Check that LibCalls is sorted alphabetically.
3019 MipsTargetLowering::LTStr Comp;
3022 for (const char * const *I = LibCalls; I < End - 1; ++I)
3023 assert(Comp(*I, *(I + 1)));
3026 return std::binary_search(LibCalls, End, CallSym, Comp);
3029 /// This function returns true if Ty is fp128 or i128 which was originally a
3031 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3032 if (Ty->isFP128Ty())
3035 const ExternalSymbolSDNode *ES =
3036 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3038 // If the Ty is i128 and the function being called is a long double emulation
3039 // routine, then the original type is f128.
3040 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3043 MipsTargetLowering::MipsCC::SpecialCallingConvType
3044 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3045 MipsCC::SpecialCallingConvType SpecialCallingConv =
3046 MipsCC::NoSpecialCallingConv;;
3047 if (Subtarget->inMips16HardFloat()) {
3048 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3049 llvm::StringRef Sym = G->getGlobal()->getName();
3050 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3051 if (F->hasFnAttribute("__Mips16RetHelper")) {
3052 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3056 return SpecialCallingConv;
3059 MipsTargetLowering::MipsCC::MipsCC(
3060 CallingConv::ID CC, bool IsO32_, CCState &Info,
3061 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3062 : CCInfo(Info), CallConv(CC), IsO32(IsO32_),
3063 SpecialCallingConv(SpecialCallingConv_){
3064 // Pre-allocate reserved argument area.
3065 CCInfo.AllocateStack(reservedArgArea(), 1);
3069 void MipsTargetLowering::MipsCC::
3070 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3071 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3072 std::vector<ArgListEntry> &FuncArgs) {
3073 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3074 "CallingConv::Fast shouldn't be used for vararg functions.");
3076 unsigned NumOpnds = Args.size();
3077 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3079 for (unsigned I = 0; I != NumOpnds; ++I) {
3080 MVT ArgVT = Args[I].VT;
3081 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3084 if (ArgFlags.isByVal()) {
3085 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3089 if (IsVarArg && !Args[I].IsFixed)
3090 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3092 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3094 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3099 dbgs() << "Call operand #" << I << " has unhandled type "
3100 << EVT(ArgVT).getEVTString();
3102 llvm_unreachable(0);
3107 void MipsTargetLowering::MipsCC::
3108 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3109 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3110 unsigned NumArgs = Args.size();
3111 llvm::CCAssignFn *FixedFn = fixedArgFn();
3112 unsigned CurArgIdx = 0;
3114 for (unsigned I = 0; I != NumArgs; ++I) {
3115 MVT ArgVT = Args[I].VT;
3116 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3117 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3118 CurArgIdx = Args[I].OrigArgIndex;
3120 if (ArgFlags.isByVal()) {
3121 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3125 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3127 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3131 dbgs() << "Formal Arg #" << I << " has unhandled type "
3132 << EVT(ArgVT).getEVTString();
3134 llvm_unreachable(0);
3138 template<typename Ty>
3139 void MipsTargetLowering::MipsCC::
3140 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3141 const SDNode *CallNode, const Type *RetTy) const {
3144 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3145 Fn = RetCC_F128Soft;
3149 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3150 MVT VT = RetVals[I].VT;
3151 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3152 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3154 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3156 dbgs() << "Call result #" << I << " has unhandled type "
3157 << EVT(VT).getEVTString() << '\n';
3159 llvm_unreachable(0);
3164 void MipsTargetLowering::MipsCC::
3165 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3166 const SDNode *CallNode, const Type *RetTy) const {
3167 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3170 void MipsTargetLowering::MipsCC::
3171 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3172 const Type *RetTy) const {
3173 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3177 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3179 CCValAssign::LocInfo LocInfo,
3180 ISD::ArgFlagsTy ArgFlags) {
3181 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3183 struct ByValArgInfo ByVal;
3184 unsigned RegSize = regSize();
3185 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3186 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3189 if (useRegsForByval())
3190 allocateRegs(ByVal, ByValSize, Align);
3192 // Allocate space on caller's stack.
3193 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3195 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3197 ByValArgs.push_back(ByVal);
3200 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3201 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3204 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3205 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3208 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3209 return IsO32 ? O32IntRegs : Mips64IntRegs;
3212 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3213 if (CallConv == CallingConv::Fast)
3214 return CC_Mips_FastCC;
3216 if (SpecialCallingConv == Mips16RetHelperConv)
3217 return CC_Mips16RetHelper;
3218 return IsO32 ? CC_MipsO32 : CC_MipsN;
3221 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3222 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
3225 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3226 return IsO32 ? O32IntRegs : Mips64DPRegs;
3229 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3232 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3233 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3234 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3235 "Byval argument's size and alignment should be a multiple of"
3238 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3240 // If Align > RegSize, the first arg register must be even.
3241 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3242 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3246 // Mark the registers allocated.
3247 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3248 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3249 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3252 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3253 const SDNode *CallNode,
3254 bool IsSoftFloat) const {
3255 if (IsSoftFloat || IsO32)
3258 // Check if the original type was fp128.
3259 if (originalTypeIsF128(OrigTy, CallNode)) {
3260 assert(VT == MVT::i64);
3267 void MipsTargetLowering::
3268 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3269 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3270 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3271 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3272 MachineFunction &MF = DAG.getMachineFunction();
3273 MachineFrameInfo *MFI = MF.getFrameInfo();
3274 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3275 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3279 FrameObjOffset = (int)CC.reservedArgArea() -
3280 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3282 FrameObjOffset = ByVal.Address;
3284 // Create frame object.
3285 EVT PtrTy = getPointerTy();
3286 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3287 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3288 InVals.push_back(FIN);
3293 // Copy arg registers.
3294 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3295 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3297 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3298 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3299 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3300 unsigned Offset = I * CC.regSize();
3301 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3302 DAG.getConstant(Offset, PtrTy));
3303 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3304 StorePtr, MachinePointerInfo(FuncArg, Offset),
3306 OutChains.push_back(Store);
3310 // Copy byVal arg to registers and stack.
3311 void MipsTargetLowering::
3312 passByValArg(SDValue Chain, DebugLoc DL,
3313 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3314 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3315 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3316 const MipsCC &CC, const ByValArgInfo &ByVal,
3317 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3318 unsigned ByValSize = Flags.getByValSize();
3319 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3320 unsigned RegSize = CC.regSize();
3321 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3322 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3324 if (ByVal.NumRegs) {
3325 const uint16_t *ArgRegs = CC.intArgRegs();
3326 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3329 // Copy words to registers.
3330 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3331 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3332 DAG.getConstant(Offset, PtrTy));
3333 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3334 MachinePointerInfo(), false, false, false,
3336 MemOpChains.push_back(LoadVal.getValue(1));
3337 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3338 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3341 // Return if the struct has been fully copied.
3342 if (ByValSize == Offset)
3345 // Copy the remainder of the byval argument with sub-word loads and shifts.
3346 if (LeftoverBytes) {
3347 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3348 "Size of the remainder should be smaller than RegSize.");
3351 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3352 Offset < ByValSize; LoadSize /= 2) {
3353 unsigned RemSize = ByValSize - Offset;
3355 if (RemSize < LoadSize)
3359 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3360 DAG.getConstant(Offset, PtrTy));
3362 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3363 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3364 false, false, Alignment);
3365 MemOpChains.push_back(LoadVal.getValue(1));
3367 // Shift the loaded value.
3371 Shamt = TotalSizeLoaded;
3373 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3375 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3376 DAG.getConstant(Shamt, MVT::i32));
3379 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3384 TotalSizeLoaded += LoadSize;
3385 Alignment = std::min(Alignment, LoadSize);
3388 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3389 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3394 // Copy remainder of byval arg to it with memcpy.
3395 unsigned MemCpySize = ByValSize - Offset;
3396 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3397 DAG.getConstant(Offset, PtrTy));
3398 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3399 DAG.getIntPtrConstant(ByVal.Address));
3400 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3401 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3402 /*isVolatile=*/false, /*AlwaysInline=*/false,
3403 MachinePointerInfo(0), MachinePointerInfo(0));
3404 MemOpChains.push_back(Chain);
3408 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3409 const MipsCC &CC, SDValue Chain,
3410 DebugLoc DL, SelectionDAG &DAG) const {
3411 unsigned NumRegs = CC.numIntArgRegs();
3412 const uint16_t *ArgRegs = CC.intArgRegs();
3413 const CCState &CCInfo = CC.getCCInfo();
3414 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3415 unsigned RegSize = CC.regSize();
3416 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3417 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3418 MachineFunction &MF = DAG.getMachineFunction();
3419 MachineFrameInfo *MFI = MF.getFrameInfo();
3420 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3422 // Offset of the first variable argument from stack pointer.
3426 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3429 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3431 // Record the frame index of the first variable argument
3432 // which is a value necessary to VASTART.
3433 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3434 MipsFI->setVarArgsFrameIndex(FI);
3436 // Copy the integer registers that have not been used for argument passing
3437 // to the argument register save area. For O32, the save area is allocated
3438 // in the caller's stack frame, while for N32/64, it is allocated in the
3439 // callee's stack frame.
3440 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3441 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3442 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3443 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3444 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3445 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3446 MachinePointerInfo(), false, false, 0);
3447 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3448 OutChains.push_back(Store);