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"
16 #include "MipsISelLowering.h"
17 #include "InstPrinter/MipsInstPrinter.h"
18 #include "MCTargetDesc/MipsBaseInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetMachine.h"
22 #include "MipsTargetObjectFile.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
43 STATISTIC(NumTailCalls, "Number of tail calls");
46 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
47 cl::desc("MIPS: Enable tail calls."), cl::init(false));
50 LargeGOT("mxgot", cl::Hidden,
51 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
54 Mips16HardFloat("mips16-hard-float", cl::NotHidden,
55 cl::desc("MIPS: mips16 hard float enable."),
60 static const uint16_t O32IntRegs[4] = {
61 Mips::A0, Mips::A1, Mips::A2, Mips::A3
64 static const uint16_t Mips64IntRegs[8] = {
65 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
66 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
69 static const uint16_t Mips64DPRegs[8] = {
70 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
71 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
74 // If I is a shifted mask, set the size (Size) and the first bit of the
75 // mask (Pos), and return true.
76 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
77 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
78 if (!isShiftedMask_64(I))
81 Size = CountPopulation_64(I);
82 Pos = CountTrailingZeros_64(I);
86 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
87 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
88 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
91 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
92 EVT Ty = Op.getValueType();
94 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
95 return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
97 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
98 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
99 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
100 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
102 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
103 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
104 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
105 N->getOffset(), Flag);
107 llvm_unreachable("Unexpected node type.");
111 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
112 DebugLoc DL = Op.getDebugLoc();
113 EVT Ty = Op.getValueType();
114 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
115 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
116 return DAG.getNode(ISD::ADD, DL, Ty,
117 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
118 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
121 static SDValue getAddrLocal(SDValue Op, SelectionDAG &DAG, bool HasMips64) {
122 DebugLoc DL = Op.getDebugLoc();
123 EVT Ty = Op.getValueType();
124 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
125 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
126 getTargetNode(Op, DAG, GOTFlag));
127 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
128 MachinePointerInfo::getGOT(), false, false, false,
130 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
131 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
132 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
135 static SDValue getAddrGlobal(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
136 DebugLoc DL = Op.getDebugLoc();
137 EVT Ty = Op.getValueType();
138 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
139 getTargetNode(Op, DAG, Flag));
140 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
141 MachinePointerInfo::getGOT(), false, false, false, 0);
144 static SDValue getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
145 unsigned HiFlag, unsigned LoFlag) {
146 DebugLoc DL = Op.getDebugLoc();
147 EVT Ty = Op.getValueType();
148 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
149 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, GetGlobalReg(DAG, Ty));
150 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
151 getTargetNode(Op, DAG, LoFlag));
152 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
153 MachinePointerInfo::getGOT(), false, false, false, 0);
156 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
158 case MipsISD::JmpLink: return "MipsISD::JmpLink";
159 case MipsISD::TailCall: return "MipsISD::TailCall";
160 case MipsISD::Hi: return "MipsISD::Hi";
161 case MipsISD::Lo: return "MipsISD::Lo";
162 case MipsISD::GPRel: return "MipsISD::GPRel";
163 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
164 case MipsISD::Ret: return "MipsISD::Ret";
165 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
166 case MipsISD::FPCmp: return "MipsISD::FPCmp";
167 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
168 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
169 case MipsISD::FPRound: return "MipsISD::FPRound";
170 case MipsISD::MAdd: return "MipsISD::MAdd";
171 case MipsISD::MAddu: return "MipsISD::MAddu";
172 case MipsISD::MSub: return "MipsISD::MSub";
173 case MipsISD::MSubu: return "MipsISD::MSubu";
174 case MipsISD::DivRem: return "MipsISD::DivRem";
175 case MipsISD::DivRemU: return "MipsISD::DivRemU";
176 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
177 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
178 case MipsISD::Wrapper: return "MipsISD::Wrapper";
179 case MipsISD::Sync: return "MipsISD::Sync";
180 case MipsISD::Ext: return "MipsISD::Ext";
181 case MipsISD::Ins: return "MipsISD::Ins";
182 case MipsISD::LWL: return "MipsISD::LWL";
183 case MipsISD::LWR: return "MipsISD::LWR";
184 case MipsISD::SWL: return "MipsISD::SWL";
185 case MipsISD::SWR: return "MipsISD::SWR";
186 case MipsISD::LDL: return "MipsISD::LDL";
187 case MipsISD::LDR: return "MipsISD::LDR";
188 case MipsISD::SDL: return "MipsISD::SDL";
189 case MipsISD::SDR: return "MipsISD::SDR";
190 case MipsISD::EXTP: return "MipsISD::EXTP";
191 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
192 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
193 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
194 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
195 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
196 case MipsISD::SHILO: return "MipsISD::SHILO";
197 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
198 case MipsISD::MULT: return "MipsISD::MULT";
199 case MipsISD::MULTU: return "MipsISD::MULTU";
200 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSPDSP";
201 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
202 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
203 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
204 default: return NULL;
210 bool operator()(const char *s1, const char *s2) const
212 return strcmp(s1, s2) < 0;
216 std::set<const char*, ltstr> noHelperNeeded;
218 const char* addToNoHelperNeeded(const char* s) {
219 noHelperNeeded.insert(s);
225 void MipsTargetLowering::SetMips16LibcallName
226 (RTLIB::Libcall l, const char *Name) {
227 setLibcallName(l, Name);
228 noHelperNeeded.insert(Name);
231 void MipsTargetLowering::setMips16HardFloatLibCalls() {
232 SetMips16LibcallName(RTLIB::ADD_F32, "__mips16_addsf3");
233 SetMips16LibcallName(RTLIB::ADD_F64, "__mips16_adddf3");
234 SetMips16LibcallName(RTLIB::SUB_F32, "__mips16_subsf3");
235 SetMips16LibcallName(RTLIB::SUB_F64, "__mips16_subdf3");
236 SetMips16LibcallName(RTLIB::MUL_F32, "__mips16_mulsf3");
237 SetMips16LibcallName(RTLIB::MUL_F64, "__mips16_muldf3");
238 SetMips16LibcallName(RTLIB::DIV_F32, "__mips16_divsf3");
239 SetMips16LibcallName(RTLIB::DIV_F64, "__mips16_divdf3");
240 SetMips16LibcallName(RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2");
241 SetMips16LibcallName(RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2");
242 SetMips16LibcallName(RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi");
243 SetMips16LibcallName(RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi");
244 SetMips16LibcallName(RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf");
245 SetMips16LibcallName(RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf");
246 SetMips16LibcallName(RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf");
247 SetMips16LibcallName(RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf");
248 SetMips16LibcallName(RTLIB::OEQ_F32, "__mips16_eqsf2");
249 SetMips16LibcallName(RTLIB::OEQ_F64, "__mips16_eqdf2");
250 SetMips16LibcallName(RTLIB::UNE_F32, "__mips16_nesf2");
251 SetMips16LibcallName(RTLIB::UNE_F64, "__mips16_nedf2");
252 SetMips16LibcallName(RTLIB::OGE_F32, "__mips16_gesf2");
253 SetMips16LibcallName(RTLIB::OGE_F64, "__mips16_gedf2");
254 SetMips16LibcallName(RTLIB::OLT_F32, "__mips16_ltsf2");
255 SetMips16LibcallName(RTLIB::OLT_F64, "__mips16_ltdf2");
256 SetMips16LibcallName(RTLIB::OLE_F32, "__mips16_lesf2");
257 SetMips16LibcallName(RTLIB::OLE_F64, "__mips16_ledf2");
258 SetMips16LibcallName(RTLIB::OGT_F32, "__mips16_gtsf2");
259 SetMips16LibcallName(RTLIB::OGT_F64, "__mips16_gtdf2");
260 SetMips16LibcallName(RTLIB::UO_F32, "__mips16_unordsf2");
261 SetMips16LibcallName(RTLIB::UO_F64, "__mips16_unorddf2");
262 SetMips16LibcallName(RTLIB::O_F32, "__mips16_unordsf2");
263 SetMips16LibcallName(RTLIB::O_F64, "__mips16_unorddf2");
267 MipsTargetLowering(MipsTargetMachine &TM)
268 : TargetLowering(TM, new MipsTargetObjectFile()),
269 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
270 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
271 IsO32(Subtarget->isABI_O32()) {
273 // Mips does not have i1 type, so use i32 for
274 // setcc operations results (slt, sgt, ...).
275 setBooleanContents(ZeroOrOneBooleanContent);
276 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
278 // Set up the register classes
279 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
282 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
284 if (Subtarget->inMips16Mode()) {
285 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
287 setMips16HardFloatLibCalls();
290 if (Subtarget->hasDSP()) {
291 MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
293 for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
294 addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
296 // Expand all builtin opcodes.
297 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
298 setOperationAction(Opc, VecTys[i], Expand);
300 setOperationAction(ISD::LOAD, VecTys[i], Legal);
301 setOperationAction(ISD::STORE, VecTys[i], Legal);
302 setOperationAction(ISD::BITCAST, VecTys[i], Legal);
306 if (!TM.Options.UseSoftFloat) {
307 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
309 // When dealing with single precision only, use libcalls
310 if (!Subtarget->isSingleFloat()) {
312 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
314 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
318 // Load extented operations for i1 types must be promoted
319 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
320 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
321 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
323 // MIPS doesn't have extending float->double load/store
324 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
325 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
327 // Used by legalize types to correctly generate the setcc result.
328 // Without this, every float setcc comes with a AND/OR with the result,
329 // we don't want this, since the fpcmp result goes to a flag register,
330 // which is used implicitly by brcond and select operations.
331 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
333 // Mips Custom Operations
334 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
335 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
336 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
337 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
338 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
339 setOperationAction(ISD::SELECT, MVT::f32, Custom);
340 setOperationAction(ISD::SELECT, MVT::f64, Custom);
341 setOperationAction(ISD::SELECT, MVT::i32, Custom);
342 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
343 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
344 setOperationAction(ISD::SETCC, MVT::f32, Custom);
345 setOperationAction(ISD::SETCC, MVT::f64, Custom);
346 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
347 setOperationAction(ISD::VASTART, MVT::Other, Custom);
348 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
349 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
350 if (Subtarget->inMips16Mode()) {
351 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
352 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
355 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
356 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
358 if (!Subtarget->inMips16Mode()) {
359 setOperationAction(ISD::LOAD, MVT::i32, Custom);
360 setOperationAction(ISD::STORE, MVT::i32, Custom);
363 if (!TM.Options.NoNaNsFPMath) {
364 setOperationAction(ISD::FABS, MVT::f32, Custom);
365 setOperationAction(ISD::FABS, MVT::f64, Custom);
369 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
370 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
371 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
372 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
373 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
374 setOperationAction(ISD::SELECT, MVT::i64, Custom);
375 setOperationAction(ISD::LOAD, MVT::i64, Custom);
376 setOperationAction(ISD::STORE, MVT::i64, Custom);
380 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
381 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
382 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
385 setOperationAction(ISD::ADD, MVT::i32, Custom);
387 setOperationAction(ISD::ADD, MVT::i64, Custom);
389 setOperationAction(ISD::SDIV, MVT::i32, Expand);
390 setOperationAction(ISD::SREM, MVT::i32, Expand);
391 setOperationAction(ISD::UDIV, MVT::i32, Expand);
392 setOperationAction(ISD::UREM, MVT::i32, Expand);
393 setOperationAction(ISD::SDIV, MVT::i64, Expand);
394 setOperationAction(ISD::SREM, MVT::i64, Expand);
395 setOperationAction(ISD::UDIV, MVT::i64, Expand);
396 setOperationAction(ISD::UREM, MVT::i64, Expand);
398 // Operations not directly supported by Mips.
399 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
400 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
401 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
402 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
403 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
404 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
405 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
406 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
407 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
408 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
409 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
410 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
411 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
412 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
413 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::ROTL, MVT::i32, Expand);
416 setOperationAction(ISD::ROTL, MVT::i64, Expand);
417 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
420 if (!Subtarget->hasMips32r2())
421 setOperationAction(ISD::ROTR, MVT::i32, Expand);
423 if (!Subtarget->hasMips64r2())
424 setOperationAction(ISD::ROTR, MVT::i64, Expand);
426 setOperationAction(ISD::FSIN, MVT::f32, Expand);
427 setOperationAction(ISD::FSIN, MVT::f64, Expand);
428 setOperationAction(ISD::FCOS, MVT::f32, Expand);
429 setOperationAction(ISD::FCOS, MVT::f64, Expand);
430 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
431 setOperationAction(ISD::FPOW, MVT::f32, Expand);
432 setOperationAction(ISD::FPOW, MVT::f64, Expand);
433 setOperationAction(ISD::FLOG, MVT::f32, Expand);
434 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
435 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
436 setOperationAction(ISD::FEXP, MVT::f32, Expand);
437 setOperationAction(ISD::FMA, MVT::f32, Expand);
438 setOperationAction(ISD::FMA, MVT::f64, Expand);
439 setOperationAction(ISD::FREM, MVT::f32, Expand);
440 setOperationAction(ISD::FREM, MVT::f64, Expand);
442 if (!TM.Options.NoNaNsFPMath) {
443 setOperationAction(ISD::FNEG, MVT::f32, Expand);
444 setOperationAction(ISD::FNEG, MVT::f64, Expand);
447 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
448 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
449 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
450 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
452 setOperationAction(ISD::VAARG, MVT::Other, Expand);
453 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
454 setOperationAction(ISD::VAEND, MVT::Other, Expand);
456 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
457 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
459 // Use the default for now
460 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
461 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
463 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
464 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
465 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
466 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
468 if (Subtarget->inMips16Mode()) {
469 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
470 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
471 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
472 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
473 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
474 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
475 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
476 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
477 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
478 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
479 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
480 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
483 setInsertFencesForAtomic(true);
485 if (!Subtarget->hasSEInReg()) {
486 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
487 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
490 if (!Subtarget->hasBitCount()) {
491 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
492 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
495 if (!Subtarget->hasSwap()) {
496 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
497 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
501 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
502 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
503 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
504 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
507 setTargetDAGCombine(ISD::ADDE);
508 setTargetDAGCombine(ISD::SUBE);
509 setTargetDAGCombine(ISD::SDIVREM);
510 setTargetDAGCombine(ISD::UDIVREM);
511 setTargetDAGCombine(ISD::SELECT);
512 setTargetDAGCombine(ISD::AND);
513 setTargetDAGCombine(ISD::OR);
514 setTargetDAGCombine(ISD::ADD);
516 setMinFunctionAlignment(HasMips64 ? 3 : 2);
518 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
519 computeRegisterProperties();
521 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
522 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
524 maxStoresPerMemcpy = 16;
528 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
529 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
531 if (Subtarget->inMips16Mode())
545 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
548 return VT.changeVectorElementTypeToInteger();
552 // Transforms a subgraph in CurDAG if the following pattern is found:
553 // (addc multLo, Lo0), (adde multHi, Hi0),
555 // multHi/Lo: product of multiplication
556 // Lo0: initial value of Lo register
557 // Hi0: initial value of Hi register
558 // Return true if pattern matching was successful.
559 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
560 // ADDENode's second operand must be a flag output of an ADDC node in order
561 // for the matching to be successful.
562 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
564 if (ADDCNode->getOpcode() != ISD::ADDC)
567 SDValue MultHi = ADDENode->getOperand(0);
568 SDValue MultLo = ADDCNode->getOperand(0);
569 SDNode *MultNode = MultHi.getNode();
570 unsigned MultOpc = MultHi.getOpcode();
572 // MultHi and MultLo must be generated by the same node,
573 if (MultLo.getNode() != MultNode)
576 // and it must be a multiplication.
577 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
580 // MultLo amd MultHi must be the first and second output of MultNode
582 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
585 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
586 // of the values of MultNode, in which case MultNode will be removed in later
588 // If there exist users other than ADDENode or ADDCNode, this function returns
589 // here, which will result in MultNode being mapped to a single MULT
590 // instruction node rather than a pair of MULT and MADD instructions being
592 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
595 SDValue Chain = CurDAG->getEntryNode();
596 DebugLoc dl = ADDENode->getDebugLoc();
598 // create MipsMAdd(u) node
599 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
601 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
602 MultNode->getOperand(0),// Factor 0
603 MultNode->getOperand(1),// Factor 1
604 ADDCNode->getOperand(1),// Lo0
605 ADDENode->getOperand(1));// Hi0
607 // create CopyFromReg nodes
608 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
610 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
612 CopyFromLo.getValue(2));
614 // replace uses of adde and addc here
615 if (!SDValue(ADDCNode, 0).use_empty())
616 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
618 if (!SDValue(ADDENode, 0).use_empty())
619 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
625 // Transforms a subgraph in CurDAG if the following pattern is found:
626 // (addc Lo0, multLo), (sube Hi0, multHi),
628 // multHi/Lo: product of multiplication
629 // Lo0: initial value of Lo register
630 // Hi0: initial value of Hi register
631 // Return true if pattern matching was successful.
632 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
633 // SUBENode's second operand must be a flag output of an SUBC node in order
634 // for the matching to be successful.
635 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
637 if (SUBCNode->getOpcode() != ISD::SUBC)
640 SDValue MultHi = SUBENode->getOperand(1);
641 SDValue MultLo = SUBCNode->getOperand(1);
642 SDNode *MultNode = MultHi.getNode();
643 unsigned MultOpc = MultHi.getOpcode();
645 // MultHi and MultLo must be generated by the same node,
646 if (MultLo.getNode() != MultNode)
649 // and it must be a multiplication.
650 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
653 // MultLo amd MultHi must be the first and second output of MultNode
655 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
658 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
659 // of the values of MultNode, in which case MultNode will be removed in later
661 // If there exist users other than SUBENode or SUBCNode, this function returns
662 // here, which will result in MultNode being mapped to a single MULT
663 // instruction node rather than a pair of MULT and MSUB instructions being
665 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
668 SDValue Chain = CurDAG->getEntryNode();
669 DebugLoc dl = SUBENode->getDebugLoc();
671 // create MipsSub(u) node
672 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
674 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
675 MultNode->getOperand(0),// Factor 0
676 MultNode->getOperand(1),// Factor 1
677 SUBCNode->getOperand(0),// Lo0
678 SUBENode->getOperand(0));// Hi0
680 // create CopyFromReg nodes
681 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
683 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
685 CopyFromLo.getValue(2));
687 // replace uses of sube and subc here
688 if (!SDValue(SUBCNode, 0).use_empty())
689 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
691 if (!SDValue(SUBENode, 0).use_empty())
692 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
697 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
698 TargetLowering::DAGCombinerInfo &DCI,
699 const MipsSubtarget *Subtarget) {
700 if (DCI.isBeforeLegalize())
703 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
705 return SDValue(N, 0);
710 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
711 TargetLowering::DAGCombinerInfo &DCI,
712 const MipsSubtarget *Subtarget) {
713 if (DCI.isBeforeLegalize())
716 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
718 return SDValue(N, 0);
723 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
724 TargetLowering::DAGCombinerInfo &DCI,
725 const MipsSubtarget *Subtarget) {
726 if (DCI.isBeforeLegalizeOps())
729 EVT Ty = N->getValueType(0);
730 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
731 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
732 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
734 DebugLoc dl = N->getDebugLoc();
736 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
737 N->getOperand(0), N->getOperand(1));
738 SDValue InChain = DAG.getEntryNode();
739 SDValue InGlue = DivRem;
742 if (N->hasAnyUseOfValue(0)) {
743 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
745 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
746 InChain = CopyFromLo.getValue(1);
747 InGlue = CopyFromLo.getValue(2);
751 if (N->hasAnyUseOfValue(1)) {
752 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
754 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
760 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
762 default: llvm_unreachable("Unknown fp condition code!");
764 case ISD::SETOEQ: return Mips::FCOND_OEQ;
765 case ISD::SETUNE: return Mips::FCOND_UNE;
767 case ISD::SETOLT: return Mips::FCOND_OLT;
769 case ISD::SETOGT: return Mips::FCOND_OGT;
771 case ISD::SETOLE: return Mips::FCOND_OLE;
773 case ISD::SETOGE: return Mips::FCOND_OGE;
774 case ISD::SETULT: return Mips::FCOND_ULT;
775 case ISD::SETULE: return Mips::FCOND_ULE;
776 case ISD::SETUGT: return Mips::FCOND_UGT;
777 case ISD::SETUGE: return Mips::FCOND_UGE;
778 case ISD::SETUO: return Mips::FCOND_UN;
779 case ISD::SETO: return Mips::FCOND_OR;
781 case ISD::SETONE: return Mips::FCOND_ONE;
782 case ISD::SETUEQ: return Mips::FCOND_UEQ;
787 // Returns true if condition code has to be inverted.
788 static bool InvertFPCondCode(Mips::CondCode CC) {
789 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
792 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
793 "Illegal Condition Code");
798 // Creates and returns an FPCmp node from a setcc node.
799 // Returns Op if setcc is not a floating point comparison.
800 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
801 // must be a SETCC node
802 if (Op.getOpcode() != ISD::SETCC)
805 SDValue LHS = Op.getOperand(0);
807 if (!LHS.getValueType().isFloatingPoint())
810 SDValue RHS = Op.getOperand(1);
811 DebugLoc dl = Op.getDebugLoc();
813 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
814 // node if necessary.
815 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
817 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
818 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
821 // Creates and returns a CMovFPT/F node.
822 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
823 SDValue False, DebugLoc DL) {
824 bool invert = InvertFPCondCode((Mips::CondCode)
825 cast<ConstantSDNode>(Cond.getOperand(2))
828 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
829 True.getValueType(), True, False, Cond);
832 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
833 TargetLowering::DAGCombinerInfo &DCI,
834 const MipsSubtarget *Subtarget) {
835 if (DCI.isBeforeLegalizeOps())
838 SDValue SetCC = N->getOperand(0);
840 if ((SetCC.getOpcode() != ISD::SETCC) ||
841 !SetCC.getOperand(0).getValueType().isInteger())
844 SDValue False = N->getOperand(2);
845 EVT FalseTy = False.getValueType();
847 if (!FalseTy.isInteger())
850 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
852 if (!CN || CN->getZExtValue())
855 const DebugLoc DL = N->getDebugLoc();
856 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
857 SDValue True = N->getOperand(1);
859 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
860 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
862 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
865 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
866 TargetLowering::DAGCombinerInfo &DCI,
867 const MipsSubtarget *Subtarget) {
868 // Pattern match EXT.
869 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
870 // => ext $dst, $src, size, pos
871 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
874 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
875 unsigned ShiftRightOpc = ShiftRight.getOpcode();
877 // Op's first operand must be a shift right.
878 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
881 // The second operand of the shift must be an immediate.
883 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
886 uint64_t Pos = CN->getZExtValue();
887 uint64_t SMPos, SMSize;
889 // Op's second operand must be a shifted mask.
890 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
891 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
894 // Return if the shifted mask does not start at bit 0 or the sum of its size
895 // and Pos exceeds the word's size.
896 EVT ValTy = N->getValueType(0);
897 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
900 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
901 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
902 DAG.getConstant(SMSize, MVT::i32));
905 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
906 TargetLowering::DAGCombinerInfo &DCI,
907 const MipsSubtarget *Subtarget) {
908 // Pattern match INS.
909 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
910 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
911 // => ins $dst, $src, size, pos, $src1
912 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
915 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
916 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
919 // See if Op's first operand matches (and $src1 , mask0).
920 if (And0.getOpcode() != ISD::AND)
923 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
924 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
927 // See if Op's second operand matches (and (shl $src, pos), mask1).
928 if (And1.getOpcode() != ISD::AND)
931 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
932 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
935 // The shift masks must have the same position and size.
936 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
939 SDValue Shl = And1.getOperand(0);
940 if (Shl.getOpcode() != ISD::SHL)
943 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
946 unsigned Shamt = CN->getZExtValue();
948 // Return if the shift amount and the first bit position of mask are not the
950 EVT ValTy = N->getValueType(0);
951 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
954 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
955 DAG.getConstant(SMPos0, MVT::i32),
956 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
959 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
960 TargetLowering::DAGCombinerInfo &DCI,
961 const MipsSubtarget *Subtarget) {
962 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
964 if (DCI.isBeforeLegalizeOps())
967 SDValue Add = N->getOperand(1);
969 if (Add.getOpcode() != ISD::ADD)
972 SDValue Lo = Add.getOperand(1);
974 if ((Lo.getOpcode() != MipsISD::Lo) ||
975 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
978 EVT ValTy = N->getValueType(0);
979 DebugLoc DL = N->getDebugLoc();
981 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
983 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
986 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
988 SelectionDAG &DAG = DCI.DAG;
989 unsigned opc = N->getOpcode();
994 return PerformADDECombine(N, DAG, DCI, Subtarget);
996 return PerformSUBECombine(N, DAG, DCI, Subtarget);
999 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
1001 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
1003 return PerformANDCombine(N, DAG, DCI, Subtarget);
1005 return PerformORCombine(N, DAG, DCI, Subtarget);
1007 return PerformADDCombine(N, DAG, DCI, Subtarget);
1014 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1015 SmallVectorImpl<SDValue> &Results,
1016 SelectionDAG &DAG) const {
1017 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1019 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1020 Results.push_back(Res.getValue(I));
1024 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1025 SmallVectorImpl<SDValue> &Results,
1026 SelectionDAG &DAG) const {
1027 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1029 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1030 Results.push_back(Res.getValue(I));
1033 SDValue MipsTargetLowering::
1034 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1036 switch (Op.getOpcode())
1038 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1039 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
1040 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
1041 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
1042 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
1043 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
1044 case ISD::SELECT: return LowerSELECT(Op, DAG);
1045 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
1046 case ISD::SETCC: return LowerSETCC(Op, DAG);
1047 case ISD::VASTART: return LowerVASTART(Op, DAG);
1048 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
1049 case ISD::FABS: return LowerFABS(Op, DAG);
1050 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
1051 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
1052 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
1053 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
1054 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
1055 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
1056 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
1057 case ISD::LOAD: return LowerLOAD(Op, DAG);
1058 case ISD::STORE: return LowerSTORE(Op, DAG);
1059 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1060 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1061 case ISD::ADD: return LowerADD(Op, DAG);
1066 //===----------------------------------------------------------------------===//
1067 // Lower helper functions
1068 //===----------------------------------------------------------------------===//
1070 // AddLiveIn - This helper function adds the specified physical register to the
1071 // MachineFunction as a live in value. It also creates a corresponding
1072 // virtual register for it.
1074 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1076 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1077 MF.getRegInfo().addLiveIn(PReg, VReg);
1081 // Get fp branch code (not opcode) from condition code.
1082 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1083 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1084 return Mips::BRANCH_T;
1086 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1087 "Invalid CondCode.");
1089 return Mips::BRANCH_F;
1093 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1095 const MipsSubtarget *Subtarget,
1096 const TargetInstrInfo *TII,
1097 bool isFPCmp, unsigned Opc) {
1098 // There is no need to expand CMov instructions if target has
1099 // conditional moves.
1100 if (Subtarget->hasCondMov())
1103 // To "insert" a SELECT_CC instruction, we actually have to insert the
1104 // diamond control-flow pattern. The incoming instruction knows the
1105 // destination vreg to set, the condition code register to branch on, the
1106 // true/false values to select between, and a branch opcode to use.
1107 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1108 MachineFunction::iterator It = BB;
1115 // bNE r1, r0, copy1MBB
1116 // fallthrough --> copy0MBB
1117 MachineBasicBlock *thisMBB = BB;
1118 MachineFunction *F = BB->getParent();
1119 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1120 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1121 F->insert(It, copy0MBB);
1122 F->insert(It, sinkMBB);
1124 // Transfer the remainder of BB and its successor edges to sinkMBB.
1125 sinkMBB->splice(sinkMBB->begin(), BB,
1126 llvm::next(MachineBasicBlock::iterator(MI)),
1128 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1130 // Next, add the true and fallthrough blocks as its successors.
1131 BB->addSuccessor(copy0MBB);
1132 BB->addSuccessor(sinkMBB);
1134 // Emit the right instruction according to the type of the operands compared
1136 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1138 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1139 .addReg(Mips::ZERO).addMBB(sinkMBB);
1142 // %FalseValue = ...
1143 // # fallthrough to sinkMBB
1146 // Update machine-CFG edges
1147 BB->addSuccessor(sinkMBB);
1150 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1155 BuildMI(*BB, BB->begin(), dl,
1156 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1157 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1158 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1160 BuildMI(*BB, BB->begin(), dl,
1161 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1162 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1163 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1165 MI->eraseFromParent(); // The pseudo instruction is gone now.
1171 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1173 // bposge32_pseudo $vr0
1183 // $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1185 MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1186 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1187 const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1188 DebugLoc DL = MI->getDebugLoc();
1189 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1190 MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1191 MachineFunction *F = BB->getParent();
1192 MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1193 MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1194 MachineBasicBlock *Sink = F->CreateMachineBasicBlock(LLVM_BB);
1197 F->insert(It, Sink);
1199 // Transfer the remainder of BB and its successor edges to Sink.
1200 Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1202 Sink->transferSuccessorsAndUpdatePHIs(BB);
1205 BB->addSuccessor(FBB);
1206 BB->addSuccessor(TBB);
1207 FBB->addSuccessor(Sink);
1208 TBB->addSuccessor(Sink);
1210 // Insert the real bposge32 instruction to $BB.
1211 BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1214 unsigned VR2 = RegInfo.createVirtualRegister(RC);
1215 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1216 .addReg(Mips::ZERO).addImm(0);
1217 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1220 unsigned VR1 = RegInfo.createVirtualRegister(RC);
1221 BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1222 .addReg(Mips::ZERO).addImm(1);
1224 // Insert phi function to $Sink.
1225 BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1226 MI->getOperand(0).getReg())
1227 .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1229 MI->eraseFromParent(); // The pseudo instruction is gone now.
1234 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1235 MachineBasicBlock *BB) const {
1236 switch (MI->getOpcode()) {
1237 default: llvm_unreachable("Unexpected instr type to insert");
1238 case Mips::ATOMIC_LOAD_ADD_I8:
1239 case Mips::ATOMIC_LOAD_ADD_I8_P8:
1240 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1241 case Mips::ATOMIC_LOAD_ADD_I16:
1242 case Mips::ATOMIC_LOAD_ADD_I16_P8:
1243 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1244 case Mips::ATOMIC_LOAD_ADD_I32:
1245 case Mips::ATOMIC_LOAD_ADD_I32_P8:
1246 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1247 case Mips::ATOMIC_LOAD_ADD_I64:
1248 case Mips::ATOMIC_LOAD_ADD_I64_P8:
1249 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1251 case Mips::ATOMIC_LOAD_AND_I8:
1252 case Mips::ATOMIC_LOAD_AND_I8_P8:
1253 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1254 case Mips::ATOMIC_LOAD_AND_I16:
1255 case Mips::ATOMIC_LOAD_AND_I16_P8:
1256 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1257 case Mips::ATOMIC_LOAD_AND_I32:
1258 case Mips::ATOMIC_LOAD_AND_I32_P8:
1259 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1260 case Mips::ATOMIC_LOAD_AND_I64:
1261 case Mips::ATOMIC_LOAD_AND_I64_P8:
1262 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1264 case Mips::ATOMIC_LOAD_OR_I8:
1265 case Mips::ATOMIC_LOAD_OR_I8_P8:
1266 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1267 case Mips::ATOMIC_LOAD_OR_I16:
1268 case Mips::ATOMIC_LOAD_OR_I16_P8:
1269 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1270 case Mips::ATOMIC_LOAD_OR_I32:
1271 case Mips::ATOMIC_LOAD_OR_I32_P8:
1272 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1273 case Mips::ATOMIC_LOAD_OR_I64:
1274 case Mips::ATOMIC_LOAD_OR_I64_P8:
1275 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1277 case Mips::ATOMIC_LOAD_XOR_I8:
1278 case Mips::ATOMIC_LOAD_XOR_I8_P8:
1279 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1280 case Mips::ATOMIC_LOAD_XOR_I16:
1281 case Mips::ATOMIC_LOAD_XOR_I16_P8:
1282 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1283 case Mips::ATOMIC_LOAD_XOR_I32:
1284 case Mips::ATOMIC_LOAD_XOR_I32_P8:
1285 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1286 case Mips::ATOMIC_LOAD_XOR_I64:
1287 case Mips::ATOMIC_LOAD_XOR_I64_P8:
1288 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1290 case Mips::ATOMIC_LOAD_NAND_I8:
1291 case Mips::ATOMIC_LOAD_NAND_I8_P8:
1292 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1293 case Mips::ATOMIC_LOAD_NAND_I16:
1294 case Mips::ATOMIC_LOAD_NAND_I16_P8:
1295 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1296 case Mips::ATOMIC_LOAD_NAND_I32:
1297 case Mips::ATOMIC_LOAD_NAND_I32_P8:
1298 return EmitAtomicBinary(MI, BB, 4, 0, true);
1299 case Mips::ATOMIC_LOAD_NAND_I64:
1300 case Mips::ATOMIC_LOAD_NAND_I64_P8:
1301 return EmitAtomicBinary(MI, BB, 8, 0, true);
1303 case Mips::ATOMIC_LOAD_SUB_I8:
1304 case Mips::ATOMIC_LOAD_SUB_I8_P8:
1305 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1306 case Mips::ATOMIC_LOAD_SUB_I16:
1307 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1308 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1309 case Mips::ATOMIC_LOAD_SUB_I32:
1310 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1311 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1312 case Mips::ATOMIC_LOAD_SUB_I64:
1313 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1314 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1316 case Mips::ATOMIC_SWAP_I8:
1317 case Mips::ATOMIC_SWAP_I8_P8:
1318 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1319 case Mips::ATOMIC_SWAP_I16:
1320 case Mips::ATOMIC_SWAP_I16_P8:
1321 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1322 case Mips::ATOMIC_SWAP_I32:
1323 case Mips::ATOMIC_SWAP_I32_P8:
1324 return EmitAtomicBinary(MI, BB, 4, 0);
1325 case Mips::ATOMIC_SWAP_I64:
1326 case Mips::ATOMIC_SWAP_I64_P8:
1327 return EmitAtomicBinary(MI, BB, 8, 0);
1329 case Mips::ATOMIC_CMP_SWAP_I8:
1330 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1331 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1332 case Mips::ATOMIC_CMP_SWAP_I16:
1333 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1334 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1335 case Mips::ATOMIC_CMP_SWAP_I32:
1336 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1337 return EmitAtomicCmpSwap(MI, BB, 4);
1338 case Mips::ATOMIC_CMP_SWAP_I64:
1339 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1340 return EmitAtomicCmpSwap(MI, BB, 8);
1341 case Mips::BPOSGE32_PSEUDO:
1342 return EmitBPOSGE32(MI, BB);
1346 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1347 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1349 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1350 unsigned Size, unsigned BinOpcode,
1352 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1354 MachineFunction *MF = BB->getParent();
1355 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1356 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1357 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1358 DebugLoc dl = MI->getDebugLoc();
1359 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1362 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1363 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1370 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1371 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1374 ZERO = Mips::ZERO_64;
1378 unsigned OldVal = MI->getOperand(0).getReg();
1379 unsigned Ptr = MI->getOperand(1).getReg();
1380 unsigned Incr = MI->getOperand(2).getReg();
1382 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1383 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1384 unsigned Success = RegInfo.createVirtualRegister(RC);
1386 // insert new blocks after the current block
1387 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1388 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1389 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1390 MachineFunction::iterator It = BB;
1392 MF->insert(It, loopMBB);
1393 MF->insert(It, exitMBB);
1395 // Transfer the remainder of BB and its successor edges to exitMBB.
1396 exitMBB->splice(exitMBB->begin(), BB,
1397 llvm::next(MachineBasicBlock::iterator(MI)),
1399 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1403 // fallthrough --> loopMBB
1404 BB->addSuccessor(loopMBB);
1405 loopMBB->addSuccessor(loopMBB);
1406 loopMBB->addSuccessor(exitMBB);
1409 // ll oldval, 0(ptr)
1410 // <binop> storeval, oldval, incr
1411 // sc success, storeval, 0(ptr)
1412 // beq success, $0, loopMBB
1414 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1416 // and andres, oldval, incr
1417 // nor storeval, $0, andres
1418 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1419 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1420 } else if (BinOpcode) {
1421 // <binop> storeval, oldval, incr
1422 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1426 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1427 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1429 MI->eraseFromParent(); // The instruction is gone now.
1435 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1436 MachineBasicBlock *BB,
1437 unsigned Size, unsigned BinOpcode,
1439 assert((Size == 1 || Size == 2) &&
1440 "Unsupported size for EmitAtomicBinaryPartial.");
1442 MachineFunction *MF = BB->getParent();
1443 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1444 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1445 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1446 DebugLoc dl = MI->getDebugLoc();
1447 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1448 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1450 unsigned Dest = MI->getOperand(0).getReg();
1451 unsigned Ptr = MI->getOperand(1).getReg();
1452 unsigned Incr = MI->getOperand(2).getReg();
1454 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1455 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1456 unsigned Mask = RegInfo.createVirtualRegister(RC);
1457 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1458 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1459 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1460 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1461 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1462 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1463 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1464 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1465 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1466 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1467 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1468 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1469 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1470 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1471 unsigned Success = RegInfo.createVirtualRegister(RC);
1473 // insert new blocks after the current block
1474 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1475 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1476 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1477 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1478 MachineFunction::iterator It = BB;
1480 MF->insert(It, loopMBB);
1481 MF->insert(It, sinkMBB);
1482 MF->insert(It, exitMBB);
1484 // Transfer the remainder of BB and its successor edges to exitMBB.
1485 exitMBB->splice(exitMBB->begin(), BB,
1486 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1487 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1489 BB->addSuccessor(loopMBB);
1490 loopMBB->addSuccessor(loopMBB);
1491 loopMBB->addSuccessor(sinkMBB);
1492 sinkMBB->addSuccessor(exitMBB);
1495 // addiu masklsb2,$0,-4 # 0xfffffffc
1496 // and alignedaddr,ptr,masklsb2
1497 // andi ptrlsb2,ptr,3
1498 // sll shiftamt,ptrlsb2,3
1499 // ori maskupper,$0,255 # 0xff
1500 // sll mask,maskupper,shiftamt
1501 // nor mask2,$0,mask
1502 // sll incr2,incr,shiftamt
1504 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1505 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1506 .addReg(Mips::ZERO).addImm(-4);
1507 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1508 .addReg(Ptr).addReg(MaskLSB2);
1509 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1510 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1511 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1512 .addReg(Mips::ZERO).addImm(MaskImm);
1513 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1514 .addReg(ShiftAmt).addReg(MaskUpper);
1515 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1516 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1518 // atomic.load.binop
1520 // ll oldval,0(alignedaddr)
1521 // binop binopres,oldval,incr2
1522 // and newval,binopres,mask
1523 // and maskedoldval0,oldval,mask2
1524 // or storeval,maskedoldval0,newval
1525 // sc success,storeval,0(alignedaddr)
1526 // beq success,$0,loopMBB
1530 // ll oldval,0(alignedaddr)
1531 // and newval,incr2,mask
1532 // and maskedoldval0,oldval,mask2
1533 // or storeval,maskedoldval0,newval
1534 // sc success,storeval,0(alignedaddr)
1535 // beq success,$0,loopMBB
1538 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1540 // and andres, oldval, incr2
1541 // nor binopres, $0, andres
1542 // and newval, binopres, mask
1543 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1544 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1545 .addReg(Mips::ZERO).addReg(AndRes);
1546 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1547 } else if (BinOpcode) {
1548 // <binop> binopres, oldval, incr2
1549 // and newval, binopres, mask
1550 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1551 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1552 } else {// atomic.swap
1553 // and newval, incr2, mask
1554 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1557 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1558 .addReg(OldVal).addReg(Mask2);
1559 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1560 .addReg(MaskedOldVal0).addReg(NewVal);
1561 BuildMI(BB, dl, TII->get(SC), Success)
1562 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1563 BuildMI(BB, dl, TII->get(Mips::BEQ))
1564 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1567 // and maskedoldval1,oldval,mask
1568 // srl srlres,maskedoldval1,shiftamt
1569 // sll sllres,srlres,24
1570 // sra dest,sllres,24
1572 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1574 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1575 .addReg(OldVal).addReg(Mask);
1576 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1577 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1578 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1579 .addReg(SrlRes).addImm(ShiftImm);
1580 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1581 .addReg(SllRes).addImm(ShiftImm);
1583 MI->eraseFromParent(); // The instruction is gone now.
1589 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1590 MachineBasicBlock *BB,
1591 unsigned Size) const {
1592 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1594 MachineFunction *MF = BB->getParent();
1595 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1596 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1597 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1598 DebugLoc dl = MI->getDebugLoc();
1599 unsigned LL, SC, ZERO, BNE, BEQ;
1602 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1603 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1609 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1610 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1611 ZERO = Mips::ZERO_64;
1616 unsigned Dest = MI->getOperand(0).getReg();
1617 unsigned Ptr = MI->getOperand(1).getReg();
1618 unsigned OldVal = MI->getOperand(2).getReg();
1619 unsigned NewVal = MI->getOperand(3).getReg();
1621 unsigned Success = RegInfo.createVirtualRegister(RC);
1623 // insert new blocks after the current block
1624 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1625 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1626 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1627 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1628 MachineFunction::iterator It = BB;
1630 MF->insert(It, loop1MBB);
1631 MF->insert(It, loop2MBB);
1632 MF->insert(It, exitMBB);
1634 // Transfer the remainder of BB and its successor edges to exitMBB.
1635 exitMBB->splice(exitMBB->begin(), BB,
1636 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1637 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1641 // fallthrough --> loop1MBB
1642 BB->addSuccessor(loop1MBB);
1643 loop1MBB->addSuccessor(exitMBB);
1644 loop1MBB->addSuccessor(loop2MBB);
1645 loop2MBB->addSuccessor(loop1MBB);
1646 loop2MBB->addSuccessor(exitMBB);
1650 // bne dest, oldval, exitMBB
1652 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1653 BuildMI(BB, dl, TII->get(BNE))
1654 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1657 // sc success, newval, 0(ptr)
1658 // beq success, $0, loop1MBB
1660 BuildMI(BB, dl, TII->get(SC), Success)
1661 .addReg(NewVal).addReg(Ptr).addImm(0);
1662 BuildMI(BB, dl, TII->get(BEQ))
1663 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1665 MI->eraseFromParent(); // The instruction is gone now.
1671 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1672 MachineBasicBlock *BB,
1673 unsigned Size) const {
1674 assert((Size == 1 || Size == 2) &&
1675 "Unsupported size for EmitAtomicCmpSwapPartial.");
1677 MachineFunction *MF = BB->getParent();
1678 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1679 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1680 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1681 DebugLoc dl = MI->getDebugLoc();
1682 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1683 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1685 unsigned Dest = MI->getOperand(0).getReg();
1686 unsigned Ptr = MI->getOperand(1).getReg();
1687 unsigned CmpVal = MI->getOperand(2).getReg();
1688 unsigned NewVal = MI->getOperand(3).getReg();
1690 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1691 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1692 unsigned Mask = RegInfo.createVirtualRegister(RC);
1693 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1694 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1695 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1696 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1697 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1698 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1699 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1700 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1701 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1702 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1703 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1704 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1705 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1706 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1707 unsigned Success = RegInfo.createVirtualRegister(RC);
1709 // insert new blocks after the current block
1710 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1711 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1712 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1713 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1714 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1715 MachineFunction::iterator It = BB;
1717 MF->insert(It, loop1MBB);
1718 MF->insert(It, loop2MBB);
1719 MF->insert(It, sinkMBB);
1720 MF->insert(It, exitMBB);
1722 // Transfer the remainder of BB and its successor edges to exitMBB.
1723 exitMBB->splice(exitMBB->begin(), BB,
1724 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1725 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1727 BB->addSuccessor(loop1MBB);
1728 loop1MBB->addSuccessor(sinkMBB);
1729 loop1MBB->addSuccessor(loop2MBB);
1730 loop2MBB->addSuccessor(loop1MBB);
1731 loop2MBB->addSuccessor(sinkMBB);
1732 sinkMBB->addSuccessor(exitMBB);
1734 // FIXME: computation of newval2 can be moved to loop2MBB.
1736 // addiu masklsb2,$0,-4 # 0xfffffffc
1737 // and alignedaddr,ptr,masklsb2
1738 // andi ptrlsb2,ptr,3
1739 // sll shiftamt,ptrlsb2,3
1740 // ori maskupper,$0,255 # 0xff
1741 // sll mask,maskupper,shiftamt
1742 // nor mask2,$0,mask
1743 // andi maskedcmpval,cmpval,255
1744 // sll shiftedcmpval,maskedcmpval,shiftamt
1745 // andi maskednewval,newval,255
1746 // sll shiftednewval,maskednewval,shiftamt
1747 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1748 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1749 .addReg(Mips::ZERO).addImm(-4);
1750 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1751 .addReg(Ptr).addReg(MaskLSB2);
1752 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1753 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1754 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1755 .addReg(Mips::ZERO).addImm(MaskImm);
1756 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1757 .addReg(ShiftAmt).addReg(MaskUpper);
1758 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1759 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1760 .addReg(CmpVal).addImm(MaskImm);
1761 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1762 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1763 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1764 .addReg(NewVal).addImm(MaskImm);
1765 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1766 .addReg(ShiftAmt).addReg(MaskedNewVal);
1769 // ll oldval,0(alginedaddr)
1770 // and maskedoldval0,oldval,mask
1771 // bne maskedoldval0,shiftedcmpval,sinkMBB
1773 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1774 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1775 .addReg(OldVal).addReg(Mask);
1776 BuildMI(BB, dl, TII->get(Mips::BNE))
1777 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1780 // and maskedoldval1,oldval,mask2
1781 // or storeval,maskedoldval1,shiftednewval
1782 // sc success,storeval,0(alignedaddr)
1783 // beq success,$0,loop1MBB
1785 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1786 .addReg(OldVal).addReg(Mask2);
1787 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1788 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1789 BuildMI(BB, dl, TII->get(SC), Success)
1790 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1791 BuildMI(BB, dl, TII->get(Mips::BEQ))
1792 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1795 // srl srlres,maskedoldval0,shiftamt
1796 // sll sllres,srlres,24
1797 // sra dest,sllres,24
1799 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1801 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1802 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1803 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1804 .addReg(SrlRes).addImm(ShiftImm);
1805 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1806 .addReg(SllRes).addImm(ShiftImm);
1808 MI->eraseFromParent(); // The instruction is gone now.
1813 //===----------------------------------------------------------------------===//
1814 // Misc Lower Operation implementation
1815 //===----------------------------------------------------------------------===//
1816 SDValue MipsTargetLowering::
1817 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1819 // The first operand is the chain, the second is the condition, the third is
1820 // the block to branch to if the condition is true.
1821 SDValue Chain = Op.getOperand(0);
1822 SDValue Dest = Op.getOperand(2);
1823 DebugLoc dl = Op.getDebugLoc();
1825 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1827 // Return if flag is not set by a floating point comparison.
1828 if (CondRes.getOpcode() != MipsISD::FPCmp)
1831 SDValue CCNode = CondRes.getOperand(2);
1833 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1834 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1836 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1840 SDValue MipsTargetLowering::
1841 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1843 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1845 // Return if flag is not set by a floating point comparison.
1846 if (Cond.getOpcode() != MipsISD::FPCmp)
1849 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1853 SDValue MipsTargetLowering::
1854 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1856 DebugLoc DL = Op.getDebugLoc();
1857 EVT Ty = Op.getOperand(0).getValueType();
1858 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1859 Op.getOperand(0), Op.getOperand(1),
1862 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1866 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1867 SDValue Cond = CreateFPCmp(DAG, Op);
1869 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1870 "Floating point operand expected.");
1872 SDValue True = DAG.getConstant(1, MVT::i32);
1873 SDValue False = DAG.getConstant(0, MVT::i32);
1875 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1878 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1879 SelectionDAG &DAG) const {
1880 // FIXME there isn't actually debug info here
1881 DebugLoc dl = Op.getDebugLoc();
1882 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1884 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1885 const MipsTargetObjectFile &TLOF =
1886 (const MipsTargetObjectFile&)getObjFileLowering();
1888 // %gp_rel relocation
1889 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1890 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1892 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
1893 DAG.getVTList(MVT::i32), &GA, 1);
1894 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1895 return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1898 // %hi/%lo relocation
1899 return getAddrNonPIC(Op, DAG);
1902 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1903 return getAddrLocal(Op, DAG, HasMips64);
1906 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1907 MipsII::MO_GOT_LO16);
1909 return getAddrGlobal(Op, DAG,
1910 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1913 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1914 SelectionDAG &DAG) const {
1915 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1916 return getAddrNonPIC(Op, DAG);
1918 return getAddrLocal(Op, DAG, HasMips64);
1921 SDValue MipsTargetLowering::
1922 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1924 // If the relocation model is PIC, use the General Dynamic TLS Model or
1925 // Local Dynamic TLS model, otherwise use the Initial Exec or
1926 // Local Exec TLS Model.
1928 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1929 DebugLoc dl = GA->getDebugLoc();
1930 const GlobalValue *GV = GA->getGlobal();
1931 EVT PtrVT = getPointerTy();
1933 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1935 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1936 // General Dynamic and Local Dynamic TLS Model.
1937 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1940 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1941 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1942 GetGlobalReg(DAG, PtrVT), TGA);
1943 unsigned PtrSize = PtrVT.getSizeInBits();
1944 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1946 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1950 Entry.Node = Argument;
1952 Args.push_back(Entry);
1954 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1955 false, false, false, false, 0, CallingConv::C,
1956 /*isTailCall=*/false, /*doesNotRet=*/false,
1957 /*isReturnValueUsed=*/true,
1958 TlsGetAddr, Args, DAG, dl);
1959 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1961 SDValue Ret = CallResult.first;
1963 if (model != TLSModel::LocalDynamic)
1966 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1967 MipsII::MO_DTPREL_HI);
1968 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1969 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1970 MipsII::MO_DTPREL_LO);
1971 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1972 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1973 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1977 if (model == TLSModel::InitialExec) {
1978 // Initial Exec TLS Model
1979 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1980 MipsII::MO_GOTTPREL);
1981 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1983 Offset = DAG.getLoad(PtrVT, dl,
1984 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1985 false, false, false, 0);
1987 // Local Exec TLS Model
1988 assert(model == TLSModel::LocalExec);
1989 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1990 MipsII::MO_TPREL_HI);
1991 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1992 MipsII::MO_TPREL_LO);
1993 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1994 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1995 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1998 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1999 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2002 SDValue MipsTargetLowering::
2003 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2005 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2006 return getAddrNonPIC(Op, DAG);
2008 return getAddrLocal(Op, DAG, HasMips64);
2011 SDValue MipsTargetLowering::
2012 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2014 // gp_rel relocation
2015 // FIXME: we should reference the constant pool using small data sections,
2016 // but the asm printer currently doesn't support this feature without
2017 // hacking it. This feature should come soon so we can uncomment the
2019 //if (IsInSmallSection(C->getType())) {
2020 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2021 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2022 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2024 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2025 return getAddrNonPIC(Op, DAG);
2027 return getAddrLocal(Op, DAG, HasMips64);
2030 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2031 MachineFunction &MF = DAG.getMachineFunction();
2032 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2034 DebugLoc dl = Op.getDebugLoc();
2035 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2038 // vastart just stores the address of the VarArgsFrameIndex slot into the
2039 // memory location argument.
2040 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2041 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2042 MachinePointerInfo(SV), false, false, 0);
2045 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2046 EVT TyX = Op.getOperand(0).getValueType();
2047 EVT TyY = Op.getOperand(1).getValueType();
2048 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2049 SDValue Const31 = DAG.getConstant(31, MVT::i32);
2050 DebugLoc DL = Op.getDebugLoc();
2053 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2055 SDValue X = (TyX == MVT::f32) ?
2056 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2057 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2059 SDValue Y = (TyY == MVT::f32) ?
2060 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2061 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2065 // ext E, Y, 31, 1 ; extract bit31 of Y
2066 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2067 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2068 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2071 // srl SrlX, SllX, 1
2073 // sll SllY, SrlX, 31
2074 // or Or, SrlX, SllY
2075 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2076 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2077 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2078 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2079 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2082 if (TyX == MVT::f32)
2083 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2085 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2086 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2087 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2090 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2091 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2092 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2093 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2094 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2095 DebugLoc DL = Op.getDebugLoc();
2097 // Bitcast to integer nodes.
2098 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2099 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2102 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2103 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2104 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2105 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2107 if (WidthX > WidthY)
2108 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2109 else if (WidthY > WidthX)
2110 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2112 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2113 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2114 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2117 // (d)sll SllX, X, 1
2118 // (d)srl SrlX, SllX, 1
2119 // (d)srl SrlY, Y, width(Y)-1
2120 // (d)sll SllY, SrlX, width(Y)-1
2121 // or Or, SrlX, SllY
2122 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2123 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2124 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2125 DAG.getConstant(WidthY - 1, MVT::i32));
2127 if (WidthX > WidthY)
2128 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2129 else if (WidthY > WidthX)
2130 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2132 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2133 DAG.getConstant(WidthX - 1, MVT::i32));
2134 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2135 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2139 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2140 if (Subtarget->hasMips64())
2141 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2143 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2146 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2147 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2148 DebugLoc DL = Op.getDebugLoc();
2150 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2152 SDValue X = (Op.getValueType() == MVT::f32) ?
2153 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2154 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2159 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2160 DAG.getRegister(Mips::ZERO, MVT::i32),
2161 DAG.getConstant(31, MVT::i32), Const1, X);
2163 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2164 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2167 if (Op.getValueType() == MVT::f32)
2168 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2170 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2171 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2172 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2175 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2176 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2177 DebugLoc DL = Op.getDebugLoc();
2179 // Bitcast to integer node.
2180 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2184 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2185 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2186 DAG.getConstant(63, MVT::i32), Const1, X);
2188 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2189 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2192 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2196 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2197 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2198 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2200 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2203 SDValue MipsTargetLowering::
2204 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2206 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2207 "Frame address can only be determined for current frame.");
2209 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2210 MFI->setFrameAddressIsTaken(true);
2211 EVT VT = Op.getValueType();
2212 DebugLoc dl = Op.getDebugLoc();
2213 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2214 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2218 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2219 SelectionDAG &DAG) const {
2221 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2222 "Return address can be determined only for current frame.");
2224 MachineFunction &MF = DAG.getMachineFunction();
2225 MachineFrameInfo *MFI = MF.getFrameInfo();
2226 MVT VT = Op.getSimpleValueType();
2227 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2228 MFI->setReturnAddressIsTaken(true);
2230 // Return RA, which contains the return address. Mark it an implicit live-in.
2231 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2232 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2235 // TODO: set SType according to the desired memory barrier behavior.
2237 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2239 DebugLoc dl = Op.getDebugLoc();
2240 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2241 DAG.getConstant(SType, MVT::i32));
2244 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2245 SelectionDAG &DAG) const {
2246 // FIXME: Need pseudo-fence for 'singlethread' fences
2247 // FIXME: Set SType for weaker fences where supported/appropriate.
2249 DebugLoc dl = Op.getDebugLoc();
2250 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2251 DAG.getConstant(SType, MVT::i32));
2254 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2255 SelectionDAG &DAG) const {
2256 DebugLoc DL = Op.getDebugLoc();
2257 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2258 SDValue Shamt = Op.getOperand(2);
2261 // lo = (shl lo, shamt)
2262 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2265 // hi = (shl lo, shamt[4:0])
2266 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2267 DAG.getConstant(-1, MVT::i32));
2268 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2269 DAG.getConstant(1, MVT::i32));
2270 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2272 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2273 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2274 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2275 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2276 DAG.getConstant(0x20, MVT::i32));
2277 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2278 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2279 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2281 SDValue Ops[2] = {Lo, Hi};
2282 return DAG.getMergeValues(Ops, 2, DL);
2285 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2287 DebugLoc DL = Op.getDebugLoc();
2288 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2289 SDValue Shamt = Op.getOperand(2);
2292 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2294 // hi = (sra hi, shamt)
2296 // hi = (srl hi, shamt)
2299 // lo = (sra hi, shamt[4:0])
2300 // hi = (sra hi, 31)
2302 // lo = (srl hi, shamt[4:0])
2304 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2305 DAG.getConstant(-1, MVT::i32));
2306 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2307 DAG.getConstant(1, MVT::i32));
2308 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2309 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2310 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2311 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2313 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2314 DAG.getConstant(0x20, MVT::i32));
2315 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2316 DAG.getConstant(31, MVT::i32));
2317 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2318 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2319 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2322 SDValue Ops[2] = {Lo, Hi};
2323 return DAG.getMergeValues(Ops, 2, DL);
2326 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2327 SDValue Chain, SDValue Src, unsigned Offset) {
2328 SDValue Ptr = LD->getBasePtr();
2329 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2330 EVT BasePtrVT = Ptr.getValueType();
2331 DebugLoc DL = LD->getDebugLoc();
2332 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2335 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2336 DAG.getConstant(Offset, BasePtrVT));
2338 SDValue Ops[] = { Chain, Ptr, Src };
2339 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2340 LD->getMemOperand());
2343 // Expand an unaligned 32 or 64-bit integer load node.
2344 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2345 LoadSDNode *LD = cast<LoadSDNode>(Op);
2346 EVT MemVT = LD->getMemoryVT();
2348 // Return if load is aligned or if MemVT is neither i32 nor i64.
2349 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2350 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2353 bool IsLittle = Subtarget->isLittle();
2354 EVT VT = Op.getValueType();
2355 ISD::LoadExtType ExtType = LD->getExtensionType();
2356 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2358 assert((VT == MVT::i32) || (VT == MVT::i64));
2361 // (set dst, (i64 (load baseptr)))
2363 // (set tmp, (ldl (add baseptr, 7), undef))
2364 // (set dst, (ldr baseptr, tmp))
2365 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2366 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2368 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2372 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2374 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2378 // (set dst, (i32 (load baseptr))) or
2379 // (set dst, (i64 (sextload baseptr))) or
2380 // (set dst, (i64 (extload baseptr)))
2382 // (set tmp, (lwl (add baseptr, 3), undef))
2383 // (set dst, (lwr baseptr, tmp))
2384 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2385 (ExtType == ISD::EXTLOAD))
2388 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2391 // (set dst, (i64 (zextload baseptr)))
2393 // (set tmp0, (lwl (add baseptr, 3), undef))
2394 // (set tmp1, (lwr baseptr, tmp0))
2395 // (set tmp2, (shl tmp1, 32))
2396 // (set dst, (srl tmp2, 32))
2397 DebugLoc DL = LD->getDebugLoc();
2398 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2399 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2400 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2401 SDValue Ops[] = { SRL, LWR.getValue(1) };
2402 return DAG.getMergeValues(Ops, 2, DL);
2405 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2406 SDValue Chain, unsigned Offset) {
2407 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2408 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2409 DebugLoc DL = SD->getDebugLoc();
2410 SDVTList VTList = DAG.getVTList(MVT::Other);
2413 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2414 DAG.getConstant(Offset, BasePtrVT));
2416 SDValue Ops[] = { Chain, Value, Ptr };
2417 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2418 SD->getMemOperand());
2421 // Expand an unaligned 32 or 64-bit integer store node.
2422 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2423 StoreSDNode *SD = cast<StoreSDNode>(Op);
2424 EVT MemVT = SD->getMemoryVT();
2426 // Return if store is aligned or if MemVT is neither i32 nor i64.
2427 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2428 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2431 bool IsLittle = Subtarget->isLittle();
2432 SDValue Value = SD->getValue(), Chain = SD->getChain();
2433 EVT VT = Value.getValueType();
2436 // (store val, baseptr) or
2437 // (truncstore val, baseptr)
2439 // (swl val, (add baseptr, 3))
2440 // (swr val, baseptr)
2441 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2442 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2444 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2447 assert(VT == MVT::i64);
2450 // (store val, baseptr)
2452 // (sdl val, (add baseptr, 7))
2453 // (sdr val, baseptr)
2454 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2455 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2458 // This function expands mips intrinsic nodes which have 64-bit input operands
2459 // or output values.
2461 // out64 = intrinsic-node in64
2463 // lo = copy (extract-element (in64, 0))
2464 // hi = copy (extract-element (in64, 1))
2465 // mips-specific-node
2468 // out64 = merge-values (v0, v1)
2470 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2471 unsigned Opc, bool HasI64In, bool HasI64Out) {
2472 DebugLoc DL = Op.getDebugLoc();
2473 bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2474 SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2475 SmallVector<SDValue, 3> Ops;
2478 SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2479 Op->getOperand(1 + HasChainIn),
2480 DAG.getConstant(0, MVT::i32));
2481 SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2482 Op->getOperand(1 + HasChainIn),
2483 DAG.getConstant(1, MVT::i32));
2485 Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2486 Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2488 Ops.push_back(Chain);
2489 Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2490 Ops.push_back(Chain.getValue(1));
2492 Ops.push_back(Chain);
2493 Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2497 return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2498 Ops.begin(), Ops.size());
2500 SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2501 Ops.begin(), Ops.size());
2502 SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2504 SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2506 SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2511 SDValue Vals[] = { Out, OutHi.getValue(1) };
2512 return DAG.getMergeValues(Vals, 2, DL);
2515 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2516 SelectionDAG &DAG) const {
2517 switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2520 case Intrinsic::mips_shilo:
2521 return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2522 case Intrinsic::mips_dpau_h_qbl:
2523 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2524 case Intrinsic::mips_dpau_h_qbr:
2525 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2526 case Intrinsic::mips_dpsu_h_qbl:
2527 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2528 case Intrinsic::mips_dpsu_h_qbr:
2529 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2530 case Intrinsic::mips_dpa_w_ph:
2531 return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2532 case Intrinsic::mips_dps_w_ph:
2533 return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2534 case Intrinsic::mips_dpax_w_ph:
2535 return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2536 case Intrinsic::mips_dpsx_w_ph:
2537 return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2538 case Intrinsic::mips_mulsa_w_ph:
2539 return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2540 case Intrinsic::mips_mult:
2541 return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2542 case Intrinsic::mips_multu:
2543 return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2544 case Intrinsic::mips_madd:
2545 return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2546 case Intrinsic::mips_maddu:
2547 return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2548 case Intrinsic::mips_msub:
2549 return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2550 case Intrinsic::mips_msubu:
2551 return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2555 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2556 SelectionDAG &DAG) const {
2557 switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2560 case Intrinsic::mips_extp:
2561 return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2562 case Intrinsic::mips_extpdp:
2563 return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2564 case Intrinsic::mips_extr_w:
2565 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2566 case Intrinsic::mips_extr_r_w:
2567 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2568 case Intrinsic::mips_extr_rs_w:
2569 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2570 case Intrinsic::mips_extr_s_h:
2571 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2572 case Intrinsic::mips_mthlip:
2573 return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2574 case Intrinsic::mips_mulsaq_s_w_ph:
2575 return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2576 case Intrinsic::mips_maq_s_w_phl:
2577 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2578 case Intrinsic::mips_maq_s_w_phr:
2579 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2580 case Intrinsic::mips_maq_sa_w_phl:
2581 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2582 case Intrinsic::mips_maq_sa_w_phr:
2583 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2584 case Intrinsic::mips_dpaq_s_w_ph:
2585 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2586 case Intrinsic::mips_dpsq_s_w_ph:
2587 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2588 case Intrinsic::mips_dpaq_sa_l_w:
2589 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2590 case Intrinsic::mips_dpsq_sa_l_w:
2591 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2592 case Intrinsic::mips_dpaqx_s_w_ph:
2593 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2594 case Intrinsic::mips_dpaqx_sa_w_ph:
2595 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2596 case Intrinsic::mips_dpsqx_s_w_ph:
2597 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2598 case Intrinsic::mips_dpsqx_sa_w_ph:
2599 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2603 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2604 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2605 || cast<ConstantSDNode>
2606 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2607 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2611 // (add (frameaddr 0), (frame_to_args_offset))
2612 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2613 // (add FrameObject, 0)
2614 // where FrameObject is a fixed StackObject with offset 0 which points to
2615 // the old stack pointer.
2616 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2617 EVT ValTy = Op->getValueType(0);
2618 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2619 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2620 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2621 DAG.getConstant(0, ValTy));
2624 //===----------------------------------------------------------------------===//
2625 // Calling Convention Implementation
2626 //===----------------------------------------------------------------------===//
2628 //===----------------------------------------------------------------------===//
2629 // TODO: Implement a generic logic using tblgen that can support this.
2630 // Mips O32 ABI rules:
2632 // i32 - Passed in A0, A1, A2, A3 and stack
2633 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2634 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2635 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2636 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2637 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2640 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2641 //===----------------------------------------------------------------------===//
2643 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2644 MVT LocVT, CCValAssign::LocInfo LocInfo,
2645 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2647 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2649 static const uint16_t IntRegs[] = {
2650 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2652 static const uint16_t F32Regs[] = {
2653 Mips::F12, Mips::F14
2655 static const uint16_t F64Regs[] = {
2659 // Do not process byval args here.
2660 if (ArgFlags.isByVal())
2663 // Promote i8 and i16
2664 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2666 if (ArgFlags.isSExt())
2667 LocInfo = CCValAssign::SExt;
2668 else if (ArgFlags.isZExt())
2669 LocInfo = CCValAssign::ZExt;
2671 LocInfo = CCValAssign::AExt;
2676 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2677 // is true: function is vararg, argument is 3rd or higher, there is previous
2678 // argument which is not f32 or f64.
2679 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2680 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2681 unsigned OrigAlign = ArgFlags.getOrigAlign();
2682 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2684 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2685 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2686 // If this is the first part of an i64 arg,
2687 // the allocated register must be either A0 or A2.
2688 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2689 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2691 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2692 // Allocate int register and shadow next int register. If first
2693 // available register is Mips::A1 or Mips::A3, shadow it too.
2694 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2695 if (Reg == Mips::A1 || Reg == Mips::A3)
2696 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2697 State.AllocateReg(IntRegs, IntRegsSize);
2699 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2700 // we are guaranteed to find an available float register
2701 if (ValVT == MVT::f32) {
2702 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2703 // Shadow int register
2704 State.AllocateReg(IntRegs, IntRegsSize);
2706 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2707 // Shadow int registers
2708 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2709 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2710 State.AllocateReg(IntRegs, IntRegsSize);
2711 State.AllocateReg(IntRegs, IntRegsSize);
2714 llvm_unreachable("Cannot handle this ValVT.");
2717 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2719 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2721 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2726 #include "MipsGenCallingConv.inc"
2728 //===----------------------------------------------------------------------===//
2729 // Call Calling Convention Implementation
2730 //===----------------------------------------------------------------------===//
2732 static const unsigned O32IntRegsSize = 4;
2734 // Return next O32 integer argument register.
2735 static unsigned getNextIntArgReg(unsigned Reg) {
2736 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2737 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2740 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2741 /// for tail call optimization.
2742 bool MipsTargetLowering::
2743 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
2744 unsigned NextStackOffset,
2745 const MipsFunctionInfo& FI) const {
2746 if (!EnableMipsTailCalls)
2749 // No tail call optimization for mips16.
2750 if (Subtarget->inMips16Mode())
2753 // Return false if either the callee or caller has a byval argument.
2754 if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
2757 // Return true if the callee's argument area is no larger than the
2759 return NextStackOffset <= FI.getIncomingArgSize();
2763 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2764 SDValue Chain, SDValue Arg, DebugLoc DL,
2765 bool IsTailCall, SelectionDAG &DAG) const {
2767 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2768 DAG.getIntPtrConstant(Offset));
2769 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2773 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2774 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2775 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2776 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2777 /*isVolatile=*/ true, false, 0);
2781 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
2782 // cleaner way to do all of this but it will have to wait until the traditional
2783 // gcc mechanism is completed.
2785 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
2786 // have either arguments or returned values placed in floating point registers,
2787 // we use a set of helper functions. (This includes functions which return type
2788 // complex which on Mips are returned in a pair of floating point registers).
2790 // This is an encoding that we inherited from gcc.
2791 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
2792 // floating point argument registers 1,2 only when the first and optionally
2793 // the second arguments are float (sf) or double (df).
2794 // For Mips16 we are only concerned with the situations where floating point
2795 // arguments are being passed in floating point registers by the ABI, because
2796 // Mips16 mode code cannot execute floating point instructions to load those
2797 // values and hence helper functions are needed.
2798 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
2799 // the helper function suffixs for these are:
2800 // 0, 1, 5, 9, 2, 6, 10
2801 // this suffix can then be calculated as follows:
2802 // for a given argument Arg:
2803 // Arg1x, Arg2x = 1 : Arg is sf
2805 // 0: Arg is neither sf or df
2806 // So this stub is the string for number Arg1x + Arg2x*4.
2807 // However not all numbers between 0 and 10 are possible, we check anyway and
2808 // assert if the impossible exists.
2811 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
2812 (ArgListTy &Args) const {
2813 unsigned int resultNum = 0;
2814 if (Args.size() >= 1) {
2815 Type *t = Args[0].Ty;
2816 if (t->isFloatTy()) {
2819 else if (t->isDoubleTy()) {
2824 if (Args.size() >=2) {
2825 Type *t = Args[1].Ty;
2826 if (t->isFloatTy()) {
2829 else if (t->isDoubleTy()) {
2838 // prefixs are attached to stub numbers depending on the return type .
2839 // return type: float sf_
2841 // single complex sc_
2842 // double complext dc_
2846 // The full name of a helper function is__mips16_call_stub +
2847 // return type dependent prefix + stub number
2850 // This is something that probably should be in a different source file and
2851 // perhaps done differently but my main purpose is to not waste runtime
2852 // on something that we can enumerate in the source. Another possibility is
2853 // to have a python script to generate these mapping tables. This will do
2854 // for now. There are a whole series of helper function mapping arrays, one
2855 // for each return type class as outlined above. There there are 11 possible
2856 // entries. Ones with 0 are ones which should never be selected
2858 // All the arrays are similar except for ones which return neither
2859 // sf, df, sc, dc, in which only care about ones which have sf or df as a
2862 #define P_ "__mips16_call_stub_"
2863 #define MAX_STUB_NUMBER 10
2864 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
2865 #define T P "0" , T1
2867 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
2871 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
2875 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
2879 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
2883 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
2889 const char* MipsTargetLowering::
2890 getMips16HelperFunction
2891 (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
2892 const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
2894 const unsigned int maxStubNum = 10;
2895 assert(stubNum <= maxStubNum);
2896 const bool validStubNum[maxStubNum+1] =
2897 {true, true, true, false, false, true, true, false, false, true, true};
2898 assert(validStubNum[stubNum]);
2901 if (RetTy->isFloatTy()) {
2902 result = sfMips16Helper[stubNum];
2904 else if (RetTy ->isDoubleTy()) {
2905 result = dfMips16Helper[stubNum];
2907 else if (RetTy->isStructTy()) {
2908 // check if it's complex
2909 if (RetTy->getNumContainedTypes() == 2) {
2910 if ((RetTy->getContainedType(0)->isFloatTy()) &&
2911 (RetTy->getContainedType(1)->isFloatTy())) {
2912 result = scMips16Helper[stubNum];
2914 else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
2915 (RetTy->getContainedType(1)->isDoubleTy())) {
2916 result = dcMips16Helper[stubNum];
2919 llvm_unreachable("Uncovered condition");
2923 llvm_unreachable("Uncovered condition");
2931 result = vMips16Helper[stubNum];
2937 /// LowerCall - functions arguments are copied from virtual regs to
2938 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2940 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2941 SmallVectorImpl<SDValue> &InVals) const {
2942 SelectionDAG &DAG = CLI.DAG;
2943 DebugLoc &dl = CLI.DL;
2944 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2945 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2946 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2947 SDValue Chain = CLI.Chain;
2948 SDValue Callee = CLI.Callee;
2949 bool &isTailCall = CLI.IsTailCall;
2950 CallingConv::ID CallConv = CLI.CallConv;
2951 bool isVarArg = CLI.IsVarArg;
2953 const char* mips16HelperFunction = 0;
2954 bool needMips16Helper = false;
2956 if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
2959 // currently we don't have symbols tagged with the mips16 or mips32
2960 // qualifier so we will assume that we don't know what kind it is.
2961 // and generate the helper
2963 bool lookupHelper = true;
2964 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2965 if (noHelperNeeded.find(S->getSymbol()) != noHelperNeeded.end()) {
2966 lookupHelper = false;
2969 if (lookupHelper) mips16HelperFunction =
2970 getMips16HelperFunction(CLI.RetTy, CLI.Args, needMips16Helper);
2973 MachineFunction &MF = DAG.getMachineFunction();
2974 MachineFrameInfo *MFI = MF.getFrameInfo();
2975 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2976 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2978 // Analyze operands of the call, assigning locations to each operand.
2979 SmallVector<CCValAssign, 16> ArgLocs;
2980 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2981 getTargetMachine(), ArgLocs, *DAG.getContext());
2982 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
2984 MipsCCInfo.analyzeCallOperands(Outs);
2986 // Get a count of how many bytes are to be pushed on the stack.
2987 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2989 // Check if it's really possible to do a tail call.
2992 IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2993 *MF.getInfo<MipsFunctionInfo>());
2998 // Chain is the output chain of the last Load/Store or CopyToReg node.
2999 // ByValChain is the output chain of the last Memcpy node created for copying
3000 // byval arguments to the stack.
3001 unsigned StackAlignment = TFL->getStackAlignment();
3002 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
3003 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3006 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3008 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
3009 IsN64 ? Mips::SP_64 : Mips::SP,
3012 // With EABI is it possible to have 16 args on registers.
3013 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3014 SmallVector<SDValue, 8> MemOpChains;
3015 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3017 // Walk the register/memloc assignments, inserting copies/loads.
3018 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3019 SDValue Arg = OutVals[i];
3020 CCValAssign &VA = ArgLocs[i];
3021 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3022 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3025 if (Flags.isByVal()) {
3026 assert(Flags.getByValSize() &&
3027 "ByVal args of size 0 should have been ignored by front-end.");
3028 assert(ByValArg != MipsCCInfo.byval_end());
3029 assert(!isTailCall &&
3030 "Do not tail-call optimize if there is a byval argument.");
3031 passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3032 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3037 // Promote the value if needed.
3038 switch (VA.getLocInfo()) {
3039 default: llvm_unreachable("Unknown loc info!");
3040 case CCValAssign::Full:
3041 if (VA.isRegLoc()) {
3042 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3043 (ValVT == MVT::f64 && LocVT == MVT::i64))
3044 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
3045 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3046 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3047 Arg, DAG.getConstant(0, MVT::i32));
3048 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3049 Arg, DAG.getConstant(1, MVT::i32));
3050 if (!Subtarget->isLittle())
3052 unsigned LocRegLo = VA.getLocReg();
3053 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3054 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3055 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3060 case CCValAssign::SExt:
3061 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
3063 case CCValAssign::ZExt:
3064 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
3066 case CCValAssign::AExt:
3067 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
3071 // Arguments that can be passed on register must be kept at
3072 // RegsToPass vector
3073 if (VA.isRegLoc()) {
3074 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3078 // Register can't get to this point...
3079 assert(VA.isMemLoc());
3081 // emit ISD::STORE whichs stores the
3082 // parameter value to a stack Location
3083 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3084 Chain, Arg, dl, isTailCall, DAG));
3087 // Transform all store nodes into one single node because all store
3088 // nodes are independent of each other.
3089 if (!MemOpChains.empty())
3090 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3091 &MemOpChains[0], MemOpChains.size());
3093 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3094 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3095 // node so that legalize doesn't hack it.
3096 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3097 bool GlobalOrExternal = false, InternalLinkage = false;
3100 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3102 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3104 if (InternalLinkage)
3105 Callee = getAddrLocal(Callee, DAG, HasMips64);
3107 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3108 MipsII::MO_CALL_LO16);
3110 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3112 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
3113 MipsII::MO_NO_FLAG);
3114 GlobalOrExternal = true;
3116 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3117 if (!IsN64 && !IsPIC) // !N64 && static
3118 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3119 MipsII::MO_NO_FLAG);
3121 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3122 MipsII::MO_CALL_LO16);
3124 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_DISP);
3126 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3128 GlobalOrExternal = true;
3131 SDValue JumpTarget = Callee;
3133 // T9 should contain the address of the callee function if
3134 // -reloction-model=pic or it is an indirect call.
3135 if (IsPICCall || !GlobalOrExternal) {
3136 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3137 unsigned V0Reg = Mips::V0;
3138 if (needMips16Helper) {
3139 RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3140 JumpTarget = DAG.getExternalSymbol(
3141 mips16HelperFunction, getPointerTy());
3142 JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3145 RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3147 if (!Subtarget->inMips16Mode())
3148 JumpTarget = SDValue();
3152 // Insert node "GP copy globalreg" before call to function.
3154 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3155 // in PIC mode) allow symbols to be resolved via lazy binding.
3156 // The lazy binding stub requires GP to point to the GOT.
3157 if (IsPICCall && !InternalLinkage) {
3158 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3159 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3160 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
3163 // Build a sequence of copy-to-reg nodes chained together with token
3164 // chain and flag operands which copy the outgoing args into registers.
3165 // The InFlag in necessary since all emitted instructions must be
3169 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3170 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3171 RegsToPass[i].second, InFlag);
3172 InFlag = Chain.getValue(1);
3175 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3176 // = Chain, Callee, Reg#1, Reg#2, ...
3178 // Returns a chain & a flag for retval copy to use.
3179 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3180 SmallVector<SDValue, 8> Ops(1, Chain);
3182 if (JumpTarget.getNode())
3183 Ops.push_back(JumpTarget);
3185 // Add argument registers to the end of the list so that they are
3186 // known live into the call.
3187 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3188 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3189 RegsToPass[i].second.getValueType()));
3191 // Add a register mask operand representing the call-preserved registers.
3192 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3193 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3194 assert(Mask && "Missing call preserved mask for calling convention");
3195 Ops.push_back(DAG.getRegisterMask(Mask));
3197 if (InFlag.getNode())
3198 Ops.push_back(InFlag);
3201 return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
3203 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3204 InFlag = Chain.getValue(1);
3206 // Create the CALLSEQ_END node.
3207 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3208 DAG.getIntPtrConstant(0, true), InFlag);
3209 InFlag = Chain.getValue(1);
3211 // Handle result values, copying them out of physregs into vregs that we
3213 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3214 Ins, dl, DAG, InVals);
3217 /// LowerCallResult - Lower the result values of a call into the
3218 /// appropriate copies out of appropriate physical registers.
3220 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3221 CallingConv::ID CallConv, bool isVarArg,
3222 const SmallVectorImpl<ISD::InputArg> &Ins,
3223 DebugLoc dl, SelectionDAG &DAG,
3224 SmallVectorImpl<SDValue> &InVals) const {
3225 // Assign locations to each value returned by this call.
3226 SmallVector<CCValAssign, 16> RVLocs;
3227 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3228 getTargetMachine(), RVLocs, *DAG.getContext());
3230 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3232 // Copy all of the result registers out of their specified physreg.
3233 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3234 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3235 RVLocs[i].getValVT(), InFlag).getValue(1);
3236 InFlag = Chain.getValue(2);
3237 InVals.push_back(Chain.getValue(0));
3243 //===----------------------------------------------------------------------===//
3244 // Formal Arguments Calling Convention Implementation
3245 //===----------------------------------------------------------------------===//
3246 /// LowerFormalArguments - transform physical registers into virtual registers
3247 /// and generate load operations for arguments places on the stack.
3249 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3250 CallingConv::ID CallConv,
3252 const SmallVectorImpl<ISD::InputArg> &Ins,
3253 DebugLoc dl, SelectionDAG &DAG,
3254 SmallVectorImpl<SDValue> &InVals)
3256 MachineFunction &MF = DAG.getMachineFunction();
3257 MachineFrameInfo *MFI = MF.getFrameInfo();
3258 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3260 MipsFI->setVarArgsFrameIndex(0);
3262 // Used with vargs to acumulate store chains.
3263 std::vector<SDValue> OutChains;
3265 // Assign locations to all of the incoming arguments.
3266 SmallVector<CCValAssign, 16> ArgLocs;
3267 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3268 getTargetMachine(), ArgLocs, *DAG.getContext());
3269 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3271 MipsCCInfo.analyzeFormalArguments(Ins);
3272 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3273 MipsCCInfo.hasByValArg());
3275 Function::const_arg_iterator FuncArg =
3276 DAG.getMachineFunction().getFunction()->arg_begin();
3277 unsigned CurArgIdx = 0;
3278 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3280 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3281 CCValAssign &VA = ArgLocs[i];
3282 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3283 CurArgIdx = Ins[i].OrigArgIndex;
3284 EVT ValVT = VA.getValVT();
3285 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3286 bool IsRegLoc = VA.isRegLoc();
3288 if (Flags.isByVal()) {
3289 assert(Flags.getByValSize() &&
3290 "ByVal args of size 0 should have been ignored by front-end.");
3291 assert(ByValArg != MipsCCInfo.byval_end());
3292 copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3293 MipsCCInfo, *ByValArg);
3298 // Arguments stored on registers
3300 EVT RegVT = VA.getLocVT();
3301 unsigned ArgReg = VA.getLocReg();
3302 const TargetRegisterClass *RC;
3304 if (RegVT == MVT::i32)
3305 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3306 &Mips::CPURegsRegClass;
3307 else if (RegVT == MVT::i64)
3308 RC = &Mips::CPU64RegsRegClass;
3309 else if (RegVT == MVT::f32)
3310 RC = &Mips::FGR32RegClass;
3311 else if (RegVT == MVT::f64)
3312 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3314 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3316 // Transform the arguments stored on
3317 // physical registers into virtual ones
3318 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3319 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3321 // If this is an 8 or 16-bit value, it has been passed promoted
3322 // to 32 bits. Insert an assert[sz]ext to capture this, then
3323 // truncate to the right size.
3324 if (VA.getLocInfo() != CCValAssign::Full) {
3325 unsigned Opcode = 0;
3326 if (VA.getLocInfo() == CCValAssign::SExt)
3327 Opcode = ISD::AssertSext;
3328 else if (VA.getLocInfo() == CCValAssign::ZExt)
3329 Opcode = ISD::AssertZext;
3331 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3332 DAG.getValueType(ValVT));
3333 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3336 // Handle floating point arguments passed in integer registers.
3337 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3338 (RegVT == MVT::i64 && ValVT == MVT::f64))
3339 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3340 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3341 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3342 getNextIntArgReg(ArgReg), RC);
3343 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3344 if (!Subtarget->isLittle())
3345 std::swap(ArgValue, ArgValue2);
3346 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3347 ArgValue, ArgValue2);
3350 InVals.push_back(ArgValue);
3351 } else { // VA.isRegLoc()
3354 assert(VA.isMemLoc());
3356 // The stack pointer offset is relative to the caller stack frame.
3357 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3358 VA.getLocMemOffset(), true);
3360 // Create load nodes to retrieve arguments from the stack
3361 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3362 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3363 MachinePointerInfo::getFixedStack(FI),
3364 false, false, false, 0));
3368 // The mips ABIs for returning structs by value requires that we copy
3369 // the sret argument into $v0 for the return. Save the argument into
3370 // a virtual register so that we can access it from the return points.
3371 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3372 unsigned Reg = MipsFI->getSRetReturnReg();
3374 Reg = MF.getRegInfo().
3375 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3376 MipsFI->setSRetReturnReg(Reg);
3378 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3379 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3383 writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3385 // All stores are grouped in one node to allow the matching between
3386 // the size of Ins and InVals. This only happens when on varg functions
3387 if (!OutChains.empty()) {
3388 OutChains.push_back(Chain);
3389 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3390 &OutChains[0], OutChains.size());
3396 //===----------------------------------------------------------------------===//
3397 // Return Value Calling Convention Implementation
3398 //===----------------------------------------------------------------------===//
3401 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3402 MachineFunction &MF, bool isVarArg,
3403 const SmallVectorImpl<ISD::OutputArg> &Outs,
3404 LLVMContext &Context) const {
3405 SmallVector<CCValAssign, 16> RVLocs;
3406 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3408 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3412 MipsTargetLowering::LowerReturn(SDValue Chain,
3413 CallingConv::ID CallConv, bool isVarArg,
3414 const SmallVectorImpl<ISD::OutputArg> &Outs,
3415 const SmallVectorImpl<SDValue> &OutVals,
3416 DebugLoc dl, SelectionDAG &DAG) const {
3418 // CCValAssign - represent the assignment of
3419 // the return value to a location
3420 SmallVector<CCValAssign, 16> RVLocs;
3422 // CCState - Info about the registers and stack slot.
3423 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3424 getTargetMachine(), RVLocs, *DAG.getContext());
3426 // Analize return values.
3427 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3429 // If this is the first return lowered for this function, add
3430 // the regs to the liveout set for the function.
3431 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3432 for (unsigned i = 0; i != RVLocs.size(); ++i)
3433 if (RVLocs[i].isRegLoc())
3434 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3439 // Copy the result values into the output registers.
3440 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3441 CCValAssign &VA = RVLocs[i];
3442 assert(VA.isRegLoc() && "Can only return in registers!");
3444 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3446 // guarantee that all emitted copies are
3447 // stuck together, avoiding something bad
3448 Flag = Chain.getValue(1);
3451 // The mips ABIs for returning structs by value requires that we copy
3452 // the sret argument into $v0 for the return. We saved the argument into
3453 // a virtual register in the entry block, so now we copy the value out
3455 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3456 MachineFunction &MF = DAG.getMachineFunction();
3457 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3458 unsigned Reg = MipsFI->getSRetReturnReg();
3461 llvm_unreachable("sret virtual register not created in the entry block");
3462 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3463 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3465 Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3466 Flag = Chain.getValue(1);
3467 MF.getRegInfo().addLiveOut(V0);
3470 // Return on Mips is always a "jr $ra"
3472 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3475 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3478 //===----------------------------------------------------------------------===//
3479 // Mips Inline Assembly Support
3480 //===----------------------------------------------------------------------===//
3482 /// getConstraintType - Given a constraint letter, return the type of
3483 /// constraint it is for this target.
3484 MipsTargetLowering::ConstraintType MipsTargetLowering::
3485 getConstraintType(const std::string &Constraint) const
3487 // Mips specific constrainy
3488 // GCC config/mips/constraints.md
3490 // 'd' : An address register. Equivalent to r
3491 // unless generating MIPS16 code.
3492 // 'y' : Equivalent to r; retained for
3493 // backwards compatibility.
3494 // 'c' : A register suitable for use in an indirect
3495 // jump. This will always be $25 for -mabicalls.
3496 // 'l' : The lo register. 1 word storage.
3497 // 'x' : The hilo register pair. Double word storage.
3498 if (Constraint.size() == 1) {
3499 switch (Constraint[0]) {
3507 return C_RegisterClass;
3510 return TargetLowering::getConstraintType(Constraint);
3513 /// Examine constraint type and operand type and determine a weight value.
3514 /// This object must already have been set up with the operand type
3515 /// and the current alternative constraint selected.
3516 TargetLowering::ConstraintWeight
3517 MipsTargetLowering::getSingleConstraintMatchWeight(
3518 AsmOperandInfo &info, const char *constraint) const {
3519 ConstraintWeight weight = CW_Invalid;
3520 Value *CallOperandVal = info.CallOperandVal;
3521 // If we don't have a value, we can't do a match,
3522 // but allow it at the lowest weight.
3523 if (CallOperandVal == NULL)
3525 Type *type = CallOperandVal->getType();
3526 // Look at the constraint type.
3527 switch (*constraint) {
3529 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3533 if (type->isIntegerTy())
3534 weight = CW_Register;
3537 if (type->isFloatTy())
3538 weight = CW_Register;
3540 case 'c': // $25 for indirect jumps
3541 case 'l': // lo register
3542 case 'x': // hilo register pair
3543 if (type->isIntegerTy())
3544 weight = CW_SpecificReg;
3546 case 'I': // signed 16 bit immediate
3547 case 'J': // integer zero
3548 case 'K': // unsigned 16 bit immediate
3549 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3550 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3551 case 'O': // signed 15 bit immediate (+- 16383)
3552 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3553 if (isa<ConstantInt>(CallOperandVal))
3554 weight = CW_Constant;
3560 /// Given a register class constraint, like 'r', if this corresponds directly
3561 /// to an LLVM register class, return a register of 0 and the register class
3563 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3564 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3566 if (Constraint.size() == 1) {
3567 switch (Constraint[0]) {
3568 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3569 case 'y': // Same as 'r'. Exists for compatibility.
3571 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3572 if (Subtarget->inMips16Mode())
3573 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3574 return std::make_pair(0U, &Mips::CPURegsRegClass);
3576 if (VT == MVT::i64 && !HasMips64)
3577 return std::make_pair(0U, &Mips::CPURegsRegClass);
3578 if (VT == MVT::i64 && HasMips64)
3579 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3580 // This will generate an error message
3581 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3584 return std::make_pair(0U, &Mips::FGR32RegClass);
3585 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3586 if (Subtarget->isFP64bit())
3587 return std::make_pair(0U, &Mips::FGR64RegClass);
3588 return std::make_pair(0U, &Mips::AFGR64RegClass);
3591 case 'c': // register suitable for indirect jump
3593 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3594 assert(VT == MVT::i64 && "Unexpected type.");
3595 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3596 case 'l': // register suitable for indirect jump
3598 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3599 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3600 case 'x': // register suitable for indirect jump
3601 // Fixme: Not triggering the use of both hi and low
3602 // This will generate an error message
3603 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3606 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3609 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3610 /// vector. If it is invalid, don't add anything to Ops.
3611 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3612 std::string &Constraint,
3613 std::vector<SDValue>&Ops,
3614 SelectionDAG &DAG) const {
3615 SDValue Result(0, 0);
3617 // Only support length 1 constraints for now.
3618 if (Constraint.length() > 1) return;
3620 char ConstraintLetter = Constraint[0];
3621 switch (ConstraintLetter) {
3622 default: break; // This will fall through to the generic implementation
3623 case 'I': // Signed 16 bit constant
3624 // If this fails, the parent routine will give an error
3625 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3626 EVT Type = Op.getValueType();
3627 int64_t Val = C->getSExtValue();
3628 if (isInt<16>(Val)) {
3629 Result = DAG.getTargetConstant(Val, Type);
3634 case 'J': // integer zero
3635 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3636 EVT Type = Op.getValueType();
3637 int64_t Val = C->getZExtValue();
3639 Result = DAG.getTargetConstant(0, Type);
3644 case 'K': // unsigned 16 bit immediate
3645 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3646 EVT Type = Op.getValueType();
3647 uint64_t Val = (uint64_t)C->getZExtValue();
3648 if (isUInt<16>(Val)) {
3649 Result = DAG.getTargetConstant(Val, Type);
3654 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3655 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3656 EVT Type = Op.getValueType();
3657 int64_t Val = C->getSExtValue();
3658 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3659 Result = DAG.getTargetConstant(Val, Type);
3664 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3665 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3666 EVT Type = Op.getValueType();
3667 int64_t Val = C->getSExtValue();
3668 if ((Val >= -65535) && (Val <= -1)) {
3669 Result = DAG.getTargetConstant(Val, Type);
3674 case 'O': // signed 15 bit immediate
3675 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3676 EVT Type = Op.getValueType();
3677 int64_t Val = C->getSExtValue();
3678 if ((isInt<15>(Val))) {
3679 Result = DAG.getTargetConstant(Val, Type);
3684 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3685 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3686 EVT Type = Op.getValueType();
3687 int64_t Val = C->getSExtValue();
3688 if ((Val <= 65535) && (Val >= 1)) {
3689 Result = DAG.getTargetConstant(Val, Type);
3696 if (Result.getNode()) {
3697 Ops.push_back(Result);
3701 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3705 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3706 // No global is ever allowed as a base.
3711 case 0: // "r+i" or just "i", depending on HasBaseReg.
3714 if (!AM.HasBaseReg) // allow "r+i".
3716 return false; // disallow "r+r" or "r+r+i".
3725 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3726 // The Mips target isn't yet aware of offsets.
3730 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3732 bool IsMemset, bool ZeroMemset,
3734 MachineFunction &MF) const {
3735 if (Subtarget->hasMips64())
3741 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3742 if (VT != MVT::f32 && VT != MVT::f64)
3744 if (Imm.isNegZero())
3746 return Imm.isZero();
3749 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3751 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3753 return TargetLowering::getJumpTableEncoding();
3756 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CallConv, bool IsVarArg,
3757 bool IsO32, CCState &Info) : CCInfo(Info) {
3758 UseRegsForByval = true;
3762 NumIntArgRegs = array_lengthof(O32IntRegs);
3763 ReservedArgArea = 16;
3764 IntArgRegs = ShadowRegs = O32IntRegs;
3765 FixedFn = VarFn = CC_MipsO32;
3768 NumIntArgRegs = array_lengthof(Mips64IntRegs);
3769 ReservedArgArea = 0;
3770 IntArgRegs = Mips64IntRegs;
3771 ShadowRegs = Mips64DPRegs;
3773 VarFn = CC_MipsN_VarArg;
3776 if (CallConv == CallingConv::Fast) {
3778 UseRegsForByval = false;
3779 ReservedArgArea = 0;
3780 FixedFn = VarFn = CC_Mips_FastCC;
3783 // Pre-allocate reserved argument area.
3784 CCInfo.AllocateStack(ReservedArgArea, 1);
3787 void MipsTargetLowering::MipsCC::
3788 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args) {
3789 unsigned NumOpnds = Args.size();
3791 for (unsigned I = 0; I != NumOpnds; ++I) {
3792 MVT ArgVT = Args[I].VT;
3793 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3796 if (ArgFlags.isByVal()) {
3797 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3801 if (Args[I].IsFixed)
3802 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3804 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3808 dbgs() << "Call operand #" << I << " has unhandled type "
3809 << EVT(ArgVT).getEVTString();
3811 llvm_unreachable(0);
3816 void MipsTargetLowering::MipsCC::
3817 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
3818 unsigned NumArgs = Args.size();
3820 for (unsigned I = 0; I != NumArgs; ++I) {
3821 MVT ArgVT = Args[I].VT;
3822 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3824 if (ArgFlags.isByVal()) {
3825 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3829 if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
3833 dbgs() << "Formal Arg #" << I << " has unhandled type "
3834 << EVT(ArgVT).getEVTString();
3836 llvm_unreachable(0);
3841 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3843 CCValAssign::LocInfo LocInfo,
3844 ISD::ArgFlagsTy ArgFlags) {
3845 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3847 struct ByValArgInfo ByVal;
3848 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3849 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3852 if (UseRegsForByval)
3853 allocateRegs(ByVal, ByValSize, Align);
3855 // Allocate space on caller's stack.
3856 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3858 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3860 ByValArgs.push_back(ByVal);
3863 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3866 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3867 "Byval argument's size and alignment should be a multiple of"
3870 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3872 // If Align > RegSize, the first arg register must be even.
3873 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3874 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3878 // Mark the registers allocated.
3879 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3880 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3881 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3884 void MipsTargetLowering::
3885 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3886 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3887 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3888 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3889 MachineFunction &MF = DAG.getMachineFunction();
3890 MachineFrameInfo *MFI = MF.getFrameInfo();
3891 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3892 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3896 FrameObjOffset = (int)CC.reservedArgArea() -
3897 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3899 FrameObjOffset = ByVal.Address;
3901 // Create frame object.
3902 EVT PtrTy = getPointerTy();
3903 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3904 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3905 InVals.push_back(FIN);
3910 // Copy arg registers.
3911 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3912 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3914 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3915 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3916 unsigned VReg = AddLiveIn(MF, ArgReg, RC);
3917 unsigned Offset = I * CC.regSize();
3918 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3919 DAG.getConstant(Offset, PtrTy));
3920 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3921 StorePtr, MachinePointerInfo(FuncArg, Offset),
3923 OutChains.push_back(Store);
3927 // Copy byVal arg to registers and stack.
3928 void MipsTargetLowering::
3929 passByValArg(SDValue Chain, DebugLoc DL,
3930 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3931 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3932 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3933 const MipsCC &CC, const ByValArgInfo &ByVal,
3934 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3935 unsigned ByValSize = Flags.getByValSize();
3936 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3937 unsigned RegSize = CC.regSize();
3938 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3939 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3941 if (ByVal.NumRegs) {
3942 const uint16_t *ArgRegs = CC.intArgRegs();
3943 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3946 // Copy words to registers.
3947 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3948 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3949 DAG.getConstant(Offset, PtrTy));
3950 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3951 MachinePointerInfo(), false, false, false,
3953 MemOpChains.push_back(LoadVal.getValue(1));
3954 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3955 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3958 // Return if the struct has been fully copied.
3959 if (ByValSize == Offset)
3962 // Copy the remainder of the byval argument with sub-word loads and shifts.
3963 if (LeftoverBytes) {
3964 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3965 "Size of the remainder should be smaller than RegSize.");
3968 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3969 Offset < ByValSize; LoadSize /= 2) {
3970 unsigned RemSize = ByValSize - Offset;
3972 if (RemSize < LoadSize)
3976 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3977 DAG.getConstant(Offset, PtrTy));
3979 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3980 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3981 false, false, Alignment);
3982 MemOpChains.push_back(LoadVal.getValue(1));
3984 // Shift the loaded value.
3988 Shamt = TotalSizeLoaded;
3990 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3992 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3993 DAG.getConstant(Shamt, MVT::i32));
3996 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4001 TotalSizeLoaded += LoadSize;
4002 Alignment = std::min(Alignment, LoadSize);
4005 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4006 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4011 // Copy remainder of byval arg to it with memcpy.
4012 unsigned MemCpySize = ByValSize - Offset;
4013 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4014 DAG.getConstant(Offset, PtrTy));
4015 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4016 DAG.getIntPtrConstant(ByVal.Address));
4017 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4018 DAG.getConstant(MemCpySize, PtrTy), Alignment,
4019 /*isVolatile=*/false, /*AlwaysInline=*/false,
4020 MachinePointerInfo(0), MachinePointerInfo(0));
4021 MemOpChains.push_back(Chain);
4025 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4026 const MipsCC &CC, SDValue Chain,
4027 DebugLoc DL, SelectionDAG &DAG) const {
4028 unsigned NumRegs = CC.numIntArgRegs();
4029 const uint16_t *ArgRegs = CC.intArgRegs();
4030 const CCState &CCInfo = CC.getCCInfo();
4031 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4032 unsigned RegSize = CC.regSize();
4033 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4034 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4035 MachineFunction &MF = DAG.getMachineFunction();
4036 MachineFrameInfo *MFI = MF.getFrameInfo();
4037 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4039 // Offset of the first variable argument from stack pointer.
4043 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4046 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4048 // Record the frame index of the first variable argument
4049 // which is a value necessary to VASTART.
4050 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4051 MipsFI->setVarArgsFrameIndex(FI);
4053 // Copy the integer registers that have not been used for argument passing
4054 // to the argument register save area. For O32, the save area is allocated
4055 // in the caller's stack frame, while for N32/64, it is allocated in the
4056 // callee's stack frame.
4057 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4058 unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
4059 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4060 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4061 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4062 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4063 MachinePointerInfo(), false, false, 0);
4064 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4065 OutChains.push_back(Store);