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::setMips16HardFloatLibCalls() {
226 setLibcallName(RTLIB::ADD_F32, addToNoHelperNeeded("__mips16_addsf3"));
227 setLibcallName(RTLIB::ADD_F64, addToNoHelperNeeded("__mips16_adddf3"));
228 setLibcallName(RTLIB::SUB_F32, addToNoHelperNeeded("__mips16_subsf3"));
229 setLibcallName(RTLIB::SUB_F64, addToNoHelperNeeded("__mips16_subdf3"));
230 setLibcallName(RTLIB::MUL_F32, addToNoHelperNeeded("__mips16_mulsf3"));
231 setLibcallName(RTLIB::MUL_F64, addToNoHelperNeeded("__mips16_muldf3"));
232 setLibcallName(RTLIB::DIV_F32, addToNoHelperNeeded("__mips16_divsf3"));
233 setLibcallName(RTLIB::DIV_F64, addToNoHelperNeeded("__mips16_divdf3"));
234 setLibcallName(RTLIB::FPEXT_F32_F64,
235 addToNoHelperNeeded("__mips16_extendsfdf2"));
236 setLibcallName(RTLIB::FPROUND_F64_F32,
237 addToNoHelperNeeded("__mips16_truncdfsf2"));
238 setLibcallName(RTLIB::FPTOSINT_F32_I32,
239 addToNoHelperNeeded("__mips16_fix_truncsfsi"));
240 setLibcallName(RTLIB::FPTOSINT_F64_I32,
241 addToNoHelperNeeded("__mips16_fix_truncdfsi"));
242 setLibcallName(RTLIB::SINTTOFP_I32_F32,
243 addToNoHelperNeeded("__mips16_floatsisf"));
244 setLibcallName(RTLIB::SINTTOFP_I32_F64,
245 addToNoHelperNeeded("__mips16_floatsidf"));
246 setLibcallName(RTLIB::UINTTOFP_I32_F32,
247 addToNoHelperNeeded("__mips16_floatunsisf"));
248 setLibcallName(RTLIB::UINTTOFP_I32_F64,
249 addToNoHelperNeeded("__mips16_floatunsidf"));
250 setLibcallName(RTLIB::OEQ_F32, addToNoHelperNeeded("__mips16_eqsf2"));
251 setLibcallName(RTLIB::OEQ_F64, addToNoHelperNeeded("__mips16_eqdf2"));
252 setLibcallName(RTLIB::UNE_F32, addToNoHelperNeeded("__mips16_nesf2"));
253 setLibcallName(RTLIB::UNE_F64, addToNoHelperNeeded("__mips16_nedf2"));
254 setLibcallName(RTLIB::OGE_F32, addToNoHelperNeeded("__mips16_gesf2"));
255 setLibcallName(RTLIB::OGE_F64, addToNoHelperNeeded("__mips16_gedf2"));
256 setLibcallName(RTLIB::OLT_F32, addToNoHelperNeeded("__mips16_ltsf2"));
257 setLibcallName(RTLIB::OLT_F64, addToNoHelperNeeded("__mips16_ltdf2"));
258 setLibcallName(RTLIB::OLE_F32, addToNoHelperNeeded("__mips16_lesf2"));
259 setLibcallName(RTLIB::OLE_F64, addToNoHelperNeeded("__mips16_ledf2"));
260 setLibcallName(RTLIB::OGT_F32, addToNoHelperNeeded("__mips16_gtsf2"));
261 setLibcallName(RTLIB::OGT_F64, addToNoHelperNeeded("__mips16_gtdf2"));
262 setLibcallName(RTLIB::UO_F32, addToNoHelperNeeded("__mips16_unordsf2"));
263 setLibcallName(RTLIB::UO_F64, addToNoHelperNeeded("__mips16_unorddf2"));
264 setLibcallName(RTLIB::O_F32, addToNoHelperNeeded("__mips16_unordsf2"));
265 setLibcallName(RTLIB::O_F64, addToNoHelperNeeded("__mips16_unorddf2"));
269 MipsTargetLowering(MipsTargetMachine &TM)
270 : TargetLowering(TM, new MipsTargetObjectFile()),
271 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
272 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
273 IsO32(Subtarget->isABI_O32()) {
275 // Mips does not have i1 type, so use i32 for
276 // setcc operations results (slt, sgt, ...).
277 setBooleanContents(ZeroOrOneBooleanContent);
278 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
280 // Set up the register classes
281 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
284 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
286 if (Subtarget->inMips16Mode()) {
287 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
289 setMips16HardFloatLibCalls();
292 if (Subtarget->hasDSP()) {
293 MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
295 for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
296 addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
298 // Expand all builtin opcodes.
299 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
300 setOperationAction(Opc, VecTys[i], Expand);
302 setOperationAction(ISD::LOAD, VecTys[i], Legal);
303 setOperationAction(ISD::STORE, VecTys[i], Legal);
304 setOperationAction(ISD::BITCAST, VecTys[i], Legal);
308 if (!TM.Options.UseSoftFloat) {
309 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
311 // When dealing with single precision only, use libcalls
312 if (!Subtarget->isSingleFloat()) {
314 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
316 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
320 // Load extented operations for i1 types must be promoted
321 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
322 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
323 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
325 // MIPS doesn't have extending float->double load/store
326 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
327 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
329 // Used by legalize types to correctly generate the setcc result.
330 // Without this, every float setcc comes with a AND/OR with the result,
331 // we don't want this, since the fpcmp result goes to a flag register,
332 // which is used implicitly by brcond and select operations.
333 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
335 // Mips Custom Operations
336 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
337 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
338 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
339 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
340 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
341 setOperationAction(ISD::SELECT, MVT::f32, Custom);
342 setOperationAction(ISD::SELECT, MVT::f64, Custom);
343 setOperationAction(ISD::SELECT, MVT::i32, Custom);
344 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
345 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
346 setOperationAction(ISD::SETCC, MVT::f32, Custom);
347 setOperationAction(ISD::SETCC, MVT::f64, Custom);
348 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
349 setOperationAction(ISD::VASTART, MVT::Other, Custom);
350 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
351 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
352 if (Subtarget->inMips16Mode()) {
353 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
354 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
357 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
358 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
360 if (!Subtarget->inMips16Mode()) {
361 setOperationAction(ISD::LOAD, MVT::i32, Custom);
362 setOperationAction(ISD::STORE, MVT::i32, Custom);
365 if (!TM.Options.NoNaNsFPMath) {
366 setOperationAction(ISD::FABS, MVT::f32, Custom);
367 setOperationAction(ISD::FABS, MVT::f64, Custom);
371 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
372 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
373 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
374 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
375 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
376 setOperationAction(ISD::SELECT, MVT::i64, Custom);
377 setOperationAction(ISD::LOAD, MVT::i64, Custom);
378 setOperationAction(ISD::STORE, MVT::i64, Custom);
382 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
383 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
384 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
387 setOperationAction(ISD::ADD, MVT::i32, Custom);
389 setOperationAction(ISD::ADD, MVT::i64, Custom);
391 setOperationAction(ISD::SDIV, MVT::i32, Expand);
392 setOperationAction(ISD::SREM, MVT::i32, Expand);
393 setOperationAction(ISD::UDIV, MVT::i32, Expand);
394 setOperationAction(ISD::UREM, MVT::i32, Expand);
395 setOperationAction(ISD::SDIV, MVT::i64, Expand);
396 setOperationAction(ISD::SREM, MVT::i64, Expand);
397 setOperationAction(ISD::UDIV, MVT::i64, Expand);
398 setOperationAction(ISD::UREM, MVT::i64, Expand);
400 // Operations not directly supported by Mips.
401 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
402 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
403 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
404 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
405 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
406 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
407 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
408 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
409 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
410 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
411 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
412 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
413 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
414 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
416 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
417 setOperationAction(ISD::ROTL, MVT::i32, Expand);
418 setOperationAction(ISD::ROTL, MVT::i64, Expand);
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
420 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
422 if (!Subtarget->hasMips32r2())
423 setOperationAction(ISD::ROTR, MVT::i32, Expand);
425 if (!Subtarget->hasMips64r2())
426 setOperationAction(ISD::ROTR, MVT::i64, Expand);
428 setOperationAction(ISD::FSIN, MVT::f32, Expand);
429 setOperationAction(ISD::FSIN, MVT::f64, Expand);
430 setOperationAction(ISD::FCOS, MVT::f32, Expand);
431 setOperationAction(ISD::FCOS, MVT::f64, Expand);
432 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
433 setOperationAction(ISD::FPOW, MVT::f32, Expand);
434 setOperationAction(ISD::FPOW, MVT::f64, Expand);
435 setOperationAction(ISD::FLOG, MVT::f32, Expand);
436 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
437 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
438 setOperationAction(ISD::FEXP, MVT::f32, Expand);
439 setOperationAction(ISD::FMA, MVT::f32, Expand);
440 setOperationAction(ISD::FMA, MVT::f64, Expand);
441 setOperationAction(ISD::FREM, MVT::f32, Expand);
442 setOperationAction(ISD::FREM, MVT::f64, Expand);
444 if (!TM.Options.NoNaNsFPMath) {
445 setOperationAction(ISD::FNEG, MVT::f32, Expand);
446 setOperationAction(ISD::FNEG, MVT::f64, Expand);
449 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
450 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
451 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
452 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
454 setOperationAction(ISD::VAARG, MVT::Other, Expand);
455 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
456 setOperationAction(ISD::VAEND, MVT::Other, Expand);
458 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
459 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
461 // Use the default for now
462 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
463 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
465 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
466 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
467 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
468 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
470 if (Subtarget->inMips16Mode()) {
471 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
472 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
473 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
474 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
475 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
476 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
477 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
478 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
479 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
480 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
481 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
482 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
485 setInsertFencesForAtomic(true);
487 if (!Subtarget->hasSEInReg()) {
488 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
489 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
492 if (!Subtarget->hasBitCount()) {
493 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
494 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
497 if (!Subtarget->hasSwap()) {
498 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
499 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
503 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
504 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
505 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
506 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
509 setTargetDAGCombine(ISD::ADDE);
510 setTargetDAGCombine(ISD::SUBE);
511 setTargetDAGCombine(ISD::SDIVREM);
512 setTargetDAGCombine(ISD::UDIVREM);
513 setTargetDAGCombine(ISD::SELECT);
514 setTargetDAGCombine(ISD::AND);
515 setTargetDAGCombine(ISD::OR);
516 setTargetDAGCombine(ISD::ADD);
518 setMinFunctionAlignment(HasMips64 ? 3 : 2);
520 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
521 computeRegisterProperties();
523 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
524 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
526 maxStoresPerMemcpy = 16;
530 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
531 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
533 if (Subtarget->inMips16Mode())
547 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
550 return VT.changeVectorElementTypeToInteger();
554 // Transforms a subgraph in CurDAG if the following pattern is found:
555 // (addc multLo, Lo0), (adde multHi, Hi0),
557 // multHi/Lo: product of multiplication
558 // Lo0: initial value of Lo register
559 // Hi0: initial value of Hi register
560 // Return true if pattern matching was successful.
561 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
562 // ADDENode's second operand must be a flag output of an ADDC node in order
563 // for the matching to be successful.
564 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
566 if (ADDCNode->getOpcode() != ISD::ADDC)
569 SDValue MultHi = ADDENode->getOperand(0);
570 SDValue MultLo = ADDCNode->getOperand(0);
571 SDNode *MultNode = MultHi.getNode();
572 unsigned MultOpc = MultHi.getOpcode();
574 // MultHi and MultLo must be generated by the same node,
575 if (MultLo.getNode() != MultNode)
578 // and it must be a multiplication.
579 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
582 // MultLo amd MultHi must be the first and second output of MultNode
584 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
587 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
588 // of the values of MultNode, in which case MultNode will be removed in later
590 // If there exist users other than ADDENode or ADDCNode, this function returns
591 // here, which will result in MultNode being mapped to a single MULT
592 // instruction node rather than a pair of MULT and MADD instructions being
594 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
597 SDValue Chain = CurDAG->getEntryNode();
598 DebugLoc dl = ADDENode->getDebugLoc();
600 // create MipsMAdd(u) node
601 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
603 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
604 MultNode->getOperand(0),// Factor 0
605 MultNode->getOperand(1),// Factor 1
606 ADDCNode->getOperand(1),// Lo0
607 ADDENode->getOperand(1));// Hi0
609 // create CopyFromReg nodes
610 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
612 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
614 CopyFromLo.getValue(2));
616 // replace uses of adde and addc here
617 if (!SDValue(ADDCNode, 0).use_empty())
618 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
620 if (!SDValue(ADDENode, 0).use_empty())
621 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
627 // Transforms a subgraph in CurDAG if the following pattern is found:
628 // (addc Lo0, multLo), (sube Hi0, multHi),
630 // multHi/Lo: product of multiplication
631 // Lo0: initial value of Lo register
632 // Hi0: initial value of Hi register
633 // Return true if pattern matching was successful.
634 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
635 // SUBENode's second operand must be a flag output of an SUBC node in order
636 // for the matching to be successful.
637 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
639 if (SUBCNode->getOpcode() != ISD::SUBC)
642 SDValue MultHi = SUBENode->getOperand(1);
643 SDValue MultLo = SUBCNode->getOperand(1);
644 SDNode *MultNode = MultHi.getNode();
645 unsigned MultOpc = MultHi.getOpcode();
647 // MultHi and MultLo must be generated by the same node,
648 if (MultLo.getNode() != MultNode)
651 // and it must be a multiplication.
652 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
655 // MultLo amd MultHi must be the first and second output of MultNode
657 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
660 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
661 // of the values of MultNode, in which case MultNode will be removed in later
663 // If there exist users other than SUBENode or SUBCNode, this function returns
664 // here, which will result in MultNode being mapped to a single MULT
665 // instruction node rather than a pair of MULT and MSUB instructions being
667 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
670 SDValue Chain = CurDAG->getEntryNode();
671 DebugLoc dl = SUBENode->getDebugLoc();
673 // create MipsSub(u) node
674 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
676 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
677 MultNode->getOperand(0),// Factor 0
678 MultNode->getOperand(1),// Factor 1
679 SUBCNode->getOperand(0),// Lo0
680 SUBENode->getOperand(0));// Hi0
682 // create CopyFromReg nodes
683 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
685 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
687 CopyFromLo.getValue(2));
689 // replace uses of sube and subc here
690 if (!SDValue(SUBCNode, 0).use_empty())
691 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
693 if (!SDValue(SUBENode, 0).use_empty())
694 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
699 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
700 TargetLowering::DAGCombinerInfo &DCI,
701 const MipsSubtarget *Subtarget) {
702 if (DCI.isBeforeLegalize())
705 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
707 return SDValue(N, 0);
712 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
713 TargetLowering::DAGCombinerInfo &DCI,
714 const MipsSubtarget *Subtarget) {
715 if (DCI.isBeforeLegalize())
718 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
720 return SDValue(N, 0);
725 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
726 TargetLowering::DAGCombinerInfo &DCI,
727 const MipsSubtarget *Subtarget) {
728 if (DCI.isBeforeLegalizeOps())
731 EVT Ty = N->getValueType(0);
732 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
733 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
734 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
736 DebugLoc dl = N->getDebugLoc();
738 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
739 N->getOperand(0), N->getOperand(1));
740 SDValue InChain = DAG.getEntryNode();
741 SDValue InGlue = DivRem;
744 if (N->hasAnyUseOfValue(0)) {
745 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
747 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
748 InChain = CopyFromLo.getValue(1);
749 InGlue = CopyFromLo.getValue(2);
753 if (N->hasAnyUseOfValue(1)) {
754 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
756 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
762 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
764 default: llvm_unreachable("Unknown fp condition code!");
766 case ISD::SETOEQ: return Mips::FCOND_OEQ;
767 case ISD::SETUNE: return Mips::FCOND_UNE;
769 case ISD::SETOLT: return Mips::FCOND_OLT;
771 case ISD::SETOGT: return Mips::FCOND_OGT;
773 case ISD::SETOLE: return Mips::FCOND_OLE;
775 case ISD::SETOGE: return Mips::FCOND_OGE;
776 case ISD::SETULT: return Mips::FCOND_ULT;
777 case ISD::SETULE: return Mips::FCOND_ULE;
778 case ISD::SETUGT: return Mips::FCOND_UGT;
779 case ISD::SETUGE: return Mips::FCOND_UGE;
780 case ISD::SETUO: return Mips::FCOND_UN;
781 case ISD::SETO: return Mips::FCOND_OR;
783 case ISD::SETONE: return Mips::FCOND_ONE;
784 case ISD::SETUEQ: return Mips::FCOND_UEQ;
789 // Returns true if condition code has to be inverted.
790 static bool InvertFPCondCode(Mips::CondCode CC) {
791 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
794 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
795 "Illegal Condition Code");
800 // Creates and returns an FPCmp node from a setcc node.
801 // Returns Op if setcc is not a floating point comparison.
802 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
803 // must be a SETCC node
804 if (Op.getOpcode() != ISD::SETCC)
807 SDValue LHS = Op.getOperand(0);
809 if (!LHS.getValueType().isFloatingPoint())
812 SDValue RHS = Op.getOperand(1);
813 DebugLoc dl = Op.getDebugLoc();
815 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
816 // node if necessary.
817 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
819 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
820 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
823 // Creates and returns a CMovFPT/F node.
824 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
825 SDValue False, DebugLoc DL) {
826 bool invert = InvertFPCondCode((Mips::CondCode)
827 cast<ConstantSDNode>(Cond.getOperand(2))
830 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
831 True.getValueType(), True, False, Cond);
834 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
835 TargetLowering::DAGCombinerInfo &DCI,
836 const MipsSubtarget *Subtarget) {
837 if (DCI.isBeforeLegalizeOps())
840 SDValue SetCC = N->getOperand(0);
842 if ((SetCC.getOpcode() != ISD::SETCC) ||
843 !SetCC.getOperand(0).getValueType().isInteger())
846 SDValue False = N->getOperand(2);
847 EVT FalseTy = False.getValueType();
849 if (!FalseTy.isInteger())
852 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
854 if (!CN || CN->getZExtValue())
857 const DebugLoc DL = N->getDebugLoc();
858 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
859 SDValue True = N->getOperand(1);
861 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
862 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
864 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
867 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
868 TargetLowering::DAGCombinerInfo &DCI,
869 const MipsSubtarget *Subtarget) {
870 // Pattern match EXT.
871 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
872 // => ext $dst, $src, size, pos
873 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
876 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
877 unsigned ShiftRightOpc = ShiftRight.getOpcode();
879 // Op's first operand must be a shift right.
880 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
883 // The second operand of the shift must be an immediate.
885 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
888 uint64_t Pos = CN->getZExtValue();
889 uint64_t SMPos, SMSize;
891 // Op's second operand must be a shifted mask.
892 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
893 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
896 // Return if the shifted mask does not start at bit 0 or the sum of its size
897 // and Pos exceeds the word's size.
898 EVT ValTy = N->getValueType(0);
899 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
902 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
903 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
904 DAG.getConstant(SMSize, MVT::i32));
907 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
908 TargetLowering::DAGCombinerInfo &DCI,
909 const MipsSubtarget *Subtarget) {
910 // Pattern match INS.
911 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
912 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
913 // => ins $dst, $src, size, pos, $src1
914 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
917 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
918 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
921 // See if Op's first operand matches (and $src1 , mask0).
922 if (And0.getOpcode() != ISD::AND)
925 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
926 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
929 // See if Op's second operand matches (and (shl $src, pos), mask1).
930 if (And1.getOpcode() != ISD::AND)
933 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
934 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
937 // The shift masks must have the same position and size.
938 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
941 SDValue Shl = And1.getOperand(0);
942 if (Shl.getOpcode() != ISD::SHL)
945 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
948 unsigned Shamt = CN->getZExtValue();
950 // Return if the shift amount and the first bit position of mask are not the
952 EVT ValTy = N->getValueType(0);
953 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
956 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
957 DAG.getConstant(SMPos0, MVT::i32),
958 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
961 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
962 TargetLowering::DAGCombinerInfo &DCI,
963 const MipsSubtarget *Subtarget) {
964 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
966 if (DCI.isBeforeLegalizeOps())
969 SDValue Add = N->getOperand(1);
971 if (Add.getOpcode() != ISD::ADD)
974 SDValue Lo = Add.getOperand(1);
976 if ((Lo.getOpcode() != MipsISD::Lo) ||
977 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
980 EVT ValTy = N->getValueType(0);
981 DebugLoc DL = N->getDebugLoc();
983 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
985 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
988 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
990 SelectionDAG &DAG = DCI.DAG;
991 unsigned opc = N->getOpcode();
996 return PerformADDECombine(N, DAG, DCI, Subtarget);
998 return PerformSUBECombine(N, DAG, DCI, Subtarget);
1001 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
1003 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
1005 return PerformANDCombine(N, DAG, DCI, Subtarget);
1007 return PerformORCombine(N, DAG, DCI, Subtarget);
1009 return PerformADDCombine(N, DAG, DCI, Subtarget);
1016 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1017 SmallVectorImpl<SDValue> &Results,
1018 SelectionDAG &DAG) const {
1019 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1021 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1022 Results.push_back(Res.getValue(I));
1026 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1027 SmallVectorImpl<SDValue> &Results,
1028 SelectionDAG &DAG) const {
1029 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1031 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1032 Results.push_back(Res.getValue(I));
1035 SDValue MipsTargetLowering::
1036 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1038 switch (Op.getOpcode())
1040 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1041 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
1042 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
1043 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
1044 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
1045 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
1046 case ISD::SELECT: return LowerSELECT(Op, DAG);
1047 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
1048 case ISD::SETCC: return LowerSETCC(Op, DAG);
1049 case ISD::VASTART: return LowerVASTART(Op, DAG);
1050 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
1051 case ISD::FABS: return LowerFABS(Op, DAG);
1052 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
1053 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
1054 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
1055 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
1056 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
1057 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
1058 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
1059 case ISD::LOAD: return LowerLOAD(Op, DAG);
1060 case ISD::STORE: return LowerSTORE(Op, DAG);
1061 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1062 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1063 case ISD::ADD: return LowerADD(Op, DAG);
1068 //===----------------------------------------------------------------------===//
1069 // Lower helper functions
1070 //===----------------------------------------------------------------------===//
1072 // AddLiveIn - This helper function adds the specified physical register to the
1073 // MachineFunction as a live in value. It also creates a corresponding
1074 // virtual register for it.
1076 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1078 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1079 MF.getRegInfo().addLiveIn(PReg, VReg);
1083 // Get fp branch code (not opcode) from condition code.
1084 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1085 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1086 return Mips::BRANCH_T;
1088 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1089 "Invalid CondCode.");
1091 return Mips::BRANCH_F;
1095 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1097 const MipsSubtarget *Subtarget,
1098 const TargetInstrInfo *TII,
1099 bool isFPCmp, unsigned Opc) {
1100 // There is no need to expand CMov instructions if target has
1101 // conditional moves.
1102 if (Subtarget->hasCondMov())
1105 // To "insert" a SELECT_CC instruction, we actually have to insert the
1106 // diamond control-flow pattern. The incoming instruction knows the
1107 // destination vreg to set, the condition code register to branch on, the
1108 // true/false values to select between, and a branch opcode to use.
1109 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1110 MachineFunction::iterator It = BB;
1117 // bNE r1, r0, copy1MBB
1118 // fallthrough --> copy0MBB
1119 MachineBasicBlock *thisMBB = BB;
1120 MachineFunction *F = BB->getParent();
1121 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1122 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1123 F->insert(It, copy0MBB);
1124 F->insert(It, sinkMBB);
1126 // Transfer the remainder of BB and its successor edges to sinkMBB.
1127 sinkMBB->splice(sinkMBB->begin(), BB,
1128 llvm::next(MachineBasicBlock::iterator(MI)),
1130 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1132 // Next, add the true and fallthrough blocks as its successors.
1133 BB->addSuccessor(copy0MBB);
1134 BB->addSuccessor(sinkMBB);
1136 // Emit the right instruction according to the type of the operands compared
1138 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1140 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1141 .addReg(Mips::ZERO).addMBB(sinkMBB);
1144 // %FalseValue = ...
1145 // # fallthrough to sinkMBB
1148 // Update machine-CFG edges
1149 BB->addSuccessor(sinkMBB);
1152 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1157 BuildMI(*BB, BB->begin(), dl,
1158 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1159 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1160 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1162 BuildMI(*BB, BB->begin(), dl,
1163 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1164 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1165 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1167 MI->eraseFromParent(); // The pseudo instruction is gone now.
1173 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1175 // bposge32_pseudo $vr0
1185 // $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1187 MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1188 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1189 const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1190 DebugLoc DL = MI->getDebugLoc();
1191 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1192 MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1193 MachineFunction *F = BB->getParent();
1194 MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1195 MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1196 MachineBasicBlock *Sink = F->CreateMachineBasicBlock(LLVM_BB);
1199 F->insert(It, Sink);
1201 // Transfer the remainder of BB and its successor edges to Sink.
1202 Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1204 Sink->transferSuccessorsAndUpdatePHIs(BB);
1207 BB->addSuccessor(FBB);
1208 BB->addSuccessor(TBB);
1209 FBB->addSuccessor(Sink);
1210 TBB->addSuccessor(Sink);
1212 // Insert the real bposge32 instruction to $BB.
1213 BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1216 unsigned VR2 = RegInfo.createVirtualRegister(RC);
1217 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1218 .addReg(Mips::ZERO).addImm(0);
1219 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1222 unsigned VR1 = RegInfo.createVirtualRegister(RC);
1223 BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1224 .addReg(Mips::ZERO).addImm(1);
1226 // Insert phi function to $Sink.
1227 BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1228 MI->getOperand(0).getReg())
1229 .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1231 MI->eraseFromParent(); // The pseudo instruction is gone now.
1236 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1237 MachineBasicBlock *BB) const {
1238 switch (MI->getOpcode()) {
1239 default: llvm_unreachable("Unexpected instr type to insert");
1240 case Mips::ATOMIC_LOAD_ADD_I8:
1241 case Mips::ATOMIC_LOAD_ADD_I8_P8:
1242 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1243 case Mips::ATOMIC_LOAD_ADD_I16:
1244 case Mips::ATOMIC_LOAD_ADD_I16_P8:
1245 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1246 case Mips::ATOMIC_LOAD_ADD_I32:
1247 case Mips::ATOMIC_LOAD_ADD_I32_P8:
1248 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1249 case Mips::ATOMIC_LOAD_ADD_I64:
1250 case Mips::ATOMIC_LOAD_ADD_I64_P8:
1251 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1253 case Mips::ATOMIC_LOAD_AND_I8:
1254 case Mips::ATOMIC_LOAD_AND_I8_P8:
1255 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1256 case Mips::ATOMIC_LOAD_AND_I16:
1257 case Mips::ATOMIC_LOAD_AND_I16_P8:
1258 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1259 case Mips::ATOMIC_LOAD_AND_I32:
1260 case Mips::ATOMIC_LOAD_AND_I32_P8:
1261 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1262 case Mips::ATOMIC_LOAD_AND_I64:
1263 case Mips::ATOMIC_LOAD_AND_I64_P8:
1264 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1266 case Mips::ATOMIC_LOAD_OR_I8:
1267 case Mips::ATOMIC_LOAD_OR_I8_P8:
1268 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1269 case Mips::ATOMIC_LOAD_OR_I16:
1270 case Mips::ATOMIC_LOAD_OR_I16_P8:
1271 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1272 case Mips::ATOMIC_LOAD_OR_I32:
1273 case Mips::ATOMIC_LOAD_OR_I32_P8:
1274 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1275 case Mips::ATOMIC_LOAD_OR_I64:
1276 case Mips::ATOMIC_LOAD_OR_I64_P8:
1277 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1279 case Mips::ATOMIC_LOAD_XOR_I8:
1280 case Mips::ATOMIC_LOAD_XOR_I8_P8:
1281 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1282 case Mips::ATOMIC_LOAD_XOR_I16:
1283 case Mips::ATOMIC_LOAD_XOR_I16_P8:
1284 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1285 case Mips::ATOMIC_LOAD_XOR_I32:
1286 case Mips::ATOMIC_LOAD_XOR_I32_P8:
1287 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1288 case Mips::ATOMIC_LOAD_XOR_I64:
1289 case Mips::ATOMIC_LOAD_XOR_I64_P8:
1290 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1292 case Mips::ATOMIC_LOAD_NAND_I8:
1293 case Mips::ATOMIC_LOAD_NAND_I8_P8:
1294 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1295 case Mips::ATOMIC_LOAD_NAND_I16:
1296 case Mips::ATOMIC_LOAD_NAND_I16_P8:
1297 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1298 case Mips::ATOMIC_LOAD_NAND_I32:
1299 case Mips::ATOMIC_LOAD_NAND_I32_P8:
1300 return EmitAtomicBinary(MI, BB, 4, 0, true);
1301 case Mips::ATOMIC_LOAD_NAND_I64:
1302 case Mips::ATOMIC_LOAD_NAND_I64_P8:
1303 return EmitAtomicBinary(MI, BB, 8, 0, true);
1305 case Mips::ATOMIC_LOAD_SUB_I8:
1306 case Mips::ATOMIC_LOAD_SUB_I8_P8:
1307 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1308 case Mips::ATOMIC_LOAD_SUB_I16:
1309 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1310 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1311 case Mips::ATOMIC_LOAD_SUB_I32:
1312 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1313 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1314 case Mips::ATOMIC_LOAD_SUB_I64:
1315 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1316 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1318 case Mips::ATOMIC_SWAP_I8:
1319 case Mips::ATOMIC_SWAP_I8_P8:
1320 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1321 case Mips::ATOMIC_SWAP_I16:
1322 case Mips::ATOMIC_SWAP_I16_P8:
1323 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1324 case Mips::ATOMIC_SWAP_I32:
1325 case Mips::ATOMIC_SWAP_I32_P8:
1326 return EmitAtomicBinary(MI, BB, 4, 0);
1327 case Mips::ATOMIC_SWAP_I64:
1328 case Mips::ATOMIC_SWAP_I64_P8:
1329 return EmitAtomicBinary(MI, BB, 8, 0);
1331 case Mips::ATOMIC_CMP_SWAP_I8:
1332 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1333 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1334 case Mips::ATOMIC_CMP_SWAP_I16:
1335 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1336 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1337 case Mips::ATOMIC_CMP_SWAP_I32:
1338 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1339 return EmitAtomicCmpSwap(MI, BB, 4);
1340 case Mips::ATOMIC_CMP_SWAP_I64:
1341 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1342 return EmitAtomicCmpSwap(MI, BB, 8);
1343 case Mips::BPOSGE32_PSEUDO:
1344 return EmitBPOSGE32(MI, BB);
1348 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1349 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1351 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1352 unsigned Size, unsigned BinOpcode,
1354 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1356 MachineFunction *MF = BB->getParent();
1357 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1358 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1359 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1360 DebugLoc dl = MI->getDebugLoc();
1361 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1364 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1365 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1372 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1373 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1376 ZERO = Mips::ZERO_64;
1380 unsigned OldVal = MI->getOperand(0).getReg();
1381 unsigned Ptr = MI->getOperand(1).getReg();
1382 unsigned Incr = MI->getOperand(2).getReg();
1384 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1385 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1386 unsigned Success = RegInfo.createVirtualRegister(RC);
1388 // insert new blocks after the current block
1389 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1390 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1391 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1392 MachineFunction::iterator It = BB;
1394 MF->insert(It, loopMBB);
1395 MF->insert(It, exitMBB);
1397 // Transfer the remainder of BB and its successor edges to exitMBB.
1398 exitMBB->splice(exitMBB->begin(), BB,
1399 llvm::next(MachineBasicBlock::iterator(MI)),
1401 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1405 // fallthrough --> loopMBB
1406 BB->addSuccessor(loopMBB);
1407 loopMBB->addSuccessor(loopMBB);
1408 loopMBB->addSuccessor(exitMBB);
1411 // ll oldval, 0(ptr)
1412 // <binop> storeval, oldval, incr
1413 // sc success, storeval, 0(ptr)
1414 // beq success, $0, loopMBB
1416 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1418 // and andres, oldval, incr
1419 // nor storeval, $0, andres
1420 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1421 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1422 } else if (BinOpcode) {
1423 // <binop> storeval, oldval, incr
1424 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1428 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1429 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1431 MI->eraseFromParent(); // The instruction is gone now.
1437 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1438 MachineBasicBlock *BB,
1439 unsigned Size, unsigned BinOpcode,
1441 assert((Size == 1 || Size == 2) &&
1442 "Unsupported size for EmitAtomicBinaryPartial.");
1444 MachineFunction *MF = BB->getParent();
1445 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1446 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1447 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1448 DebugLoc dl = MI->getDebugLoc();
1449 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1450 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1452 unsigned Dest = MI->getOperand(0).getReg();
1453 unsigned Ptr = MI->getOperand(1).getReg();
1454 unsigned Incr = MI->getOperand(2).getReg();
1456 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1457 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1458 unsigned Mask = RegInfo.createVirtualRegister(RC);
1459 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1460 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1461 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1462 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1463 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1464 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1465 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1466 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1467 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1468 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1469 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1470 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1471 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1472 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1473 unsigned Success = RegInfo.createVirtualRegister(RC);
1475 // insert new blocks after the current block
1476 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1477 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1478 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1479 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1480 MachineFunction::iterator It = BB;
1482 MF->insert(It, loopMBB);
1483 MF->insert(It, sinkMBB);
1484 MF->insert(It, exitMBB);
1486 // Transfer the remainder of BB and its successor edges to exitMBB.
1487 exitMBB->splice(exitMBB->begin(), BB,
1488 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1489 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1491 BB->addSuccessor(loopMBB);
1492 loopMBB->addSuccessor(loopMBB);
1493 loopMBB->addSuccessor(sinkMBB);
1494 sinkMBB->addSuccessor(exitMBB);
1497 // addiu masklsb2,$0,-4 # 0xfffffffc
1498 // and alignedaddr,ptr,masklsb2
1499 // andi ptrlsb2,ptr,3
1500 // sll shiftamt,ptrlsb2,3
1501 // ori maskupper,$0,255 # 0xff
1502 // sll mask,maskupper,shiftamt
1503 // nor mask2,$0,mask
1504 // sll incr2,incr,shiftamt
1506 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1507 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1508 .addReg(Mips::ZERO).addImm(-4);
1509 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1510 .addReg(Ptr).addReg(MaskLSB2);
1511 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1512 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1513 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1514 .addReg(Mips::ZERO).addImm(MaskImm);
1515 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1516 .addReg(ShiftAmt).addReg(MaskUpper);
1517 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1518 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1520 // atomic.load.binop
1522 // ll oldval,0(alignedaddr)
1523 // binop binopres,oldval,incr2
1524 // and newval,binopres,mask
1525 // and maskedoldval0,oldval,mask2
1526 // or storeval,maskedoldval0,newval
1527 // sc success,storeval,0(alignedaddr)
1528 // beq success,$0,loopMBB
1532 // ll oldval,0(alignedaddr)
1533 // and newval,incr2,mask
1534 // and maskedoldval0,oldval,mask2
1535 // or storeval,maskedoldval0,newval
1536 // sc success,storeval,0(alignedaddr)
1537 // beq success,$0,loopMBB
1540 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1542 // and andres, oldval, incr2
1543 // nor binopres, $0, andres
1544 // and newval, binopres, mask
1545 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1546 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1547 .addReg(Mips::ZERO).addReg(AndRes);
1548 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1549 } else if (BinOpcode) {
1550 // <binop> binopres, oldval, incr2
1551 // and newval, binopres, mask
1552 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1553 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1554 } else {// atomic.swap
1555 // and newval, incr2, mask
1556 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1559 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1560 .addReg(OldVal).addReg(Mask2);
1561 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1562 .addReg(MaskedOldVal0).addReg(NewVal);
1563 BuildMI(BB, dl, TII->get(SC), Success)
1564 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1565 BuildMI(BB, dl, TII->get(Mips::BEQ))
1566 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1569 // and maskedoldval1,oldval,mask
1570 // srl srlres,maskedoldval1,shiftamt
1571 // sll sllres,srlres,24
1572 // sra dest,sllres,24
1574 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1576 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1577 .addReg(OldVal).addReg(Mask);
1578 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1579 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1580 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1581 .addReg(SrlRes).addImm(ShiftImm);
1582 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1583 .addReg(SllRes).addImm(ShiftImm);
1585 MI->eraseFromParent(); // The instruction is gone now.
1591 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1592 MachineBasicBlock *BB,
1593 unsigned Size) const {
1594 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1596 MachineFunction *MF = BB->getParent();
1597 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1598 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1599 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1600 DebugLoc dl = MI->getDebugLoc();
1601 unsigned LL, SC, ZERO, BNE, BEQ;
1604 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1605 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1611 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1612 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1613 ZERO = Mips::ZERO_64;
1618 unsigned Dest = MI->getOperand(0).getReg();
1619 unsigned Ptr = MI->getOperand(1).getReg();
1620 unsigned OldVal = MI->getOperand(2).getReg();
1621 unsigned NewVal = MI->getOperand(3).getReg();
1623 unsigned Success = RegInfo.createVirtualRegister(RC);
1625 // insert new blocks after the current block
1626 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1627 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1628 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1629 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1630 MachineFunction::iterator It = BB;
1632 MF->insert(It, loop1MBB);
1633 MF->insert(It, loop2MBB);
1634 MF->insert(It, exitMBB);
1636 // Transfer the remainder of BB and its successor edges to exitMBB.
1637 exitMBB->splice(exitMBB->begin(), BB,
1638 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1639 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1643 // fallthrough --> loop1MBB
1644 BB->addSuccessor(loop1MBB);
1645 loop1MBB->addSuccessor(exitMBB);
1646 loop1MBB->addSuccessor(loop2MBB);
1647 loop2MBB->addSuccessor(loop1MBB);
1648 loop2MBB->addSuccessor(exitMBB);
1652 // bne dest, oldval, exitMBB
1654 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1655 BuildMI(BB, dl, TII->get(BNE))
1656 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1659 // sc success, newval, 0(ptr)
1660 // beq success, $0, loop1MBB
1662 BuildMI(BB, dl, TII->get(SC), Success)
1663 .addReg(NewVal).addReg(Ptr).addImm(0);
1664 BuildMI(BB, dl, TII->get(BEQ))
1665 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1667 MI->eraseFromParent(); // The instruction is gone now.
1673 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1674 MachineBasicBlock *BB,
1675 unsigned Size) const {
1676 assert((Size == 1 || Size == 2) &&
1677 "Unsupported size for EmitAtomicCmpSwapPartial.");
1679 MachineFunction *MF = BB->getParent();
1680 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1681 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1682 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1683 DebugLoc dl = MI->getDebugLoc();
1684 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1685 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1687 unsigned Dest = MI->getOperand(0).getReg();
1688 unsigned Ptr = MI->getOperand(1).getReg();
1689 unsigned CmpVal = MI->getOperand(2).getReg();
1690 unsigned NewVal = MI->getOperand(3).getReg();
1692 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1693 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1694 unsigned Mask = RegInfo.createVirtualRegister(RC);
1695 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1696 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1697 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1698 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1699 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1700 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1701 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1702 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1703 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1704 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1705 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1706 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1707 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1708 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1709 unsigned Success = RegInfo.createVirtualRegister(RC);
1711 // insert new blocks after the current block
1712 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1713 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1714 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1715 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1716 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1717 MachineFunction::iterator It = BB;
1719 MF->insert(It, loop1MBB);
1720 MF->insert(It, loop2MBB);
1721 MF->insert(It, sinkMBB);
1722 MF->insert(It, exitMBB);
1724 // Transfer the remainder of BB and its successor edges to exitMBB.
1725 exitMBB->splice(exitMBB->begin(), BB,
1726 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1727 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1729 BB->addSuccessor(loop1MBB);
1730 loop1MBB->addSuccessor(sinkMBB);
1731 loop1MBB->addSuccessor(loop2MBB);
1732 loop2MBB->addSuccessor(loop1MBB);
1733 loop2MBB->addSuccessor(sinkMBB);
1734 sinkMBB->addSuccessor(exitMBB);
1736 // FIXME: computation of newval2 can be moved to loop2MBB.
1738 // addiu masklsb2,$0,-4 # 0xfffffffc
1739 // and alignedaddr,ptr,masklsb2
1740 // andi ptrlsb2,ptr,3
1741 // sll shiftamt,ptrlsb2,3
1742 // ori maskupper,$0,255 # 0xff
1743 // sll mask,maskupper,shiftamt
1744 // nor mask2,$0,mask
1745 // andi maskedcmpval,cmpval,255
1746 // sll shiftedcmpval,maskedcmpval,shiftamt
1747 // andi maskednewval,newval,255
1748 // sll shiftednewval,maskednewval,shiftamt
1749 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1750 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1751 .addReg(Mips::ZERO).addImm(-4);
1752 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1753 .addReg(Ptr).addReg(MaskLSB2);
1754 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1755 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1756 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1757 .addReg(Mips::ZERO).addImm(MaskImm);
1758 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1759 .addReg(ShiftAmt).addReg(MaskUpper);
1760 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1761 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1762 .addReg(CmpVal).addImm(MaskImm);
1763 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1764 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1765 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1766 .addReg(NewVal).addImm(MaskImm);
1767 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1768 .addReg(ShiftAmt).addReg(MaskedNewVal);
1771 // ll oldval,0(alginedaddr)
1772 // and maskedoldval0,oldval,mask
1773 // bne maskedoldval0,shiftedcmpval,sinkMBB
1775 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1776 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1777 .addReg(OldVal).addReg(Mask);
1778 BuildMI(BB, dl, TII->get(Mips::BNE))
1779 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1782 // and maskedoldval1,oldval,mask2
1783 // or storeval,maskedoldval1,shiftednewval
1784 // sc success,storeval,0(alignedaddr)
1785 // beq success,$0,loop1MBB
1787 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1788 .addReg(OldVal).addReg(Mask2);
1789 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1790 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1791 BuildMI(BB, dl, TII->get(SC), Success)
1792 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1793 BuildMI(BB, dl, TII->get(Mips::BEQ))
1794 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1797 // srl srlres,maskedoldval0,shiftamt
1798 // sll sllres,srlres,24
1799 // sra dest,sllres,24
1801 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1803 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1804 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1805 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1806 .addReg(SrlRes).addImm(ShiftImm);
1807 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1808 .addReg(SllRes).addImm(ShiftImm);
1810 MI->eraseFromParent(); // The instruction is gone now.
1815 //===----------------------------------------------------------------------===//
1816 // Misc Lower Operation implementation
1817 //===----------------------------------------------------------------------===//
1818 SDValue MipsTargetLowering::
1819 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1821 // The first operand is the chain, the second is the condition, the third is
1822 // the block to branch to if the condition is true.
1823 SDValue Chain = Op.getOperand(0);
1824 SDValue Dest = Op.getOperand(2);
1825 DebugLoc dl = Op.getDebugLoc();
1827 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1829 // Return if flag is not set by a floating point comparison.
1830 if (CondRes.getOpcode() != MipsISD::FPCmp)
1833 SDValue CCNode = CondRes.getOperand(2);
1835 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1836 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1838 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1842 SDValue MipsTargetLowering::
1843 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1845 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1847 // Return if flag is not set by a floating point comparison.
1848 if (Cond.getOpcode() != MipsISD::FPCmp)
1851 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1855 SDValue MipsTargetLowering::
1856 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1858 DebugLoc DL = Op.getDebugLoc();
1859 EVT Ty = Op.getOperand(0).getValueType();
1860 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1861 Op.getOperand(0), Op.getOperand(1),
1864 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1868 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1869 SDValue Cond = CreateFPCmp(DAG, Op);
1871 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1872 "Floating point operand expected.");
1874 SDValue True = DAG.getConstant(1, MVT::i32);
1875 SDValue False = DAG.getConstant(0, MVT::i32);
1877 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1880 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1881 SelectionDAG &DAG) const {
1882 // FIXME there isn't actually debug info here
1883 DebugLoc dl = Op.getDebugLoc();
1884 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1886 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1887 const MipsTargetObjectFile &TLOF =
1888 (const MipsTargetObjectFile&)getObjFileLowering();
1890 // %gp_rel relocation
1891 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1892 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1894 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
1895 DAG.getVTList(MVT::i32), &GA, 1);
1896 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1897 return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1900 // %hi/%lo relocation
1901 return getAddrNonPIC(Op, DAG);
1904 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1905 return getAddrLocal(Op, DAG, HasMips64);
1908 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1909 MipsII::MO_GOT_LO16);
1911 return getAddrGlobal(Op, DAG,
1912 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1915 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1916 SelectionDAG &DAG) const {
1917 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1918 return getAddrNonPIC(Op, DAG);
1920 return getAddrLocal(Op, DAG, HasMips64);
1923 SDValue MipsTargetLowering::
1924 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1926 // If the relocation model is PIC, use the General Dynamic TLS Model or
1927 // Local Dynamic TLS model, otherwise use the Initial Exec or
1928 // Local Exec TLS Model.
1930 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1931 DebugLoc dl = GA->getDebugLoc();
1932 const GlobalValue *GV = GA->getGlobal();
1933 EVT PtrVT = getPointerTy();
1935 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1937 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1938 // General Dynamic and Local Dynamic TLS Model.
1939 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1942 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1943 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1944 GetGlobalReg(DAG, PtrVT), TGA);
1945 unsigned PtrSize = PtrVT.getSizeInBits();
1946 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1948 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1952 Entry.Node = Argument;
1954 Args.push_back(Entry);
1956 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1957 false, false, false, false, 0, CallingConv::C,
1958 /*isTailCall=*/false, /*doesNotRet=*/false,
1959 /*isReturnValueUsed=*/true,
1960 TlsGetAddr, Args, DAG, dl);
1961 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1963 SDValue Ret = CallResult.first;
1965 if (model != TLSModel::LocalDynamic)
1968 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1969 MipsII::MO_DTPREL_HI);
1970 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1971 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1972 MipsII::MO_DTPREL_LO);
1973 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1974 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1975 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1979 if (model == TLSModel::InitialExec) {
1980 // Initial Exec TLS Model
1981 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1982 MipsII::MO_GOTTPREL);
1983 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1985 Offset = DAG.getLoad(PtrVT, dl,
1986 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1987 false, false, false, 0);
1989 // Local Exec TLS Model
1990 assert(model == TLSModel::LocalExec);
1991 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1992 MipsII::MO_TPREL_HI);
1993 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1994 MipsII::MO_TPREL_LO);
1995 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1996 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1997 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
2000 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
2001 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2004 SDValue MipsTargetLowering::
2005 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2007 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2008 return getAddrNonPIC(Op, DAG);
2010 return getAddrLocal(Op, DAG, HasMips64);
2013 SDValue MipsTargetLowering::
2014 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2016 // gp_rel relocation
2017 // FIXME: we should reference the constant pool using small data sections,
2018 // but the asm printer currently doesn't support this feature without
2019 // hacking it. This feature should come soon so we can uncomment the
2021 //if (IsInSmallSection(C->getType())) {
2022 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2023 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2024 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2026 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2027 return getAddrNonPIC(Op, DAG);
2029 return getAddrLocal(Op, DAG, HasMips64);
2032 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2033 MachineFunction &MF = DAG.getMachineFunction();
2034 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2036 DebugLoc dl = Op.getDebugLoc();
2037 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2040 // vastart just stores the address of the VarArgsFrameIndex slot into the
2041 // memory location argument.
2042 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2043 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2044 MachinePointerInfo(SV), false, false, 0);
2047 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2048 EVT TyX = Op.getOperand(0).getValueType();
2049 EVT TyY = Op.getOperand(1).getValueType();
2050 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2051 SDValue Const31 = DAG.getConstant(31, MVT::i32);
2052 DebugLoc DL = Op.getDebugLoc();
2055 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2057 SDValue X = (TyX == MVT::f32) ?
2058 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2059 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2061 SDValue Y = (TyY == MVT::f32) ?
2062 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2063 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2067 // ext E, Y, 31, 1 ; extract bit31 of Y
2068 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2069 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2070 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2073 // srl SrlX, SllX, 1
2075 // sll SllY, SrlX, 31
2076 // or Or, SrlX, SllY
2077 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2078 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2079 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2080 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2081 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2084 if (TyX == MVT::f32)
2085 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2087 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2088 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2089 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2092 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2093 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2094 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2095 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2096 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2097 DebugLoc DL = Op.getDebugLoc();
2099 // Bitcast to integer nodes.
2100 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2101 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2104 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2105 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2106 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2107 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2109 if (WidthX > WidthY)
2110 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2111 else if (WidthY > WidthX)
2112 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2114 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2115 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2116 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2119 // (d)sll SllX, X, 1
2120 // (d)srl SrlX, SllX, 1
2121 // (d)srl SrlY, Y, width(Y)-1
2122 // (d)sll SllY, SrlX, width(Y)-1
2123 // or Or, SrlX, SllY
2124 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2125 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2126 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2127 DAG.getConstant(WidthY - 1, MVT::i32));
2129 if (WidthX > WidthY)
2130 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2131 else if (WidthY > WidthX)
2132 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2134 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2135 DAG.getConstant(WidthX - 1, MVT::i32));
2136 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2137 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2141 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2142 if (Subtarget->hasMips64())
2143 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2145 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2148 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2149 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2150 DebugLoc DL = Op.getDebugLoc();
2152 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2154 SDValue X = (Op.getValueType() == MVT::f32) ?
2155 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2156 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2161 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2162 DAG.getRegister(Mips::ZERO, MVT::i32),
2163 DAG.getConstant(31, MVT::i32), Const1, X);
2165 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2166 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2169 if (Op.getValueType() == MVT::f32)
2170 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2172 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2173 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2174 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2177 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2178 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2179 DebugLoc DL = Op.getDebugLoc();
2181 // Bitcast to integer node.
2182 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2186 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2187 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2188 DAG.getConstant(63, MVT::i32), Const1, X);
2190 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2191 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2194 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2198 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2199 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2200 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2202 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2205 SDValue MipsTargetLowering::
2206 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2208 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2209 "Frame address can only be determined for current frame.");
2211 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2212 MFI->setFrameAddressIsTaken(true);
2213 EVT VT = Op.getValueType();
2214 DebugLoc dl = Op.getDebugLoc();
2215 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2216 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2220 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2221 SelectionDAG &DAG) const {
2223 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2224 "Return address can be determined only for current frame.");
2226 MachineFunction &MF = DAG.getMachineFunction();
2227 MachineFrameInfo *MFI = MF.getFrameInfo();
2228 MVT VT = Op.getSimpleValueType();
2229 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2230 MFI->setReturnAddressIsTaken(true);
2232 // Return RA, which contains the return address. Mark it an implicit live-in.
2233 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2234 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2237 // TODO: set SType according to the desired memory barrier behavior.
2239 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2241 DebugLoc dl = Op.getDebugLoc();
2242 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2243 DAG.getConstant(SType, MVT::i32));
2246 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2247 SelectionDAG &DAG) const {
2248 // FIXME: Need pseudo-fence for 'singlethread' fences
2249 // FIXME: Set SType for weaker fences where supported/appropriate.
2251 DebugLoc dl = Op.getDebugLoc();
2252 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2253 DAG.getConstant(SType, MVT::i32));
2256 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2257 SelectionDAG &DAG) const {
2258 DebugLoc DL = Op.getDebugLoc();
2259 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2260 SDValue Shamt = Op.getOperand(2);
2263 // lo = (shl lo, shamt)
2264 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2267 // hi = (shl lo, shamt[4:0])
2268 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2269 DAG.getConstant(-1, MVT::i32));
2270 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2271 DAG.getConstant(1, MVT::i32));
2272 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2274 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2275 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2276 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2277 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2278 DAG.getConstant(0x20, MVT::i32));
2279 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2280 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2281 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2283 SDValue Ops[2] = {Lo, Hi};
2284 return DAG.getMergeValues(Ops, 2, DL);
2287 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2289 DebugLoc DL = Op.getDebugLoc();
2290 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2291 SDValue Shamt = Op.getOperand(2);
2294 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2296 // hi = (sra hi, shamt)
2298 // hi = (srl hi, shamt)
2301 // lo = (sra hi, shamt[4:0])
2302 // hi = (sra hi, 31)
2304 // lo = (srl hi, shamt[4:0])
2306 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2307 DAG.getConstant(-1, MVT::i32));
2308 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2309 DAG.getConstant(1, MVT::i32));
2310 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2311 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2312 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2313 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2315 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2316 DAG.getConstant(0x20, MVT::i32));
2317 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2318 DAG.getConstant(31, MVT::i32));
2319 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2320 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2321 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2324 SDValue Ops[2] = {Lo, Hi};
2325 return DAG.getMergeValues(Ops, 2, DL);
2328 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2329 SDValue Chain, SDValue Src, unsigned Offset) {
2330 SDValue Ptr = LD->getBasePtr();
2331 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2332 EVT BasePtrVT = Ptr.getValueType();
2333 DebugLoc DL = LD->getDebugLoc();
2334 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2337 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2338 DAG.getConstant(Offset, BasePtrVT));
2340 SDValue Ops[] = { Chain, Ptr, Src };
2341 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2342 LD->getMemOperand());
2345 // Expand an unaligned 32 or 64-bit integer load node.
2346 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2347 LoadSDNode *LD = cast<LoadSDNode>(Op);
2348 EVT MemVT = LD->getMemoryVT();
2350 // Return if load is aligned or if MemVT is neither i32 nor i64.
2351 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2352 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2355 bool IsLittle = Subtarget->isLittle();
2356 EVT VT = Op.getValueType();
2357 ISD::LoadExtType ExtType = LD->getExtensionType();
2358 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2360 assert((VT == MVT::i32) || (VT == MVT::i64));
2363 // (set dst, (i64 (load baseptr)))
2365 // (set tmp, (ldl (add baseptr, 7), undef))
2366 // (set dst, (ldr baseptr, tmp))
2367 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2368 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2370 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2374 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2376 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2380 // (set dst, (i32 (load baseptr))) or
2381 // (set dst, (i64 (sextload baseptr))) or
2382 // (set dst, (i64 (extload baseptr)))
2384 // (set tmp, (lwl (add baseptr, 3), undef))
2385 // (set dst, (lwr baseptr, tmp))
2386 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2387 (ExtType == ISD::EXTLOAD))
2390 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2393 // (set dst, (i64 (zextload baseptr)))
2395 // (set tmp0, (lwl (add baseptr, 3), undef))
2396 // (set tmp1, (lwr baseptr, tmp0))
2397 // (set tmp2, (shl tmp1, 32))
2398 // (set dst, (srl tmp2, 32))
2399 DebugLoc DL = LD->getDebugLoc();
2400 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2401 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2402 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2403 SDValue Ops[] = { SRL, LWR.getValue(1) };
2404 return DAG.getMergeValues(Ops, 2, DL);
2407 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2408 SDValue Chain, unsigned Offset) {
2409 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2410 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2411 DebugLoc DL = SD->getDebugLoc();
2412 SDVTList VTList = DAG.getVTList(MVT::Other);
2415 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2416 DAG.getConstant(Offset, BasePtrVT));
2418 SDValue Ops[] = { Chain, Value, Ptr };
2419 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2420 SD->getMemOperand());
2423 // Expand an unaligned 32 or 64-bit integer store node.
2424 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2425 StoreSDNode *SD = cast<StoreSDNode>(Op);
2426 EVT MemVT = SD->getMemoryVT();
2428 // Return if store is aligned or if MemVT is neither i32 nor i64.
2429 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2430 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2433 bool IsLittle = Subtarget->isLittle();
2434 SDValue Value = SD->getValue(), Chain = SD->getChain();
2435 EVT VT = Value.getValueType();
2438 // (store val, baseptr) or
2439 // (truncstore val, baseptr)
2441 // (swl val, (add baseptr, 3))
2442 // (swr val, baseptr)
2443 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2444 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2446 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2449 assert(VT == MVT::i64);
2452 // (store val, baseptr)
2454 // (sdl val, (add baseptr, 7))
2455 // (sdr val, baseptr)
2456 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2457 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2460 // This function expands mips intrinsic nodes which have 64-bit input operands
2461 // or output values.
2463 // out64 = intrinsic-node in64
2465 // lo = copy (extract-element (in64, 0))
2466 // hi = copy (extract-element (in64, 1))
2467 // mips-specific-node
2470 // out64 = merge-values (v0, v1)
2472 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2473 unsigned Opc, bool HasI64In, bool HasI64Out) {
2474 DebugLoc DL = Op.getDebugLoc();
2475 bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2476 SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2477 SmallVector<SDValue, 3> Ops;
2480 SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2481 Op->getOperand(1 + HasChainIn),
2482 DAG.getConstant(0, MVT::i32));
2483 SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2484 Op->getOperand(1 + HasChainIn),
2485 DAG.getConstant(1, MVT::i32));
2487 Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2488 Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2490 Ops.push_back(Chain);
2491 Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2492 Ops.push_back(Chain.getValue(1));
2494 Ops.push_back(Chain);
2495 Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2499 return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2500 Ops.begin(), Ops.size());
2502 SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2503 Ops.begin(), Ops.size());
2504 SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2506 SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2508 SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2513 SDValue Vals[] = { Out, OutHi.getValue(1) };
2514 return DAG.getMergeValues(Vals, 2, DL);
2517 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2518 SelectionDAG &DAG) const {
2519 switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2522 case Intrinsic::mips_shilo:
2523 return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2524 case Intrinsic::mips_dpau_h_qbl:
2525 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2526 case Intrinsic::mips_dpau_h_qbr:
2527 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2528 case Intrinsic::mips_dpsu_h_qbl:
2529 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2530 case Intrinsic::mips_dpsu_h_qbr:
2531 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2532 case Intrinsic::mips_dpa_w_ph:
2533 return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2534 case Intrinsic::mips_dps_w_ph:
2535 return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2536 case Intrinsic::mips_dpax_w_ph:
2537 return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2538 case Intrinsic::mips_dpsx_w_ph:
2539 return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2540 case Intrinsic::mips_mulsa_w_ph:
2541 return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2542 case Intrinsic::mips_mult:
2543 return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2544 case Intrinsic::mips_multu:
2545 return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2546 case Intrinsic::mips_madd:
2547 return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2548 case Intrinsic::mips_maddu:
2549 return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2550 case Intrinsic::mips_msub:
2551 return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2552 case Intrinsic::mips_msubu:
2553 return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2557 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2558 SelectionDAG &DAG) const {
2559 switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2562 case Intrinsic::mips_extp:
2563 return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2564 case Intrinsic::mips_extpdp:
2565 return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2566 case Intrinsic::mips_extr_w:
2567 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2568 case Intrinsic::mips_extr_r_w:
2569 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2570 case Intrinsic::mips_extr_rs_w:
2571 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2572 case Intrinsic::mips_extr_s_h:
2573 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2574 case Intrinsic::mips_mthlip:
2575 return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2576 case Intrinsic::mips_mulsaq_s_w_ph:
2577 return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2578 case Intrinsic::mips_maq_s_w_phl:
2579 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2580 case Intrinsic::mips_maq_s_w_phr:
2581 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2582 case Intrinsic::mips_maq_sa_w_phl:
2583 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2584 case Intrinsic::mips_maq_sa_w_phr:
2585 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2586 case Intrinsic::mips_dpaq_s_w_ph:
2587 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2588 case Intrinsic::mips_dpsq_s_w_ph:
2589 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2590 case Intrinsic::mips_dpaq_sa_l_w:
2591 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2592 case Intrinsic::mips_dpsq_sa_l_w:
2593 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2594 case Intrinsic::mips_dpaqx_s_w_ph:
2595 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2596 case Intrinsic::mips_dpaqx_sa_w_ph:
2597 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2598 case Intrinsic::mips_dpsqx_s_w_ph:
2599 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2600 case Intrinsic::mips_dpsqx_sa_w_ph:
2601 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2605 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2606 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2607 || cast<ConstantSDNode>
2608 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2609 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2613 // (add (frameaddr 0), (frame_to_args_offset))
2614 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2615 // (add FrameObject, 0)
2616 // where FrameObject is a fixed StackObject with offset 0 which points to
2617 // the old stack pointer.
2618 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2619 EVT ValTy = Op->getValueType(0);
2620 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2621 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2622 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2623 DAG.getConstant(0, ValTy));
2626 //===----------------------------------------------------------------------===//
2627 // Calling Convention Implementation
2628 //===----------------------------------------------------------------------===//
2630 //===----------------------------------------------------------------------===//
2631 // TODO: Implement a generic logic using tblgen that can support this.
2632 // Mips O32 ABI rules:
2634 // i32 - Passed in A0, A1, A2, A3 and stack
2635 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2636 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2637 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2638 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2639 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2642 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2643 //===----------------------------------------------------------------------===//
2645 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2646 MVT LocVT, CCValAssign::LocInfo LocInfo,
2647 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2649 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2651 static const uint16_t IntRegs[] = {
2652 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2654 static const uint16_t F32Regs[] = {
2655 Mips::F12, Mips::F14
2657 static const uint16_t F64Regs[] = {
2661 // Do not process byval args here.
2662 if (ArgFlags.isByVal())
2665 // Promote i8 and i16
2666 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2668 if (ArgFlags.isSExt())
2669 LocInfo = CCValAssign::SExt;
2670 else if (ArgFlags.isZExt())
2671 LocInfo = CCValAssign::ZExt;
2673 LocInfo = CCValAssign::AExt;
2678 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2679 // is true: function is vararg, argument is 3rd or higher, there is previous
2680 // argument which is not f32 or f64.
2681 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2682 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2683 unsigned OrigAlign = ArgFlags.getOrigAlign();
2684 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2686 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2687 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2688 // If this is the first part of an i64 arg,
2689 // the allocated register must be either A0 or A2.
2690 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2691 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2693 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2694 // Allocate int register and shadow next int register. If first
2695 // available register is Mips::A1 or Mips::A3, shadow it too.
2696 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2697 if (Reg == Mips::A1 || Reg == Mips::A3)
2698 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2699 State.AllocateReg(IntRegs, IntRegsSize);
2701 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2702 // we are guaranteed to find an available float register
2703 if (ValVT == MVT::f32) {
2704 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2705 // Shadow int register
2706 State.AllocateReg(IntRegs, IntRegsSize);
2708 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2709 // Shadow int registers
2710 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2711 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2712 State.AllocateReg(IntRegs, IntRegsSize);
2713 State.AllocateReg(IntRegs, IntRegsSize);
2716 llvm_unreachable("Cannot handle this ValVT.");
2719 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2721 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2723 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2728 #include "MipsGenCallingConv.inc"
2730 //===----------------------------------------------------------------------===//
2731 // Call Calling Convention Implementation
2732 //===----------------------------------------------------------------------===//
2734 static const unsigned O32IntRegsSize = 4;
2736 // Return next O32 integer argument register.
2737 static unsigned getNextIntArgReg(unsigned Reg) {
2738 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2739 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2742 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2743 /// for tail call optimization.
2744 bool MipsTargetLowering::
2745 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
2746 unsigned NextStackOffset,
2747 const MipsFunctionInfo& FI) const {
2748 if (!EnableMipsTailCalls)
2751 // No tail call optimization for mips16.
2752 if (Subtarget->inMips16Mode())
2755 // Return false if either the callee or caller has a byval argument.
2756 if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
2759 // Return true if the callee's argument area is no larger than the
2761 return NextStackOffset <= FI.getIncomingArgSize();
2765 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2766 SDValue Chain, SDValue Arg, DebugLoc DL,
2767 bool IsTailCall, SelectionDAG &DAG) const {
2769 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2770 DAG.getIntPtrConstant(Offset));
2771 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2775 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2776 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2777 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2778 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2779 /*isVolatile=*/ true, false, 0);
2783 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
2784 // cleaner way to do all of this but it will have to wait until the traditional
2785 // gcc mechanism is completed.
2787 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
2788 // have either arguments or returned values placed in floating point registers,
2789 // we use a set of helper functions. (This includes functions which return type
2790 // complex which on Mips are returned in a pair of floating point registers).
2792 // This is an encoding that we inherited from gcc.
2793 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
2794 // floating point argument registers 1,2 only when the first and optionally
2795 // the second arguments are float (sf) or double (df).
2796 // For Mips16 we are only concerned with the situations where floating point
2797 // arguments are being passed in floating point registers by the ABI, because
2798 // Mips16 mode code cannot execute floating point instructions to load those
2799 // values and hence helper functions are needed.
2800 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
2801 // the helper function suffixs for these are:
2802 // 0, 1, 5, 9, 2, 6, 10
2803 // this suffix can then be calculated as follows:
2804 // for a given argument Arg:
2805 // Arg1x, Arg2x = 1 : Arg is sf
2807 // 0: Arg is neither sf or df
2808 // So this stub is the string for number Arg1x + Arg2x*4.
2809 // However not all numbers between 0 and 10 are possible, we check anyway and
2810 // assert if the impossible exists.
2813 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
2814 (ArgListTy &Args) const {
2815 unsigned int resultNum = 0;
2816 if (Args.size() >= 1) {
2817 Type *t = Args[0].Ty;
2818 if (t->isFloatTy()) {
2821 else if (t->isDoubleTy()) {
2826 if (Args.size() >=2) {
2827 Type *t = Args[1].Ty;
2828 if (t->isFloatTy()) {
2831 else if (t->isDoubleTy()) {
2840 // prefixs are attached to stub numbers depending on the return type .
2841 // return type: float sf_
2843 // single complex sc_
2844 // double complext dc_
2848 // The full name of a helper function is__mips16_call_stub +
2849 // return type dependent prefix + stub number
2852 // This is something that probably should be in a different source file and
2853 // perhaps done differently but my main purpose is to not waste runtime
2854 // on something that we can enumerate in the source. Another possibility is
2855 // to have a python script to generate these mapping tables. This will do
2856 // for now. There are a whole series of helper function mapping arrays, one
2857 // for each return type class as outlined above. There there are 11 possible
2858 // entries. Ones with 0 are ones which should never be selected
2860 // All the arrays are similar except for ones which return neither
2861 // sf, df, sc, dc, in which only care about ones which have sf or df as a
2864 #define P_ "__mips16_call_stub_"
2865 #define MAX_STUB_NUMBER 10
2866 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
2867 #define T P "0" , T1
2869 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
2873 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
2877 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
2881 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
2885 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
2891 const char* MipsTargetLowering::
2892 getMips16HelperFunction
2893 (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
2894 const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
2896 const unsigned int maxStubNum = 10;
2897 assert(stubNum <= maxStubNum);
2898 const bool validStubNum[maxStubNum+1] =
2899 {true, true, true, false, false, true, true, false, false, true, true};
2900 assert(validStubNum[stubNum]);
2903 if (RetTy->isFloatTy()) {
2904 result = sfMips16Helper[stubNum];
2906 else if (RetTy ->isDoubleTy()) {
2907 result = dfMips16Helper[stubNum];
2909 else if (RetTy->isStructTy()) {
2910 // check if it's complex
2911 if (RetTy->getNumContainedTypes() == 2) {
2912 if ((RetTy->getContainedType(0)->isFloatTy()) &&
2913 (RetTy->getContainedType(1)->isFloatTy())) {
2914 result = scMips16Helper[stubNum];
2916 else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
2917 (RetTy->getContainedType(1)->isDoubleTy())) {
2918 result = dcMips16Helper[stubNum];
2921 llvm_unreachable("Uncovered condition");
2925 llvm_unreachable("Uncovered condition");
2933 result = vMips16Helper[stubNum];
2939 /// LowerCall - functions arguments are copied from virtual regs to
2940 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2942 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2943 SmallVectorImpl<SDValue> &InVals) const {
2944 SelectionDAG &DAG = CLI.DAG;
2945 DebugLoc &dl = CLI.DL;
2946 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2947 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2948 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2949 SDValue Chain = CLI.Chain;
2950 SDValue Callee = CLI.Callee;
2951 bool &isTailCall = CLI.IsTailCall;
2952 CallingConv::ID CallConv = CLI.CallConv;
2953 bool isVarArg = CLI.IsVarArg;
2955 const char* mips16HelperFunction = 0;
2956 bool needMips16Helper = false;
2958 if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
2961 // currently we don't have symbols tagged with the mips16 or mips32
2962 // qualifier so we will assume that we don't know what kind it is.
2963 // and generate the helper
2965 bool lookupHelper = true;
2966 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2967 if (noHelperNeeded.find(S->getSymbol()) != noHelperNeeded.end()) {
2968 lookupHelper = false;
2971 if (lookupHelper) mips16HelperFunction =
2972 getMips16HelperFunction(CLI.RetTy, CLI.Args, needMips16Helper);
2975 MachineFunction &MF = DAG.getMachineFunction();
2976 MachineFrameInfo *MFI = MF.getFrameInfo();
2977 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2978 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2980 // Analyze operands of the call, assigning locations to each operand.
2981 SmallVector<CCValAssign, 16> ArgLocs;
2982 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2983 getTargetMachine(), ArgLocs, *DAG.getContext());
2984 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
2986 MipsCCInfo.analyzeCallOperands(Outs);
2988 // Get a count of how many bytes are to be pushed on the stack.
2989 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2991 // Check if it's really possible to do a tail call.
2994 IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2995 *MF.getInfo<MipsFunctionInfo>());
3000 // Chain is the output chain of the last Load/Store or CopyToReg node.
3001 // ByValChain is the output chain of the last Memcpy node created for copying
3002 // byval arguments to the stack.
3003 unsigned StackAlignment = TFL->getStackAlignment();
3004 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
3005 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3008 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3010 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
3011 IsN64 ? Mips::SP_64 : Mips::SP,
3014 // With EABI is it possible to have 16 args on registers.
3015 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3016 SmallVector<SDValue, 8> MemOpChains;
3017 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3019 // Walk the register/memloc assignments, inserting copies/loads.
3020 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3021 SDValue Arg = OutVals[i];
3022 CCValAssign &VA = ArgLocs[i];
3023 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3024 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3027 if (Flags.isByVal()) {
3028 assert(Flags.getByValSize() &&
3029 "ByVal args of size 0 should have been ignored by front-end.");
3030 assert(ByValArg != MipsCCInfo.byval_end());
3031 assert(!isTailCall &&
3032 "Do not tail-call optimize if there is a byval argument.");
3033 passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3034 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3039 // Promote the value if needed.
3040 switch (VA.getLocInfo()) {
3041 default: llvm_unreachable("Unknown loc info!");
3042 case CCValAssign::Full:
3043 if (VA.isRegLoc()) {
3044 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3045 (ValVT == MVT::f64 && LocVT == MVT::i64))
3046 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
3047 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3048 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3049 Arg, DAG.getConstant(0, MVT::i32));
3050 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3051 Arg, DAG.getConstant(1, MVT::i32));
3052 if (!Subtarget->isLittle())
3054 unsigned LocRegLo = VA.getLocReg();
3055 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3056 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3057 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3062 case CCValAssign::SExt:
3063 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
3065 case CCValAssign::ZExt:
3066 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
3068 case CCValAssign::AExt:
3069 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
3073 // Arguments that can be passed on register must be kept at
3074 // RegsToPass vector
3075 if (VA.isRegLoc()) {
3076 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3080 // Register can't get to this point...
3081 assert(VA.isMemLoc());
3083 // emit ISD::STORE whichs stores the
3084 // parameter value to a stack Location
3085 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3086 Chain, Arg, dl, isTailCall, DAG));
3089 // Transform all store nodes into one single node because all store
3090 // nodes are independent of each other.
3091 if (!MemOpChains.empty())
3092 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3093 &MemOpChains[0], MemOpChains.size());
3095 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3096 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3097 // node so that legalize doesn't hack it.
3098 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3099 bool GlobalOrExternal = false, InternalLinkage = false;
3102 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3104 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3106 if (InternalLinkage)
3107 Callee = getAddrLocal(Callee, DAG, HasMips64);
3109 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3110 MipsII::MO_CALL_LO16);
3112 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3114 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
3115 MipsII::MO_NO_FLAG);
3116 GlobalOrExternal = true;
3118 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3119 if (!IsN64 && !IsPIC) // !N64 && static
3120 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3121 MipsII::MO_NO_FLAG);
3123 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3124 MipsII::MO_CALL_LO16);
3126 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_DISP);
3128 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3130 GlobalOrExternal = true;
3133 SDValue JumpTarget = Callee;
3135 // T9 should contain the address of the callee function if
3136 // -reloction-model=pic or it is an indirect call.
3137 if (IsPICCall || !GlobalOrExternal) {
3138 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3139 unsigned V0Reg = Mips::V0;
3140 if (needMips16Helper) {
3141 RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3142 JumpTarget = DAG.getExternalSymbol(
3143 mips16HelperFunction, getPointerTy());
3144 JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3147 RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3149 if (!Subtarget->inMips16Mode())
3150 JumpTarget = SDValue();
3154 // Insert node "GP copy globalreg" before call to function.
3156 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3157 // in PIC mode) allow symbols to be resolved via lazy binding.
3158 // The lazy binding stub requires GP to point to the GOT.
3159 if (IsPICCall && !InternalLinkage) {
3160 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3161 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3162 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
3165 // Build a sequence of copy-to-reg nodes chained together with token
3166 // chain and flag operands which copy the outgoing args into registers.
3167 // The InFlag in necessary since all emitted instructions must be
3171 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3172 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3173 RegsToPass[i].second, InFlag);
3174 InFlag = Chain.getValue(1);
3177 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3178 // = Chain, Callee, Reg#1, Reg#2, ...
3180 // Returns a chain & a flag for retval copy to use.
3181 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3182 SmallVector<SDValue, 8> Ops(1, Chain);
3184 if (JumpTarget.getNode())
3185 Ops.push_back(JumpTarget);
3187 // Add argument registers to the end of the list so that they are
3188 // known live into the call.
3189 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3190 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3191 RegsToPass[i].second.getValueType()));
3193 // Add a register mask operand representing the call-preserved registers.
3194 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3195 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3196 assert(Mask && "Missing call preserved mask for calling convention");
3197 Ops.push_back(DAG.getRegisterMask(Mask));
3199 if (InFlag.getNode())
3200 Ops.push_back(InFlag);
3203 return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
3205 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3206 InFlag = Chain.getValue(1);
3208 // Create the CALLSEQ_END node.
3209 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3210 DAG.getIntPtrConstant(0, true), InFlag);
3211 InFlag = Chain.getValue(1);
3213 // Handle result values, copying them out of physregs into vregs that we
3215 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3216 Ins, dl, DAG, InVals);
3219 /// LowerCallResult - Lower the result values of a call into the
3220 /// appropriate copies out of appropriate physical registers.
3222 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3223 CallingConv::ID CallConv, bool isVarArg,
3224 const SmallVectorImpl<ISD::InputArg> &Ins,
3225 DebugLoc dl, SelectionDAG &DAG,
3226 SmallVectorImpl<SDValue> &InVals) const {
3227 // Assign locations to each value returned by this call.
3228 SmallVector<CCValAssign, 16> RVLocs;
3229 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3230 getTargetMachine(), RVLocs, *DAG.getContext());
3232 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3234 // Copy all of the result registers out of their specified physreg.
3235 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3236 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3237 RVLocs[i].getValVT(), InFlag).getValue(1);
3238 InFlag = Chain.getValue(2);
3239 InVals.push_back(Chain.getValue(0));
3245 //===----------------------------------------------------------------------===//
3246 // Formal Arguments Calling Convention Implementation
3247 //===----------------------------------------------------------------------===//
3248 /// LowerFormalArguments - transform physical registers into virtual registers
3249 /// and generate load operations for arguments places on the stack.
3251 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3252 CallingConv::ID CallConv,
3254 const SmallVectorImpl<ISD::InputArg> &Ins,
3255 DebugLoc dl, SelectionDAG &DAG,
3256 SmallVectorImpl<SDValue> &InVals)
3258 MachineFunction &MF = DAG.getMachineFunction();
3259 MachineFrameInfo *MFI = MF.getFrameInfo();
3260 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3262 MipsFI->setVarArgsFrameIndex(0);
3264 // Used with vargs to acumulate store chains.
3265 std::vector<SDValue> OutChains;
3267 // Assign locations to all of the incoming arguments.
3268 SmallVector<CCValAssign, 16> ArgLocs;
3269 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3270 getTargetMachine(), ArgLocs, *DAG.getContext());
3271 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3273 MipsCCInfo.analyzeFormalArguments(Ins);
3274 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3275 MipsCCInfo.hasByValArg());
3277 Function::const_arg_iterator FuncArg =
3278 DAG.getMachineFunction().getFunction()->arg_begin();
3279 unsigned CurArgIdx = 0;
3280 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3282 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3283 CCValAssign &VA = ArgLocs[i];
3284 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3285 CurArgIdx = Ins[i].OrigArgIndex;
3286 EVT ValVT = VA.getValVT();
3287 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3288 bool IsRegLoc = VA.isRegLoc();
3290 if (Flags.isByVal()) {
3291 assert(Flags.getByValSize() &&
3292 "ByVal args of size 0 should have been ignored by front-end.");
3293 assert(ByValArg != MipsCCInfo.byval_end());
3294 copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3295 MipsCCInfo, *ByValArg);
3300 // Arguments stored on registers
3302 EVT RegVT = VA.getLocVT();
3303 unsigned ArgReg = VA.getLocReg();
3304 const TargetRegisterClass *RC;
3306 if (RegVT == MVT::i32)
3307 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3308 &Mips::CPURegsRegClass;
3309 else if (RegVT == MVT::i64)
3310 RC = &Mips::CPU64RegsRegClass;
3311 else if (RegVT == MVT::f32)
3312 RC = &Mips::FGR32RegClass;
3313 else if (RegVT == MVT::f64)
3314 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3316 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3318 // Transform the arguments stored on
3319 // physical registers into virtual ones
3320 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3321 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3323 // If this is an 8 or 16-bit value, it has been passed promoted
3324 // to 32 bits. Insert an assert[sz]ext to capture this, then
3325 // truncate to the right size.
3326 if (VA.getLocInfo() != CCValAssign::Full) {
3327 unsigned Opcode = 0;
3328 if (VA.getLocInfo() == CCValAssign::SExt)
3329 Opcode = ISD::AssertSext;
3330 else if (VA.getLocInfo() == CCValAssign::ZExt)
3331 Opcode = ISD::AssertZext;
3333 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3334 DAG.getValueType(ValVT));
3335 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3338 // Handle floating point arguments passed in integer registers.
3339 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3340 (RegVT == MVT::i64 && ValVT == MVT::f64))
3341 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3342 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3343 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3344 getNextIntArgReg(ArgReg), RC);
3345 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3346 if (!Subtarget->isLittle())
3347 std::swap(ArgValue, ArgValue2);
3348 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3349 ArgValue, ArgValue2);
3352 InVals.push_back(ArgValue);
3353 } else { // VA.isRegLoc()
3356 assert(VA.isMemLoc());
3358 // The stack pointer offset is relative to the caller stack frame.
3359 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3360 VA.getLocMemOffset(), true);
3362 // Create load nodes to retrieve arguments from the stack
3363 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3364 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3365 MachinePointerInfo::getFixedStack(FI),
3366 false, false, false, 0));
3370 // The mips ABIs for returning structs by value requires that we copy
3371 // the sret argument into $v0 for the return. Save the argument into
3372 // a virtual register so that we can access it from the return points.
3373 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3374 unsigned Reg = MipsFI->getSRetReturnReg();
3376 Reg = MF.getRegInfo().
3377 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3378 MipsFI->setSRetReturnReg(Reg);
3380 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3381 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3385 writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3387 // All stores are grouped in one node to allow the matching between
3388 // the size of Ins and InVals. This only happens when on varg functions
3389 if (!OutChains.empty()) {
3390 OutChains.push_back(Chain);
3391 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3392 &OutChains[0], OutChains.size());
3398 //===----------------------------------------------------------------------===//
3399 // Return Value Calling Convention Implementation
3400 //===----------------------------------------------------------------------===//
3403 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3404 MachineFunction &MF, bool isVarArg,
3405 const SmallVectorImpl<ISD::OutputArg> &Outs,
3406 LLVMContext &Context) const {
3407 SmallVector<CCValAssign, 16> RVLocs;
3408 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3410 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3414 MipsTargetLowering::LowerReturn(SDValue Chain,
3415 CallingConv::ID CallConv, bool isVarArg,
3416 const SmallVectorImpl<ISD::OutputArg> &Outs,
3417 const SmallVectorImpl<SDValue> &OutVals,
3418 DebugLoc dl, SelectionDAG &DAG) const {
3420 // CCValAssign - represent the assignment of
3421 // the return value to a location
3422 SmallVector<CCValAssign, 16> RVLocs;
3424 // CCState - Info about the registers and stack slot.
3425 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3426 getTargetMachine(), RVLocs, *DAG.getContext());
3428 // Analize return values.
3429 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3431 // If this is the first return lowered for this function, add
3432 // the regs to the liveout set for the function.
3433 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3434 for (unsigned i = 0; i != RVLocs.size(); ++i)
3435 if (RVLocs[i].isRegLoc())
3436 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3441 // Copy the result values into the output registers.
3442 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3443 CCValAssign &VA = RVLocs[i];
3444 assert(VA.isRegLoc() && "Can only return in registers!");
3446 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3448 // guarantee that all emitted copies are
3449 // stuck together, avoiding something bad
3450 Flag = Chain.getValue(1);
3453 // The mips ABIs for returning structs by value requires that we copy
3454 // the sret argument into $v0 for the return. We saved the argument into
3455 // a virtual register in the entry block, so now we copy the value out
3457 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3458 MachineFunction &MF = DAG.getMachineFunction();
3459 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3460 unsigned Reg = MipsFI->getSRetReturnReg();
3463 llvm_unreachable("sret virtual register not created in the entry block");
3464 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3465 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3467 Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3468 Flag = Chain.getValue(1);
3469 MF.getRegInfo().addLiveOut(V0);
3472 // Return on Mips is always a "jr $ra"
3474 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3477 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3480 //===----------------------------------------------------------------------===//
3481 // Mips Inline Assembly Support
3482 //===----------------------------------------------------------------------===//
3484 /// getConstraintType - Given a constraint letter, return the type of
3485 /// constraint it is for this target.
3486 MipsTargetLowering::ConstraintType MipsTargetLowering::
3487 getConstraintType(const std::string &Constraint) const
3489 // Mips specific constrainy
3490 // GCC config/mips/constraints.md
3492 // 'd' : An address register. Equivalent to r
3493 // unless generating MIPS16 code.
3494 // 'y' : Equivalent to r; retained for
3495 // backwards compatibility.
3496 // 'c' : A register suitable for use in an indirect
3497 // jump. This will always be $25 for -mabicalls.
3498 // 'l' : The lo register. 1 word storage.
3499 // 'x' : The hilo register pair. Double word storage.
3500 if (Constraint.size() == 1) {
3501 switch (Constraint[0]) {
3509 return C_RegisterClass;
3512 return TargetLowering::getConstraintType(Constraint);
3515 /// Examine constraint type and operand type and determine a weight value.
3516 /// This object must already have been set up with the operand type
3517 /// and the current alternative constraint selected.
3518 TargetLowering::ConstraintWeight
3519 MipsTargetLowering::getSingleConstraintMatchWeight(
3520 AsmOperandInfo &info, const char *constraint) const {
3521 ConstraintWeight weight = CW_Invalid;
3522 Value *CallOperandVal = info.CallOperandVal;
3523 // If we don't have a value, we can't do a match,
3524 // but allow it at the lowest weight.
3525 if (CallOperandVal == NULL)
3527 Type *type = CallOperandVal->getType();
3528 // Look at the constraint type.
3529 switch (*constraint) {
3531 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3535 if (type->isIntegerTy())
3536 weight = CW_Register;
3539 if (type->isFloatTy())
3540 weight = CW_Register;
3542 case 'c': // $25 for indirect jumps
3543 case 'l': // lo register
3544 case 'x': // hilo register pair
3545 if (type->isIntegerTy())
3546 weight = CW_SpecificReg;
3548 case 'I': // signed 16 bit immediate
3549 case 'J': // integer zero
3550 case 'K': // unsigned 16 bit immediate
3551 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3552 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3553 case 'O': // signed 15 bit immediate (+- 16383)
3554 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3555 if (isa<ConstantInt>(CallOperandVal))
3556 weight = CW_Constant;
3562 /// Given a register class constraint, like 'r', if this corresponds directly
3563 /// to an LLVM register class, return a register of 0 and the register class
3565 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3566 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3568 if (Constraint.size() == 1) {
3569 switch (Constraint[0]) {
3570 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3571 case 'y': // Same as 'r'. Exists for compatibility.
3573 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3574 if (Subtarget->inMips16Mode())
3575 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3576 return std::make_pair(0U, &Mips::CPURegsRegClass);
3578 if (VT == MVT::i64 && !HasMips64)
3579 return std::make_pair(0U, &Mips::CPURegsRegClass);
3580 if (VT == MVT::i64 && HasMips64)
3581 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3582 // This will generate an error message
3583 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3586 return std::make_pair(0U, &Mips::FGR32RegClass);
3587 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3588 if (Subtarget->isFP64bit())
3589 return std::make_pair(0U, &Mips::FGR64RegClass);
3590 return std::make_pair(0U, &Mips::AFGR64RegClass);
3593 case 'c': // register suitable for indirect jump
3595 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3596 assert(VT == MVT::i64 && "Unexpected type.");
3597 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3598 case 'l': // register suitable for indirect jump
3600 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3601 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3602 case 'x': // register suitable for indirect jump
3603 // Fixme: Not triggering the use of both hi and low
3604 // This will generate an error message
3605 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3608 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3611 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3612 /// vector. If it is invalid, don't add anything to Ops.
3613 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3614 std::string &Constraint,
3615 std::vector<SDValue>&Ops,
3616 SelectionDAG &DAG) const {
3617 SDValue Result(0, 0);
3619 // Only support length 1 constraints for now.
3620 if (Constraint.length() > 1) return;
3622 char ConstraintLetter = Constraint[0];
3623 switch (ConstraintLetter) {
3624 default: break; // This will fall through to the generic implementation
3625 case 'I': // Signed 16 bit constant
3626 // If this fails, the parent routine will give an error
3627 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3628 EVT Type = Op.getValueType();
3629 int64_t Val = C->getSExtValue();
3630 if (isInt<16>(Val)) {
3631 Result = DAG.getTargetConstant(Val, Type);
3636 case 'J': // integer zero
3637 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3638 EVT Type = Op.getValueType();
3639 int64_t Val = C->getZExtValue();
3641 Result = DAG.getTargetConstant(0, Type);
3646 case 'K': // unsigned 16 bit immediate
3647 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3648 EVT Type = Op.getValueType();
3649 uint64_t Val = (uint64_t)C->getZExtValue();
3650 if (isUInt<16>(Val)) {
3651 Result = DAG.getTargetConstant(Val, Type);
3656 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3657 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3658 EVT Type = Op.getValueType();
3659 int64_t Val = C->getSExtValue();
3660 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3661 Result = DAG.getTargetConstant(Val, Type);
3666 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3667 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3668 EVT Type = Op.getValueType();
3669 int64_t Val = C->getSExtValue();
3670 if ((Val >= -65535) && (Val <= -1)) {
3671 Result = DAG.getTargetConstant(Val, Type);
3676 case 'O': // signed 15 bit immediate
3677 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3678 EVT Type = Op.getValueType();
3679 int64_t Val = C->getSExtValue();
3680 if ((isInt<15>(Val))) {
3681 Result = DAG.getTargetConstant(Val, Type);
3686 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3687 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3688 EVT Type = Op.getValueType();
3689 int64_t Val = C->getSExtValue();
3690 if ((Val <= 65535) && (Val >= 1)) {
3691 Result = DAG.getTargetConstant(Val, Type);
3698 if (Result.getNode()) {
3699 Ops.push_back(Result);
3703 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3707 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3708 // No global is ever allowed as a base.
3713 case 0: // "r+i" or just "i", depending on HasBaseReg.
3716 if (!AM.HasBaseReg) // allow "r+i".
3718 return false; // disallow "r+r" or "r+r+i".
3727 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3728 // The Mips target isn't yet aware of offsets.
3732 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3734 bool IsMemset, bool ZeroMemset,
3736 MachineFunction &MF) const {
3737 if (Subtarget->hasMips64())
3743 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3744 if (VT != MVT::f32 && VT != MVT::f64)
3746 if (Imm.isNegZero())
3748 return Imm.isZero();
3751 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3753 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3755 return TargetLowering::getJumpTableEncoding();
3758 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CallConv, bool IsVarArg,
3759 bool IsO32, CCState &Info) : CCInfo(Info) {
3760 UseRegsForByval = true;
3764 NumIntArgRegs = array_lengthof(O32IntRegs);
3765 ReservedArgArea = 16;
3766 IntArgRegs = ShadowRegs = O32IntRegs;
3767 FixedFn = VarFn = CC_MipsO32;
3770 NumIntArgRegs = array_lengthof(Mips64IntRegs);
3771 ReservedArgArea = 0;
3772 IntArgRegs = Mips64IntRegs;
3773 ShadowRegs = Mips64DPRegs;
3775 VarFn = CC_MipsN_VarArg;
3778 if (CallConv == CallingConv::Fast) {
3780 UseRegsForByval = false;
3781 ReservedArgArea = 0;
3782 FixedFn = VarFn = CC_Mips_FastCC;
3785 // Pre-allocate reserved argument area.
3786 CCInfo.AllocateStack(ReservedArgArea, 1);
3789 void MipsTargetLowering::MipsCC::
3790 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args) {
3791 unsigned NumOpnds = Args.size();
3793 for (unsigned I = 0; I != NumOpnds; ++I) {
3794 MVT ArgVT = Args[I].VT;
3795 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3798 if (ArgFlags.isByVal()) {
3799 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3803 if (Args[I].IsFixed)
3804 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3806 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3810 dbgs() << "Call operand #" << I << " has unhandled type "
3811 << EVT(ArgVT).getEVTString();
3813 llvm_unreachable(0);
3818 void MipsTargetLowering::MipsCC::
3819 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
3820 unsigned NumArgs = Args.size();
3822 for (unsigned I = 0; I != NumArgs; ++I) {
3823 MVT ArgVT = Args[I].VT;
3824 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3826 if (ArgFlags.isByVal()) {
3827 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3831 if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
3835 dbgs() << "Formal Arg #" << I << " has unhandled type "
3836 << EVT(ArgVT).getEVTString();
3838 llvm_unreachable(0);
3843 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3845 CCValAssign::LocInfo LocInfo,
3846 ISD::ArgFlagsTy ArgFlags) {
3847 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3849 struct ByValArgInfo ByVal;
3850 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3851 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3854 if (UseRegsForByval)
3855 allocateRegs(ByVal, ByValSize, Align);
3857 // Allocate space on caller's stack.
3858 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3860 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3862 ByValArgs.push_back(ByVal);
3865 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3868 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3869 "Byval argument's size and alignment should be a multiple of"
3872 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3874 // If Align > RegSize, the first arg register must be even.
3875 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3876 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3880 // Mark the registers allocated.
3881 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3882 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3883 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3886 void MipsTargetLowering::
3887 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3888 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3889 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3890 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3891 MachineFunction &MF = DAG.getMachineFunction();
3892 MachineFrameInfo *MFI = MF.getFrameInfo();
3893 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3894 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3898 FrameObjOffset = (int)CC.reservedArgArea() -
3899 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3901 FrameObjOffset = ByVal.Address;
3903 // Create frame object.
3904 EVT PtrTy = getPointerTy();
3905 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3906 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3907 InVals.push_back(FIN);
3912 // Copy arg registers.
3913 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3914 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3916 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3917 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3918 unsigned VReg = AddLiveIn(MF, ArgReg, RC);
3919 unsigned Offset = I * CC.regSize();
3920 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3921 DAG.getConstant(Offset, PtrTy));
3922 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3923 StorePtr, MachinePointerInfo(FuncArg, Offset),
3925 OutChains.push_back(Store);
3929 // Copy byVal arg to registers and stack.
3930 void MipsTargetLowering::
3931 passByValArg(SDValue Chain, DebugLoc DL,
3932 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3933 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3934 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3935 const MipsCC &CC, const ByValArgInfo &ByVal,
3936 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3937 unsigned ByValSize = Flags.getByValSize();
3938 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3939 unsigned RegSize = CC.regSize();
3940 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3941 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3943 if (ByVal.NumRegs) {
3944 const uint16_t *ArgRegs = CC.intArgRegs();
3945 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3948 // Copy words to registers.
3949 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3950 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3951 DAG.getConstant(Offset, PtrTy));
3952 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3953 MachinePointerInfo(), false, false, false,
3955 MemOpChains.push_back(LoadVal.getValue(1));
3956 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3957 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3960 // Return if the struct has been fully copied.
3961 if (ByValSize == Offset)
3964 // Copy the remainder of the byval argument with sub-word loads and shifts.
3965 if (LeftoverBytes) {
3966 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3967 "Size of the remainder should be smaller than RegSize.");
3970 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3971 Offset < ByValSize; LoadSize /= 2) {
3972 unsigned RemSize = ByValSize - Offset;
3974 if (RemSize < LoadSize)
3978 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3979 DAG.getConstant(Offset, PtrTy));
3981 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3982 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3983 false, false, Alignment);
3984 MemOpChains.push_back(LoadVal.getValue(1));
3986 // Shift the loaded value.
3990 Shamt = TotalSizeLoaded;
3992 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3994 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3995 DAG.getConstant(Shamt, MVT::i32));
3998 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4003 TotalSizeLoaded += LoadSize;
4004 Alignment = std::min(Alignment, LoadSize);
4007 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4008 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4013 // Copy remainder of byval arg to it with memcpy.
4014 unsigned MemCpySize = ByValSize - Offset;
4015 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4016 DAG.getConstant(Offset, PtrTy));
4017 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4018 DAG.getIntPtrConstant(ByVal.Address));
4019 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4020 DAG.getConstant(MemCpySize, PtrTy), Alignment,
4021 /*isVolatile=*/false, /*AlwaysInline=*/false,
4022 MachinePointerInfo(0), MachinePointerInfo(0));
4023 MemOpChains.push_back(Chain);
4027 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4028 const MipsCC &CC, SDValue Chain,
4029 DebugLoc DL, SelectionDAG &DAG) const {
4030 unsigned NumRegs = CC.numIntArgRegs();
4031 const uint16_t *ArgRegs = CC.intArgRegs();
4032 const CCState &CCInfo = CC.getCCInfo();
4033 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4034 unsigned RegSize = CC.regSize();
4035 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4036 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4037 MachineFunction &MF = DAG.getMachineFunction();
4038 MachineFrameInfo *MFI = MF.getFrameInfo();
4039 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4041 // Offset of the first variable argument from stack pointer.
4045 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4048 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4050 // Record the frame index of the first variable argument
4051 // which is a value necessary to VASTART.
4052 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4053 MipsFI->setVarArgsFrameIndex(FI);
4055 // Copy the integer registers that have not been used for argument passing
4056 // to the argument register save area. For O32, the save area is allocated
4057 // in the caller's stack frame, while for N32/64, it is allocated in the
4058 // callee's stack frame.
4059 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4060 unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
4061 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4062 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4063 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4064 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4065 MachinePointerInfo(), false, false, 0);
4066 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4067 OutChains.push_back(Store);