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"
41 STATISTIC(NumTailCalls, "Number of tail calls");
44 LargeGOT("mxgot", cl::Hidden,
45 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
48 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
49 cl::desc("MIPS: Don't trap on integer division by zero."),
52 static const uint16_t O32IntRegs[4] = {
53 Mips::A0, Mips::A1, Mips::A2, Mips::A3
56 static const uint16_t Mips64IntRegs[8] = {
57 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
58 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
61 static const uint16_t Mips64DPRegs[8] = {
62 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
73 Size = CountPopulation_64(I);
74 Pos = countTrailingZeros(I);
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
83 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
84 EVT Ty = Op.getValueType();
86 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(Op), Ty, 0,
89 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
90 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
91 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
92 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
93 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
94 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
95 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
96 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
97 N->getOffset(), Flag);
99 llvm_unreachable("Unexpected node type.");
103 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
105 EVT Ty = Op.getValueType();
106 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
107 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
108 return DAG.getNode(ISD::ADD, DL, Ty,
109 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
110 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
113 SDValue MipsTargetLowering::getAddrLocal(SDValue Op, SelectionDAG &DAG,
114 bool HasMips64) const {
116 EVT Ty = Op.getValueType();
117 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
118 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
119 getTargetNode(Op, DAG, GOTFlag));
120 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
121 MachinePointerInfo::getGOT(), false, false, false,
123 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
124 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
125 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
128 SDValue MipsTargetLowering::getAddrGlobal(SDValue Op, SelectionDAG &DAG,
129 unsigned Flag) const {
131 EVT Ty = Op.getValueType();
132 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
133 getTargetNode(Op, DAG, Flag));
134 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
135 MachinePointerInfo::getGOT(), false, false, false, 0);
138 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
140 unsigned LoFlag) const {
142 EVT Ty = Op.getValueType();
143 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
144 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
145 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
146 getTargetNode(Op, DAG, LoFlag));
147 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
148 MachinePointerInfo::getGOT(), false, false, false, 0);
151 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
153 case MipsISD::JmpLink: return "MipsISD::JmpLink";
154 case MipsISD::TailCall: return "MipsISD::TailCall";
155 case MipsISD::Hi: return "MipsISD::Hi";
156 case MipsISD::Lo: return "MipsISD::Lo";
157 case MipsISD::GPRel: return "MipsISD::GPRel";
158 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
159 case MipsISD::Ret: return "MipsISD::Ret";
160 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
161 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
162 case MipsISD::FPCmp: return "MipsISD::FPCmp";
163 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
164 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
165 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
166 case MipsISD::ExtractLOHI: return "MipsISD::ExtractLOHI";
167 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
168 case MipsISD::Mult: return "MipsISD::Mult";
169 case MipsISD::Multu: return "MipsISD::Multu";
170 case MipsISD::MAdd: return "MipsISD::MAdd";
171 case MipsISD::MAddu: return "MipsISD::MAddu";
172 case MipsISD::MSub: return "MipsISD::MSub";
173 case MipsISD::MSubu: return "MipsISD::MSubu";
174 case MipsISD::DivRem: return "MipsISD::DivRem";
175 case MipsISD::DivRemU: return "MipsISD::DivRemU";
176 case MipsISD::DivRem16: return "MipsISD::DivRem16";
177 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
178 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
179 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
180 case MipsISD::Wrapper: return "MipsISD::Wrapper";
181 case MipsISD::Sync: return "MipsISD::Sync";
182 case MipsISD::Ext: return "MipsISD::Ext";
183 case MipsISD::Ins: return "MipsISD::Ins";
184 case MipsISD::LWL: return "MipsISD::LWL";
185 case MipsISD::LWR: return "MipsISD::LWR";
186 case MipsISD::SWL: return "MipsISD::SWL";
187 case MipsISD::SWR: return "MipsISD::SWR";
188 case MipsISD::LDL: return "MipsISD::LDL";
189 case MipsISD::LDR: return "MipsISD::LDR";
190 case MipsISD::SDL: return "MipsISD::SDL";
191 case MipsISD::SDR: return "MipsISD::SDR";
192 case MipsISD::EXTP: return "MipsISD::EXTP";
193 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
194 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
195 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
196 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
197 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
198 case MipsISD::SHILO: return "MipsISD::SHILO";
199 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
200 case MipsISD::MULT: return "MipsISD::MULT";
201 case MipsISD::MULTU: return "MipsISD::MULTU";
202 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
203 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
204 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
205 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
206 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
207 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
208 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
209 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
210 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
211 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
212 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
213 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
214 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
215 case MipsISD::VCEQ: return "MipsISD::VCEQ";
216 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
217 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
218 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
219 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
220 case MipsISD::VSPLAT: return "MipsISD::VSPLAT";
221 case MipsISD::VSPLATD: return "MipsISD::VSPLATD";
222 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
223 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
224 case MipsISD::VNOR: return "MipsISD::VNOR";
225 default: return NULL;
230 MipsTargetLowering(MipsTargetMachine &TM)
231 : TargetLowering(TM, new MipsTargetObjectFile()),
232 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
233 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
234 IsO32(Subtarget->isABI_O32()) {
235 // Mips does not have i1 type, so use i32 for
236 // setcc operations results (slt, sgt, ...).
237 setBooleanContents(ZeroOrOneBooleanContent);
238 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
240 // Load extented operations for i1 types must be promoted
241 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
242 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
243 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
245 // MIPS doesn't have extending float->double load/store
246 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
247 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
249 // Used by legalize types to correctly generate the setcc result.
250 // Without this, every float setcc comes with a AND/OR with the result,
251 // we don't want this, since the fpcmp result goes to a flag register,
252 // which is used implicitly by brcond and select operations.
253 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
255 // Mips Custom Operations
256 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
257 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
258 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
259 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
260 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
261 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
262 setOperationAction(ISD::SELECT, MVT::f32, Custom);
263 setOperationAction(ISD::SELECT, MVT::f64, Custom);
264 setOperationAction(ISD::SELECT, MVT::i32, Custom);
265 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
266 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
267 setOperationAction(ISD::SETCC, MVT::f32, Custom);
268 setOperationAction(ISD::SETCC, MVT::f64, Custom);
269 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
270 setOperationAction(ISD::VASTART, MVT::Other, Custom);
271 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
272 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
273 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
275 if (!TM.Options.NoNaNsFPMath) {
276 setOperationAction(ISD::FABS, MVT::f32, Custom);
277 setOperationAction(ISD::FABS, MVT::f64, Custom);
281 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
282 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
283 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
284 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
285 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
286 setOperationAction(ISD::SELECT, MVT::i64, Custom);
287 setOperationAction(ISD::LOAD, MVT::i64, Custom);
288 setOperationAction(ISD::STORE, MVT::i64, Custom);
289 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
293 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
294 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
295 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
298 setOperationAction(ISD::ADD, MVT::i32, Custom);
300 setOperationAction(ISD::ADD, MVT::i64, Custom);
302 setOperationAction(ISD::SDIV, MVT::i32, Expand);
303 setOperationAction(ISD::SREM, MVT::i32, Expand);
304 setOperationAction(ISD::UDIV, MVT::i32, Expand);
305 setOperationAction(ISD::UREM, MVT::i32, Expand);
306 setOperationAction(ISD::SDIV, MVT::i64, Expand);
307 setOperationAction(ISD::SREM, MVT::i64, Expand);
308 setOperationAction(ISD::UDIV, MVT::i64, Expand);
309 setOperationAction(ISD::UREM, MVT::i64, Expand);
311 // Operations not directly supported by Mips.
312 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
313 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
314 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
315 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
316 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
317 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
318 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
319 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
320 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
321 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
322 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
323 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
324 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
325 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
326 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
327 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
328 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
329 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
330 setOperationAction(ISD::ROTL, MVT::i32, Expand);
331 setOperationAction(ISD::ROTL, MVT::i64, Expand);
332 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
333 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
335 if (!Subtarget->hasMips32r2())
336 setOperationAction(ISD::ROTR, MVT::i32, Expand);
338 if (!Subtarget->hasMips64r2())
339 setOperationAction(ISD::ROTR, MVT::i64, Expand);
341 setOperationAction(ISD::FSIN, MVT::f32, Expand);
342 setOperationAction(ISD::FSIN, MVT::f64, Expand);
343 setOperationAction(ISD::FCOS, MVT::f32, Expand);
344 setOperationAction(ISD::FCOS, MVT::f64, Expand);
345 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
346 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
347 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
348 setOperationAction(ISD::FPOW, MVT::f32, Expand);
349 setOperationAction(ISD::FPOW, MVT::f64, Expand);
350 setOperationAction(ISD::FLOG, MVT::f32, Expand);
351 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
352 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
353 setOperationAction(ISD::FEXP, MVT::f32, Expand);
354 setOperationAction(ISD::FMA, MVT::f32, Expand);
355 setOperationAction(ISD::FMA, MVT::f64, Expand);
356 setOperationAction(ISD::FREM, MVT::f32, Expand);
357 setOperationAction(ISD::FREM, MVT::f64, Expand);
359 if (!TM.Options.NoNaNsFPMath) {
360 setOperationAction(ISD::FNEG, MVT::f32, Expand);
361 setOperationAction(ISD::FNEG, MVT::f64, Expand);
364 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
366 setOperationAction(ISD::VAARG, MVT::Other, Expand);
367 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
368 setOperationAction(ISD::VAEND, MVT::Other, Expand);
370 // Use the default for now
371 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
372 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
374 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
375 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
376 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
377 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
379 setInsertFencesForAtomic(true);
381 if (!Subtarget->hasSEInReg()) {
382 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
383 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
386 if (!Subtarget->hasBitCount()) {
387 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
388 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
391 if (!Subtarget->hasSwap()) {
392 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
393 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
397 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
398 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
399 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
400 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
403 setOperationAction(ISD::TRAP, MVT::Other, Legal);
405 setTargetDAGCombine(ISD::SDIVREM);
406 setTargetDAGCombine(ISD::UDIVREM);
407 setTargetDAGCombine(ISD::SELECT);
408 setTargetDAGCombine(ISD::AND);
409 setTargetDAGCombine(ISD::OR);
410 setTargetDAGCombine(ISD::ADD);
412 setMinFunctionAlignment(HasMips64 ? 3 : 2);
414 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
416 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
417 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
419 MaxStoresPerMemcpy = 16;
422 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
423 if (TM.getSubtargetImpl()->inMips16Mode())
424 return llvm::createMips16TargetLowering(TM);
426 return llvm::createMipsSETargetLowering(TM);
429 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
432 return VT.changeVectorElementTypeToInteger();
435 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
436 TargetLowering::DAGCombinerInfo &DCI,
437 const MipsSubtarget *Subtarget) {
438 if (DCI.isBeforeLegalizeOps())
441 EVT Ty = N->getValueType(0);
442 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
443 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
444 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
448 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
449 N->getOperand(0), N->getOperand(1));
450 SDValue InChain = DAG.getEntryNode();
451 SDValue InGlue = DivRem;
454 if (N->hasAnyUseOfValue(0)) {
455 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
457 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
458 InChain = CopyFromLo.getValue(1);
459 InGlue = CopyFromLo.getValue(2);
463 if (N->hasAnyUseOfValue(1)) {
464 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
472 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
474 default: llvm_unreachable("Unknown fp condition code!");
476 case ISD::SETOEQ: return Mips::FCOND_OEQ;
477 case ISD::SETUNE: return Mips::FCOND_UNE;
479 case ISD::SETOLT: return Mips::FCOND_OLT;
481 case ISD::SETOGT: return Mips::FCOND_OGT;
483 case ISD::SETOLE: return Mips::FCOND_OLE;
485 case ISD::SETOGE: return Mips::FCOND_OGE;
486 case ISD::SETULT: return Mips::FCOND_ULT;
487 case ISD::SETULE: return Mips::FCOND_ULE;
488 case ISD::SETUGT: return Mips::FCOND_UGT;
489 case ISD::SETUGE: return Mips::FCOND_UGE;
490 case ISD::SETUO: return Mips::FCOND_UN;
491 case ISD::SETO: return Mips::FCOND_OR;
493 case ISD::SETONE: return Mips::FCOND_ONE;
494 case ISD::SETUEQ: return Mips::FCOND_UEQ;
499 /// This function returns true if the floating point conditional branches and
500 /// conditional moves which use condition code CC should be inverted.
501 static bool invertFPCondCodeUser(Mips::CondCode CC) {
502 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
505 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
506 "Illegal Condition Code");
511 // Creates and returns an FPCmp node from a setcc node.
512 // Returns Op if setcc is not a floating point comparison.
513 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
514 // must be a SETCC node
515 if (Op.getOpcode() != ISD::SETCC)
518 SDValue LHS = Op.getOperand(0);
520 if (!LHS.getValueType().isFloatingPoint())
523 SDValue RHS = Op.getOperand(1);
526 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
527 // node if necessary.
528 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
530 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
531 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
534 // Creates and returns a CMovFPT/F node.
535 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
536 SDValue False, SDLoc DL) {
537 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
538 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
539 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
541 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
542 True.getValueType(), True, FCC0, False, Cond);
545 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
546 TargetLowering::DAGCombinerInfo &DCI,
547 const MipsSubtarget *Subtarget) {
548 if (DCI.isBeforeLegalizeOps())
551 SDValue SetCC = N->getOperand(0);
553 if ((SetCC.getOpcode() != ISD::SETCC) ||
554 !SetCC.getOperand(0).getValueType().isInteger())
557 SDValue False = N->getOperand(2);
558 EVT FalseTy = False.getValueType();
560 if (!FalseTy.isInteger())
563 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
565 if (!CN || CN->getZExtValue())
569 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
570 SDValue True = N->getOperand(1);
572 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
573 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
575 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
578 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
579 TargetLowering::DAGCombinerInfo &DCI,
580 const MipsSubtarget *Subtarget) {
581 // Pattern match EXT.
582 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
583 // => ext $dst, $src, size, pos
584 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
587 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
588 unsigned ShiftRightOpc = ShiftRight.getOpcode();
590 // Op's first operand must be a shift right.
591 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
594 // The second operand of the shift must be an immediate.
596 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
599 uint64_t Pos = CN->getZExtValue();
600 uint64_t SMPos, SMSize;
602 // Op's second operand must be a shifted mask.
603 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
604 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
607 // Return if the shifted mask does not start at bit 0 or the sum of its size
608 // and Pos exceeds the word's size.
609 EVT ValTy = N->getValueType(0);
610 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
613 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
614 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
615 DAG.getConstant(SMSize, MVT::i32));
618 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
619 TargetLowering::DAGCombinerInfo &DCI,
620 const MipsSubtarget *Subtarget) {
621 // Pattern match INS.
622 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
623 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
624 // => ins $dst, $src, size, pos, $src1
625 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
628 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
629 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
632 // See if Op's first operand matches (and $src1 , mask0).
633 if (And0.getOpcode() != ISD::AND)
636 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
637 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
640 // See if Op's second operand matches (and (shl $src, pos), mask1).
641 if (And1.getOpcode() != ISD::AND)
644 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
645 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
648 // The shift masks must have the same position and size.
649 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
652 SDValue Shl = And1.getOperand(0);
653 if (Shl.getOpcode() != ISD::SHL)
656 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
659 unsigned Shamt = CN->getZExtValue();
661 // Return if the shift amount and the first bit position of mask are not the
663 EVT ValTy = N->getValueType(0);
664 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
667 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
668 DAG.getConstant(SMPos0, MVT::i32),
669 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
672 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
673 TargetLowering::DAGCombinerInfo &DCI,
674 const MipsSubtarget *Subtarget) {
675 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
677 if (DCI.isBeforeLegalizeOps())
680 SDValue Add = N->getOperand(1);
682 if (Add.getOpcode() != ISD::ADD)
685 SDValue Lo = Add.getOperand(1);
687 if ((Lo.getOpcode() != MipsISD::Lo) ||
688 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
691 EVT ValTy = N->getValueType(0);
694 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
696 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
699 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
701 SelectionDAG &DAG = DCI.DAG;
702 unsigned Opc = N->getOpcode();
708 return performDivRemCombine(N, DAG, DCI, Subtarget);
710 return performSELECTCombine(N, DAG, DCI, Subtarget);
712 return performANDCombine(N, DAG, DCI, Subtarget);
714 return performORCombine(N, DAG, DCI, Subtarget);
716 return performADDCombine(N, DAG, DCI, Subtarget);
723 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
724 SmallVectorImpl<SDValue> &Results,
725 SelectionDAG &DAG) const {
726 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
728 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
729 Results.push_back(Res.getValue(I));
733 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
734 SmallVectorImpl<SDValue> &Results,
735 SelectionDAG &DAG) const {
736 return LowerOperationWrapper(N, Results, DAG);
739 SDValue MipsTargetLowering::
740 LowerOperation(SDValue Op, SelectionDAG &DAG) const
742 switch (Op.getOpcode())
744 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
745 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
746 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
747 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
748 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
749 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
750 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
751 case ISD::SELECT: return lowerSELECT(Op, DAG);
752 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
753 case ISD::SETCC: return lowerSETCC(Op, DAG);
754 case ISD::VASTART: return lowerVASTART(Op, DAG);
755 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
756 case ISD::FABS: return lowerFABS(Op, DAG);
757 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
758 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
759 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
760 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
761 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
762 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
763 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
764 case ISD::LOAD: return lowerLOAD(Op, DAG);
765 case ISD::STORE: return lowerSTORE(Op, DAG);
766 case ISD::ADD: return lowerADD(Op, DAG);
767 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
772 //===----------------------------------------------------------------------===//
773 // Lower helper functions
774 //===----------------------------------------------------------------------===//
776 // addLiveIn - This helper function adds the specified physical register to the
777 // MachineFunction as a live in value. It also creates a corresponding
778 // virtual register for it.
780 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
782 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
783 MF.getRegInfo().addLiveIn(PReg, VReg);
787 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
788 MachineBasicBlock &MBB,
789 const TargetInstrInfo &TII,
794 // Insert instruction "teq $divisor_reg, $zero, 7".
795 MachineBasicBlock::iterator I(MI);
796 MachineInstrBuilder MIB;
797 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
798 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
800 // Use the 32-bit sub-register if this is a 64-bit division.
802 MIB->getOperand(0).setSubReg(Mips::sub_32);
808 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
809 MachineBasicBlock *BB) const {
810 switch (MI->getOpcode()) {
812 llvm_unreachable("Unexpected instr type to insert");
813 case Mips::ATOMIC_LOAD_ADD_I8:
814 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
815 case Mips::ATOMIC_LOAD_ADD_I16:
816 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
817 case Mips::ATOMIC_LOAD_ADD_I32:
818 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
819 case Mips::ATOMIC_LOAD_ADD_I64:
820 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
822 case Mips::ATOMIC_LOAD_AND_I8:
823 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
824 case Mips::ATOMIC_LOAD_AND_I16:
825 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
826 case Mips::ATOMIC_LOAD_AND_I32:
827 return emitAtomicBinary(MI, BB, 4, Mips::AND);
828 case Mips::ATOMIC_LOAD_AND_I64:
829 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
831 case Mips::ATOMIC_LOAD_OR_I8:
832 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
833 case Mips::ATOMIC_LOAD_OR_I16:
834 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
835 case Mips::ATOMIC_LOAD_OR_I32:
836 return emitAtomicBinary(MI, BB, 4, Mips::OR);
837 case Mips::ATOMIC_LOAD_OR_I64:
838 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
840 case Mips::ATOMIC_LOAD_XOR_I8:
841 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
842 case Mips::ATOMIC_LOAD_XOR_I16:
843 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
844 case Mips::ATOMIC_LOAD_XOR_I32:
845 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
846 case Mips::ATOMIC_LOAD_XOR_I64:
847 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
849 case Mips::ATOMIC_LOAD_NAND_I8:
850 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
851 case Mips::ATOMIC_LOAD_NAND_I16:
852 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
853 case Mips::ATOMIC_LOAD_NAND_I32:
854 return emitAtomicBinary(MI, BB, 4, 0, true);
855 case Mips::ATOMIC_LOAD_NAND_I64:
856 return emitAtomicBinary(MI, BB, 8, 0, true);
858 case Mips::ATOMIC_LOAD_SUB_I8:
859 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
860 case Mips::ATOMIC_LOAD_SUB_I16:
861 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
862 case Mips::ATOMIC_LOAD_SUB_I32:
863 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
864 case Mips::ATOMIC_LOAD_SUB_I64:
865 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
867 case Mips::ATOMIC_SWAP_I8:
868 return emitAtomicBinaryPartword(MI, BB, 1, 0);
869 case Mips::ATOMIC_SWAP_I16:
870 return emitAtomicBinaryPartword(MI, BB, 2, 0);
871 case Mips::ATOMIC_SWAP_I32:
872 return emitAtomicBinary(MI, BB, 4, 0);
873 case Mips::ATOMIC_SWAP_I64:
874 return emitAtomicBinary(MI, BB, 8, 0);
876 case Mips::ATOMIC_CMP_SWAP_I8:
877 return emitAtomicCmpSwapPartword(MI, BB, 1);
878 case Mips::ATOMIC_CMP_SWAP_I16:
879 return emitAtomicCmpSwapPartword(MI, BB, 2);
880 case Mips::ATOMIC_CMP_SWAP_I32:
881 return emitAtomicCmpSwap(MI, BB, 4);
882 case Mips::ATOMIC_CMP_SWAP_I64:
883 return emitAtomicCmpSwap(MI, BB, 8);
884 case Mips::PseudoSDIV:
885 case Mips::PseudoUDIV:
886 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
887 case Mips::PseudoDSDIV:
888 case Mips::PseudoDUDIV:
889 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
893 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
894 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
896 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
897 unsigned Size, unsigned BinOpcode,
899 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
901 MachineFunction *MF = BB->getParent();
902 MachineRegisterInfo &RegInfo = MF->getRegInfo();
903 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
904 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
905 DebugLoc DL = MI->getDebugLoc();
906 unsigned LL, SC, AND, NOR, ZERO, BEQ;
921 ZERO = Mips::ZERO_64;
925 unsigned OldVal = MI->getOperand(0).getReg();
926 unsigned Ptr = MI->getOperand(1).getReg();
927 unsigned Incr = MI->getOperand(2).getReg();
929 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
930 unsigned AndRes = RegInfo.createVirtualRegister(RC);
931 unsigned Success = RegInfo.createVirtualRegister(RC);
933 // insert new blocks after the current block
934 const BasicBlock *LLVM_BB = BB->getBasicBlock();
935 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
936 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
937 MachineFunction::iterator It = BB;
939 MF->insert(It, loopMBB);
940 MF->insert(It, exitMBB);
942 // Transfer the remainder of BB and its successor edges to exitMBB.
943 exitMBB->splice(exitMBB->begin(), BB,
944 llvm::next(MachineBasicBlock::iterator(MI)),
946 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
950 // fallthrough --> loopMBB
951 BB->addSuccessor(loopMBB);
952 loopMBB->addSuccessor(loopMBB);
953 loopMBB->addSuccessor(exitMBB);
957 // <binop> storeval, oldval, incr
958 // sc success, storeval, 0(ptr)
959 // beq success, $0, loopMBB
961 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
963 // and andres, oldval, incr
964 // nor storeval, $0, andres
965 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
966 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
967 } else if (BinOpcode) {
968 // <binop> storeval, oldval, incr
969 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
973 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
974 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
976 MI->eraseFromParent(); // The instruction is gone now.
982 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
983 MachineBasicBlock *BB,
984 unsigned Size, unsigned BinOpcode,
986 assert((Size == 1 || Size == 2) &&
987 "Unsupported size for EmitAtomicBinaryPartial.");
989 MachineFunction *MF = BB->getParent();
990 MachineRegisterInfo &RegInfo = MF->getRegInfo();
991 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
992 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
993 DebugLoc DL = MI->getDebugLoc();
995 unsigned Dest = MI->getOperand(0).getReg();
996 unsigned Ptr = MI->getOperand(1).getReg();
997 unsigned Incr = MI->getOperand(2).getReg();
999 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1000 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1001 unsigned Mask = RegInfo.createVirtualRegister(RC);
1002 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1003 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1004 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1005 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1006 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1007 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1008 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1009 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1010 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1011 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1012 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1013 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1014 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1015 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1016 unsigned Success = RegInfo.createVirtualRegister(RC);
1018 // insert new blocks after the current block
1019 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1020 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1021 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1022 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1023 MachineFunction::iterator It = BB;
1025 MF->insert(It, loopMBB);
1026 MF->insert(It, sinkMBB);
1027 MF->insert(It, exitMBB);
1029 // Transfer the remainder of BB and its successor edges to exitMBB.
1030 exitMBB->splice(exitMBB->begin(), BB,
1031 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1032 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1034 BB->addSuccessor(loopMBB);
1035 loopMBB->addSuccessor(loopMBB);
1036 loopMBB->addSuccessor(sinkMBB);
1037 sinkMBB->addSuccessor(exitMBB);
1040 // addiu masklsb2,$0,-4 # 0xfffffffc
1041 // and alignedaddr,ptr,masklsb2
1042 // andi ptrlsb2,ptr,3
1043 // sll shiftamt,ptrlsb2,3
1044 // ori maskupper,$0,255 # 0xff
1045 // sll mask,maskupper,shiftamt
1046 // nor mask2,$0,mask
1047 // sll incr2,incr,shiftamt
1049 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1050 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1051 .addReg(Mips::ZERO).addImm(-4);
1052 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1053 .addReg(Ptr).addReg(MaskLSB2);
1054 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1055 if (Subtarget->isLittle()) {
1056 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1058 unsigned Off = RegInfo.createVirtualRegister(RC);
1059 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1060 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1061 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1063 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1064 .addReg(Mips::ZERO).addImm(MaskImm);
1065 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1066 .addReg(MaskUpper).addReg(ShiftAmt);
1067 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1068 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1070 // atomic.load.binop
1072 // ll oldval,0(alignedaddr)
1073 // binop binopres,oldval,incr2
1074 // and newval,binopres,mask
1075 // and maskedoldval0,oldval,mask2
1076 // or storeval,maskedoldval0,newval
1077 // sc success,storeval,0(alignedaddr)
1078 // beq success,$0,loopMBB
1082 // ll oldval,0(alignedaddr)
1083 // and newval,incr2,mask
1084 // and maskedoldval0,oldval,mask2
1085 // or storeval,maskedoldval0,newval
1086 // sc success,storeval,0(alignedaddr)
1087 // beq success,$0,loopMBB
1090 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1092 // and andres, oldval, incr2
1093 // nor binopres, $0, andres
1094 // and newval, binopres, mask
1095 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1096 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1097 .addReg(Mips::ZERO).addReg(AndRes);
1098 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1099 } else if (BinOpcode) {
1100 // <binop> binopres, oldval, incr2
1101 // and newval, binopres, mask
1102 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1103 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1104 } else {// atomic.swap
1105 // and newval, incr2, mask
1106 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1109 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1110 .addReg(OldVal).addReg(Mask2);
1111 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1112 .addReg(MaskedOldVal0).addReg(NewVal);
1113 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1114 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1115 BuildMI(BB, DL, TII->get(Mips::BEQ))
1116 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1119 // and maskedoldval1,oldval,mask
1120 // srl srlres,maskedoldval1,shiftamt
1121 // sll sllres,srlres,24
1122 // sra dest,sllres,24
1124 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1126 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1127 .addReg(OldVal).addReg(Mask);
1128 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1129 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1130 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1131 .addReg(SrlRes).addImm(ShiftImm);
1132 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1133 .addReg(SllRes).addImm(ShiftImm);
1135 MI->eraseFromParent(); // The instruction is gone now.
1141 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1142 MachineBasicBlock *BB,
1143 unsigned Size) const {
1144 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1146 MachineFunction *MF = BB->getParent();
1147 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1148 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1149 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1150 DebugLoc DL = MI->getDebugLoc();
1151 unsigned LL, SC, ZERO, BNE, BEQ;
1163 ZERO = Mips::ZERO_64;
1168 unsigned Dest = MI->getOperand(0).getReg();
1169 unsigned Ptr = MI->getOperand(1).getReg();
1170 unsigned OldVal = MI->getOperand(2).getReg();
1171 unsigned NewVal = MI->getOperand(3).getReg();
1173 unsigned Success = RegInfo.createVirtualRegister(RC);
1175 // insert new blocks after the current block
1176 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1177 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1178 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1179 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1180 MachineFunction::iterator It = BB;
1182 MF->insert(It, loop1MBB);
1183 MF->insert(It, loop2MBB);
1184 MF->insert(It, exitMBB);
1186 // Transfer the remainder of BB and its successor edges to exitMBB.
1187 exitMBB->splice(exitMBB->begin(), BB,
1188 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1189 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1193 // fallthrough --> loop1MBB
1194 BB->addSuccessor(loop1MBB);
1195 loop1MBB->addSuccessor(exitMBB);
1196 loop1MBB->addSuccessor(loop2MBB);
1197 loop2MBB->addSuccessor(loop1MBB);
1198 loop2MBB->addSuccessor(exitMBB);
1202 // bne dest, oldval, exitMBB
1204 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1205 BuildMI(BB, DL, TII->get(BNE))
1206 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1209 // sc success, newval, 0(ptr)
1210 // beq success, $0, loop1MBB
1212 BuildMI(BB, DL, TII->get(SC), Success)
1213 .addReg(NewVal).addReg(Ptr).addImm(0);
1214 BuildMI(BB, DL, TII->get(BEQ))
1215 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1217 MI->eraseFromParent(); // The instruction is gone now.
1223 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1224 MachineBasicBlock *BB,
1225 unsigned Size) const {
1226 assert((Size == 1 || Size == 2) &&
1227 "Unsupported size for EmitAtomicCmpSwapPartial.");
1229 MachineFunction *MF = BB->getParent();
1230 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1231 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1232 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1233 DebugLoc DL = MI->getDebugLoc();
1235 unsigned Dest = MI->getOperand(0).getReg();
1236 unsigned Ptr = MI->getOperand(1).getReg();
1237 unsigned CmpVal = MI->getOperand(2).getReg();
1238 unsigned NewVal = MI->getOperand(3).getReg();
1240 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1241 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1242 unsigned Mask = RegInfo.createVirtualRegister(RC);
1243 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1244 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1245 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1246 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1247 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1248 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1249 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1250 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1251 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1252 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1253 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1254 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1255 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1256 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1257 unsigned Success = RegInfo.createVirtualRegister(RC);
1259 // insert new blocks after the current block
1260 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1261 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1262 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1263 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1264 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1265 MachineFunction::iterator It = BB;
1267 MF->insert(It, loop1MBB);
1268 MF->insert(It, loop2MBB);
1269 MF->insert(It, sinkMBB);
1270 MF->insert(It, exitMBB);
1272 // Transfer the remainder of BB and its successor edges to exitMBB.
1273 exitMBB->splice(exitMBB->begin(), BB,
1274 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1275 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1277 BB->addSuccessor(loop1MBB);
1278 loop1MBB->addSuccessor(sinkMBB);
1279 loop1MBB->addSuccessor(loop2MBB);
1280 loop2MBB->addSuccessor(loop1MBB);
1281 loop2MBB->addSuccessor(sinkMBB);
1282 sinkMBB->addSuccessor(exitMBB);
1284 // FIXME: computation of newval2 can be moved to loop2MBB.
1286 // addiu masklsb2,$0,-4 # 0xfffffffc
1287 // and alignedaddr,ptr,masklsb2
1288 // andi ptrlsb2,ptr,3
1289 // sll shiftamt,ptrlsb2,3
1290 // ori maskupper,$0,255 # 0xff
1291 // sll mask,maskupper,shiftamt
1292 // nor mask2,$0,mask
1293 // andi maskedcmpval,cmpval,255
1294 // sll shiftedcmpval,maskedcmpval,shiftamt
1295 // andi maskednewval,newval,255
1296 // sll shiftednewval,maskednewval,shiftamt
1297 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1298 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1299 .addReg(Mips::ZERO).addImm(-4);
1300 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1301 .addReg(Ptr).addReg(MaskLSB2);
1302 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1303 if (Subtarget->isLittle()) {
1304 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1306 unsigned Off = RegInfo.createVirtualRegister(RC);
1307 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1308 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1309 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1311 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1312 .addReg(Mips::ZERO).addImm(MaskImm);
1313 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1314 .addReg(MaskUpper).addReg(ShiftAmt);
1315 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1316 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1317 .addReg(CmpVal).addImm(MaskImm);
1318 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1319 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1320 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1321 .addReg(NewVal).addImm(MaskImm);
1322 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1323 .addReg(MaskedNewVal).addReg(ShiftAmt);
1326 // ll oldval,0(alginedaddr)
1327 // and maskedoldval0,oldval,mask
1328 // bne maskedoldval0,shiftedcmpval,sinkMBB
1330 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1331 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1332 .addReg(OldVal).addReg(Mask);
1333 BuildMI(BB, DL, TII->get(Mips::BNE))
1334 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1337 // and maskedoldval1,oldval,mask2
1338 // or storeval,maskedoldval1,shiftednewval
1339 // sc success,storeval,0(alignedaddr)
1340 // beq success,$0,loop1MBB
1342 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1343 .addReg(OldVal).addReg(Mask2);
1344 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1345 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1346 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1347 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1348 BuildMI(BB, DL, TII->get(Mips::BEQ))
1349 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1352 // srl srlres,maskedoldval0,shiftamt
1353 // sll sllres,srlres,24
1354 // sra dest,sllres,24
1356 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1358 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1359 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1360 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1361 .addReg(SrlRes).addImm(ShiftImm);
1362 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1363 .addReg(SllRes).addImm(ShiftImm);
1365 MI->eraseFromParent(); // The instruction is gone now.
1370 //===----------------------------------------------------------------------===//
1371 // Misc Lower Operation implementation
1372 //===----------------------------------------------------------------------===//
1373 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1374 SDValue Chain = Op.getOperand(0);
1375 SDValue Table = Op.getOperand(1);
1376 SDValue Index = Op.getOperand(2);
1378 EVT PTy = getPointerTy();
1379 unsigned EntrySize =
1380 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1382 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1383 DAG.getConstant(EntrySize, PTy));
1384 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1386 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1387 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1388 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1390 Chain = Addr.getValue(1);
1392 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1393 // For PIC, the sequence is:
1394 // BRIND(load(Jumptable + index) + RelocBase)
1395 // RelocBase can be JumpTable, GOT or some sort of global base.
1396 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1397 getPICJumpTableRelocBase(Table, DAG));
1400 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1403 SDValue MipsTargetLowering::
1404 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1406 // The first operand is the chain, the second is the condition, the third is
1407 // the block to branch to if the condition is true.
1408 SDValue Chain = Op.getOperand(0);
1409 SDValue Dest = Op.getOperand(2);
1412 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1414 // Return if flag is not set by a floating point comparison.
1415 if (CondRes.getOpcode() != MipsISD::FPCmp)
1418 SDValue CCNode = CondRes.getOperand(2);
1420 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1421 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1422 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1423 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1424 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1425 FCC0, Dest, CondRes);
1428 SDValue MipsTargetLowering::
1429 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1431 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1433 // Return if flag is not set by a floating point comparison.
1434 if (Cond.getOpcode() != MipsISD::FPCmp)
1437 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1441 SDValue MipsTargetLowering::
1442 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1445 EVT Ty = Op.getOperand(0).getValueType();
1446 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1447 getSetCCResultType(*DAG.getContext(), Ty),
1448 Op.getOperand(0), Op.getOperand(1),
1451 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1455 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1456 SDValue Cond = createFPCmp(DAG, Op);
1458 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1459 "Floating point operand expected.");
1461 SDValue True = DAG.getConstant(1, MVT::i32);
1462 SDValue False = DAG.getConstant(0, MVT::i32);
1464 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1467 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1468 SelectionDAG &DAG) const {
1469 // FIXME there isn't actually debug info here
1471 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1473 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1474 const MipsTargetObjectFile &TLOF =
1475 (const MipsTargetObjectFile&)getObjFileLowering();
1477 // %gp_rel relocation
1478 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1479 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1481 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1482 DAG.getVTList(MVT::i32), &GA, 1);
1483 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1484 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1487 // %hi/%lo relocation
1488 return getAddrNonPIC(Op, DAG);
1491 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1492 return getAddrLocal(Op, DAG, HasMips64);
1495 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1496 MipsII::MO_GOT_LO16);
1498 return getAddrGlobal(Op, DAG,
1499 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1502 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1503 SelectionDAG &DAG) const {
1504 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1505 return getAddrNonPIC(Op, DAG);
1507 return getAddrLocal(Op, DAG, HasMips64);
1510 SDValue MipsTargetLowering::
1511 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1513 // If the relocation model is PIC, use the General Dynamic TLS Model or
1514 // Local Dynamic TLS model, otherwise use the Initial Exec or
1515 // Local Exec TLS Model.
1517 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1519 const GlobalValue *GV = GA->getGlobal();
1520 EVT PtrVT = getPointerTy();
1522 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1524 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1525 // General Dynamic and Local Dynamic TLS Model.
1526 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1529 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1530 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1531 getGlobalReg(DAG, PtrVT), TGA);
1532 unsigned PtrSize = PtrVT.getSizeInBits();
1533 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1535 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1539 Entry.Node = Argument;
1541 Args.push_back(Entry);
1543 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1544 false, false, false, false, 0, CallingConv::C,
1545 /*IsTailCall=*/false, /*doesNotRet=*/false,
1546 /*isReturnValueUsed=*/true,
1547 TlsGetAddr, Args, DAG, DL);
1548 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1550 SDValue Ret = CallResult.first;
1552 if (model != TLSModel::LocalDynamic)
1555 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1556 MipsII::MO_DTPREL_HI);
1557 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1558 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1559 MipsII::MO_DTPREL_LO);
1560 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1561 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1562 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1566 if (model == TLSModel::InitialExec) {
1567 // Initial Exec TLS Model
1568 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1569 MipsII::MO_GOTTPREL);
1570 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1572 Offset = DAG.getLoad(PtrVT, DL,
1573 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1574 false, false, false, 0);
1576 // Local Exec TLS Model
1577 assert(model == TLSModel::LocalExec);
1578 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1579 MipsII::MO_TPREL_HI);
1580 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1581 MipsII::MO_TPREL_LO);
1582 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1583 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1584 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1587 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1588 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1591 SDValue MipsTargetLowering::
1592 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1594 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1595 return getAddrNonPIC(Op, DAG);
1597 return getAddrLocal(Op, DAG, HasMips64);
1600 SDValue MipsTargetLowering::
1601 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1603 // gp_rel relocation
1604 // FIXME: we should reference the constant pool using small data sections,
1605 // but the asm printer currently doesn't support this feature without
1606 // hacking it. This feature should come soon so we can uncomment the
1608 //if (IsInSmallSection(C->getType())) {
1609 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1610 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1611 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1613 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1614 return getAddrNonPIC(Op, DAG);
1616 return getAddrLocal(Op, DAG, HasMips64);
1619 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1620 MachineFunction &MF = DAG.getMachineFunction();
1621 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1624 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1627 // vastart just stores the address of the VarArgsFrameIndex slot into the
1628 // memory location argument.
1629 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1630 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1631 MachinePointerInfo(SV), false, false, 0);
1634 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1635 EVT TyX = Op.getOperand(0).getValueType();
1636 EVT TyY = Op.getOperand(1).getValueType();
1637 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1638 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1642 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1644 SDValue X = (TyX == MVT::f32) ?
1645 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1646 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1648 SDValue Y = (TyY == MVT::f32) ?
1649 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1650 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1654 // ext E, Y, 31, 1 ; extract bit31 of Y
1655 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1656 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1657 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1660 // srl SrlX, SllX, 1
1662 // sll SllY, SrlX, 31
1663 // or Or, SrlX, SllY
1664 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1665 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1666 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1667 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1668 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1671 if (TyX == MVT::f32)
1672 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1674 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1675 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1676 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1679 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1680 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1681 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1682 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1683 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1686 // Bitcast to integer nodes.
1687 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1688 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1691 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1692 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1693 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1694 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1696 if (WidthX > WidthY)
1697 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1698 else if (WidthY > WidthX)
1699 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1701 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1702 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1703 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1706 // (d)sll SllX, X, 1
1707 // (d)srl SrlX, SllX, 1
1708 // (d)srl SrlY, Y, width(Y)-1
1709 // (d)sll SllY, SrlX, width(Y)-1
1710 // or Or, SrlX, SllY
1711 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1712 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1713 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1714 DAG.getConstant(WidthY - 1, MVT::i32));
1716 if (WidthX > WidthY)
1717 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1718 else if (WidthY > WidthX)
1719 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1721 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1722 DAG.getConstant(WidthX - 1, MVT::i32));
1723 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1724 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1728 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1729 if (Subtarget->hasMips64())
1730 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1732 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1735 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1736 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1739 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1741 SDValue X = (Op.getValueType() == MVT::f32) ?
1742 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1743 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1748 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1749 DAG.getRegister(Mips::ZERO, MVT::i32),
1750 DAG.getConstant(31, MVT::i32), Const1, X);
1752 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1753 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1756 if (Op.getValueType() == MVT::f32)
1757 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1759 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1760 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1761 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1764 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1765 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1768 // Bitcast to integer node.
1769 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1773 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1774 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1775 DAG.getConstant(63, MVT::i32), Const1, X);
1777 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1778 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1781 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1785 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1786 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1787 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1789 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1792 SDValue MipsTargetLowering::
1793 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1795 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1796 "Frame address can only be determined for current frame.");
1798 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1799 MFI->setFrameAddressIsTaken(true);
1800 EVT VT = Op.getValueType();
1802 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1803 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1807 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1808 SelectionDAG &DAG) const {
1810 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1811 "Return address can be determined only for current frame.");
1813 MachineFunction &MF = DAG.getMachineFunction();
1814 MachineFrameInfo *MFI = MF.getFrameInfo();
1815 MVT VT = Op.getSimpleValueType();
1816 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1817 MFI->setReturnAddressIsTaken(true);
1819 // Return RA, which contains the return address. Mark it an implicit live-in.
1820 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1821 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1824 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1825 // generated from __builtin_eh_return (offset, handler)
1826 // The effect of this is to adjust the stack pointer by "offset"
1827 // and then branch to "handler".
1828 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1830 MachineFunction &MF = DAG.getMachineFunction();
1831 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1833 MipsFI->setCallsEhReturn();
1834 SDValue Chain = Op.getOperand(0);
1835 SDValue Offset = Op.getOperand(1);
1836 SDValue Handler = Op.getOperand(2);
1838 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1840 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1841 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1842 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1843 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1844 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1845 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1846 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1847 DAG.getRegister(OffsetReg, Ty),
1848 DAG.getRegister(AddrReg, getPointerTy()),
1852 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1853 SelectionDAG &DAG) const {
1854 // FIXME: Need pseudo-fence for 'singlethread' fences
1855 // FIXME: Set SType for weaker fences where supported/appropriate.
1858 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1859 DAG.getConstant(SType, MVT::i32));
1862 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1863 SelectionDAG &DAG) const {
1865 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1866 SDValue Shamt = Op.getOperand(2);
1869 // lo = (shl lo, shamt)
1870 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1873 // hi = (shl lo, shamt[4:0])
1874 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1875 DAG.getConstant(-1, MVT::i32));
1876 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1877 DAG.getConstant(1, MVT::i32));
1878 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1880 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1881 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1882 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1883 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1884 DAG.getConstant(0x20, MVT::i32));
1885 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1886 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1887 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1889 SDValue Ops[2] = {Lo, Hi};
1890 return DAG.getMergeValues(Ops, 2, DL);
1893 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1896 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1897 SDValue Shamt = Op.getOperand(2);
1900 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1902 // hi = (sra hi, shamt)
1904 // hi = (srl hi, shamt)
1907 // lo = (sra hi, shamt[4:0])
1908 // hi = (sra hi, 31)
1910 // lo = (srl hi, shamt[4:0])
1912 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1913 DAG.getConstant(-1, MVT::i32));
1914 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1915 DAG.getConstant(1, MVT::i32));
1916 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1917 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1918 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1919 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1921 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1922 DAG.getConstant(0x20, MVT::i32));
1923 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1924 DAG.getConstant(31, MVT::i32));
1925 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1926 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1927 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1930 SDValue Ops[2] = {Lo, Hi};
1931 return DAG.getMergeValues(Ops, 2, DL);
1934 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1935 SDValue Chain, SDValue Src, unsigned Offset) {
1936 SDValue Ptr = LD->getBasePtr();
1937 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1938 EVT BasePtrVT = Ptr.getValueType();
1940 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1943 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1944 DAG.getConstant(Offset, BasePtrVT));
1946 SDValue Ops[] = { Chain, Ptr, Src };
1947 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1948 LD->getMemOperand());
1951 // Expand an unaligned 32 or 64-bit integer load node.
1952 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1953 LoadSDNode *LD = cast<LoadSDNode>(Op);
1954 EVT MemVT = LD->getMemoryVT();
1956 // Return if load is aligned or if MemVT is neither i32 nor i64.
1957 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1958 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1961 bool IsLittle = Subtarget->isLittle();
1962 EVT VT = Op.getValueType();
1963 ISD::LoadExtType ExtType = LD->getExtensionType();
1964 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1966 assert((VT == MVT::i32) || (VT == MVT::i64));
1969 // (set dst, (i64 (load baseptr)))
1971 // (set tmp, (ldl (add baseptr, 7), undef))
1972 // (set dst, (ldr baseptr, tmp))
1973 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1974 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1976 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1980 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1982 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1986 // (set dst, (i32 (load baseptr))) or
1987 // (set dst, (i64 (sextload baseptr))) or
1988 // (set dst, (i64 (extload baseptr)))
1990 // (set tmp, (lwl (add baseptr, 3), undef))
1991 // (set dst, (lwr baseptr, tmp))
1992 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1993 (ExtType == ISD::EXTLOAD))
1996 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1999 // (set dst, (i64 (zextload baseptr)))
2001 // (set tmp0, (lwl (add baseptr, 3), undef))
2002 // (set tmp1, (lwr baseptr, tmp0))
2003 // (set tmp2, (shl tmp1, 32))
2004 // (set dst, (srl tmp2, 32))
2006 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2007 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2008 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2009 SDValue Ops[] = { SRL, LWR.getValue(1) };
2010 return DAG.getMergeValues(Ops, 2, DL);
2013 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2014 SDValue Chain, unsigned Offset) {
2015 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2016 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2018 SDVTList VTList = DAG.getVTList(MVT::Other);
2021 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2022 DAG.getConstant(Offset, BasePtrVT));
2024 SDValue Ops[] = { Chain, Value, Ptr };
2025 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2026 SD->getMemOperand());
2029 // Expand an unaligned 32 or 64-bit integer store node.
2030 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2032 SDValue Value = SD->getValue(), Chain = SD->getChain();
2033 EVT VT = Value.getValueType();
2036 // (store val, baseptr) or
2037 // (truncstore val, baseptr)
2039 // (swl val, (add baseptr, 3))
2040 // (swr val, baseptr)
2041 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2042 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2044 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2047 assert(VT == MVT::i64);
2050 // (store val, baseptr)
2052 // (sdl val, (add baseptr, 7))
2053 // (sdr val, baseptr)
2054 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2055 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2058 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2059 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2060 SDValue Val = SD->getValue();
2062 if (Val.getOpcode() != ISD::FP_TO_SINT)
2065 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2066 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2069 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2070 SD->getPointerInfo(), SD->isVolatile(),
2071 SD->isNonTemporal(), SD->getAlignment());
2074 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2075 StoreSDNode *SD = cast<StoreSDNode>(Op);
2076 EVT MemVT = SD->getMemoryVT();
2078 // Lower unaligned integer stores.
2079 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2080 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2081 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2083 return lowerFP_TO_SINT_STORE(SD, DAG);
2086 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2087 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2088 || cast<ConstantSDNode>
2089 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2090 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2094 // (add (frameaddr 0), (frame_to_args_offset))
2095 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2096 // (add FrameObject, 0)
2097 // where FrameObject is a fixed StackObject with offset 0 which points to
2098 // the old stack pointer.
2099 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2100 EVT ValTy = Op->getValueType(0);
2101 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2102 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2103 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2104 DAG.getConstant(0, ValTy));
2107 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2108 SelectionDAG &DAG) const {
2109 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2110 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2112 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2115 //===----------------------------------------------------------------------===//
2116 // Calling Convention Implementation
2117 //===----------------------------------------------------------------------===//
2119 //===----------------------------------------------------------------------===//
2120 // TODO: Implement a generic logic using tblgen that can support this.
2121 // Mips O32 ABI rules:
2123 // i32 - Passed in A0, A1, A2, A3 and stack
2124 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2125 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2126 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2127 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2128 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2131 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2132 //===----------------------------------------------------------------------===//
2134 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2135 MVT LocVT, CCValAssign::LocInfo LocInfo,
2136 ISD::ArgFlagsTy ArgFlags, CCState &State,
2137 const uint16_t *F64Regs) {
2139 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2141 static const uint16_t IntRegs[] = {
2142 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2144 static const uint16_t F32Regs[] = {
2145 Mips::F12, Mips::F14
2148 // Do not process byval args here.
2149 if (ArgFlags.isByVal())
2152 // Promote i8 and i16
2153 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2155 if (ArgFlags.isSExt())
2156 LocInfo = CCValAssign::SExt;
2157 else if (ArgFlags.isZExt())
2158 LocInfo = CCValAssign::ZExt;
2160 LocInfo = CCValAssign::AExt;
2165 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2166 // is true: function is vararg, argument is 3rd or higher, there is previous
2167 // argument which is not f32 or f64.
2168 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2169 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2170 unsigned OrigAlign = ArgFlags.getOrigAlign();
2171 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2173 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2174 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2175 // If this is the first part of an i64 arg,
2176 // the allocated register must be either A0 or A2.
2177 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2178 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2180 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2181 // Allocate int register and shadow next int register. If first
2182 // available register is Mips::A1 or Mips::A3, shadow it too.
2183 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2184 if (Reg == Mips::A1 || Reg == Mips::A3)
2185 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2186 State.AllocateReg(IntRegs, IntRegsSize);
2188 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2189 // we are guaranteed to find an available float register
2190 if (ValVT == MVT::f32) {
2191 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2192 // Shadow int register
2193 State.AllocateReg(IntRegs, IntRegsSize);
2195 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2196 // Shadow int registers
2197 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2198 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2199 State.AllocateReg(IntRegs, IntRegsSize);
2200 State.AllocateReg(IntRegs, IntRegsSize);
2203 llvm_unreachable("Cannot handle this ValVT.");
2206 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2208 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2210 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2215 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2216 MVT LocVT, CCValAssign::LocInfo LocInfo,
2217 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2218 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2220 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2223 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2224 MVT LocVT, CCValAssign::LocInfo LocInfo,
2225 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2226 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2228 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2231 #include "MipsGenCallingConv.inc"
2233 //===----------------------------------------------------------------------===//
2234 // Call Calling Convention Implementation
2235 //===----------------------------------------------------------------------===//
2237 // Return next O32 integer argument register.
2238 static unsigned getNextIntArgReg(unsigned Reg) {
2239 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2240 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2244 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2245 SDValue Chain, SDValue Arg, SDLoc DL,
2246 bool IsTailCall, SelectionDAG &DAG) const {
2248 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2249 DAG.getIntPtrConstant(Offset));
2250 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2254 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2255 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2256 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2257 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2258 /*isVolatile=*/ true, false, 0);
2261 void MipsTargetLowering::
2262 getOpndList(SmallVectorImpl<SDValue> &Ops,
2263 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2264 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2265 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2266 // Insert node "GP copy globalreg" before call to function.
2268 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2269 // in PIC mode) allow symbols to be resolved via lazy binding.
2270 // The lazy binding stub requires GP to point to the GOT.
2271 if (IsPICCall && !InternalLinkage) {
2272 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2273 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2274 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2277 // Build a sequence of copy-to-reg nodes chained together with token
2278 // chain and flag operands which copy the outgoing args into registers.
2279 // The InFlag in necessary since all emitted instructions must be
2283 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2284 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2285 RegsToPass[i].second, InFlag);
2286 InFlag = Chain.getValue(1);
2289 // Add argument registers to the end of the list so that they are
2290 // known live into the call.
2291 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2292 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2293 RegsToPass[i].second.getValueType()));
2295 // Add a register mask operand representing the call-preserved registers.
2296 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2297 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2298 assert(Mask && "Missing call preserved mask for calling convention");
2299 if (Subtarget->inMips16HardFloat()) {
2300 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2301 llvm::StringRef Sym = G->getGlobal()->getName();
2302 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2303 if (F->hasFnAttribute("__Mips16RetHelper")) {
2304 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2308 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2310 if (InFlag.getNode())
2311 Ops.push_back(InFlag);
2314 /// LowerCall - functions arguments are copied from virtual regs to
2315 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2317 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2318 SmallVectorImpl<SDValue> &InVals) const {
2319 SelectionDAG &DAG = CLI.DAG;
2321 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2322 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2323 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2324 SDValue Chain = CLI.Chain;
2325 SDValue Callee = CLI.Callee;
2326 bool &IsTailCall = CLI.IsTailCall;
2327 CallingConv::ID CallConv = CLI.CallConv;
2328 bool IsVarArg = CLI.IsVarArg;
2330 MachineFunction &MF = DAG.getMachineFunction();
2331 MachineFrameInfo *MFI = MF.getFrameInfo();
2332 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2333 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2335 // Analyze operands of the call, assigning locations to each operand.
2336 SmallVector<CCValAssign, 16> ArgLocs;
2337 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2338 getTargetMachine(), ArgLocs, *DAG.getContext());
2339 MipsCC::SpecialCallingConvType SpecialCallingConv =
2340 getSpecialCallingConv(Callee);
2341 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2342 SpecialCallingConv);
2344 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2345 Subtarget->mipsSEUsesSoftFloat(),
2346 Callee.getNode(), CLI.Args);
2348 // Get a count of how many bytes are to be pushed on the stack.
2349 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2351 // Check if it's really possible to do a tail call.
2354 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2355 *MF.getInfo<MipsFunctionInfo>());
2360 // Chain is the output chain of the last Load/Store or CopyToReg node.
2361 // ByValChain is the output chain of the last Memcpy node created for copying
2362 // byval arguments to the stack.
2363 unsigned StackAlignment = TFL->getStackAlignment();
2364 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2365 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2368 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2370 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2371 IsN64 ? Mips::SP_64 : Mips::SP,
2374 // With EABI is it possible to have 16 args on registers.
2375 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2376 SmallVector<SDValue, 8> MemOpChains;
2377 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2379 // Walk the register/memloc assignments, inserting copies/loads.
2380 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2381 SDValue Arg = OutVals[i];
2382 CCValAssign &VA = ArgLocs[i];
2383 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2384 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2387 if (Flags.isByVal()) {
2388 assert(Flags.getByValSize() &&
2389 "ByVal args of size 0 should have been ignored by front-end.");
2390 assert(ByValArg != MipsCCInfo.byval_end());
2391 assert(!IsTailCall &&
2392 "Do not tail-call optimize if there is a byval argument.");
2393 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2394 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2399 // Promote the value if needed.
2400 switch (VA.getLocInfo()) {
2401 default: llvm_unreachable("Unknown loc info!");
2402 case CCValAssign::Full:
2403 if (VA.isRegLoc()) {
2404 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2405 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2406 (ValVT == MVT::i64 && LocVT == MVT::f64))
2407 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2408 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2409 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2410 Arg, DAG.getConstant(0, MVT::i32));
2411 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2412 Arg, DAG.getConstant(1, MVT::i32));
2413 if (!Subtarget->isLittle())
2415 unsigned LocRegLo = VA.getLocReg();
2416 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2417 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2418 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2423 case CCValAssign::SExt:
2424 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2426 case CCValAssign::ZExt:
2427 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2429 case CCValAssign::AExt:
2430 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2434 // Arguments that can be passed on register must be kept at
2435 // RegsToPass vector
2436 if (VA.isRegLoc()) {
2437 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2441 // Register can't get to this point...
2442 assert(VA.isMemLoc());
2444 // emit ISD::STORE whichs stores the
2445 // parameter value to a stack Location
2446 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2447 Chain, Arg, DL, IsTailCall, DAG));
2450 // Transform all store nodes into one single node because all store
2451 // nodes are independent of each other.
2452 if (!MemOpChains.empty())
2453 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2454 &MemOpChains[0], MemOpChains.size());
2456 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2457 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2458 // node so that legalize doesn't hack it.
2459 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2460 bool GlobalOrExternal = false, InternalLinkage = false;
2463 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2465 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2467 if (InternalLinkage)
2468 Callee = getAddrLocal(Callee, DAG, HasMips64);
2470 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2471 MipsII::MO_CALL_LO16);
2473 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2475 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2476 MipsII::MO_NO_FLAG);
2477 GlobalOrExternal = true;
2479 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2480 if (!IsN64 && !IsPIC) // !N64 && static
2481 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2482 MipsII::MO_NO_FLAG);
2484 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2485 MipsII::MO_CALL_LO16);
2487 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2489 GlobalOrExternal = true;
2492 SmallVector<SDValue, 8> Ops(1, Chain);
2493 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2495 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2496 CLI, Callee, Chain);
2499 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2501 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2502 SDValue InFlag = Chain.getValue(1);
2504 // Create the CALLSEQ_END node.
2505 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2506 DAG.getIntPtrConstant(0, true), InFlag, DL);
2507 InFlag = Chain.getValue(1);
2509 // Handle result values, copying them out of physregs into vregs that we
2511 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2512 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2515 /// LowerCallResult - Lower the result values of a call into the
2516 /// appropriate copies out of appropriate physical registers.
2518 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2519 CallingConv::ID CallConv, bool IsVarArg,
2520 const SmallVectorImpl<ISD::InputArg> &Ins,
2521 SDLoc DL, SelectionDAG &DAG,
2522 SmallVectorImpl<SDValue> &InVals,
2523 const SDNode *CallNode,
2524 const Type *RetTy) const {
2525 // Assign locations to each value returned by this call.
2526 SmallVector<CCValAssign, 16> RVLocs;
2527 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2528 getTargetMachine(), RVLocs, *DAG.getContext());
2529 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2531 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2534 // Copy all of the result registers out of their specified physreg.
2535 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2536 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2537 RVLocs[i].getLocVT(), InFlag);
2538 Chain = Val.getValue(1);
2539 InFlag = Val.getValue(2);
2541 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2542 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2544 InVals.push_back(Val);
2550 //===----------------------------------------------------------------------===//
2551 // Formal Arguments Calling Convention Implementation
2552 //===----------------------------------------------------------------------===//
2553 /// LowerFormalArguments - transform physical registers into virtual registers
2554 /// and generate load operations for arguments places on the stack.
2556 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2557 CallingConv::ID CallConv,
2559 const SmallVectorImpl<ISD::InputArg> &Ins,
2560 SDLoc DL, SelectionDAG &DAG,
2561 SmallVectorImpl<SDValue> &InVals)
2563 MachineFunction &MF = DAG.getMachineFunction();
2564 MachineFrameInfo *MFI = MF.getFrameInfo();
2565 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2567 MipsFI->setVarArgsFrameIndex(0);
2569 // Used with vargs to acumulate store chains.
2570 std::vector<SDValue> OutChains;
2572 // Assign locations to all of the incoming arguments.
2573 SmallVector<CCValAssign, 16> ArgLocs;
2574 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2575 getTargetMachine(), ArgLocs, *DAG.getContext());
2576 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2577 Function::const_arg_iterator FuncArg =
2578 DAG.getMachineFunction().getFunction()->arg_begin();
2579 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2581 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2582 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2583 MipsCCInfo.hasByValArg());
2585 unsigned CurArgIdx = 0;
2586 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2588 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2589 CCValAssign &VA = ArgLocs[i];
2590 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2591 CurArgIdx = Ins[i].OrigArgIndex;
2592 EVT ValVT = VA.getValVT();
2593 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2594 bool IsRegLoc = VA.isRegLoc();
2596 if (Flags.isByVal()) {
2597 assert(Flags.getByValSize() &&
2598 "ByVal args of size 0 should have been ignored by front-end.");
2599 assert(ByValArg != MipsCCInfo.byval_end());
2600 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2601 MipsCCInfo, *ByValArg);
2606 // Arguments stored on registers
2608 EVT RegVT = VA.getLocVT();
2609 unsigned ArgReg = VA.getLocReg();
2610 const TargetRegisterClass *RC;
2612 if (RegVT == MVT::i32)
2613 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2614 &Mips::GPR32RegClass;
2615 else if (RegVT == MVT::i64)
2616 RC = &Mips::GPR64RegClass;
2617 else if (RegVT == MVT::f32)
2618 RC = &Mips::FGR32RegClass;
2619 else if (RegVT == MVT::f64)
2620 RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2621 &Mips::AFGR64RegClass;
2623 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2625 // Transform the arguments stored on
2626 // physical registers into virtual ones
2627 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2628 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2630 // If this is an 8 or 16-bit value, it has been passed promoted
2631 // to 32 bits. Insert an assert[sz]ext to capture this, then
2632 // truncate to the right size.
2633 if (VA.getLocInfo() != CCValAssign::Full) {
2634 unsigned Opcode = 0;
2635 if (VA.getLocInfo() == CCValAssign::SExt)
2636 Opcode = ISD::AssertSext;
2637 else if (VA.getLocInfo() == CCValAssign::ZExt)
2638 Opcode = ISD::AssertZext;
2640 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2641 DAG.getValueType(ValVT));
2642 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2645 // Handle floating point arguments passed in integer registers and
2646 // long double arguments passed in floating point registers.
2647 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2648 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2649 (RegVT == MVT::f64 && ValVT == MVT::i64))
2650 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2651 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2652 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2653 getNextIntArgReg(ArgReg), RC);
2654 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2655 if (!Subtarget->isLittle())
2656 std::swap(ArgValue, ArgValue2);
2657 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2658 ArgValue, ArgValue2);
2661 InVals.push_back(ArgValue);
2662 } else { // VA.isRegLoc()
2665 assert(VA.isMemLoc());
2667 // The stack pointer offset is relative to the caller stack frame.
2668 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2669 VA.getLocMemOffset(), true);
2671 // Create load nodes to retrieve arguments from the stack
2672 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2673 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2674 MachinePointerInfo::getFixedStack(FI),
2675 false, false, false, 0));
2679 // The mips ABIs for returning structs by value requires that we copy
2680 // the sret argument into $v0 for the return. Save the argument into
2681 // a virtual register so that we can access it from the return points.
2682 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2683 unsigned Reg = MipsFI->getSRetReturnReg();
2685 Reg = MF.getRegInfo().
2686 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2687 MipsFI->setSRetReturnReg(Reg);
2689 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2690 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2694 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2696 // All stores are grouped in one node to allow the matching between
2697 // the size of Ins and InVals. This only happens when on varg functions
2698 if (!OutChains.empty()) {
2699 OutChains.push_back(Chain);
2700 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2701 &OutChains[0], OutChains.size());
2707 //===----------------------------------------------------------------------===//
2708 // Return Value Calling Convention Implementation
2709 //===----------------------------------------------------------------------===//
2712 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2713 MachineFunction &MF, bool IsVarArg,
2714 const SmallVectorImpl<ISD::OutputArg> &Outs,
2715 LLVMContext &Context) const {
2716 SmallVector<CCValAssign, 16> RVLocs;
2717 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2719 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2723 MipsTargetLowering::LowerReturn(SDValue Chain,
2724 CallingConv::ID CallConv, bool IsVarArg,
2725 const SmallVectorImpl<ISD::OutputArg> &Outs,
2726 const SmallVectorImpl<SDValue> &OutVals,
2727 SDLoc DL, SelectionDAG &DAG) const {
2728 // CCValAssign - represent the assignment of
2729 // the return value to a location
2730 SmallVector<CCValAssign, 16> RVLocs;
2731 MachineFunction &MF = DAG.getMachineFunction();
2733 // CCState - Info about the registers and stack slot.
2734 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2736 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2738 // Analyze return values.
2739 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2740 MF.getFunction()->getReturnType());
2743 SmallVector<SDValue, 4> RetOps(1, Chain);
2745 // Copy the result values into the output registers.
2746 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2747 SDValue Val = OutVals[i];
2748 CCValAssign &VA = RVLocs[i];
2749 assert(VA.isRegLoc() && "Can only return in registers!");
2751 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2752 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2754 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2756 // Guarantee that all emitted copies are stuck together with flags.
2757 Flag = Chain.getValue(1);
2758 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2761 // The mips ABIs for returning structs by value requires that we copy
2762 // the sret argument into $v0 for the return. We saved the argument into
2763 // a virtual register in the entry block, so now we copy the value out
2765 if (MF.getFunction()->hasStructRetAttr()) {
2766 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2767 unsigned Reg = MipsFI->getSRetReturnReg();
2770 llvm_unreachable("sret virtual register not created in the entry block");
2771 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2772 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2774 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2775 Flag = Chain.getValue(1);
2776 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2779 RetOps[0] = Chain; // Update chain.
2781 // Add the flag if we have it.
2783 RetOps.push_back(Flag);
2785 // Return on Mips is always a "jr $ra"
2786 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2789 //===----------------------------------------------------------------------===//
2790 // Mips Inline Assembly Support
2791 //===----------------------------------------------------------------------===//
2793 /// getConstraintType - Given a constraint letter, return the type of
2794 /// constraint it is for this target.
2795 MipsTargetLowering::ConstraintType MipsTargetLowering::
2796 getConstraintType(const std::string &Constraint) const
2798 // Mips specific constrainy
2799 // GCC config/mips/constraints.md
2801 // 'd' : An address register. Equivalent to r
2802 // unless generating MIPS16 code.
2803 // 'y' : Equivalent to r; retained for
2804 // backwards compatibility.
2805 // 'c' : A register suitable for use in an indirect
2806 // jump. This will always be $25 for -mabicalls.
2807 // 'l' : The lo register. 1 word storage.
2808 // 'x' : The hilo register pair. Double word storage.
2809 if (Constraint.size() == 1) {
2810 switch (Constraint[0]) {
2818 return C_RegisterClass;
2823 return TargetLowering::getConstraintType(Constraint);
2826 /// Examine constraint type and operand type and determine a weight value.
2827 /// This object must already have been set up with the operand type
2828 /// and the current alternative constraint selected.
2829 TargetLowering::ConstraintWeight
2830 MipsTargetLowering::getSingleConstraintMatchWeight(
2831 AsmOperandInfo &info, const char *constraint) const {
2832 ConstraintWeight weight = CW_Invalid;
2833 Value *CallOperandVal = info.CallOperandVal;
2834 // If we don't have a value, we can't do a match,
2835 // but allow it at the lowest weight.
2836 if (CallOperandVal == NULL)
2838 Type *type = CallOperandVal->getType();
2839 // Look at the constraint type.
2840 switch (*constraint) {
2842 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2846 if (type->isIntegerTy())
2847 weight = CW_Register;
2850 if (type->isFloatTy())
2851 weight = CW_Register;
2853 case 'c': // $25 for indirect jumps
2854 case 'l': // lo register
2855 case 'x': // hilo register pair
2856 if (type->isIntegerTy())
2857 weight = CW_SpecificReg;
2859 case 'I': // signed 16 bit immediate
2860 case 'J': // integer zero
2861 case 'K': // unsigned 16 bit immediate
2862 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2863 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2864 case 'O': // signed 15 bit immediate (+- 16383)
2865 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2866 if (isa<ConstantInt>(CallOperandVal))
2867 weight = CW_Constant;
2876 /// This is a helper function to parse a physical register string and split it
2877 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2878 /// that is returned indicates whether parsing was successful. The second flag
2879 /// is true if the numeric part exists.
2880 static std::pair<bool, bool>
2881 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2882 unsigned long long &Reg) {
2883 if (C.front() != '{' || C.back() != '}')
2884 return std::make_pair(false, false);
2886 // Search for the first numeric character.
2887 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2888 I = std::find_if(B, E, std::ptr_fun(isdigit));
2890 Prefix.assign(B, I - B);
2892 // The second flag is set to false if no numeric characters were found.
2894 return std::make_pair(true, false);
2896 // Parse the numeric characters.
2897 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2901 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2902 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2903 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2904 const TargetRegisterClass *RC;
2906 unsigned long long Reg;
2908 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2911 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2913 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2914 // No numeric characters follow "hi" or "lo".
2916 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2918 RC = TRI->getRegClass(Prefix == "hi" ?
2919 Mips::HI32RegClassID : Mips::LO32RegClassID);
2920 return std::make_pair(*(RC->begin()), RC);
2924 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2926 if (Prefix == "$f") { // Parse $f0-$f31.
2927 // If the size of FP registers is 64-bit or Reg is an even number, select
2928 // the 64-bit register class. Otherwise, select the 32-bit register class.
2929 if (VT == MVT::Other)
2930 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2932 RC= getRegClassFor(VT);
2934 if (RC == &Mips::AFGR64RegClass) {
2935 assert(Reg % 2 == 0);
2938 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2939 RC = TRI->getRegClass(Mips::FCCRegClassID);
2940 } else { // Parse $0-$31.
2941 assert(Prefix == "$");
2942 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2945 assert(Reg < RC->getNumRegs());
2946 return std::make_pair(*(RC->begin() + Reg), RC);
2949 /// Given a register class constraint, like 'r', if this corresponds directly
2950 /// to an LLVM register class, return a register of 0 and the register class
2952 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2953 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2955 if (Constraint.size() == 1) {
2956 switch (Constraint[0]) {
2957 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2958 case 'y': // Same as 'r'. Exists for compatibility.
2960 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2961 if (Subtarget->inMips16Mode())
2962 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2963 return std::make_pair(0U, &Mips::GPR32RegClass);
2965 if (VT == MVT::i64 && !HasMips64)
2966 return std::make_pair(0U, &Mips::GPR32RegClass);
2967 if (VT == MVT::i64 && HasMips64)
2968 return std::make_pair(0U, &Mips::GPR64RegClass);
2969 // This will generate an error message
2970 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2973 return std::make_pair(0U, &Mips::FGR32RegClass);
2974 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2975 if (Subtarget->isFP64bit())
2976 return std::make_pair(0U, &Mips::FGR64RegClass);
2977 return std::make_pair(0U, &Mips::AFGR64RegClass);
2980 case 'c': // register suitable for indirect jump
2982 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2983 assert(VT == MVT::i64 && "Unexpected type.");
2984 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2985 case 'l': // register suitable for indirect jump
2987 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2988 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2989 case 'x': // register suitable for indirect jump
2990 // Fixme: Not triggering the use of both hi and low
2991 // This will generate an error message
2992 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2996 std::pair<unsigned, const TargetRegisterClass *> R;
2997 R = parseRegForInlineAsmConstraint(Constraint, VT);
3002 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3005 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3006 /// vector. If it is invalid, don't add anything to Ops.
3007 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3008 std::string &Constraint,
3009 std::vector<SDValue>&Ops,
3010 SelectionDAG &DAG) const {
3011 SDValue Result(0, 0);
3013 // Only support length 1 constraints for now.
3014 if (Constraint.length() > 1) return;
3016 char ConstraintLetter = Constraint[0];
3017 switch (ConstraintLetter) {
3018 default: break; // This will fall through to the generic implementation
3019 case 'I': // Signed 16 bit constant
3020 // If this fails, the parent routine will give an error
3021 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3022 EVT Type = Op.getValueType();
3023 int64_t Val = C->getSExtValue();
3024 if (isInt<16>(Val)) {
3025 Result = DAG.getTargetConstant(Val, Type);
3030 case 'J': // integer zero
3031 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3032 EVT Type = Op.getValueType();
3033 int64_t Val = C->getZExtValue();
3035 Result = DAG.getTargetConstant(0, Type);
3040 case 'K': // unsigned 16 bit immediate
3041 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3042 EVT Type = Op.getValueType();
3043 uint64_t Val = (uint64_t)C->getZExtValue();
3044 if (isUInt<16>(Val)) {
3045 Result = DAG.getTargetConstant(Val, Type);
3050 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3051 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3052 EVT Type = Op.getValueType();
3053 int64_t Val = C->getSExtValue();
3054 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3055 Result = DAG.getTargetConstant(Val, Type);
3060 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3061 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3062 EVT Type = Op.getValueType();
3063 int64_t Val = C->getSExtValue();
3064 if ((Val >= -65535) && (Val <= -1)) {
3065 Result = DAG.getTargetConstant(Val, Type);
3070 case 'O': // signed 15 bit immediate
3071 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3072 EVT Type = Op.getValueType();
3073 int64_t Val = C->getSExtValue();
3074 if ((isInt<15>(Val))) {
3075 Result = DAG.getTargetConstant(Val, Type);
3080 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3081 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3082 EVT Type = Op.getValueType();
3083 int64_t Val = C->getSExtValue();
3084 if ((Val <= 65535) && (Val >= 1)) {
3085 Result = DAG.getTargetConstant(Val, Type);
3092 if (Result.getNode()) {
3093 Ops.push_back(Result);
3097 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3101 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3102 // No global is ever allowed as a base.
3107 case 0: // "r+i" or just "i", depending on HasBaseReg.
3110 if (!AM.HasBaseReg) // allow "r+i".
3112 return false; // disallow "r+r" or "r+r+i".
3121 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3122 // The Mips target isn't yet aware of offsets.
3126 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3128 bool IsMemset, bool ZeroMemset,
3130 MachineFunction &MF) const {
3131 if (Subtarget->hasMips64())
3137 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3138 if (VT != MVT::f32 && VT != MVT::f64)
3140 if (Imm.isNegZero())
3142 return Imm.isZero();
3145 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3147 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3149 return TargetLowering::getJumpTableEncoding();
3152 /// This function returns true if CallSym is a long double emulation routine.
3153 static bool isF128SoftLibCall(const char *CallSym) {
3154 const char *const LibCalls[] =
3155 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3156 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3157 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3158 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3159 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3160 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3161 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3162 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3165 const char * const *End = LibCalls + array_lengthof(LibCalls);
3167 // Check that LibCalls is sorted alphabetically.
3168 MipsTargetLowering::LTStr Comp;
3171 for (const char * const *I = LibCalls; I < End - 1; ++I)
3172 assert(Comp(*I, *(I + 1)));
3175 return std::binary_search(LibCalls, End, CallSym, Comp);
3178 /// This function returns true if Ty is fp128 or i128 which was originally a
3180 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3181 if (Ty->isFP128Ty())
3184 const ExternalSymbolSDNode *ES =
3185 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3187 // If the Ty is i128 and the function being called is a long double emulation
3188 // routine, then the original type is f128.
3189 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3192 MipsTargetLowering::MipsCC::SpecialCallingConvType
3193 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3194 MipsCC::SpecialCallingConvType SpecialCallingConv =
3195 MipsCC::NoSpecialCallingConv;;
3196 if (Subtarget->inMips16HardFloat()) {
3197 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3198 llvm::StringRef Sym = G->getGlobal()->getName();
3199 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3200 if (F->hasFnAttribute("__Mips16RetHelper")) {
3201 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3205 return SpecialCallingConv;
3208 MipsTargetLowering::MipsCC::MipsCC(
3209 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3210 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3211 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3212 SpecialCallingConv(SpecialCallingConv_){
3213 // Pre-allocate reserved argument area.
3214 CCInfo.AllocateStack(reservedArgArea(), 1);
3218 void MipsTargetLowering::MipsCC::
3219 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3220 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3221 std::vector<ArgListEntry> &FuncArgs) {
3222 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3223 "CallingConv::Fast shouldn't be used for vararg functions.");
3225 unsigned NumOpnds = Args.size();
3226 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3228 for (unsigned I = 0; I != NumOpnds; ++I) {
3229 MVT ArgVT = Args[I].VT;
3230 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3233 if (ArgFlags.isByVal()) {
3234 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3238 if (IsVarArg && !Args[I].IsFixed)
3239 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3241 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3243 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3248 dbgs() << "Call operand #" << I << " has unhandled type "
3249 << EVT(ArgVT).getEVTString();
3251 llvm_unreachable(0);
3256 void MipsTargetLowering::MipsCC::
3257 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3258 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3259 unsigned NumArgs = Args.size();
3260 llvm::CCAssignFn *FixedFn = fixedArgFn();
3261 unsigned CurArgIdx = 0;
3263 for (unsigned I = 0; I != NumArgs; ++I) {
3264 MVT ArgVT = Args[I].VT;
3265 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3266 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3267 CurArgIdx = Args[I].OrigArgIndex;
3269 if (ArgFlags.isByVal()) {
3270 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3274 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3276 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3280 dbgs() << "Formal Arg #" << I << " has unhandled type "
3281 << EVT(ArgVT).getEVTString();
3283 llvm_unreachable(0);
3287 template<typename Ty>
3288 void MipsTargetLowering::MipsCC::
3289 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3290 const SDNode *CallNode, const Type *RetTy) const {
3293 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3294 Fn = RetCC_F128Soft;
3298 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3299 MVT VT = RetVals[I].VT;
3300 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3301 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3303 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3305 dbgs() << "Call result #" << I << " has unhandled type "
3306 << EVT(VT).getEVTString() << '\n';
3308 llvm_unreachable(0);
3313 void MipsTargetLowering::MipsCC::
3314 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3315 const SDNode *CallNode, const Type *RetTy) const {
3316 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3319 void MipsTargetLowering::MipsCC::
3320 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3321 const Type *RetTy) const {
3322 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3326 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3328 CCValAssign::LocInfo LocInfo,
3329 ISD::ArgFlagsTy ArgFlags) {
3330 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3332 struct ByValArgInfo ByVal;
3333 unsigned RegSize = regSize();
3334 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3335 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3338 if (useRegsForByval())
3339 allocateRegs(ByVal, ByValSize, Align);
3341 // Allocate space on caller's stack.
3342 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3344 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3346 ByValArgs.push_back(ByVal);
3349 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3350 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3353 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3354 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3357 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3358 return IsO32 ? O32IntRegs : Mips64IntRegs;
3361 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3362 if (CallConv == CallingConv::Fast)
3363 return CC_Mips_FastCC;
3365 if (SpecialCallingConv == Mips16RetHelperConv)
3366 return CC_Mips16RetHelper;
3367 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3370 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3371 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3374 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3375 return IsO32 ? O32IntRegs : Mips64DPRegs;
3378 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3381 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3382 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3383 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3384 "Byval argument's size and alignment should be a multiple of"
3387 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3389 // If Align > RegSize, the first arg register must be even.
3390 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3391 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3395 // Mark the registers allocated.
3396 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3397 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3398 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3401 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3402 const SDNode *CallNode,
3403 bool IsSoftFloat) const {
3404 if (IsSoftFloat || IsO32)
3407 // Check if the original type was fp128.
3408 if (originalTypeIsF128(OrigTy, CallNode)) {
3409 assert(VT == MVT::i64);
3416 void MipsTargetLowering::
3417 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3418 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3419 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3420 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3421 MachineFunction &MF = DAG.getMachineFunction();
3422 MachineFrameInfo *MFI = MF.getFrameInfo();
3423 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3424 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3428 FrameObjOffset = (int)CC.reservedArgArea() -
3429 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3431 FrameObjOffset = ByVal.Address;
3433 // Create frame object.
3434 EVT PtrTy = getPointerTy();
3435 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3436 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3437 InVals.push_back(FIN);
3442 // Copy arg registers.
3443 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3444 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3446 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3447 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3448 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3449 unsigned Offset = I * CC.regSize();
3450 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3451 DAG.getConstant(Offset, PtrTy));
3452 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3453 StorePtr, MachinePointerInfo(FuncArg, Offset),
3455 OutChains.push_back(Store);
3459 // Copy byVal arg to registers and stack.
3460 void MipsTargetLowering::
3461 passByValArg(SDValue Chain, SDLoc DL,
3462 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3463 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3464 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3465 const MipsCC &CC, const ByValArgInfo &ByVal,
3466 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3467 unsigned ByValSize = Flags.getByValSize();
3468 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3469 unsigned RegSize = CC.regSize();
3470 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3471 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3473 if (ByVal.NumRegs) {
3474 const uint16_t *ArgRegs = CC.intArgRegs();
3475 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3478 // Copy words to registers.
3479 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3480 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3481 DAG.getConstant(Offset, PtrTy));
3482 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3483 MachinePointerInfo(), false, false, false,
3485 MemOpChains.push_back(LoadVal.getValue(1));
3486 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3487 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3490 // Return if the struct has been fully copied.
3491 if (ByValSize == Offset)
3494 // Copy the remainder of the byval argument with sub-word loads and shifts.
3495 if (LeftoverBytes) {
3496 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3497 "Size of the remainder should be smaller than RegSize.");
3500 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3501 Offset < ByValSize; LoadSize /= 2) {
3502 unsigned RemSize = ByValSize - Offset;
3504 if (RemSize < LoadSize)
3508 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3509 DAG.getConstant(Offset, PtrTy));
3511 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3512 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3513 false, false, Alignment);
3514 MemOpChains.push_back(LoadVal.getValue(1));
3516 // Shift the loaded value.
3520 Shamt = TotalSizeLoaded;
3522 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3524 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3525 DAG.getConstant(Shamt, MVT::i32));
3528 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3533 TotalSizeLoaded += LoadSize;
3534 Alignment = std::min(Alignment, LoadSize);
3537 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3538 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3543 // Copy remainder of byval arg to it with memcpy.
3544 unsigned MemCpySize = ByValSize - Offset;
3545 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3546 DAG.getConstant(Offset, PtrTy));
3547 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3548 DAG.getIntPtrConstant(ByVal.Address));
3549 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3550 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3551 /*isVolatile=*/false, /*AlwaysInline=*/false,
3552 MachinePointerInfo(0), MachinePointerInfo(0));
3553 MemOpChains.push_back(Chain);
3557 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3558 const MipsCC &CC, SDValue Chain,
3559 SDLoc DL, SelectionDAG &DAG) const {
3560 unsigned NumRegs = CC.numIntArgRegs();
3561 const uint16_t *ArgRegs = CC.intArgRegs();
3562 const CCState &CCInfo = CC.getCCInfo();
3563 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3564 unsigned RegSize = CC.regSize();
3565 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3566 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3567 MachineFunction &MF = DAG.getMachineFunction();
3568 MachineFrameInfo *MFI = MF.getFrameInfo();
3569 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3571 // Offset of the first variable argument from stack pointer.
3575 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3578 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3580 // Record the frame index of the first variable argument
3581 // which is a value necessary to VASTART.
3582 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3583 MipsFI->setVarArgsFrameIndex(FI);
3585 // Copy the integer registers that have not been used for argument passing
3586 // to the argument register save area. For O32, the save area is allocated
3587 // in the caller's stack frame, while for N32/64, it is allocated in the
3588 // callee's stack frame.
3589 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3590 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3591 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3592 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3593 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3594 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3595 MachinePointerInfo(), false, false, 0);
3596 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3597 OutChains.push_back(Store);