1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "mips-lower"
15 #include "MipsISelLowering.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
40 STATISTIC(NumTailCalls, "Number of tail calls");
43 LargeGOT("mxgot", cl::Hidden,
44 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
46 static const uint16_t O32IntRegs[4] = {
47 Mips::A0, Mips::A1, Mips::A2, Mips::A3
50 static const uint16_t Mips64IntRegs[8] = {
51 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
52 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
55 static const uint16_t Mips64DPRegs[8] = {
56 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
57 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
60 // If I is a shifted mask, set the size (Size) and the first bit of the
61 // mask (Pos), and return true.
62 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
63 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
64 if (!isShiftedMask_64(I))
67 Size = CountPopulation_64(I);
68 Pos = CountTrailingZeros_64(I);
72 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
73 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
74 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
77 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
78 EVT Ty = Op.getValueType();
80 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
81 return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
83 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
84 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
85 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
86 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
87 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
88 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
89 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
90 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
91 N->getOffset(), Flag);
93 llvm_unreachable("Unexpected node type.");
97 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
98 DebugLoc DL = Op.getDebugLoc();
99 EVT Ty = Op.getValueType();
100 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
101 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
102 return DAG.getNode(ISD::ADD, DL, Ty,
103 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
104 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
107 SDValue MipsTargetLowering::getAddrLocal(SDValue Op, SelectionDAG &DAG,
108 bool HasMips64) const {
109 DebugLoc DL = Op.getDebugLoc();
110 EVT Ty = Op.getValueType();
111 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
112 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
113 getTargetNode(Op, DAG, GOTFlag));
114 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
115 MachinePointerInfo::getGOT(), false, false, false,
117 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
118 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
119 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
122 SDValue MipsTargetLowering::getAddrGlobal(SDValue Op, SelectionDAG &DAG,
123 unsigned Flag) const {
124 DebugLoc DL = Op.getDebugLoc();
125 EVT Ty = Op.getValueType();
126 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
127 getTargetNode(Op, DAG, Flag));
128 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
129 MachinePointerInfo::getGOT(), false, false, false, 0);
132 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
134 unsigned LoFlag) const {
135 DebugLoc DL = Op.getDebugLoc();
136 EVT Ty = Op.getValueType();
137 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
138 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
139 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
140 getTargetNode(Op, DAG, LoFlag));
141 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
142 MachinePointerInfo::getGOT(), false, false, false, 0);
145 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
147 case MipsISD::JmpLink: return "MipsISD::JmpLink";
148 case MipsISD::TailCall: return "MipsISD::TailCall";
149 case MipsISD::Hi: return "MipsISD::Hi";
150 case MipsISD::Lo: return "MipsISD::Lo";
151 case MipsISD::GPRel: return "MipsISD::GPRel";
152 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
153 case MipsISD::Ret: return "MipsISD::Ret";
154 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
155 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
156 case MipsISD::FPCmp: return "MipsISD::FPCmp";
157 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
158 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
159 case MipsISD::FPRound: return "MipsISD::FPRound";
160 case MipsISD::ExtractLOHI: return "MipsISD::ExtractLOHI";
161 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
162 case MipsISD::Mult: return "MipsISD::Mult";
163 case MipsISD::Multu: return "MipsISD::Multu";
164 case MipsISD::MAdd: return "MipsISD::MAdd";
165 case MipsISD::MAddu: return "MipsISD::MAddu";
166 case MipsISD::MSub: return "MipsISD::MSub";
167 case MipsISD::MSubu: return "MipsISD::MSubu";
168 case MipsISD::DivRem: return "MipsISD::DivRem";
169 case MipsISD::DivRemU: return "MipsISD::DivRemU";
170 case MipsISD::DivRem16: return "MipsISD::DivRem16";
171 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
172 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
173 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
174 case MipsISD::Wrapper: return "MipsISD::Wrapper";
175 case MipsISD::Sync: return "MipsISD::Sync";
176 case MipsISD::Ext: return "MipsISD::Ext";
177 case MipsISD::Ins: return "MipsISD::Ins";
178 case MipsISD::LWL: return "MipsISD::LWL";
179 case MipsISD::LWR: return "MipsISD::LWR";
180 case MipsISD::SWL: return "MipsISD::SWL";
181 case MipsISD::SWR: return "MipsISD::SWR";
182 case MipsISD::LDL: return "MipsISD::LDL";
183 case MipsISD::LDR: return "MipsISD::LDR";
184 case MipsISD::SDL: return "MipsISD::SDL";
185 case MipsISD::SDR: return "MipsISD::SDR";
186 case MipsISD::EXTP: return "MipsISD::EXTP";
187 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
188 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
189 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
190 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
191 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
192 case MipsISD::SHILO: return "MipsISD::SHILO";
193 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
194 case MipsISD::MULT: return "MipsISD::MULT";
195 case MipsISD::MULTU: return "MipsISD::MULTU";
196 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
197 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
198 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
199 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
200 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
201 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
202 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
203 default: return NULL;
208 MipsTargetLowering(MipsTargetMachine &TM)
209 : TargetLowering(TM, new MipsTargetObjectFile()),
210 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
211 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
212 IsO32(Subtarget->isABI_O32()) {
213 // Mips does not have i1 type, so use i32 for
214 // setcc operations results (slt, sgt, ...).
215 setBooleanContents(ZeroOrOneBooleanContent);
216 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
218 // Load extented operations for i1 types must be promoted
219 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
220 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
221 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
223 // MIPS doesn't have extending float->double load/store
224 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
225 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
227 // Used by legalize types to correctly generate the setcc result.
228 // Without this, every float setcc comes with a AND/OR with the result,
229 // we don't want this, since the fpcmp result goes to a flag register,
230 // which is used implicitly by brcond and select operations.
231 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
233 // Mips Custom Operations
234 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
235 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
236 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
237 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
238 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
239 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
240 setOperationAction(ISD::SELECT, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT, MVT::f64, Custom);
242 setOperationAction(ISD::SELECT, MVT::i32, Custom);
243 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
244 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
245 setOperationAction(ISD::SETCC, MVT::f32, Custom);
246 setOperationAction(ISD::SETCC, MVT::f64, Custom);
247 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
248 setOperationAction(ISD::VASTART, MVT::Other, Custom);
249 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
252 if (!TM.Options.NoNaNsFPMath) {
253 setOperationAction(ISD::FABS, MVT::f32, Custom);
254 setOperationAction(ISD::FABS, MVT::f64, Custom);
258 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
259 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
260 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
261 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
262 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
263 setOperationAction(ISD::SELECT, MVT::i64, Custom);
264 setOperationAction(ISD::LOAD, MVT::i64, Custom);
265 setOperationAction(ISD::STORE, MVT::i64, Custom);
269 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
270 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
271 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
274 setOperationAction(ISD::ADD, MVT::i32, Custom);
276 setOperationAction(ISD::ADD, MVT::i64, Custom);
278 setOperationAction(ISD::SDIV, MVT::i32, Expand);
279 setOperationAction(ISD::SREM, MVT::i32, Expand);
280 setOperationAction(ISD::UDIV, MVT::i32, Expand);
281 setOperationAction(ISD::UREM, MVT::i32, Expand);
282 setOperationAction(ISD::SDIV, MVT::i64, Expand);
283 setOperationAction(ISD::SREM, MVT::i64, Expand);
284 setOperationAction(ISD::UDIV, MVT::i64, Expand);
285 setOperationAction(ISD::UREM, MVT::i64, Expand);
287 // Operations not directly supported by Mips.
288 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
289 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
290 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
291 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
292 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
293 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
294 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
296 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
297 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
298 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
299 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
300 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
301 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
302 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
303 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
304 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
305 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
306 setOperationAction(ISD::ROTL, MVT::i32, Expand);
307 setOperationAction(ISD::ROTL, MVT::i64, Expand);
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
311 if (!Subtarget->hasMips32r2())
312 setOperationAction(ISD::ROTR, MVT::i32, Expand);
314 if (!Subtarget->hasMips64r2())
315 setOperationAction(ISD::ROTR, MVT::i64, Expand);
317 setOperationAction(ISD::FSIN, MVT::f32, Expand);
318 setOperationAction(ISD::FSIN, MVT::f64, Expand);
319 setOperationAction(ISD::FCOS, MVT::f32, Expand);
320 setOperationAction(ISD::FCOS, MVT::f64, Expand);
321 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
322 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
323 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
324 setOperationAction(ISD::FPOW, MVT::f32, Expand);
325 setOperationAction(ISD::FPOW, MVT::f64, Expand);
326 setOperationAction(ISD::FLOG, MVT::f32, Expand);
327 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
328 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
329 setOperationAction(ISD::FEXP, MVT::f32, Expand);
330 setOperationAction(ISD::FMA, MVT::f32, Expand);
331 setOperationAction(ISD::FMA, MVT::f64, Expand);
332 setOperationAction(ISD::FREM, MVT::f32, Expand);
333 setOperationAction(ISD::FREM, MVT::f64, Expand);
335 if (!TM.Options.NoNaNsFPMath) {
336 setOperationAction(ISD::FNEG, MVT::f32, Expand);
337 setOperationAction(ISD::FNEG, MVT::f64, Expand);
340 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
341 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
342 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
345 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
347 setOperationAction(ISD::VAARG, MVT::Other, Expand);
348 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
349 setOperationAction(ISD::VAEND, MVT::Other, Expand);
351 // Use the default for now
352 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
353 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
355 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
356 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
357 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
358 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
360 setInsertFencesForAtomic(true);
362 if (!Subtarget->hasSEInReg()) {
363 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
364 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
367 if (!Subtarget->hasBitCount()) {
368 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
369 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
372 if (!Subtarget->hasSwap()) {
373 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
374 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
378 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
379 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
380 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
381 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
384 setTargetDAGCombine(ISD::SDIVREM);
385 setTargetDAGCombine(ISD::UDIVREM);
386 setTargetDAGCombine(ISD::SELECT);
387 setTargetDAGCombine(ISD::AND);
388 setTargetDAGCombine(ISD::OR);
389 setTargetDAGCombine(ISD::ADD);
391 setMinFunctionAlignment(HasMips64 ? 3 : 2);
393 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
395 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
396 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
398 MaxStoresPerMemcpy = 16;
401 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
402 if (TM.getSubtargetImpl()->inMips16Mode())
403 return llvm::createMips16TargetLowering(TM);
405 return llvm::createMipsSETargetLowering(TM);
408 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
411 return VT.changeVectorElementTypeToInteger();
414 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
415 TargetLowering::DAGCombinerInfo &DCI,
416 const MipsSubtarget *Subtarget) {
417 if (DCI.isBeforeLegalizeOps())
420 EVT Ty = N->getValueType(0);
421 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
422 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
423 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
425 DebugLoc DL = N->getDebugLoc();
427 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
428 N->getOperand(0), N->getOperand(1));
429 SDValue InChain = DAG.getEntryNode();
430 SDValue InGlue = DivRem;
433 if (N->hasAnyUseOfValue(0)) {
434 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
436 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
437 InChain = CopyFromLo.getValue(1);
438 InGlue = CopyFromLo.getValue(2);
442 if (N->hasAnyUseOfValue(1)) {
443 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
451 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
453 default: llvm_unreachable("Unknown fp condition code!");
455 case ISD::SETOEQ: return Mips::FCOND_OEQ;
456 case ISD::SETUNE: return Mips::FCOND_UNE;
458 case ISD::SETOLT: return Mips::FCOND_OLT;
460 case ISD::SETOGT: return Mips::FCOND_OGT;
462 case ISD::SETOLE: return Mips::FCOND_OLE;
464 case ISD::SETOGE: return Mips::FCOND_OGE;
465 case ISD::SETULT: return Mips::FCOND_ULT;
466 case ISD::SETULE: return Mips::FCOND_ULE;
467 case ISD::SETUGT: return Mips::FCOND_UGT;
468 case ISD::SETUGE: return Mips::FCOND_UGE;
469 case ISD::SETUO: return Mips::FCOND_UN;
470 case ISD::SETO: return Mips::FCOND_OR;
472 case ISD::SETONE: return Mips::FCOND_ONE;
473 case ISD::SETUEQ: return Mips::FCOND_UEQ;
478 /// This function returns true if the floating point conditional branches and
479 /// conditional moves which use condition code CC should be inverted.
480 static bool invertFPCondCodeUser(Mips::CondCode CC) {
481 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
484 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
485 "Illegal Condition Code");
490 // Creates and returns an FPCmp node from a setcc node.
491 // Returns Op if setcc is not a floating point comparison.
492 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
493 // must be a SETCC node
494 if (Op.getOpcode() != ISD::SETCC)
497 SDValue LHS = Op.getOperand(0);
499 if (!LHS.getValueType().isFloatingPoint())
502 SDValue RHS = Op.getOperand(1);
503 DebugLoc DL = Op.getDebugLoc();
505 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
506 // node if necessary.
507 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
509 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
510 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
513 // Creates and returns a CMovFPT/F node.
514 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
515 SDValue False, DebugLoc DL) {
516 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
517 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
519 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
520 True.getValueType(), True, False, Cond);
523 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
524 TargetLowering::DAGCombinerInfo &DCI,
525 const MipsSubtarget *Subtarget) {
526 if (DCI.isBeforeLegalizeOps())
529 SDValue SetCC = N->getOperand(0);
531 if ((SetCC.getOpcode() != ISD::SETCC) ||
532 !SetCC.getOperand(0).getValueType().isInteger())
535 SDValue False = N->getOperand(2);
536 EVT FalseTy = False.getValueType();
538 if (!FalseTy.isInteger())
541 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
543 if (!CN || CN->getZExtValue())
546 const DebugLoc DL = N->getDebugLoc();
547 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
548 SDValue True = N->getOperand(1);
550 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
551 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
553 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
556 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
557 TargetLowering::DAGCombinerInfo &DCI,
558 const MipsSubtarget *Subtarget) {
559 // Pattern match EXT.
560 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
561 // => ext $dst, $src, size, pos
562 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
565 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
566 unsigned ShiftRightOpc = ShiftRight.getOpcode();
568 // Op's first operand must be a shift right.
569 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
572 // The second operand of the shift must be an immediate.
574 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
577 uint64_t Pos = CN->getZExtValue();
578 uint64_t SMPos, SMSize;
580 // Op's second operand must be a shifted mask.
581 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
582 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
585 // Return if the shifted mask does not start at bit 0 or the sum of its size
586 // and Pos exceeds the word's size.
587 EVT ValTy = N->getValueType(0);
588 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
591 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
592 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
593 DAG.getConstant(SMSize, MVT::i32));
596 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
597 TargetLowering::DAGCombinerInfo &DCI,
598 const MipsSubtarget *Subtarget) {
599 // Pattern match INS.
600 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
601 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
602 // => ins $dst, $src, size, pos, $src1
603 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
606 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
607 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
610 // See if Op's first operand matches (and $src1 , mask0).
611 if (And0.getOpcode() != ISD::AND)
614 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
615 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
618 // See if Op's second operand matches (and (shl $src, pos), mask1).
619 if (And1.getOpcode() != ISD::AND)
622 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
623 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
626 // The shift masks must have the same position and size.
627 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
630 SDValue Shl = And1.getOperand(0);
631 if (Shl.getOpcode() != ISD::SHL)
634 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
637 unsigned Shamt = CN->getZExtValue();
639 // Return if the shift amount and the first bit position of mask are not the
641 EVT ValTy = N->getValueType(0);
642 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
645 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
646 DAG.getConstant(SMPos0, MVT::i32),
647 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
650 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
651 TargetLowering::DAGCombinerInfo &DCI,
652 const MipsSubtarget *Subtarget) {
653 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
655 if (DCI.isBeforeLegalizeOps())
658 SDValue Add = N->getOperand(1);
660 if (Add.getOpcode() != ISD::ADD)
663 SDValue Lo = Add.getOperand(1);
665 if ((Lo.getOpcode() != MipsISD::Lo) ||
666 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
669 EVT ValTy = N->getValueType(0);
670 DebugLoc DL = N->getDebugLoc();
672 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
674 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
677 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
679 SelectionDAG &DAG = DCI.DAG;
680 unsigned Opc = N->getOpcode();
686 return performDivRemCombine(N, DAG, DCI, Subtarget);
688 return performSELECTCombine(N, DAG, DCI, Subtarget);
690 return performANDCombine(N, DAG, DCI, Subtarget);
692 return performORCombine(N, DAG, DCI, Subtarget);
694 return performADDCombine(N, DAG, DCI, Subtarget);
701 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
702 SmallVectorImpl<SDValue> &Results,
703 SelectionDAG &DAG) const {
704 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
706 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
707 Results.push_back(Res.getValue(I));
711 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
712 SmallVectorImpl<SDValue> &Results,
713 SelectionDAG &DAG) const {
714 return LowerOperationWrapper(N, Results, DAG);
717 SDValue MipsTargetLowering::
718 LowerOperation(SDValue Op, SelectionDAG &DAG) const
720 switch (Op.getOpcode())
722 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
723 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
724 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
725 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
726 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
727 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
728 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
729 case ISD::SELECT: return lowerSELECT(Op, DAG);
730 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
731 case ISD::SETCC: return lowerSETCC(Op, DAG);
732 case ISD::VASTART: return lowerVASTART(Op, DAG);
733 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
734 case ISD::FABS: return lowerFABS(Op, DAG);
735 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
736 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
737 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
738 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
739 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
740 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
741 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
742 case ISD::LOAD: return lowerLOAD(Op, DAG);
743 case ISD::STORE: return lowerSTORE(Op, DAG);
744 case ISD::ADD: return lowerADD(Op, DAG);
749 //===----------------------------------------------------------------------===//
750 // Lower helper functions
751 //===----------------------------------------------------------------------===//
753 // addLiveIn - This helper function adds the specified physical register to the
754 // MachineFunction as a live in value. It also creates a corresponding
755 // virtual register for it.
757 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
759 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
760 MF.getRegInfo().addLiveIn(PReg, VReg);
765 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
766 MachineBasicBlock *BB) const {
767 switch (MI->getOpcode()) {
769 llvm_unreachable("Unexpected instr type to insert");
770 case Mips::ATOMIC_LOAD_ADD_I8:
771 case Mips::ATOMIC_LOAD_ADD_I8_P8:
772 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
773 case Mips::ATOMIC_LOAD_ADD_I16:
774 case Mips::ATOMIC_LOAD_ADD_I16_P8:
775 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
776 case Mips::ATOMIC_LOAD_ADD_I32:
777 case Mips::ATOMIC_LOAD_ADD_I32_P8:
778 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
779 case Mips::ATOMIC_LOAD_ADD_I64:
780 case Mips::ATOMIC_LOAD_ADD_I64_P8:
781 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
783 case Mips::ATOMIC_LOAD_AND_I8:
784 case Mips::ATOMIC_LOAD_AND_I8_P8:
785 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
786 case Mips::ATOMIC_LOAD_AND_I16:
787 case Mips::ATOMIC_LOAD_AND_I16_P8:
788 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
789 case Mips::ATOMIC_LOAD_AND_I32:
790 case Mips::ATOMIC_LOAD_AND_I32_P8:
791 return emitAtomicBinary(MI, BB, 4, Mips::AND);
792 case Mips::ATOMIC_LOAD_AND_I64:
793 case Mips::ATOMIC_LOAD_AND_I64_P8:
794 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
796 case Mips::ATOMIC_LOAD_OR_I8:
797 case Mips::ATOMIC_LOAD_OR_I8_P8:
798 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
799 case Mips::ATOMIC_LOAD_OR_I16:
800 case Mips::ATOMIC_LOAD_OR_I16_P8:
801 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
802 case Mips::ATOMIC_LOAD_OR_I32:
803 case Mips::ATOMIC_LOAD_OR_I32_P8:
804 return emitAtomicBinary(MI, BB, 4, Mips::OR);
805 case Mips::ATOMIC_LOAD_OR_I64:
806 case Mips::ATOMIC_LOAD_OR_I64_P8:
807 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
809 case Mips::ATOMIC_LOAD_XOR_I8:
810 case Mips::ATOMIC_LOAD_XOR_I8_P8:
811 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
812 case Mips::ATOMIC_LOAD_XOR_I16:
813 case Mips::ATOMIC_LOAD_XOR_I16_P8:
814 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
815 case Mips::ATOMIC_LOAD_XOR_I32:
816 case Mips::ATOMIC_LOAD_XOR_I32_P8:
817 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
818 case Mips::ATOMIC_LOAD_XOR_I64:
819 case Mips::ATOMIC_LOAD_XOR_I64_P8:
820 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
822 case Mips::ATOMIC_LOAD_NAND_I8:
823 case Mips::ATOMIC_LOAD_NAND_I8_P8:
824 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
825 case Mips::ATOMIC_LOAD_NAND_I16:
826 case Mips::ATOMIC_LOAD_NAND_I16_P8:
827 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
828 case Mips::ATOMIC_LOAD_NAND_I32:
829 case Mips::ATOMIC_LOAD_NAND_I32_P8:
830 return emitAtomicBinary(MI, BB, 4, 0, true);
831 case Mips::ATOMIC_LOAD_NAND_I64:
832 case Mips::ATOMIC_LOAD_NAND_I64_P8:
833 return emitAtomicBinary(MI, BB, 8, 0, true);
835 case Mips::ATOMIC_LOAD_SUB_I8:
836 case Mips::ATOMIC_LOAD_SUB_I8_P8:
837 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
838 case Mips::ATOMIC_LOAD_SUB_I16:
839 case Mips::ATOMIC_LOAD_SUB_I16_P8:
840 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
841 case Mips::ATOMIC_LOAD_SUB_I32:
842 case Mips::ATOMIC_LOAD_SUB_I32_P8:
843 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
844 case Mips::ATOMIC_LOAD_SUB_I64:
845 case Mips::ATOMIC_LOAD_SUB_I64_P8:
846 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
848 case Mips::ATOMIC_SWAP_I8:
849 case Mips::ATOMIC_SWAP_I8_P8:
850 return emitAtomicBinaryPartword(MI, BB, 1, 0);
851 case Mips::ATOMIC_SWAP_I16:
852 case Mips::ATOMIC_SWAP_I16_P8:
853 return emitAtomicBinaryPartword(MI, BB, 2, 0);
854 case Mips::ATOMIC_SWAP_I32:
855 case Mips::ATOMIC_SWAP_I32_P8:
856 return emitAtomicBinary(MI, BB, 4, 0);
857 case Mips::ATOMIC_SWAP_I64:
858 case Mips::ATOMIC_SWAP_I64_P8:
859 return emitAtomicBinary(MI, BB, 8, 0);
861 case Mips::ATOMIC_CMP_SWAP_I8:
862 case Mips::ATOMIC_CMP_SWAP_I8_P8:
863 return emitAtomicCmpSwapPartword(MI, BB, 1);
864 case Mips::ATOMIC_CMP_SWAP_I16:
865 case Mips::ATOMIC_CMP_SWAP_I16_P8:
866 return emitAtomicCmpSwapPartword(MI, BB, 2);
867 case Mips::ATOMIC_CMP_SWAP_I32:
868 case Mips::ATOMIC_CMP_SWAP_I32_P8:
869 return emitAtomicCmpSwap(MI, BB, 4);
870 case Mips::ATOMIC_CMP_SWAP_I64:
871 case Mips::ATOMIC_CMP_SWAP_I64_P8:
872 return emitAtomicCmpSwap(MI, BB, 8);
876 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
877 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
879 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
880 unsigned Size, unsigned BinOpcode,
882 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
884 MachineFunction *MF = BB->getParent();
885 MachineRegisterInfo &RegInfo = MF->getRegInfo();
886 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
887 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
888 DebugLoc DL = MI->getDebugLoc();
889 unsigned LL, SC, AND, NOR, ZERO, BEQ;
892 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
893 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
900 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
901 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
904 ZERO = Mips::ZERO_64;
908 unsigned OldVal = MI->getOperand(0).getReg();
909 unsigned Ptr = MI->getOperand(1).getReg();
910 unsigned Incr = MI->getOperand(2).getReg();
912 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
913 unsigned AndRes = RegInfo.createVirtualRegister(RC);
914 unsigned Success = RegInfo.createVirtualRegister(RC);
916 // insert new blocks after the current block
917 const BasicBlock *LLVM_BB = BB->getBasicBlock();
918 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
919 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
920 MachineFunction::iterator It = BB;
922 MF->insert(It, loopMBB);
923 MF->insert(It, exitMBB);
925 // Transfer the remainder of BB and its successor edges to exitMBB.
926 exitMBB->splice(exitMBB->begin(), BB,
927 llvm::next(MachineBasicBlock::iterator(MI)),
929 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
933 // fallthrough --> loopMBB
934 BB->addSuccessor(loopMBB);
935 loopMBB->addSuccessor(loopMBB);
936 loopMBB->addSuccessor(exitMBB);
940 // <binop> storeval, oldval, incr
941 // sc success, storeval, 0(ptr)
942 // beq success, $0, loopMBB
944 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
946 // and andres, oldval, incr
947 // nor storeval, $0, andres
948 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
949 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
950 } else if (BinOpcode) {
951 // <binop> storeval, oldval, incr
952 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
956 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
957 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
959 MI->eraseFromParent(); // The instruction is gone now.
965 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
966 MachineBasicBlock *BB,
967 unsigned Size, unsigned BinOpcode,
969 assert((Size == 1 || Size == 2) &&
970 "Unsupported size for EmitAtomicBinaryPartial.");
972 MachineFunction *MF = BB->getParent();
973 MachineRegisterInfo &RegInfo = MF->getRegInfo();
974 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
975 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
976 DebugLoc DL = MI->getDebugLoc();
977 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
978 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
980 unsigned Dest = MI->getOperand(0).getReg();
981 unsigned Ptr = MI->getOperand(1).getReg();
982 unsigned Incr = MI->getOperand(2).getReg();
984 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
985 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
986 unsigned Mask = RegInfo.createVirtualRegister(RC);
987 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
988 unsigned NewVal = RegInfo.createVirtualRegister(RC);
989 unsigned OldVal = RegInfo.createVirtualRegister(RC);
990 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
991 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
992 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
993 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
994 unsigned AndRes = RegInfo.createVirtualRegister(RC);
995 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
996 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
997 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
998 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
999 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1000 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1001 unsigned Success = RegInfo.createVirtualRegister(RC);
1003 // insert new blocks after the current block
1004 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1005 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1006 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1007 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1008 MachineFunction::iterator It = BB;
1010 MF->insert(It, loopMBB);
1011 MF->insert(It, sinkMBB);
1012 MF->insert(It, exitMBB);
1014 // Transfer the remainder of BB and its successor edges to exitMBB.
1015 exitMBB->splice(exitMBB->begin(), BB,
1016 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1017 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1019 BB->addSuccessor(loopMBB);
1020 loopMBB->addSuccessor(loopMBB);
1021 loopMBB->addSuccessor(sinkMBB);
1022 sinkMBB->addSuccessor(exitMBB);
1025 // addiu masklsb2,$0,-4 # 0xfffffffc
1026 // and alignedaddr,ptr,masklsb2
1027 // andi ptrlsb2,ptr,3
1028 // sll shiftamt,ptrlsb2,3
1029 // ori maskupper,$0,255 # 0xff
1030 // sll mask,maskupper,shiftamt
1031 // nor mask2,$0,mask
1032 // sll incr2,incr,shiftamt
1034 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1035 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1036 .addReg(Mips::ZERO).addImm(-4);
1037 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1038 .addReg(Ptr).addReg(MaskLSB2);
1039 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1040 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1041 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1042 .addReg(Mips::ZERO).addImm(MaskImm);
1043 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1044 .addReg(ShiftAmt).addReg(MaskUpper);
1045 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1046 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1048 // atomic.load.binop
1050 // ll oldval,0(alignedaddr)
1051 // binop binopres,oldval,incr2
1052 // and newval,binopres,mask
1053 // and maskedoldval0,oldval,mask2
1054 // or storeval,maskedoldval0,newval
1055 // sc success,storeval,0(alignedaddr)
1056 // beq success,$0,loopMBB
1060 // ll oldval,0(alignedaddr)
1061 // and newval,incr2,mask
1062 // and maskedoldval0,oldval,mask2
1063 // or storeval,maskedoldval0,newval
1064 // sc success,storeval,0(alignedaddr)
1065 // beq success,$0,loopMBB
1068 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1070 // and andres, oldval, incr2
1071 // nor binopres, $0, andres
1072 // and newval, binopres, mask
1073 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1074 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1075 .addReg(Mips::ZERO).addReg(AndRes);
1076 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1077 } else if (BinOpcode) {
1078 // <binop> binopres, oldval, incr2
1079 // and newval, binopres, mask
1080 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1081 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1082 } else {// atomic.swap
1083 // and newval, incr2, mask
1084 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1087 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1088 .addReg(OldVal).addReg(Mask2);
1089 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1090 .addReg(MaskedOldVal0).addReg(NewVal);
1091 BuildMI(BB, DL, TII->get(SC), Success)
1092 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1093 BuildMI(BB, DL, TII->get(Mips::BEQ))
1094 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1097 // and maskedoldval1,oldval,mask
1098 // srl srlres,maskedoldval1,shiftamt
1099 // sll sllres,srlres,24
1100 // sra dest,sllres,24
1102 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1104 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1105 .addReg(OldVal).addReg(Mask);
1106 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1107 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1108 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1109 .addReg(SrlRes).addImm(ShiftImm);
1110 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1111 .addReg(SllRes).addImm(ShiftImm);
1113 MI->eraseFromParent(); // The instruction is gone now.
1119 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1120 MachineBasicBlock *BB,
1121 unsigned Size) const {
1122 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1124 MachineFunction *MF = BB->getParent();
1125 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1126 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1127 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1128 DebugLoc DL = MI->getDebugLoc();
1129 unsigned LL, SC, ZERO, BNE, BEQ;
1132 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1133 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1139 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1140 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1141 ZERO = Mips::ZERO_64;
1146 unsigned Dest = MI->getOperand(0).getReg();
1147 unsigned Ptr = MI->getOperand(1).getReg();
1148 unsigned OldVal = MI->getOperand(2).getReg();
1149 unsigned NewVal = MI->getOperand(3).getReg();
1151 unsigned Success = RegInfo.createVirtualRegister(RC);
1153 // insert new blocks after the current block
1154 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1155 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1156 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1157 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1158 MachineFunction::iterator It = BB;
1160 MF->insert(It, loop1MBB);
1161 MF->insert(It, loop2MBB);
1162 MF->insert(It, exitMBB);
1164 // Transfer the remainder of BB and its successor edges to exitMBB.
1165 exitMBB->splice(exitMBB->begin(), BB,
1166 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1167 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1171 // fallthrough --> loop1MBB
1172 BB->addSuccessor(loop1MBB);
1173 loop1MBB->addSuccessor(exitMBB);
1174 loop1MBB->addSuccessor(loop2MBB);
1175 loop2MBB->addSuccessor(loop1MBB);
1176 loop2MBB->addSuccessor(exitMBB);
1180 // bne dest, oldval, exitMBB
1182 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1183 BuildMI(BB, DL, TII->get(BNE))
1184 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1187 // sc success, newval, 0(ptr)
1188 // beq success, $0, loop1MBB
1190 BuildMI(BB, DL, TII->get(SC), Success)
1191 .addReg(NewVal).addReg(Ptr).addImm(0);
1192 BuildMI(BB, DL, TII->get(BEQ))
1193 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1195 MI->eraseFromParent(); // The instruction is gone now.
1201 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1202 MachineBasicBlock *BB,
1203 unsigned Size) const {
1204 assert((Size == 1 || Size == 2) &&
1205 "Unsupported size for EmitAtomicCmpSwapPartial.");
1207 MachineFunction *MF = BB->getParent();
1208 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1209 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1210 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1211 DebugLoc DL = MI->getDebugLoc();
1212 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1213 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1215 unsigned Dest = MI->getOperand(0).getReg();
1216 unsigned Ptr = MI->getOperand(1).getReg();
1217 unsigned CmpVal = MI->getOperand(2).getReg();
1218 unsigned NewVal = MI->getOperand(3).getReg();
1220 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1221 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1222 unsigned Mask = RegInfo.createVirtualRegister(RC);
1223 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1224 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1225 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1226 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1227 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1228 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1229 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1230 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1231 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1232 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1233 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1234 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1235 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1236 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1237 unsigned Success = RegInfo.createVirtualRegister(RC);
1239 // insert new blocks after the current block
1240 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1241 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1242 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1243 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1244 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245 MachineFunction::iterator It = BB;
1247 MF->insert(It, loop1MBB);
1248 MF->insert(It, loop2MBB);
1249 MF->insert(It, sinkMBB);
1250 MF->insert(It, exitMBB);
1252 // Transfer the remainder of BB and its successor edges to exitMBB.
1253 exitMBB->splice(exitMBB->begin(), BB,
1254 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1255 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1257 BB->addSuccessor(loop1MBB);
1258 loop1MBB->addSuccessor(sinkMBB);
1259 loop1MBB->addSuccessor(loop2MBB);
1260 loop2MBB->addSuccessor(loop1MBB);
1261 loop2MBB->addSuccessor(sinkMBB);
1262 sinkMBB->addSuccessor(exitMBB);
1264 // FIXME: computation of newval2 can be moved to loop2MBB.
1266 // addiu masklsb2,$0,-4 # 0xfffffffc
1267 // and alignedaddr,ptr,masklsb2
1268 // andi ptrlsb2,ptr,3
1269 // sll shiftamt,ptrlsb2,3
1270 // ori maskupper,$0,255 # 0xff
1271 // sll mask,maskupper,shiftamt
1272 // nor mask2,$0,mask
1273 // andi maskedcmpval,cmpval,255
1274 // sll shiftedcmpval,maskedcmpval,shiftamt
1275 // andi maskednewval,newval,255
1276 // sll shiftednewval,maskednewval,shiftamt
1277 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1278 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1279 .addReg(Mips::ZERO).addImm(-4);
1280 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1281 .addReg(Ptr).addReg(MaskLSB2);
1282 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1283 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1284 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1285 .addReg(Mips::ZERO).addImm(MaskImm);
1286 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1287 .addReg(ShiftAmt).addReg(MaskUpper);
1288 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1289 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1290 .addReg(CmpVal).addImm(MaskImm);
1291 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1292 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1293 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1294 .addReg(NewVal).addImm(MaskImm);
1295 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1296 .addReg(ShiftAmt).addReg(MaskedNewVal);
1299 // ll oldval,0(alginedaddr)
1300 // and maskedoldval0,oldval,mask
1301 // bne maskedoldval0,shiftedcmpval,sinkMBB
1303 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1304 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1305 .addReg(OldVal).addReg(Mask);
1306 BuildMI(BB, DL, TII->get(Mips::BNE))
1307 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1310 // and maskedoldval1,oldval,mask2
1311 // or storeval,maskedoldval1,shiftednewval
1312 // sc success,storeval,0(alignedaddr)
1313 // beq success,$0,loop1MBB
1315 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1316 .addReg(OldVal).addReg(Mask2);
1317 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1318 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1319 BuildMI(BB, DL, TII->get(SC), Success)
1320 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1321 BuildMI(BB, DL, TII->get(Mips::BEQ))
1322 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1325 // srl srlres,maskedoldval0,shiftamt
1326 // sll sllres,srlres,24
1327 // sra dest,sllres,24
1329 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1331 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1332 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1333 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1334 .addReg(SrlRes).addImm(ShiftImm);
1335 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1336 .addReg(SllRes).addImm(ShiftImm);
1338 MI->eraseFromParent(); // The instruction is gone now.
1343 //===----------------------------------------------------------------------===//
1344 // Misc Lower Operation implementation
1345 //===----------------------------------------------------------------------===//
1346 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1347 SDValue Chain = Op.getOperand(0);
1348 SDValue Table = Op.getOperand(1);
1349 SDValue Index = Op.getOperand(2);
1350 DebugLoc DL = Op.getDebugLoc();
1351 EVT PTy = getPointerTy();
1352 unsigned EntrySize =
1353 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1355 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1356 DAG.getConstant(EntrySize, PTy));
1357 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1359 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1360 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1361 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1363 Chain = Addr.getValue(1);
1365 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1366 // For PIC, the sequence is:
1367 // BRIND(load(Jumptable + index) + RelocBase)
1368 // RelocBase can be JumpTable, GOT or some sort of global base.
1369 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1370 getPICJumpTableRelocBase(Table, DAG));
1373 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1376 SDValue MipsTargetLowering::
1377 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1379 // The first operand is the chain, the second is the condition, the third is
1380 // the block to branch to if the condition is true.
1381 SDValue Chain = Op.getOperand(0);
1382 SDValue Dest = Op.getOperand(2);
1383 DebugLoc DL = Op.getDebugLoc();
1385 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1387 // Return if flag is not set by a floating point comparison.
1388 if (CondRes.getOpcode() != MipsISD::FPCmp)
1391 SDValue CCNode = CondRes.getOperand(2);
1393 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1394 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1395 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1396 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1400 SDValue MipsTargetLowering::
1401 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1403 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1405 // Return if flag is not set by a floating point comparison.
1406 if (Cond.getOpcode() != MipsISD::FPCmp)
1409 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1413 SDValue MipsTargetLowering::
1414 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1416 DebugLoc DL = Op.getDebugLoc();
1417 EVT Ty = Op.getOperand(0).getValueType();
1418 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1419 Op.getOperand(0), Op.getOperand(1),
1422 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1426 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1427 SDValue Cond = createFPCmp(DAG, Op);
1429 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1430 "Floating point operand expected.");
1432 SDValue True = DAG.getConstant(1, MVT::i32);
1433 SDValue False = DAG.getConstant(0, MVT::i32);
1435 return createCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1438 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1439 SelectionDAG &DAG) const {
1440 // FIXME there isn't actually debug info here
1441 DebugLoc DL = Op.getDebugLoc();
1442 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1444 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1445 const MipsTargetObjectFile &TLOF =
1446 (const MipsTargetObjectFile&)getObjFileLowering();
1448 // %gp_rel relocation
1449 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1450 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1452 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1453 DAG.getVTList(MVT::i32), &GA, 1);
1454 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1455 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1458 // %hi/%lo relocation
1459 return getAddrNonPIC(Op, DAG);
1462 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1463 return getAddrLocal(Op, DAG, HasMips64);
1466 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1467 MipsII::MO_GOT_LO16);
1469 return getAddrGlobal(Op, DAG,
1470 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1473 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1474 SelectionDAG &DAG) const {
1475 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1476 return getAddrNonPIC(Op, DAG);
1478 return getAddrLocal(Op, DAG, HasMips64);
1481 SDValue MipsTargetLowering::
1482 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1484 // If the relocation model is PIC, use the General Dynamic TLS Model or
1485 // Local Dynamic TLS model, otherwise use the Initial Exec or
1486 // Local Exec TLS Model.
1488 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1489 DebugLoc DL = GA->getDebugLoc();
1490 const GlobalValue *GV = GA->getGlobal();
1491 EVT PtrVT = getPointerTy();
1493 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1495 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1496 // General Dynamic and Local Dynamic TLS Model.
1497 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1500 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1501 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1502 getGlobalReg(DAG, PtrVT), TGA);
1503 unsigned PtrSize = PtrVT.getSizeInBits();
1504 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1506 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1510 Entry.Node = Argument;
1512 Args.push_back(Entry);
1514 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1515 false, false, false, false, 0, CallingConv::C,
1516 /*IsTailCall=*/false, /*doesNotRet=*/false,
1517 /*isReturnValueUsed=*/true,
1518 TlsGetAddr, Args, DAG, DL);
1519 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1521 SDValue Ret = CallResult.first;
1523 if (model != TLSModel::LocalDynamic)
1526 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1527 MipsII::MO_DTPREL_HI);
1528 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1529 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1530 MipsII::MO_DTPREL_LO);
1531 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1532 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1533 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1537 if (model == TLSModel::InitialExec) {
1538 // Initial Exec TLS Model
1539 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1540 MipsII::MO_GOTTPREL);
1541 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1543 Offset = DAG.getLoad(PtrVT, DL,
1544 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1545 false, false, false, 0);
1547 // Local Exec TLS Model
1548 assert(model == TLSModel::LocalExec);
1549 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1550 MipsII::MO_TPREL_HI);
1551 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1552 MipsII::MO_TPREL_LO);
1553 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1554 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1555 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1558 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1559 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1562 SDValue MipsTargetLowering::
1563 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1565 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1566 return getAddrNonPIC(Op, DAG);
1568 return getAddrLocal(Op, DAG, HasMips64);
1571 SDValue MipsTargetLowering::
1572 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1574 // gp_rel relocation
1575 // FIXME: we should reference the constant pool using small data sections,
1576 // but the asm printer currently doesn't support this feature without
1577 // hacking it. This feature should come soon so we can uncomment the
1579 //if (IsInSmallSection(C->getType())) {
1580 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1581 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1582 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1584 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1585 return getAddrNonPIC(Op, DAG);
1587 return getAddrLocal(Op, DAG, HasMips64);
1590 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1591 MachineFunction &MF = DAG.getMachineFunction();
1592 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1594 DebugLoc DL = Op.getDebugLoc();
1595 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1598 // vastart just stores the address of the VarArgsFrameIndex slot into the
1599 // memory location argument.
1600 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1601 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1602 MachinePointerInfo(SV), false, false, 0);
1605 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1606 EVT TyX = Op.getOperand(0).getValueType();
1607 EVT TyY = Op.getOperand(1).getValueType();
1608 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1609 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1610 DebugLoc DL = Op.getDebugLoc();
1613 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1615 SDValue X = (TyX == MVT::f32) ?
1616 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1617 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1619 SDValue Y = (TyY == MVT::f32) ?
1620 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1621 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1625 // ext E, Y, 31, 1 ; extract bit31 of Y
1626 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1627 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1628 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1631 // srl SrlX, SllX, 1
1633 // sll SllY, SrlX, 31
1634 // or Or, SrlX, SllY
1635 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1636 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1637 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1638 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1639 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1642 if (TyX == MVT::f32)
1643 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1645 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1646 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1647 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1650 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1651 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1652 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1653 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1654 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1655 DebugLoc DL = Op.getDebugLoc();
1657 // Bitcast to integer nodes.
1658 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1659 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1662 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1663 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1664 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1665 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1667 if (WidthX > WidthY)
1668 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1669 else if (WidthY > WidthX)
1670 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1672 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1673 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1674 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1677 // (d)sll SllX, X, 1
1678 // (d)srl SrlX, SllX, 1
1679 // (d)srl SrlY, Y, width(Y)-1
1680 // (d)sll SllY, SrlX, width(Y)-1
1681 // or Or, SrlX, SllY
1682 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1683 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1684 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1685 DAG.getConstant(WidthY - 1, MVT::i32));
1687 if (WidthX > WidthY)
1688 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1689 else if (WidthY > WidthX)
1690 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1692 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1693 DAG.getConstant(WidthX - 1, MVT::i32));
1694 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1695 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1699 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1700 if (Subtarget->hasMips64())
1701 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1703 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1706 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1707 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1708 DebugLoc DL = Op.getDebugLoc();
1710 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1712 SDValue X = (Op.getValueType() == MVT::f32) ?
1713 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1714 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1719 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1720 DAG.getRegister(Mips::ZERO, MVT::i32),
1721 DAG.getConstant(31, MVT::i32), Const1, X);
1723 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1724 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1727 if (Op.getValueType() == MVT::f32)
1728 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1730 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1731 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1732 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1735 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1736 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1737 DebugLoc DL = Op.getDebugLoc();
1739 // Bitcast to integer node.
1740 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1744 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1745 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1746 DAG.getConstant(63, MVT::i32), Const1, X);
1748 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1749 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1752 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1756 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1757 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1758 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1760 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1763 SDValue MipsTargetLowering::
1764 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1766 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1767 "Frame address can only be determined for current frame.");
1769 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1770 MFI->setFrameAddressIsTaken(true);
1771 EVT VT = Op.getValueType();
1772 DebugLoc DL = Op.getDebugLoc();
1773 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1774 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1778 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1779 SelectionDAG &DAG) const {
1781 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1782 "Return address can be determined only for current frame.");
1784 MachineFunction &MF = DAG.getMachineFunction();
1785 MachineFrameInfo *MFI = MF.getFrameInfo();
1786 MVT VT = Op.getSimpleValueType();
1787 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1788 MFI->setReturnAddressIsTaken(true);
1790 // Return RA, which contains the return address. Mark it an implicit live-in.
1791 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1792 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
1795 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1796 // generated from __builtin_eh_return (offset, handler)
1797 // The effect of this is to adjust the stack pointer by "offset"
1798 // and then branch to "handler".
1799 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1801 MachineFunction &MF = DAG.getMachineFunction();
1802 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1804 MipsFI->setCallsEhReturn();
1805 SDValue Chain = Op.getOperand(0);
1806 SDValue Offset = Op.getOperand(1);
1807 SDValue Handler = Op.getOperand(2);
1808 DebugLoc DL = Op.getDebugLoc();
1809 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1811 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1812 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1813 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1814 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1815 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1816 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1817 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1818 DAG.getRegister(OffsetReg, Ty),
1819 DAG.getRegister(AddrReg, getPointerTy()),
1823 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1824 SelectionDAG &DAG) const {
1825 // FIXME: Need pseudo-fence for 'singlethread' fences
1826 // FIXME: Set SType for weaker fences where supported/appropriate.
1828 DebugLoc DL = Op.getDebugLoc();
1829 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1830 DAG.getConstant(SType, MVT::i32));
1833 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1834 SelectionDAG &DAG) const {
1835 DebugLoc DL = Op.getDebugLoc();
1836 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1837 SDValue Shamt = Op.getOperand(2);
1840 // lo = (shl lo, shamt)
1841 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1844 // hi = (shl lo, shamt[4:0])
1845 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1846 DAG.getConstant(-1, MVT::i32));
1847 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1848 DAG.getConstant(1, MVT::i32));
1849 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1851 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1852 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1853 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1854 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1855 DAG.getConstant(0x20, MVT::i32));
1856 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1857 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1858 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1860 SDValue Ops[2] = {Lo, Hi};
1861 return DAG.getMergeValues(Ops, 2, DL);
1864 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1866 DebugLoc DL = Op.getDebugLoc();
1867 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1868 SDValue Shamt = Op.getOperand(2);
1871 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1873 // hi = (sra hi, shamt)
1875 // hi = (srl hi, shamt)
1878 // lo = (sra hi, shamt[4:0])
1879 // hi = (sra hi, 31)
1881 // lo = (srl hi, shamt[4:0])
1883 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1884 DAG.getConstant(-1, MVT::i32));
1885 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1886 DAG.getConstant(1, MVT::i32));
1887 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1888 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1889 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1890 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1892 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1893 DAG.getConstant(0x20, MVT::i32));
1894 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1895 DAG.getConstant(31, MVT::i32));
1896 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1897 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1898 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1901 SDValue Ops[2] = {Lo, Hi};
1902 return DAG.getMergeValues(Ops, 2, DL);
1905 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1906 SDValue Chain, SDValue Src, unsigned Offset) {
1907 SDValue Ptr = LD->getBasePtr();
1908 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1909 EVT BasePtrVT = Ptr.getValueType();
1910 DebugLoc DL = LD->getDebugLoc();
1911 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1914 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1915 DAG.getConstant(Offset, BasePtrVT));
1917 SDValue Ops[] = { Chain, Ptr, Src };
1918 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1919 LD->getMemOperand());
1922 // Expand an unaligned 32 or 64-bit integer load node.
1923 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1924 LoadSDNode *LD = cast<LoadSDNode>(Op);
1925 EVT MemVT = LD->getMemoryVT();
1927 // Return if load is aligned or if MemVT is neither i32 nor i64.
1928 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1929 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1932 bool IsLittle = Subtarget->isLittle();
1933 EVT VT = Op.getValueType();
1934 ISD::LoadExtType ExtType = LD->getExtensionType();
1935 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1937 assert((VT == MVT::i32) || (VT == MVT::i64));
1940 // (set dst, (i64 (load baseptr)))
1942 // (set tmp, (ldl (add baseptr, 7), undef))
1943 // (set dst, (ldr baseptr, tmp))
1944 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1945 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1947 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1951 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1953 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1957 // (set dst, (i32 (load baseptr))) or
1958 // (set dst, (i64 (sextload baseptr))) or
1959 // (set dst, (i64 (extload baseptr)))
1961 // (set tmp, (lwl (add baseptr, 3), undef))
1962 // (set dst, (lwr baseptr, tmp))
1963 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1964 (ExtType == ISD::EXTLOAD))
1967 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1970 // (set dst, (i64 (zextload baseptr)))
1972 // (set tmp0, (lwl (add baseptr, 3), undef))
1973 // (set tmp1, (lwr baseptr, tmp0))
1974 // (set tmp2, (shl tmp1, 32))
1975 // (set dst, (srl tmp2, 32))
1976 DebugLoc DL = LD->getDebugLoc();
1977 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1978 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1979 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1980 SDValue Ops[] = { SRL, LWR.getValue(1) };
1981 return DAG.getMergeValues(Ops, 2, DL);
1984 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
1985 SDValue Chain, unsigned Offset) {
1986 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
1987 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
1988 DebugLoc DL = SD->getDebugLoc();
1989 SDVTList VTList = DAG.getVTList(MVT::Other);
1992 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1993 DAG.getConstant(Offset, BasePtrVT));
1995 SDValue Ops[] = { Chain, Value, Ptr };
1996 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1997 SD->getMemOperand());
2000 // Expand an unaligned 32 or 64-bit integer store node.
2001 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2002 StoreSDNode *SD = cast<StoreSDNode>(Op);
2003 EVT MemVT = SD->getMemoryVT();
2005 // Return if store is aligned or if MemVT is neither i32 nor i64.
2006 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2007 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2010 bool IsLittle = Subtarget->isLittle();
2011 SDValue Value = SD->getValue(), Chain = SD->getChain();
2012 EVT VT = Value.getValueType();
2015 // (store val, baseptr) or
2016 // (truncstore val, baseptr)
2018 // (swl val, (add baseptr, 3))
2019 // (swr val, baseptr)
2020 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2021 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2023 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2026 assert(VT == MVT::i64);
2029 // (store val, baseptr)
2031 // (sdl val, (add baseptr, 7))
2032 // (sdr val, baseptr)
2033 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2034 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2037 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2038 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2039 || cast<ConstantSDNode>
2040 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2041 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2045 // (add (frameaddr 0), (frame_to_args_offset))
2046 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2047 // (add FrameObject, 0)
2048 // where FrameObject is a fixed StackObject with offset 0 which points to
2049 // the old stack pointer.
2050 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2051 EVT ValTy = Op->getValueType(0);
2052 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2053 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2054 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2055 DAG.getConstant(0, ValTy));
2058 //===----------------------------------------------------------------------===//
2059 // Calling Convention Implementation
2060 //===----------------------------------------------------------------------===//
2062 //===----------------------------------------------------------------------===//
2063 // TODO: Implement a generic logic using tblgen that can support this.
2064 // Mips O32 ABI rules:
2066 // i32 - Passed in A0, A1, A2, A3 and stack
2067 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2068 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2069 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2070 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2071 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2074 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2075 //===----------------------------------------------------------------------===//
2077 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2078 MVT LocVT, CCValAssign::LocInfo LocInfo,
2079 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2081 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2083 static const uint16_t IntRegs[] = {
2084 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2086 static const uint16_t F32Regs[] = {
2087 Mips::F12, Mips::F14
2089 static const uint16_t F64Regs[] = {
2093 // Do not process byval args here.
2094 if (ArgFlags.isByVal())
2097 // Promote i8 and i16
2098 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2100 if (ArgFlags.isSExt())
2101 LocInfo = CCValAssign::SExt;
2102 else if (ArgFlags.isZExt())
2103 LocInfo = CCValAssign::ZExt;
2105 LocInfo = CCValAssign::AExt;
2110 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2111 // is true: function is vararg, argument is 3rd or higher, there is previous
2112 // argument which is not f32 or f64.
2113 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2114 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2115 unsigned OrigAlign = ArgFlags.getOrigAlign();
2116 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2118 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2119 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2120 // If this is the first part of an i64 arg,
2121 // the allocated register must be either A0 or A2.
2122 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2123 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2125 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2126 // Allocate int register and shadow next int register. If first
2127 // available register is Mips::A1 or Mips::A3, shadow it too.
2128 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2129 if (Reg == Mips::A1 || Reg == Mips::A3)
2130 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2131 State.AllocateReg(IntRegs, IntRegsSize);
2133 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2134 // we are guaranteed to find an available float register
2135 if (ValVT == MVT::f32) {
2136 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2137 // Shadow int register
2138 State.AllocateReg(IntRegs, IntRegsSize);
2140 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2141 // Shadow int registers
2142 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2143 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2144 State.AllocateReg(IntRegs, IntRegsSize);
2145 State.AllocateReg(IntRegs, IntRegsSize);
2148 llvm_unreachable("Cannot handle this ValVT.");
2151 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2153 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2155 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2160 #include "MipsGenCallingConv.inc"
2162 //===----------------------------------------------------------------------===//
2163 // Call Calling Convention Implementation
2164 //===----------------------------------------------------------------------===//
2166 static const unsigned O32IntRegsSize = 4;
2168 // Return next O32 integer argument register.
2169 static unsigned getNextIntArgReg(unsigned Reg) {
2170 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2171 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2175 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2176 SDValue Chain, SDValue Arg, DebugLoc DL,
2177 bool IsTailCall, SelectionDAG &DAG) const {
2179 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2180 DAG.getIntPtrConstant(Offset));
2181 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2185 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2186 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2187 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2188 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2189 /*isVolatile=*/ true, false, 0);
2192 void MipsTargetLowering::
2193 getOpndList(SmallVectorImpl<SDValue> &Ops,
2194 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2195 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2196 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2197 // Insert node "GP copy globalreg" before call to function.
2199 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2200 // in PIC mode) allow symbols to be resolved via lazy binding.
2201 // The lazy binding stub requires GP to point to the GOT.
2202 if (IsPICCall && !InternalLinkage) {
2203 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2204 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2205 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2208 // Build a sequence of copy-to-reg nodes chained together with token
2209 // chain and flag operands which copy the outgoing args into registers.
2210 // The InFlag in necessary since all emitted instructions must be
2214 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2215 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2216 RegsToPass[i].second, InFlag);
2217 InFlag = Chain.getValue(1);
2220 // Add argument registers to the end of the list so that they are
2221 // known live into the call.
2222 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2223 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2224 RegsToPass[i].second.getValueType()));
2226 // Add a register mask operand representing the call-preserved registers.
2227 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2228 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2229 assert(Mask && "Missing call preserved mask for calling convention");
2230 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2232 if (InFlag.getNode())
2233 Ops.push_back(InFlag);
2236 /// LowerCall - functions arguments are copied from virtual regs to
2237 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2239 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2240 SmallVectorImpl<SDValue> &InVals) const {
2241 SelectionDAG &DAG = CLI.DAG;
2242 DebugLoc &DL = CLI.DL;
2243 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2244 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2245 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2246 SDValue Chain = CLI.Chain;
2247 SDValue Callee = CLI.Callee;
2248 bool &IsTailCall = CLI.IsTailCall;
2249 CallingConv::ID CallConv = CLI.CallConv;
2250 bool IsVarArg = CLI.IsVarArg;
2252 MachineFunction &MF = DAG.getMachineFunction();
2253 MachineFrameInfo *MFI = MF.getFrameInfo();
2254 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2255 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2257 // Analyze operands of the call, assigning locations to each operand.
2258 SmallVector<CCValAssign, 16> ArgLocs;
2259 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2260 getTargetMachine(), ArgLocs, *DAG.getContext());
2261 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2263 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2264 getTargetMachine().Options.UseSoftFloat,
2265 Callee.getNode(), CLI.Args);
2267 // Get a count of how many bytes are to be pushed on the stack.
2268 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2270 // Check if it's really possible to do a tail call.
2273 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2274 *MF.getInfo<MipsFunctionInfo>());
2279 // Chain is the output chain of the last Load/Store or CopyToReg node.
2280 // ByValChain is the output chain of the last Memcpy node created for copying
2281 // byval arguments to the stack.
2282 unsigned StackAlignment = TFL->getStackAlignment();
2283 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2284 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2287 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
2289 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2290 IsN64 ? Mips::SP_64 : Mips::SP,
2293 // With EABI is it possible to have 16 args on registers.
2294 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2295 SmallVector<SDValue, 8> MemOpChains;
2296 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2298 // Walk the register/memloc assignments, inserting copies/loads.
2299 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2300 SDValue Arg = OutVals[i];
2301 CCValAssign &VA = ArgLocs[i];
2302 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2303 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2306 if (Flags.isByVal()) {
2307 assert(Flags.getByValSize() &&
2308 "ByVal args of size 0 should have been ignored by front-end.");
2309 assert(ByValArg != MipsCCInfo.byval_end());
2310 assert(!IsTailCall &&
2311 "Do not tail-call optimize if there is a byval argument.");
2312 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2313 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2318 // Promote the value if needed.
2319 switch (VA.getLocInfo()) {
2320 default: llvm_unreachable("Unknown loc info!");
2321 case CCValAssign::Full:
2322 if (VA.isRegLoc()) {
2323 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2324 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2325 (ValVT == MVT::i64 && LocVT == MVT::f64))
2326 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2327 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2328 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2329 Arg, DAG.getConstant(0, MVT::i32));
2330 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2331 Arg, DAG.getConstant(1, MVT::i32));
2332 if (!Subtarget->isLittle())
2334 unsigned LocRegLo = VA.getLocReg();
2335 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2336 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2337 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2342 case CCValAssign::SExt:
2343 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2345 case CCValAssign::ZExt:
2346 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2348 case CCValAssign::AExt:
2349 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2353 // Arguments that can be passed on register must be kept at
2354 // RegsToPass vector
2355 if (VA.isRegLoc()) {
2356 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2360 // Register can't get to this point...
2361 assert(VA.isMemLoc());
2363 // emit ISD::STORE whichs stores the
2364 // parameter value to a stack Location
2365 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2366 Chain, Arg, DL, IsTailCall, DAG));
2369 // Transform all store nodes into one single node because all store
2370 // nodes are independent of each other.
2371 if (!MemOpChains.empty())
2372 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2373 &MemOpChains[0], MemOpChains.size());
2375 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2376 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2377 // node so that legalize doesn't hack it.
2378 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2379 bool GlobalOrExternal = false, InternalLinkage = false;
2382 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2384 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2386 if (InternalLinkage)
2387 Callee = getAddrLocal(Callee, DAG, HasMips64);
2389 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2390 MipsII::MO_CALL_LO16);
2392 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2394 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2395 MipsII::MO_NO_FLAG);
2396 GlobalOrExternal = true;
2398 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2399 if (!IsN64 && !IsPIC) // !N64 && static
2400 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2401 MipsII::MO_NO_FLAG);
2403 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2404 MipsII::MO_CALL_LO16);
2406 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2408 GlobalOrExternal = true;
2411 SmallVector<SDValue, 8> Ops(1, Chain);
2412 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2414 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2415 CLI, Callee, Chain);
2418 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2420 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2421 SDValue InFlag = Chain.getValue(1);
2423 // Create the CALLSEQ_END node.
2424 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2425 DAG.getIntPtrConstant(0, true), InFlag);
2426 InFlag = Chain.getValue(1);
2428 // Handle result values, copying them out of physregs into vregs that we
2430 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2431 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2434 /// LowerCallResult - Lower the result values of a call into the
2435 /// appropriate copies out of appropriate physical registers.
2437 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2438 CallingConv::ID CallConv, bool IsVarArg,
2439 const SmallVectorImpl<ISD::InputArg> &Ins,
2440 DebugLoc DL, SelectionDAG &DAG,
2441 SmallVectorImpl<SDValue> &InVals,
2442 const SDNode *CallNode,
2443 const Type *RetTy) const {
2444 // Assign locations to each value returned by this call.
2445 SmallVector<CCValAssign, 16> RVLocs;
2446 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2447 getTargetMachine(), RVLocs, *DAG.getContext());
2448 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2450 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2453 // Copy all of the result registers out of their specified physreg.
2454 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2455 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2456 RVLocs[i].getLocVT(), InFlag);
2457 Chain = Val.getValue(1);
2458 InFlag = Val.getValue(2);
2460 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2461 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2463 InVals.push_back(Val);
2469 //===----------------------------------------------------------------------===//
2470 // Formal Arguments Calling Convention Implementation
2471 //===----------------------------------------------------------------------===//
2472 /// LowerFormalArguments - transform physical registers into virtual registers
2473 /// and generate load operations for arguments places on the stack.
2475 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2476 CallingConv::ID CallConv,
2478 const SmallVectorImpl<ISD::InputArg> &Ins,
2479 DebugLoc DL, SelectionDAG &DAG,
2480 SmallVectorImpl<SDValue> &InVals)
2482 MachineFunction &MF = DAG.getMachineFunction();
2483 MachineFrameInfo *MFI = MF.getFrameInfo();
2484 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2486 MipsFI->setVarArgsFrameIndex(0);
2488 // Used with vargs to acumulate store chains.
2489 std::vector<SDValue> OutChains;
2491 // Assign locations to all of the incoming arguments.
2492 SmallVector<CCValAssign, 16> ArgLocs;
2493 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2494 getTargetMachine(), ArgLocs, *DAG.getContext());
2495 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2496 Function::const_arg_iterator FuncArg =
2497 DAG.getMachineFunction().getFunction()->arg_begin();
2498 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2500 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2501 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2502 MipsCCInfo.hasByValArg());
2504 unsigned CurArgIdx = 0;
2505 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2507 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2508 CCValAssign &VA = ArgLocs[i];
2509 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2510 CurArgIdx = Ins[i].OrigArgIndex;
2511 EVT ValVT = VA.getValVT();
2512 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2513 bool IsRegLoc = VA.isRegLoc();
2515 if (Flags.isByVal()) {
2516 assert(Flags.getByValSize() &&
2517 "ByVal args of size 0 should have been ignored by front-end.");
2518 assert(ByValArg != MipsCCInfo.byval_end());
2519 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2520 MipsCCInfo, *ByValArg);
2525 // Arguments stored on registers
2527 EVT RegVT = VA.getLocVT();
2528 unsigned ArgReg = VA.getLocReg();
2529 const TargetRegisterClass *RC;
2531 if (RegVT == MVT::i32)
2532 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2533 &Mips::CPURegsRegClass;
2534 else if (RegVT == MVT::i64)
2535 RC = &Mips::CPU64RegsRegClass;
2536 else if (RegVT == MVT::f32)
2537 RC = &Mips::FGR32RegClass;
2538 else if (RegVT == MVT::f64)
2539 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2541 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2543 // Transform the arguments stored on
2544 // physical registers into virtual ones
2545 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2546 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2548 // If this is an 8 or 16-bit value, it has been passed promoted
2549 // to 32 bits. Insert an assert[sz]ext to capture this, then
2550 // truncate to the right size.
2551 if (VA.getLocInfo() != CCValAssign::Full) {
2552 unsigned Opcode = 0;
2553 if (VA.getLocInfo() == CCValAssign::SExt)
2554 Opcode = ISD::AssertSext;
2555 else if (VA.getLocInfo() == CCValAssign::ZExt)
2556 Opcode = ISD::AssertZext;
2558 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2559 DAG.getValueType(ValVT));
2560 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2563 // Handle floating point arguments passed in integer registers and
2564 // long double arguments passed in floating point registers.
2565 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2566 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2567 (RegVT == MVT::f64 && ValVT == MVT::i64))
2568 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2569 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2570 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2571 getNextIntArgReg(ArgReg), RC);
2572 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2573 if (!Subtarget->isLittle())
2574 std::swap(ArgValue, ArgValue2);
2575 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2576 ArgValue, ArgValue2);
2579 InVals.push_back(ArgValue);
2580 } else { // VA.isRegLoc()
2583 assert(VA.isMemLoc());
2585 // The stack pointer offset is relative to the caller stack frame.
2586 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2587 VA.getLocMemOffset(), true);
2589 // Create load nodes to retrieve arguments from the stack
2590 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2591 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2592 MachinePointerInfo::getFixedStack(FI),
2593 false, false, false, 0));
2597 // The mips ABIs for returning structs by value requires that we copy
2598 // the sret argument into $v0 for the return. Save the argument into
2599 // a virtual register so that we can access it from the return points.
2600 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2601 unsigned Reg = MipsFI->getSRetReturnReg();
2603 Reg = MF.getRegInfo().
2604 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2605 MipsFI->setSRetReturnReg(Reg);
2607 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2608 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2612 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2614 // All stores are grouped in one node to allow the matching between
2615 // the size of Ins and InVals. This only happens when on varg functions
2616 if (!OutChains.empty()) {
2617 OutChains.push_back(Chain);
2618 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2619 &OutChains[0], OutChains.size());
2625 //===----------------------------------------------------------------------===//
2626 // Return Value Calling Convention Implementation
2627 //===----------------------------------------------------------------------===//
2630 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2631 MachineFunction &MF, bool IsVarArg,
2632 const SmallVectorImpl<ISD::OutputArg> &Outs,
2633 LLVMContext &Context) const {
2634 SmallVector<CCValAssign, 16> RVLocs;
2635 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2637 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2641 MipsTargetLowering::LowerReturn(SDValue Chain,
2642 CallingConv::ID CallConv, bool IsVarArg,
2643 const SmallVectorImpl<ISD::OutputArg> &Outs,
2644 const SmallVectorImpl<SDValue> &OutVals,
2645 DebugLoc DL, SelectionDAG &DAG) const {
2646 // CCValAssign - represent the assignment of
2647 // the return value to a location
2648 SmallVector<CCValAssign, 16> RVLocs;
2649 MachineFunction &MF = DAG.getMachineFunction();
2651 // CCState - Info about the registers and stack slot.
2652 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2654 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2656 // Analyze return values.
2657 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2658 MF.getFunction()->getReturnType());
2661 SmallVector<SDValue, 4> RetOps(1, Chain);
2663 // Copy the result values into the output registers.
2664 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2665 SDValue Val = OutVals[i];
2666 CCValAssign &VA = RVLocs[i];
2667 assert(VA.isRegLoc() && "Can only return in registers!");
2669 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2670 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2672 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2674 // Guarantee that all emitted copies are stuck together with flags.
2675 Flag = Chain.getValue(1);
2676 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2679 // The mips ABIs for returning structs by value requires that we copy
2680 // the sret argument into $v0 for the return. We saved the argument into
2681 // a virtual register in the entry block, so now we copy the value out
2683 if (MF.getFunction()->hasStructRetAttr()) {
2684 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2685 unsigned Reg = MipsFI->getSRetReturnReg();
2688 llvm_unreachable("sret virtual register not created in the entry block");
2689 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2690 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2692 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2693 Flag = Chain.getValue(1);
2694 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2697 RetOps[0] = Chain; // Update chain.
2699 // Add the flag if we have it.
2701 RetOps.push_back(Flag);
2703 // Return on Mips is always a "jr $ra"
2704 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2707 //===----------------------------------------------------------------------===//
2708 // Mips Inline Assembly Support
2709 //===----------------------------------------------------------------------===//
2711 /// getConstraintType - Given a constraint letter, return the type of
2712 /// constraint it is for this target.
2713 MipsTargetLowering::ConstraintType MipsTargetLowering::
2714 getConstraintType(const std::string &Constraint) const
2716 // Mips specific constrainy
2717 // GCC config/mips/constraints.md
2719 // 'd' : An address register. Equivalent to r
2720 // unless generating MIPS16 code.
2721 // 'y' : Equivalent to r; retained for
2722 // backwards compatibility.
2723 // 'c' : A register suitable for use in an indirect
2724 // jump. This will always be $25 for -mabicalls.
2725 // 'l' : The lo register. 1 word storage.
2726 // 'x' : The hilo register pair. Double word storage.
2727 if (Constraint.size() == 1) {
2728 switch (Constraint[0]) {
2736 return C_RegisterClass;
2741 return TargetLowering::getConstraintType(Constraint);
2744 /// Examine constraint type and operand type and determine a weight value.
2745 /// This object must already have been set up with the operand type
2746 /// and the current alternative constraint selected.
2747 TargetLowering::ConstraintWeight
2748 MipsTargetLowering::getSingleConstraintMatchWeight(
2749 AsmOperandInfo &info, const char *constraint) const {
2750 ConstraintWeight weight = CW_Invalid;
2751 Value *CallOperandVal = info.CallOperandVal;
2752 // If we don't have a value, we can't do a match,
2753 // but allow it at the lowest weight.
2754 if (CallOperandVal == NULL)
2756 Type *type = CallOperandVal->getType();
2757 // Look at the constraint type.
2758 switch (*constraint) {
2760 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2764 if (type->isIntegerTy())
2765 weight = CW_Register;
2768 if (type->isFloatTy())
2769 weight = CW_Register;
2771 case 'c': // $25 for indirect jumps
2772 case 'l': // lo register
2773 case 'x': // hilo register pair
2774 if (type->isIntegerTy())
2775 weight = CW_SpecificReg;
2777 case 'I': // signed 16 bit immediate
2778 case 'J': // integer zero
2779 case 'K': // unsigned 16 bit immediate
2780 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2781 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2782 case 'O': // signed 15 bit immediate (+- 16383)
2783 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2784 if (isa<ConstantInt>(CallOperandVal))
2785 weight = CW_Constant;
2794 /// Given a register class constraint, like 'r', if this corresponds directly
2795 /// to an LLVM register class, return a register of 0 and the register class
2797 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2798 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2800 if (Constraint.size() == 1) {
2801 switch (Constraint[0]) {
2802 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2803 case 'y': // Same as 'r'. Exists for compatibility.
2805 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2806 if (Subtarget->inMips16Mode())
2807 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2808 return std::make_pair(0U, &Mips::CPURegsRegClass);
2810 if (VT == MVT::i64 && !HasMips64)
2811 return std::make_pair(0U, &Mips::CPURegsRegClass);
2812 if (VT == MVT::i64 && HasMips64)
2813 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
2814 // This will generate an error message
2815 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2818 return std::make_pair(0U, &Mips::FGR32RegClass);
2819 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2820 if (Subtarget->isFP64bit())
2821 return std::make_pair(0U, &Mips::FGR64RegClass);
2822 return std::make_pair(0U, &Mips::AFGR64RegClass);
2825 case 'c': // register suitable for indirect jump
2827 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
2828 assert(VT == MVT::i64 && "Unexpected type.");
2829 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
2830 case 'l': // register suitable for indirect jump
2832 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
2833 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
2834 case 'x': // register suitable for indirect jump
2835 // Fixme: Not triggering the use of both hi and low
2836 // This will generate an error message
2837 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2840 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2843 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2844 /// vector. If it is invalid, don't add anything to Ops.
2845 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2846 std::string &Constraint,
2847 std::vector<SDValue>&Ops,
2848 SelectionDAG &DAG) const {
2849 SDValue Result(0, 0);
2851 // Only support length 1 constraints for now.
2852 if (Constraint.length() > 1) return;
2854 char ConstraintLetter = Constraint[0];
2855 switch (ConstraintLetter) {
2856 default: break; // This will fall through to the generic implementation
2857 case 'I': // Signed 16 bit constant
2858 // If this fails, the parent routine will give an error
2859 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2860 EVT Type = Op.getValueType();
2861 int64_t Val = C->getSExtValue();
2862 if (isInt<16>(Val)) {
2863 Result = DAG.getTargetConstant(Val, Type);
2868 case 'J': // integer zero
2869 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2870 EVT Type = Op.getValueType();
2871 int64_t Val = C->getZExtValue();
2873 Result = DAG.getTargetConstant(0, Type);
2878 case 'K': // unsigned 16 bit immediate
2879 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2880 EVT Type = Op.getValueType();
2881 uint64_t Val = (uint64_t)C->getZExtValue();
2882 if (isUInt<16>(Val)) {
2883 Result = DAG.getTargetConstant(Val, Type);
2888 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2889 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2890 EVT Type = Op.getValueType();
2891 int64_t Val = C->getSExtValue();
2892 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
2893 Result = DAG.getTargetConstant(Val, Type);
2898 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2899 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2900 EVT Type = Op.getValueType();
2901 int64_t Val = C->getSExtValue();
2902 if ((Val >= -65535) && (Val <= -1)) {
2903 Result = DAG.getTargetConstant(Val, Type);
2908 case 'O': // signed 15 bit immediate
2909 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2910 EVT Type = Op.getValueType();
2911 int64_t Val = C->getSExtValue();
2912 if ((isInt<15>(Val))) {
2913 Result = DAG.getTargetConstant(Val, Type);
2918 case 'P': // immediate in the range of 1 to 65535 (inclusive)
2919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2920 EVT Type = Op.getValueType();
2921 int64_t Val = C->getSExtValue();
2922 if ((Val <= 65535) && (Val >= 1)) {
2923 Result = DAG.getTargetConstant(Val, Type);
2930 if (Result.getNode()) {
2931 Ops.push_back(Result);
2935 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2939 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
2940 // No global is ever allowed as a base.
2945 case 0: // "r+i" or just "i", depending on HasBaseReg.
2948 if (!AM.HasBaseReg) // allow "r+i".
2950 return false; // disallow "r+r" or "r+r+i".
2959 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2960 // The Mips target isn't yet aware of offsets.
2964 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
2966 bool IsMemset, bool ZeroMemset,
2968 MachineFunction &MF) const {
2969 if (Subtarget->hasMips64())
2975 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2976 if (VT != MVT::f32 && VT != MVT::f64)
2978 if (Imm.isNegZero())
2980 return Imm.isZero();
2983 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2985 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2987 return TargetLowering::getJumpTableEncoding();
2990 /// This function returns true if CallSym is a long double emulation routine.
2991 static bool isF128SoftLibCall(const char *CallSym) {
2992 const char *const LibCalls[] =
2993 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
2994 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
2995 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
2996 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
2997 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
2998 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
2999 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3000 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3003 const char * const *End = LibCalls + array_lengthof(LibCalls);
3005 // Check that LibCalls is sorted alphabetically.
3006 MipsTargetLowering::LTStr Comp;
3009 for (const char * const *I = LibCalls; I < End - 1; ++I)
3010 assert(Comp(*I, *(I + 1)));
3013 return std::binary_search(LibCalls, End, CallSym, Comp);
3016 /// This function returns true if Ty is fp128 or i128 which was originally a
3018 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3019 if (Ty->isFP128Ty())
3022 const ExternalSymbolSDNode *ES =
3023 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3025 // If the Ty is i128 and the function being called is a long double emulation
3026 // routine, then the original type is f128.
3027 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3030 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC, bool IsO32_,
3032 : CCInfo(Info), CallConv(CC), IsO32(IsO32_) {
3033 // Pre-allocate reserved argument area.
3034 CCInfo.AllocateStack(reservedArgArea(), 1);
3037 void MipsTargetLowering::MipsCC::
3038 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3039 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3040 std::vector<ArgListEntry> &FuncArgs) {
3041 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3042 "CallingConv::Fast shouldn't be used for vararg functions.");
3044 unsigned NumOpnds = Args.size();
3045 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3047 for (unsigned I = 0; I != NumOpnds; ++I) {
3048 MVT ArgVT = Args[I].VT;
3049 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3052 if (ArgFlags.isByVal()) {
3053 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3057 if (IsVarArg && !Args[I].IsFixed)
3058 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3060 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3062 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3067 dbgs() << "Call operand #" << I << " has unhandled type "
3068 << EVT(ArgVT).getEVTString();
3070 llvm_unreachable(0);
3075 void MipsTargetLowering::MipsCC::
3076 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3077 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3078 unsigned NumArgs = Args.size();
3079 llvm::CCAssignFn *FixedFn = fixedArgFn();
3080 unsigned CurArgIdx = 0;
3082 for (unsigned I = 0; I != NumArgs; ++I) {
3083 MVT ArgVT = Args[I].VT;
3084 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3085 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3086 CurArgIdx = Args[I].OrigArgIndex;
3088 if (ArgFlags.isByVal()) {
3089 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3093 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3095 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3099 dbgs() << "Formal Arg #" << I << " has unhandled type "
3100 << EVT(ArgVT).getEVTString();
3102 llvm_unreachable(0);
3106 template<typename Ty>
3107 void MipsTargetLowering::MipsCC::
3108 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3109 const SDNode *CallNode, const Type *RetTy) const {
3112 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3113 Fn = RetCC_F128Soft;
3117 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3118 MVT VT = RetVals[I].VT;
3119 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3120 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3122 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3124 dbgs() << "Call result #" << I << " has unhandled type "
3125 << EVT(VT).getEVTString() << '\n';
3127 llvm_unreachable(0);
3132 void MipsTargetLowering::MipsCC::
3133 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3134 const SDNode *CallNode, const Type *RetTy) const {
3135 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3138 void MipsTargetLowering::MipsCC::
3139 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3140 const Type *RetTy) const {
3141 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3145 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3147 CCValAssign::LocInfo LocInfo,
3148 ISD::ArgFlagsTy ArgFlags) {
3149 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3151 struct ByValArgInfo ByVal;
3152 unsigned RegSize = regSize();
3153 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3154 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3157 if (useRegsForByval())
3158 allocateRegs(ByVal, ByValSize, Align);
3160 // Allocate space on caller's stack.
3161 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3163 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3165 ByValArgs.push_back(ByVal);
3168 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3169 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3172 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3173 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3176 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3177 return IsO32 ? O32IntRegs : Mips64IntRegs;
3180 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3181 if (CallConv == CallingConv::Fast)
3182 return CC_Mips_FastCC;
3184 return IsO32 ? CC_MipsO32 : CC_MipsN;
3187 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3188 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
3191 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3192 return IsO32 ? O32IntRegs : Mips64DPRegs;
3195 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3198 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3199 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3200 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3201 "Byval argument's size and alignment should be a multiple of"
3204 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3206 // If Align > RegSize, the first arg register must be even.
3207 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3208 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3212 // Mark the registers allocated.
3213 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3214 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3215 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3218 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3219 const SDNode *CallNode,
3220 bool IsSoftFloat) const {
3221 if (IsSoftFloat || IsO32)
3224 // Check if the original type was fp128.
3225 if (originalTypeIsF128(OrigTy, CallNode)) {
3226 assert(VT == MVT::i64);
3233 void MipsTargetLowering::
3234 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3235 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3236 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3237 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3238 MachineFunction &MF = DAG.getMachineFunction();
3239 MachineFrameInfo *MFI = MF.getFrameInfo();
3240 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3241 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3245 FrameObjOffset = (int)CC.reservedArgArea() -
3246 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3248 FrameObjOffset = ByVal.Address;
3250 // Create frame object.
3251 EVT PtrTy = getPointerTy();
3252 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3253 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3254 InVals.push_back(FIN);
3259 // Copy arg registers.
3260 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3261 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3263 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3264 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3265 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3266 unsigned Offset = I * CC.regSize();
3267 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3268 DAG.getConstant(Offset, PtrTy));
3269 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3270 StorePtr, MachinePointerInfo(FuncArg, Offset),
3272 OutChains.push_back(Store);
3276 // Copy byVal arg to registers and stack.
3277 void MipsTargetLowering::
3278 passByValArg(SDValue Chain, DebugLoc DL,
3279 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3280 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3281 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3282 const MipsCC &CC, const ByValArgInfo &ByVal,
3283 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3284 unsigned ByValSize = Flags.getByValSize();
3285 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3286 unsigned RegSize = CC.regSize();
3287 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3288 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3290 if (ByVal.NumRegs) {
3291 const uint16_t *ArgRegs = CC.intArgRegs();
3292 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3295 // Copy words to registers.
3296 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3297 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3298 DAG.getConstant(Offset, PtrTy));
3299 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3300 MachinePointerInfo(), false, false, false,
3302 MemOpChains.push_back(LoadVal.getValue(1));
3303 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3304 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3307 // Return if the struct has been fully copied.
3308 if (ByValSize == Offset)
3311 // Copy the remainder of the byval argument with sub-word loads and shifts.
3312 if (LeftoverBytes) {
3313 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3314 "Size of the remainder should be smaller than RegSize.");
3317 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3318 Offset < ByValSize; LoadSize /= 2) {
3319 unsigned RemSize = ByValSize - Offset;
3321 if (RemSize < LoadSize)
3325 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3326 DAG.getConstant(Offset, PtrTy));
3328 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3329 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3330 false, false, Alignment);
3331 MemOpChains.push_back(LoadVal.getValue(1));
3333 // Shift the loaded value.
3337 Shamt = TotalSizeLoaded;
3339 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3341 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3342 DAG.getConstant(Shamt, MVT::i32));
3345 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3350 TotalSizeLoaded += LoadSize;
3351 Alignment = std::min(Alignment, LoadSize);
3354 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3355 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3360 // Copy remainder of byval arg to it with memcpy.
3361 unsigned MemCpySize = ByValSize - Offset;
3362 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3363 DAG.getConstant(Offset, PtrTy));
3364 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3365 DAG.getIntPtrConstant(ByVal.Address));
3366 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3367 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3368 /*isVolatile=*/false, /*AlwaysInline=*/false,
3369 MachinePointerInfo(0), MachinePointerInfo(0));
3370 MemOpChains.push_back(Chain);
3374 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3375 const MipsCC &CC, SDValue Chain,
3376 DebugLoc DL, SelectionDAG &DAG) const {
3377 unsigned NumRegs = CC.numIntArgRegs();
3378 const uint16_t *ArgRegs = CC.intArgRegs();
3379 const CCState &CCInfo = CC.getCCInfo();
3380 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3381 unsigned RegSize = CC.regSize();
3382 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3383 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3384 MachineFunction &MF = DAG.getMachineFunction();
3385 MachineFrameInfo *MFI = MF.getFrameInfo();
3386 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3388 // Offset of the first variable argument from stack pointer.
3392 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3395 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3397 // Record the frame index of the first variable argument
3398 // which is a value necessary to VASTART.
3399 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3400 MipsFI->setVarArgsFrameIndex(FI);
3402 // Copy the integer registers that have not been used for argument passing
3403 // to the argument register save area. For O32, the save area is allocated
3404 // in the caller's stack frame, while for N32/64, it is allocated in the
3405 // callee's stack frame.
3406 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3407 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3408 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3409 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3410 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3411 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3412 MachinePointerInfo(), false, false, 0);
3413 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3414 OutChains.push_back(Store);