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::VSPLAT: return "MipsISD::VSPLAT";
216 case MipsISD::VSPLATD: return "MipsISD::VSPLATD";
217 case MipsISD::VNOR: return "MipsISD::VNOR";
218 default: return NULL;
223 MipsTargetLowering(MipsTargetMachine &TM)
224 : TargetLowering(TM, new MipsTargetObjectFile()),
225 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
226 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
227 IsO32(Subtarget->isABI_O32()) {
228 // Mips does not have i1 type, so use i32 for
229 // setcc operations results (slt, sgt, ...).
230 setBooleanContents(ZeroOrOneBooleanContent);
231 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
233 // Load extented operations for i1 types must be promoted
234 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
235 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
236 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
238 // MIPS doesn't have extending float->double load/store
239 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
240 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
242 // Used by legalize types to correctly generate the setcc result.
243 // Without this, every float setcc comes with a AND/OR with the result,
244 // we don't want this, since the fpcmp result goes to a flag register,
245 // which is used implicitly by brcond and select operations.
246 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
248 // Mips Custom Operations
249 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
250 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
251 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
252 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
253 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
254 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
255 setOperationAction(ISD::SELECT, MVT::f32, Custom);
256 setOperationAction(ISD::SELECT, MVT::f64, Custom);
257 setOperationAction(ISD::SELECT, MVT::i32, Custom);
258 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
259 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
260 setOperationAction(ISD::SETCC, MVT::f32, Custom);
261 setOperationAction(ISD::SETCC, MVT::f64, Custom);
262 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
263 setOperationAction(ISD::VASTART, MVT::Other, Custom);
264 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
265 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
266 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
268 if (!TM.Options.NoNaNsFPMath) {
269 setOperationAction(ISD::FABS, MVT::f32, Custom);
270 setOperationAction(ISD::FABS, MVT::f64, Custom);
274 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
275 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
276 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
277 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
278 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
279 setOperationAction(ISD::SELECT, MVT::i64, Custom);
280 setOperationAction(ISD::LOAD, MVT::i64, Custom);
281 setOperationAction(ISD::STORE, MVT::i64, Custom);
282 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
286 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
287 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
288 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
291 setOperationAction(ISD::ADD, MVT::i32, Custom);
293 setOperationAction(ISD::ADD, MVT::i64, Custom);
295 setOperationAction(ISD::SDIV, MVT::i32, Expand);
296 setOperationAction(ISD::SREM, MVT::i32, Expand);
297 setOperationAction(ISD::UDIV, MVT::i32, Expand);
298 setOperationAction(ISD::UREM, MVT::i32, Expand);
299 setOperationAction(ISD::SDIV, MVT::i64, Expand);
300 setOperationAction(ISD::SREM, MVT::i64, Expand);
301 setOperationAction(ISD::UDIV, MVT::i64, Expand);
302 setOperationAction(ISD::UREM, MVT::i64, Expand);
304 // Operations not directly supported by Mips.
305 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
306 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
307 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
308 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
309 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
310 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
311 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
312 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
313 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
314 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
315 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
316 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
317 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
318 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
319 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
320 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
321 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
322 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
323 setOperationAction(ISD::ROTL, MVT::i32, Expand);
324 setOperationAction(ISD::ROTL, MVT::i64, Expand);
325 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
326 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
328 if (!Subtarget->hasMips32r2())
329 setOperationAction(ISD::ROTR, MVT::i32, Expand);
331 if (!Subtarget->hasMips64r2())
332 setOperationAction(ISD::ROTR, MVT::i64, Expand);
334 setOperationAction(ISD::FSIN, MVT::f32, Expand);
335 setOperationAction(ISD::FSIN, MVT::f64, Expand);
336 setOperationAction(ISD::FCOS, MVT::f32, Expand);
337 setOperationAction(ISD::FCOS, MVT::f64, Expand);
338 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
339 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
340 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
341 setOperationAction(ISD::FPOW, MVT::f32, Expand);
342 setOperationAction(ISD::FPOW, MVT::f64, Expand);
343 setOperationAction(ISD::FLOG, MVT::f32, Expand);
344 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
345 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
346 setOperationAction(ISD::FEXP, MVT::f32, Expand);
347 setOperationAction(ISD::FMA, MVT::f32, Expand);
348 setOperationAction(ISD::FMA, MVT::f64, Expand);
349 setOperationAction(ISD::FREM, MVT::f32, Expand);
350 setOperationAction(ISD::FREM, MVT::f64, Expand);
352 if (!TM.Options.NoNaNsFPMath) {
353 setOperationAction(ISD::FNEG, MVT::f32, Expand);
354 setOperationAction(ISD::FNEG, MVT::f64, Expand);
357 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
359 setOperationAction(ISD::VAARG, MVT::Other, Expand);
360 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
361 setOperationAction(ISD::VAEND, MVT::Other, Expand);
363 // Use the default for now
364 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
365 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
367 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
368 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
369 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
370 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
372 setInsertFencesForAtomic(true);
374 if (!Subtarget->hasSEInReg()) {
375 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
376 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
379 if (!Subtarget->hasBitCount()) {
380 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
381 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
384 if (!Subtarget->hasSwap()) {
385 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
386 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
390 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
391 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
392 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
393 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
396 setOperationAction(ISD::TRAP, MVT::Other, Legal);
398 setTargetDAGCombine(ISD::SDIVREM);
399 setTargetDAGCombine(ISD::UDIVREM);
400 setTargetDAGCombine(ISD::SELECT);
401 setTargetDAGCombine(ISD::AND);
402 setTargetDAGCombine(ISD::OR);
403 setTargetDAGCombine(ISD::ADD);
405 setMinFunctionAlignment(HasMips64 ? 3 : 2);
407 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
409 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
410 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
412 MaxStoresPerMemcpy = 16;
415 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
416 if (TM.getSubtargetImpl()->inMips16Mode())
417 return llvm::createMips16TargetLowering(TM);
419 return llvm::createMipsSETargetLowering(TM);
422 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
425 return VT.changeVectorElementTypeToInteger();
428 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
429 TargetLowering::DAGCombinerInfo &DCI,
430 const MipsSubtarget *Subtarget) {
431 if (DCI.isBeforeLegalizeOps())
434 EVT Ty = N->getValueType(0);
435 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
436 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
437 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
441 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
442 N->getOperand(0), N->getOperand(1));
443 SDValue InChain = DAG.getEntryNode();
444 SDValue InGlue = DivRem;
447 if (N->hasAnyUseOfValue(0)) {
448 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
451 InChain = CopyFromLo.getValue(1);
452 InGlue = CopyFromLo.getValue(2);
456 if (N->hasAnyUseOfValue(1)) {
457 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
465 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
467 default: llvm_unreachable("Unknown fp condition code!");
469 case ISD::SETOEQ: return Mips::FCOND_OEQ;
470 case ISD::SETUNE: return Mips::FCOND_UNE;
472 case ISD::SETOLT: return Mips::FCOND_OLT;
474 case ISD::SETOGT: return Mips::FCOND_OGT;
476 case ISD::SETOLE: return Mips::FCOND_OLE;
478 case ISD::SETOGE: return Mips::FCOND_OGE;
479 case ISD::SETULT: return Mips::FCOND_ULT;
480 case ISD::SETULE: return Mips::FCOND_ULE;
481 case ISD::SETUGT: return Mips::FCOND_UGT;
482 case ISD::SETUGE: return Mips::FCOND_UGE;
483 case ISD::SETUO: return Mips::FCOND_UN;
484 case ISD::SETO: return Mips::FCOND_OR;
486 case ISD::SETONE: return Mips::FCOND_ONE;
487 case ISD::SETUEQ: return Mips::FCOND_UEQ;
492 /// This function returns true if the floating point conditional branches and
493 /// conditional moves which use condition code CC should be inverted.
494 static bool invertFPCondCodeUser(Mips::CondCode CC) {
495 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
498 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
499 "Illegal Condition Code");
504 // Creates and returns an FPCmp node from a setcc node.
505 // Returns Op if setcc is not a floating point comparison.
506 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
507 // must be a SETCC node
508 if (Op.getOpcode() != ISD::SETCC)
511 SDValue LHS = Op.getOperand(0);
513 if (!LHS.getValueType().isFloatingPoint())
516 SDValue RHS = Op.getOperand(1);
519 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
520 // node if necessary.
521 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
523 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
524 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
527 // Creates and returns a CMovFPT/F node.
528 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
529 SDValue False, SDLoc DL) {
530 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
531 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
532 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
534 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
535 True.getValueType(), True, FCC0, False, Cond);
538 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
539 TargetLowering::DAGCombinerInfo &DCI,
540 const MipsSubtarget *Subtarget) {
541 if (DCI.isBeforeLegalizeOps())
544 SDValue SetCC = N->getOperand(0);
546 if ((SetCC.getOpcode() != ISD::SETCC) ||
547 !SetCC.getOperand(0).getValueType().isInteger())
550 SDValue False = N->getOperand(2);
551 EVT FalseTy = False.getValueType();
553 if (!FalseTy.isInteger())
556 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
558 if (!CN || CN->getZExtValue())
562 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
563 SDValue True = N->getOperand(1);
565 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
566 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
568 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
571 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
572 TargetLowering::DAGCombinerInfo &DCI,
573 const MipsSubtarget *Subtarget) {
574 // Pattern match EXT.
575 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
576 // => ext $dst, $src, size, pos
577 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
580 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
581 unsigned ShiftRightOpc = ShiftRight.getOpcode();
583 // Op's first operand must be a shift right.
584 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
587 // The second operand of the shift must be an immediate.
589 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
592 uint64_t Pos = CN->getZExtValue();
593 uint64_t SMPos, SMSize;
595 // Op's second operand must be a shifted mask.
596 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
597 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
600 // Return if the shifted mask does not start at bit 0 or the sum of its size
601 // and Pos exceeds the word's size.
602 EVT ValTy = N->getValueType(0);
603 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
606 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
607 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
608 DAG.getConstant(SMSize, MVT::i32));
611 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
612 TargetLowering::DAGCombinerInfo &DCI,
613 const MipsSubtarget *Subtarget) {
614 // Pattern match INS.
615 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
616 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
617 // => ins $dst, $src, size, pos, $src1
618 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
621 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
622 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
625 // See if Op's first operand matches (and $src1 , mask0).
626 if (And0.getOpcode() != ISD::AND)
629 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
630 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
633 // See if Op's second operand matches (and (shl $src, pos), mask1).
634 if (And1.getOpcode() != ISD::AND)
637 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
638 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
641 // The shift masks must have the same position and size.
642 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
645 SDValue Shl = And1.getOperand(0);
646 if (Shl.getOpcode() != ISD::SHL)
649 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
652 unsigned Shamt = CN->getZExtValue();
654 // Return if the shift amount and the first bit position of mask are not the
656 EVT ValTy = N->getValueType(0);
657 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
660 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
661 DAG.getConstant(SMPos0, MVT::i32),
662 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
665 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
666 TargetLowering::DAGCombinerInfo &DCI,
667 const MipsSubtarget *Subtarget) {
668 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
670 if (DCI.isBeforeLegalizeOps())
673 SDValue Add = N->getOperand(1);
675 if (Add.getOpcode() != ISD::ADD)
678 SDValue Lo = Add.getOperand(1);
680 if ((Lo.getOpcode() != MipsISD::Lo) ||
681 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
684 EVT ValTy = N->getValueType(0);
687 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
689 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
692 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
694 SelectionDAG &DAG = DCI.DAG;
695 unsigned Opc = N->getOpcode();
701 return performDivRemCombine(N, DAG, DCI, Subtarget);
703 return performSELECTCombine(N, DAG, DCI, Subtarget);
705 return performANDCombine(N, DAG, DCI, Subtarget);
707 return performORCombine(N, DAG, DCI, Subtarget);
709 return performADDCombine(N, DAG, DCI, Subtarget);
716 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
717 SmallVectorImpl<SDValue> &Results,
718 SelectionDAG &DAG) const {
719 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
721 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
722 Results.push_back(Res.getValue(I));
726 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
727 SmallVectorImpl<SDValue> &Results,
728 SelectionDAG &DAG) const {
729 return LowerOperationWrapper(N, Results, DAG);
732 SDValue MipsTargetLowering::
733 LowerOperation(SDValue Op, SelectionDAG &DAG) const
735 switch (Op.getOpcode())
737 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
738 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
739 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
740 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
741 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
742 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
743 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
744 case ISD::SELECT: return lowerSELECT(Op, DAG);
745 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
746 case ISD::SETCC: return lowerSETCC(Op, DAG);
747 case ISD::VASTART: return lowerVASTART(Op, DAG);
748 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
749 case ISD::FABS: return lowerFABS(Op, DAG);
750 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
751 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
752 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
753 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
754 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
755 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
756 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
757 case ISD::LOAD: return lowerLOAD(Op, DAG);
758 case ISD::STORE: return lowerSTORE(Op, DAG);
759 case ISD::ADD: return lowerADD(Op, DAG);
760 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
765 //===----------------------------------------------------------------------===//
766 // Lower helper functions
767 //===----------------------------------------------------------------------===//
769 // addLiveIn - This helper function adds the specified physical register to the
770 // MachineFunction as a live in value. It also creates a corresponding
771 // virtual register for it.
773 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
775 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
776 MF.getRegInfo().addLiveIn(PReg, VReg);
780 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
781 MachineBasicBlock &MBB,
782 const TargetInstrInfo &TII,
787 // Insert instruction "teq $divisor_reg, $zero, 7".
788 MachineBasicBlock::iterator I(MI);
789 MachineInstrBuilder MIB;
790 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
791 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
793 // Use the 32-bit sub-register if this is a 64-bit division.
795 MIB->getOperand(0).setSubReg(Mips::sub_32);
801 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
802 MachineBasicBlock *BB) const {
803 switch (MI->getOpcode()) {
805 llvm_unreachable("Unexpected instr type to insert");
806 case Mips::ATOMIC_LOAD_ADD_I8:
807 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
808 case Mips::ATOMIC_LOAD_ADD_I16:
809 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
810 case Mips::ATOMIC_LOAD_ADD_I32:
811 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
812 case Mips::ATOMIC_LOAD_ADD_I64:
813 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
815 case Mips::ATOMIC_LOAD_AND_I8:
816 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
817 case Mips::ATOMIC_LOAD_AND_I16:
818 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
819 case Mips::ATOMIC_LOAD_AND_I32:
820 return emitAtomicBinary(MI, BB, 4, Mips::AND);
821 case Mips::ATOMIC_LOAD_AND_I64:
822 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
824 case Mips::ATOMIC_LOAD_OR_I8:
825 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
826 case Mips::ATOMIC_LOAD_OR_I16:
827 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
828 case Mips::ATOMIC_LOAD_OR_I32:
829 return emitAtomicBinary(MI, BB, 4, Mips::OR);
830 case Mips::ATOMIC_LOAD_OR_I64:
831 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
833 case Mips::ATOMIC_LOAD_XOR_I8:
834 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
835 case Mips::ATOMIC_LOAD_XOR_I16:
836 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
837 case Mips::ATOMIC_LOAD_XOR_I32:
838 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
839 case Mips::ATOMIC_LOAD_XOR_I64:
840 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
842 case Mips::ATOMIC_LOAD_NAND_I8:
843 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
844 case Mips::ATOMIC_LOAD_NAND_I16:
845 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
846 case Mips::ATOMIC_LOAD_NAND_I32:
847 return emitAtomicBinary(MI, BB, 4, 0, true);
848 case Mips::ATOMIC_LOAD_NAND_I64:
849 return emitAtomicBinary(MI, BB, 8, 0, true);
851 case Mips::ATOMIC_LOAD_SUB_I8:
852 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
853 case Mips::ATOMIC_LOAD_SUB_I16:
854 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
855 case Mips::ATOMIC_LOAD_SUB_I32:
856 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
857 case Mips::ATOMIC_LOAD_SUB_I64:
858 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
860 case Mips::ATOMIC_SWAP_I8:
861 return emitAtomicBinaryPartword(MI, BB, 1, 0);
862 case Mips::ATOMIC_SWAP_I16:
863 return emitAtomicBinaryPartword(MI, BB, 2, 0);
864 case Mips::ATOMIC_SWAP_I32:
865 return emitAtomicBinary(MI, BB, 4, 0);
866 case Mips::ATOMIC_SWAP_I64:
867 return emitAtomicBinary(MI, BB, 8, 0);
869 case Mips::ATOMIC_CMP_SWAP_I8:
870 return emitAtomicCmpSwapPartword(MI, BB, 1);
871 case Mips::ATOMIC_CMP_SWAP_I16:
872 return emitAtomicCmpSwapPartword(MI, BB, 2);
873 case Mips::ATOMIC_CMP_SWAP_I32:
874 return emitAtomicCmpSwap(MI, BB, 4);
875 case Mips::ATOMIC_CMP_SWAP_I64:
876 return emitAtomicCmpSwap(MI, BB, 8);
877 case Mips::PseudoSDIV:
878 case Mips::PseudoUDIV:
879 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
880 case Mips::PseudoDSDIV:
881 case Mips::PseudoDUDIV:
882 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
886 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
887 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
889 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
890 unsigned Size, unsigned BinOpcode,
892 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
894 MachineFunction *MF = BB->getParent();
895 MachineRegisterInfo &RegInfo = MF->getRegInfo();
896 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
897 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
898 DebugLoc DL = MI->getDebugLoc();
899 unsigned LL, SC, AND, NOR, ZERO, BEQ;
914 ZERO = Mips::ZERO_64;
918 unsigned OldVal = MI->getOperand(0).getReg();
919 unsigned Ptr = MI->getOperand(1).getReg();
920 unsigned Incr = MI->getOperand(2).getReg();
922 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
923 unsigned AndRes = RegInfo.createVirtualRegister(RC);
924 unsigned Success = RegInfo.createVirtualRegister(RC);
926 // insert new blocks after the current block
927 const BasicBlock *LLVM_BB = BB->getBasicBlock();
928 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
929 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
930 MachineFunction::iterator It = BB;
932 MF->insert(It, loopMBB);
933 MF->insert(It, exitMBB);
935 // Transfer the remainder of BB and its successor edges to exitMBB.
936 exitMBB->splice(exitMBB->begin(), BB,
937 llvm::next(MachineBasicBlock::iterator(MI)),
939 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
943 // fallthrough --> loopMBB
944 BB->addSuccessor(loopMBB);
945 loopMBB->addSuccessor(loopMBB);
946 loopMBB->addSuccessor(exitMBB);
950 // <binop> storeval, oldval, incr
951 // sc success, storeval, 0(ptr)
952 // beq success, $0, loopMBB
954 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
956 // and andres, oldval, incr
957 // nor storeval, $0, andres
958 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
959 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
960 } else if (BinOpcode) {
961 // <binop> storeval, oldval, incr
962 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
966 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
967 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
969 MI->eraseFromParent(); // The instruction is gone now.
975 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
976 MachineBasicBlock *BB,
977 unsigned Size, unsigned BinOpcode,
979 assert((Size == 1 || Size == 2) &&
980 "Unsupported size for EmitAtomicBinaryPartial.");
982 MachineFunction *MF = BB->getParent();
983 MachineRegisterInfo &RegInfo = MF->getRegInfo();
984 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
985 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
986 DebugLoc DL = MI->getDebugLoc();
988 unsigned Dest = MI->getOperand(0).getReg();
989 unsigned Ptr = MI->getOperand(1).getReg();
990 unsigned Incr = MI->getOperand(2).getReg();
992 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
993 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
994 unsigned Mask = RegInfo.createVirtualRegister(RC);
995 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
996 unsigned NewVal = RegInfo.createVirtualRegister(RC);
997 unsigned OldVal = RegInfo.createVirtualRegister(RC);
998 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
999 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1000 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1001 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1002 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1003 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1004 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1005 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1006 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1007 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1008 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1009 unsigned Success = RegInfo.createVirtualRegister(RC);
1011 // insert new blocks after the current block
1012 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1013 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1014 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1015 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1016 MachineFunction::iterator It = BB;
1018 MF->insert(It, loopMBB);
1019 MF->insert(It, sinkMBB);
1020 MF->insert(It, exitMBB);
1022 // Transfer the remainder of BB and its successor edges to exitMBB.
1023 exitMBB->splice(exitMBB->begin(), BB,
1024 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1025 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1027 BB->addSuccessor(loopMBB);
1028 loopMBB->addSuccessor(loopMBB);
1029 loopMBB->addSuccessor(sinkMBB);
1030 sinkMBB->addSuccessor(exitMBB);
1033 // addiu masklsb2,$0,-4 # 0xfffffffc
1034 // and alignedaddr,ptr,masklsb2
1035 // andi ptrlsb2,ptr,3
1036 // sll shiftamt,ptrlsb2,3
1037 // ori maskupper,$0,255 # 0xff
1038 // sll mask,maskupper,shiftamt
1039 // nor mask2,$0,mask
1040 // sll incr2,incr,shiftamt
1042 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1043 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1044 .addReg(Mips::ZERO).addImm(-4);
1045 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1046 .addReg(Ptr).addReg(MaskLSB2);
1047 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1048 if (Subtarget->isLittle()) {
1049 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1051 unsigned Off = RegInfo.createVirtualRegister(RC);
1052 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1053 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1054 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1056 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1057 .addReg(Mips::ZERO).addImm(MaskImm);
1058 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1059 .addReg(MaskUpper).addReg(ShiftAmt);
1060 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1061 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1063 // atomic.load.binop
1065 // ll oldval,0(alignedaddr)
1066 // binop binopres,oldval,incr2
1067 // and newval,binopres,mask
1068 // and maskedoldval0,oldval,mask2
1069 // or storeval,maskedoldval0,newval
1070 // sc success,storeval,0(alignedaddr)
1071 // beq success,$0,loopMBB
1075 // ll oldval,0(alignedaddr)
1076 // and newval,incr2,mask
1077 // and maskedoldval0,oldval,mask2
1078 // or storeval,maskedoldval0,newval
1079 // sc success,storeval,0(alignedaddr)
1080 // beq success,$0,loopMBB
1083 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1085 // and andres, oldval, incr2
1086 // nor binopres, $0, andres
1087 // and newval, binopres, mask
1088 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1089 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1090 .addReg(Mips::ZERO).addReg(AndRes);
1091 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1092 } else if (BinOpcode) {
1093 // <binop> binopres, oldval, incr2
1094 // and newval, binopres, mask
1095 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1096 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1097 } else {// atomic.swap
1098 // and newval, incr2, mask
1099 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1102 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1103 .addReg(OldVal).addReg(Mask2);
1104 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1105 .addReg(MaskedOldVal0).addReg(NewVal);
1106 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1107 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1108 BuildMI(BB, DL, TII->get(Mips::BEQ))
1109 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1112 // and maskedoldval1,oldval,mask
1113 // srl srlres,maskedoldval1,shiftamt
1114 // sll sllres,srlres,24
1115 // sra dest,sllres,24
1117 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1119 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1120 .addReg(OldVal).addReg(Mask);
1121 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1122 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1123 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1124 .addReg(SrlRes).addImm(ShiftImm);
1125 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1126 .addReg(SllRes).addImm(ShiftImm);
1128 MI->eraseFromParent(); // The instruction is gone now.
1134 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1135 MachineBasicBlock *BB,
1136 unsigned Size) const {
1137 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1139 MachineFunction *MF = BB->getParent();
1140 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1141 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1142 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1143 DebugLoc DL = MI->getDebugLoc();
1144 unsigned LL, SC, ZERO, BNE, BEQ;
1156 ZERO = Mips::ZERO_64;
1161 unsigned Dest = MI->getOperand(0).getReg();
1162 unsigned Ptr = MI->getOperand(1).getReg();
1163 unsigned OldVal = MI->getOperand(2).getReg();
1164 unsigned NewVal = MI->getOperand(3).getReg();
1166 unsigned Success = RegInfo.createVirtualRegister(RC);
1168 // insert new blocks after the current block
1169 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1170 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1171 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1172 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1173 MachineFunction::iterator It = BB;
1175 MF->insert(It, loop1MBB);
1176 MF->insert(It, loop2MBB);
1177 MF->insert(It, exitMBB);
1179 // Transfer the remainder of BB and its successor edges to exitMBB.
1180 exitMBB->splice(exitMBB->begin(), BB,
1181 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1182 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1186 // fallthrough --> loop1MBB
1187 BB->addSuccessor(loop1MBB);
1188 loop1MBB->addSuccessor(exitMBB);
1189 loop1MBB->addSuccessor(loop2MBB);
1190 loop2MBB->addSuccessor(loop1MBB);
1191 loop2MBB->addSuccessor(exitMBB);
1195 // bne dest, oldval, exitMBB
1197 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1198 BuildMI(BB, DL, TII->get(BNE))
1199 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1202 // sc success, newval, 0(ptr)
1203 // beq success, $0, loop1MBB
1205 BuildMI(BB, DL, TII->get(SC), Success)
1206 .addReg(NewVal).addReg(Ptr).addImm(0);
1207 BuildMI(BB, DL, TII->get(BEQ))
1208 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1210 MI->eraseFromParent(); // The instruction is gone now.
1216 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1217 MachineBasicBlock *BB,
1218 unsigned Size) const {
1219 assert((Size == 1 || Size == 2) &&
1220 "Unsupported size for EmitAtomicCmpSwapPartial.");
1222 MachineFunction *MF = BB->getParent();
1223 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1224 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1225 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1226 DebugLoc DL = MI->getDebugLoc();
1228 unsigned Dest = MI->getOperand(0).getReg();
1229 unsigned Ptr = MI->getOperand(1).getReg();
1230 unsigned CmpVal = MI->getOperand(2).getReg();
1231 unsigned NewVal = MI->getOperand(3).getReg();
1233 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1234 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1235 unsigned Mask = RegInfo.createVirtualRegister(RC);
1236 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1237 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1238 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1239 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1240 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1241 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1242 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1243 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1244 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1245 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1246 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1247 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1248 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1249 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1250 unsigned Success = RegInfo.createVirtualRegister(RC);
1252 // insert new blocks after the current block
1253 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1254 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1255 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1256 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1257 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1258 MachineFunction::iterator It = BB;
1260 MF->insert(It, loop1MBB);
1261 MF->insert(It, loop2MBB);
1262 MF->insert(It, sinkMBB);
1263 MF->insert(It, exitMBB);
1265 // Transfer the remainder of BB and its successor edges to exitMBB.
1266 exitMBB->splice(exitMBB->begin(), BB,
1267 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1268 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1270 BB->addSuccessor(loop1MBB);
1271 loop1MBB->addSuccessor(sinkMBB);
1272 loop1MBB->addSuccessor(loop2MBB);
1273 loop2MBB->addSuccessor(loop1MBB);
1274 loop2MBB->addSuccessor(sinkMBB);
1275 sinkMBB->addSuccessor(exitMBB);
1277 // FIXME: computation of newval2 can be moved to loop2MBB.
1279 // addiu masklsb2,$0,-4 # 0xfffffffc
1280 // and alignedaddr,ptr,masklsb2
1281 // andi ptrlsb2,ptr,3
1282 // sll shiftamt,ptrlsb2,3
1283 // ori maskupper,$0,255 # 0xff
1284 // sll mask,maskupper,shiftamt
1285 // nor mask2,$0,mask
1286 // andi maskedcmpval,cmpval,255
1287 // sll shiftedcmpval,maskedcmpval,shiftamt
1288 // andi maskednewval,newval,255
1289 // sll shiftednewval,maskednewval,shiftamt
1290 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1291 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1292 .addReg(Mips::ZERO).addImm(-4);
1293 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1294 .addReg(Ptr).addReg(MaskLSB2);
1295 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1296 if (Subtarget->isLittle()) {
1297 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1299 unsigned Off = RegInfo.createVirtualRegister(RC);
1300 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1301 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1302 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1304 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1305 .addReg(Mips::ZERO).addImm(MaskImm);
1306 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1307 .addReg(MaskUpper).addReg(ShiftAmt);
1308 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1309 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1310 .addReg(CmpVal).addImm(MaskImm);
1311 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1312 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1313 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1314 .addReg(NewVal).addImm(MaskImm);
1315 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1316 .addReg(MaskedNewVal).addReg(ShiftAmt);
1319 // ll oldval,0(alginedaddr)
1320 // and maskedoldval0,oldval,mask
1321 // bne maskedoldval0,shiftedcmpval,sinkMBB
1323 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1324 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1325 .addReg(OldVal).addReg(Mask);
1326 BuildMI(BB, DL, TII->get(Mips::BNE))
1327 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1330 // and maskedoldval1,oldval,mask2
1331 // or storeval,maskedoldval1,shiftednewval
1332 // sc success,storeval,0(alignedaddr)
1333 // beq success,$0,loop1MBB
1335 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1336 .addReg(OldVal).addReg(Mask2);
1337 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1338 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1339 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1340 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1341 BuildMI(BB, DL, TII->get(Mips::BEQ))
1342 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1345 // srl srlres,maskedoldval0,shiftamt
1346 // sll sllres,srlres,24
1347 // sra dest,sllres,24
1349 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1351 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1352 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1353 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1354 .addReg(SrlRes).addImm(ShiftImm);
1355 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1356 .addReg(SllRes).addImm(ShiftImm);
1358 MI->eraseFromParent(); // The instruction is gone now.
1363 //===----------------------------------------------------------------------===//
1364 // Misc Lower Operation implementation
1365 //===----------------------------------------------------------------------===//
1366 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1367 SDValue Chain = Op.getOperand(0);
1368 SDValue Table = Op.getOperand(1);
1369 SDValue Index = Op.getOperand(2);
1371 EVT PTy = getPointerTy();
1372 unsigned EntrySize =
1373 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1375 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1376 DAG.getConstant(EntrySize, PTy));
1377 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1379 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1380 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1381 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1383 Chain = Addr.getValue(1);
1385 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1386 // For PIC, the sequence is:
1387 // BRIND(load(Jumptable + index) + RelocBase)
1388 // RelocBase can be JumpTable, GOT or some sort of global base.
1389 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1390 getPICJumpTableRelocBase(Table, DAG));
1393 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1396 SDValue MipsTargetLowering::
1397 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1399 // The first operand is the chain, the second is the condition, the third is
1400 // the block to branch to if the condition is true.
1401 SDValue Chain = Op.getOperand(0);
1402 SDValue Dest = Op.getOperand(2);
1405 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1407 // Return if flag is not set by a floating point comparison.
1408 if (CondRes.getOpcode() != MipsISD::FPCmp)
1411 SDValue CCNode = CondRes.getOperand(2);
1413 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1414 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1415 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1416 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1417 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1418 FCC0, Dest, CondRes);
1421 SDValue MipsTargetLowering::
1422 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1424 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1426 // Return if flag is not set by a floating point comparison.
1427 if (Cond.getOpcode() != MipsISD::FPCmp)
1430 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1434 SDValue MipsTargetLowering::
1435 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1438 EVT Ty = Op.getOperand(0).getValueType();
1439 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1440 getSetCCResultType(*DAG.getContext(), Ty),
1441 Op.getOperand(0), Op.getOperand(1),
1444 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1448 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1449 SDValue Cond = createFPCmp(DAG, Op);
1451 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1452 "Floating point operand expected.");
1454 SDValue True = DAG.getConstant(1, MVT::i32);
1455 SDValue False = DAG.getConstant(0, MVT::i32);
1457 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1460 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1461 SelectionDAG &DAG) const {
1462 // FIXME there isn't actually debug info here
1464 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1466 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1467 const MipsTargetObjectFile &TLOF =
1468 (const MipsTargetObjectFile&)getObjFileLowering();
1470 // %gp_rel relocation
1471 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1472 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1474 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1475 DAG.getVTList(MVT::i32), &GA, 1);
1476 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1477 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1480 // %hi/%lo relocation
1481 return getAddrNonPIC(Op, DAG);
1484 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1485 return getAddrLocal(Op, DAG, HasMips64);
1488 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1489 MipsII::MO_GOT_LO16);
1491 return getAddrGlobal(Op, DAG,
1492 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1495 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1496 SelectionDAG &DAG) const {
1497 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1498 return getAddrNonPIC(Op, DAG);
1500 return getAddrLocal(Op, DAG, HasMips64);
1503 SDValue MipsTargetLowering::
1504 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1506 // If the relocation model is PIC, use the General Dynamic TLS Model or
1507 // Local Dynamic TLS model, otherwise use the Initial Exec or
1508 // Local Exec TLS Model.
1510 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1512 const GlobalValue *GV = GA->getGlobal();
1513 EVT PtrVT = getPointerTy();
1515 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1517 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1518 // General Dynamic and Local Dynamic TLS Model.
1519 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1522 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1523 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1524 getGlobalReg(DAG, PtrVT), TGA);
1525 unsigned PtrSize = PtrVT.getSizeInBits();
1526 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1528 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1532 Entry.Node = Argument;
1534 Args.push_back(Entry);
1536 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1537 false, false, false, false, 0, CallingConv::C,
1538 /*IsTailCall=*/false, /*doesNotRet=*/false,
1539 /*isReturnValueUsed=*/true,
1540 TlsGetAddr, Args, DAG, DL);
1541 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1543 SDValue Ret = CallResult.first;
1545 if (model != TLSModel::LocalDynamic)
1548 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1549 MipsII::MO_DTPREL_HI);
1550 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1551 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1552 MipsII::MO_DTPREL_LO);
1553 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1554 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1555 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1559 if (model == TLSModel::InitialExec) {
1560 // Initial Exec TLS Model
1561 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1562 MipsII::MO_GOTTPREL);
1563 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1565 Offset = DAG.getLoad(PtrVT, DL,
1566 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1567 false, false, false, 0);
1569 // Local Exec TLS Model
1570 assert(model == TLSModel::LocalExec);
1571 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1572 MipsII::MO_TPREL_HI);
1573 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1574 MipsII::MO_TPREL_LO);
1575 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1576 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1577 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1580 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1581 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1584 SDValue MipsTargetLowering::
1585 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1587 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1588 return getAddrNonPIC(Op, DAG);
1590 return getAddrLocal(Op, DAG, HasMips64);
1593 SDValue MipsTargetLowering::
1594 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1596 // gp_rel relocation
1597 // FIXME: we should reference the constant pool using small data sections,
1598 // but the asm printer currently doesn't support this feature without
1599 // hacking it. This feature should come soon so we can uncomment the
1601 //if (IsInSmallSection(C->getType())) {
1602 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1603 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1604 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1606 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1607 return getAddrNonPIC(Op, DAG);
1609 return getAddrLocal(Op, DAG, HasMips64);
1612 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1613 MachineFunction &MF = DAG.getMachineFunction();
1614 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1617 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1620 // vastart just stores the address of the VarArgsFrameIndex slot into the
1621 // memory location argument.
1622 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1623 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1624 MachinePointerInfo(SV), false, false, 0);
1627 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1628 EVT TyX = Op.getOperand(0).getValueType();
1629 EVT TyY = Op.getOperand(1).getValueType();
1630 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1631 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1635 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1637 SDValue X = (TyX == MVT::f32) ?
1638 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1639 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1641 SDValue Y = (TyY == MVT::f32) ?
1642 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1643 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1647 // ext E, Y, 31, 1 ; extract bit31 of Y
1648 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1649 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1650 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1653 // srl SrlX, SllX, 1
1655 // sll SllY, SrlX, 31
1656 // or Or, SrlX, SllY
1657 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1658 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1659 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1660 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1661 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1664 if (TyX == MVT::f32)
1665 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1667 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1668 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1669 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1672 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1673 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1674 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1675 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1676 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1679 // Bitcast to integer nodes.
1680 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1681 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1684 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1685 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1686 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1687 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1689 if (WidthX > WidthY)
1690 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1691 else if (WidthY > WidthX)
1692 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1694 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1695 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1696 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1699 // (d)sll SllX, X, 1
1700 // (d)srl SrlX, SllX, 1
1701 // (d)srl SrlY, Y, width(Y)-1
1702 // (d)sll SllY, SrlX, width(Y)-1
1703 // or Or, SrlX, SllY
1704 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1705 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1706 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1707 DAG.getConstant(WidthY - 1, MVT::i32));
1709 if (WidthX > WidthY)
1710 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1711 else if (WidthY > WidthX)
1712 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1714 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1715 DAG.getConstant(WidthX - 1, MVT::i32));
1716 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1717 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1721 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1722 if (Subtarget->hasMips64())
1723 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1725 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1728 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1729 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1732 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1734 SDValue X = (Op.getValueType() == MVT::f32) ?
1735 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1736 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1741 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1742 DAG.getRegister(Mips::ZERO, MVT::i32),
1743 DAG.getConstant(31, MVT::i32), Const1, X);
1745 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1746 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1749 if (Op.getValueType() == MVT::f32)
1750 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1752 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1753 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1754 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1757 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1758 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1761 // Bitcast to integer node.
1762 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1766 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1767 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1768 DAG.getConstant(63, MVT::i32), Const1, X);
1770 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1771 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1774 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1778 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1779 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1780 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1782 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1785 SDValue MipsTargetLowering::
1786 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1788 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1789 "Frame address can only be determined for current frame.");
1791 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1792 MFI->setFrameAddressIsTaken(true);
1793 EVT VT = Op.getValueType();
1795 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1796 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1800 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1801 SelectionDAG &DAG) const {
1803 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1804 "Return address can be determined only for current frame.");
1806 MachineFunction &MF = DAG.getMachineFunction();
1807 MachineFrameInfo *MFI = MF.getFrameInfo();
1808 MVT VT = Op.getSimpleValueType();
1809 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1810 MFI->setReturnAddressIsTaken(true);
1812 // Return RA, which contains the return address. Mark it an implicit live-in.
1813 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1814 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1817 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1818 // generated from __builtin_eh_return (offset, handler)
1819 // The effect of this is to adjust the stack pointer by "offset"
1820 // and then branch to "handler".
1821 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1823 MachineFunction &MF = DAG.getMachineFunction();
1824 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1826 MipsFI->setCallsEhReturn();
1827 SDValue Chain = Op.getOperand(0);
1828 SDValue Offset = Op.getOperand(1);
1829 SDValue Handler = Op.getOperand(2);
1831 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1833 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1834 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1835 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1836 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1837 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1838 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1839 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1840 DAG.getRegister(OffsetReg, Ty),
1841 DAG.getRegister(AddrReg, getPointerTy()),
1845 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1846 SelectionDAG &DAG) const {
1847 // FIXME: Need pseudo-fence for 'singlethread' fences
1848 // FIXME: Set SType for weaker fences where supported/appropriate.
1851 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1852 DAG.getConstant(SType, MVT::i32));
1855 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1856 SelectionDAG &DAG) const {
1858 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1859 SDValue Shamt = Op.getOperand(2);
1862 // lo = (shl lo, shamt)
1863 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1866 // hi = (shl lo, shamt[4:0])
1867 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1868 DAG.getConstant(-1, MVT::i32));
1869 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1870 DAG.getConstant(1, MVT::i32));
1871 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1873 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1874 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1875 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1876 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1877 DAG.getConstant(0x20, MVT::i32));
1878 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1879 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1880 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1882 SDValue Ops[2] = {Lo, Hi};
1883 return DAG.getMergeValues(Ops, 2, DL);
1886 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1889 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1890 SDValue Shamt = Op.getOperand(2);
1893 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1895 // hi = (sra hi, shamt)
1897 // hi = (srl hi, shamt)
1900 // lo = (sra hi, shamt[4:0])
1901 // hi = (sra hi, 31)
1903 // lo = (srl hi, shamt[4:0])
1905 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1906 DAG.getConstant(-1, MVT::i32));
1907 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1908 DAG.getConstant(1, MVT::i32));
1909 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1910 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1911 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1912 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1914 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1915 DAG.getConstant(0x20, MVT::i32));
1916 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1917 DAG.getConstant(31, MVT::i32));
1918 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1919 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1920 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1923 SDValue Ops[2] = {Lo, Hi};
1924 return DAG.getMergeValues(Ops, 2, DL);
1927 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1928 SDValue Chain, SDValue Src, unsigned Offset) {
1929 SDValue Ptr = LD->getBasePtr();
1930 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1931 EVT BasePtrVT = Ptr.getValueType();
1933 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1936 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1937 DAG.getConstant(Offset, BasePtrVT));
1939 SDValue Ops[] = { Chain, Ptr, Src };
1940 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1941 LD->getMemOperand());
1944 // Expand an unaligned 32 or 64-bit integer load node.
1945 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1946 LoadSDNode *LD = cast<LoadSDNode>(Op);
1947 EVT MemVT = LD->getMemoryVT();
1949 // Return if load is aligned or if MemVT is neither i32 nor i64.
1950 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1951 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1954 bool IsLittle = Subtarget->isLittle();
1955 EVT VT = Op.getValueType();
1956 ISD::LoadExtType ExtType = LD->getExtensionType();
1957 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1959 assert((VT == MVT::i32) || (VT == MVT::i64));
1962 // (set dst, (i64 (load baseptr)))
1964 // (set tmp, (ldl (add baseptr, 7), undef))
1965 // (set dst, (ldr baseptr, tmp))
1966 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1967 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1969 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1973 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1975 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1979 // (set dst, (i32 (load baseptr))) or
1980 // (set dst, (i64 (sextload baseptr))) or
1981 // (set dst, (i64 (extload baseptr)))
1983 // (set tmp, (lwl (add baseptr, 3), undef))
1984 // (set dst, (lwr baseptr, tmp))
1985 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1986 (ExtType == ISD::EXTLOAD))
1989 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1992 // (set dst, (i64 (zextload baseptr)))
1994 // (set tmp0, (lwl (add baseptr, 3), undef))
1995 // (set tmp1, (lwr baseptr, tmp0))
1996 // (set tmp2, (shl tmp1, 32))
1997 // (set dst, (srl tmp2, 32))
1999 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2000 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2001 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2002 SDValue Ops[] = { SRL, LWR.getValue(1) };
2003 return DAG.getMergeValues(Ops, 2, DL);
2006 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2007 SDValue Chain, unsigned Offset) {
2008 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2009 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2011 SDVTList VTList = DAG.getVTList(MVT::Other);
2014 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2015 DAG.getConstant(Offset, BasePtrVT));
2017 SDValue Ops[] = { Chain, Value, Ptr };
2018 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2019 SD->getMemOperand());
2022 // Expand an unaligned 32 or 64-bit integer store node.
2023 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2025 SDValue Value = SD->getValue(), Chain = SD->getChain();
2026 EVT VT = Value.getValueType();
2029 // (store val, baseptr) or
2030 // (truncstore val, baseptr)
2032 // (swl val, (add baseptr, 3))
2033 // (swr val, baseptr)
2034 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2035 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2037 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2040 assert(VT == MVT::i64);
2043 // (store val, baseptr)
2045 // (sdl val, (add baseptr, 7))
2046 // (sdr val, baseptr)
2047 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2048 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2051 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2052 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2053 SDValue Val = SD->getValue();
2055 if (Val.getOpcode() != ISD::FP_TO_SINT)
2058 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2059 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2062 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2063 SD->getPointerInfo(), SD->isVolatile(),
2064 SD->isNonTemporal(), SD->getAlignment());
2067 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2068 StoreSDNode *SD = cast<StoreSDNode>(Op);
2069 EVT MemVT = SD->getMemoryVT();
2071 // Lower unaligned integer stores.
2072 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2073 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2074 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2076 return lowerFP_TO_SINT_STORE(SD, DAG);
2079 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2080 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2081 || cast<ConstantSDNode>
2082 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2083 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2087 // (add (frameaddr 0), (frame_to_args_offset))
2088 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2089 // (add FrameObject, 0)
2090 // where FrameObject is a fixed StackObject with offset 0 which points to
2091 // the old stack pointer.
2092 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2093 EVT ValTy = Op->getValueType(0);
2094 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2095 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2096 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2097 DAG.getConstant(0, ValTy));
2100 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2101 SelectionDAG &DAG) const {
2102 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2103 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2105 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2108 //===----------------------------------------------------------------------===//
2109 // Calling Convention Implementation
2110 //===----------------------------------------------------------------------===//
2112 //===----------------------------------------------------------------------===//
2113 // TODO: Implement a generic logic using tblgen that can support this.
2114 // Mips O32 ABI rules:
2116 // i32 - Passed in A0, A1, A2, A3 and stack
2117 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2118 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2119 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2120 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2121 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2124 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2125 //===----------------------------------------------------------------------===//
2127 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2128 MVT LocVT, CCValAssign::LocInfo LocInfo,
2129 ISD::ArgFlagsTy ArgFlags, CCState &State,
2130 const uint16_t *F64Regs) {
2132 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2134 static const uint16_t IntRegs[] = {
2135 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2137 static const uint16_t F32Regs[] = {
2138 Mips::F12, Mips::F14
2141 // Do not process byval args here.
2142 if (ArgFlags.isByVal())
2145 // Promote i8 and i16
2146 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2148 if (ArgFlags.isSExt())
2149 LocInfo = CCValAssign::SExt;
2150 else if (ArgFlags.isZExt())
2151 LocInfo = CCValAssign::ZExt;
2153 LocInfo = CCValAssign::AExt;
2158 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2159 // is true: function is vararg, argument is 3rd or higher, there is previous
2160 // argument which is not f32 or f64.
2161 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2162 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2163 unsigned OrigAlign = ArgFlags.getOrigAlign();
2164 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2166 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2167 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2168 // If this is the first part of an i64 arg,
2169 // the allocated register must be either A0 or A2.
2170 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2171 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2173 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2174 // Allocate int register and shadow next int register. If first
2175 // available register is Mips::A1 or Mips::A3, shadow it too.
2176 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2177 if (Reg == Mips::A1 || Reg == Mips::A3)
2178 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2179 State.AllocateReg(IntRegs, IntRegsSize);
2181 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2182 // we are guaranteed to find an available float register
2183 if (ValVT == MVT::f32) {
2184 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2185 // Shadow int register
2186 State.AllocateReg(IntRegs, IntRegsSize);
2188 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2189 // Shadow int registers
2190 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2191 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2192 State.AllocateReg(IntRegs, IntRegsSize);
2193 State.AllocateReg(IntRegs, IntRegsSize);
2196 llvm_unreachable("Cannot handle this ValVT.");
2199 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2201 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2203 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2208 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2209 MVT LocVT, CCValAssign::LocInfo LocInfo,
2210 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2211 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2213 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2216 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2217 MVT LocVT, CCValAssign::LocInfo LocInfo,
2218 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2219 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2221 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2224 #include "MipsGenCallingConv.inc"
2226 //===----------------------------------------------------------------------===//
2227 // Call Calling Convention Implementation
2228 //===----------------------------------------------------------------------===//
2230 // Return next O32 integer argument register.
2231 static unsigned getNextIntArgReg(unsigned Reg) {
2232 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2233 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2237 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2238 SDValue Chain, SDValue Arg, SDLoc DL,
2239 bool IsTailCall, SelectionDAG &DAG) const {
2241 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2242 DAG.getIntPtrConstant(Offset));
2243 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2247 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2248 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2249 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2250 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2251 /*isVolatile=*/ true, false, 0);
2254 void MipsTargetLowering::
2255 getOpndList(SmallVectorImpl<SDValue> &Ops,
2256 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2257 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2258 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2259 // Insert node "GP copy globalreg" before call to function.
2261 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2262 // in PIC mode) allow symbols to be resolved via lazy binding.
2263 // The lazy binding stub requires GP to point to the GOT.
2264 if (IsPICCall && !InternalLinkage) {
2265 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2266 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2267 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2270 // Build a sequence of copy-to-reg nodes chained together with token
2271 // chain and flag operands which copy the outgoing args into registers.
2272 // The InFlag in necessary since all emitted instructions must be
2276 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2277 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2278 RegsToPass[i].second, InFlag);
2279 InFlag = Chain.getValue(1);
2282 // Add argument registers to the end of the list so that they are
2283 // known live into the call.
2284 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2285 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2286 RegsToPass[i].second.getValueType()));
2288 // Add a register mask operand representing the call-preserved registers.
2289 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2290 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2291 assert(Mask && "Missing call preserved mask for calling convention");
2292 if (Subtarget->inMips16HardFloat()) {
2293 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2294 llvm::StringRef Sym = G->getGlobal()->getName();
2295 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2296 if (F->hasFnAttribute("__Mips16RetHelper")) {
2297 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2301 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2303 if (InFlag.getNode())
2304 Ops.push_back(InFlag);
2307 /// LowerCall - functions arguments are copied from virtual regs to
2308 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2310 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2311 SmallVectorImpl<SDValue> &InVals) const {
2312 SelectionDAG &DAG = CLI.DAG;
2314 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2315 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2316 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2317 SDValue Chain = CLI.Chain;
2318 SDValue Callee = CLI.Callee;
2319 bool &IsTailCall = CLI.IsTailCall;
2320 CallingConv::ID CallConv = CLI.CallConv;
2321 bool IsVarArg = CLI.IsVarArg;
2323 MachineFunction &MF = DAG.getMachineFunction();
2324 MachineFrameInfo *MFI = MF.getFrameInfo();
2325 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2326 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2328 // Analyze operands of the call, assigning locations to each operand.
2329 SmallVector<CCValAssign, 16> ArgLocs;
2330 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2331 getTargetMachine(), ArgLocs, *DAG.getContext());
2332 MipsCC::SpecialCallingConvType SpecialCallingConv =
2333 getSpecialCallingConv(Callee);
2334 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2335 SpecialCallingConv);
2337 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2338 Subtarget->mipsSEUsesSoftFloat(),
2339 Callee.getNode(), CLI.Args);
2341 // Get a count of how many bytes are to be pushed on the stack.
2342 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2344 // Check if it's really possible to do a tail call.
2347 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2348 *MF.getInfo<MipsFunctionInfo>());
2353 // Chain is the output chain of the last Load/Store or CopyToReg node.
2354 // ByValChain is the output chain of the last Memcpy node created for copying
2355 // byval arguments to the stack.
2356 unsigned StackAlignment = TFL->getStackAlignment();
2357 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2358 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2361 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2363 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2364 IsN64 ? Mips::SP_64 : Mips::SP,
2367 // With EABI is it possible to have 16 args on registers.
2368 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2369 SmallVector<SDValue, 8> MemOpChains;
2370 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2372 // Walk the register/memloc assignments, inserting copies/loads.
2373 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2374 SDValue Arg = OutVals[i];
2375 CCValAssign &VA = ArgLocs[i];
2376 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2377 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2380 if (Flags.isByVal()) {
2381 assert(Flags.getByValSize() &&
2382 "ByVal args of size 0 should have been ignored by front-end.");
2383 assert(ByValArg != MipsCCInfo.byval_end());
2384 assert(!IsTailCall &&
2385 "Do not tail-call optimize if there is a byval argument.");
2386 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2387 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2392 // Promote the value if needed.
2393 switch (VA.getLocInfo()) {
2394 default: llvm_unreachable("Unknown loc info!");
2395 case CCValAssign::Full:
2396 if (VA.isRegLoc()) {
2397 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2398 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2399 (ValVT == MVT::i64 && LocVT == MVT::f64))
2400 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2401 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2402 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2403 Arg, DAG.getConstant(0, MVT::i32));
2404 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2405 Arg, DAG.getConstant(1, MVT::i32));
2406 if (!Subtarget->isLittle())
2408 unsigned LocRegLo = VA.getLocReg();
2409 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2410 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2411 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2416 case CCValAssign::SExt:
2417 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2419 case CCValAssign::ZExt:
2420 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2422 case CCValAssign::AExt:
2423 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2427 // Arguments that can be passed on register must be kept at
2428 // RegsToPass vector
2429 if (VA.isRegLoc()) {
2430 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2434 // Register can't get to this point...
2435 assert(VA.isMemLoc());
2437 // emit ISD::STORE whichs stores the
2438 // parameter value to a stack Location
2439 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2440 Chain, Arg, DL, IsTailCall, DAG));
2443 // Transform all store nodes into one single node because all store
2444 // nodes are independent of each other.
2445 if (!MemOpChains.empty())
2446 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2447 &MemOpChains[0], MemOpChains.size());
2449 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2450 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2451 // node so that legalize doesn't hack it.
2452 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2453 bool GlobalOrExternal = false, InternalLinkage = false;
2456 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2458 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2460 if (InternalLinkage)
2461 Callee = getAddrLocal(Callee, DAG, HasMips64);
2463 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2464 MipsII::MO_CALL_LO16);
2466 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2468 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2469 MipsII::MO_NO_FLAG);
2470 GlobalOrExternal = true;
2472 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2473 if (!IsN64 && !IsPIC) // !N64 && static
2474 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2475 MipsII::MO_NO_FLAG);
2477 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2478 MipsII::MO_CALL_LO16);
2480 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2482 GlobalOrExternal = true;
2485 SmallVector<SDValue, 8> Ops(1, Chain);
2486 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2488 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2489 CLI, Callee, Chain);
2492 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2494 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2495 SDValue InFlag = Chain.getValue(1);
2497 // Create the CALLSEQ_END node.
2498 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2499 DAG.getIntPtrConstant(0, true), InFlag, DL);
2500 InFlag = Chain.getValue(1);
2502 // Handle result values, copying them out of physregs into vregs that we
2504 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2505 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2508 /// LowerCallResult - Lower the result values of a call into the
2509 /// appropriate copies out of appropriate physical registers.
2511 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2512 CallingConv::ID CallConv, bool IsVarArg,
2513 const SmallVectorImpl<ISD::InputArg> &Ins,
2514 SDLoc DL, SelectionDAG &DAG,
2515 SmallVectorImpl<SDValue> &InVals,
2516 const SDNode *CallNode,
2517 const Type *RetTy) const {
2518 // Assign locations to each value returned by this call.
2519 SmallVector<CCValAssign, 16> RVLocs;
2520 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2521 getTargetMachine(), RVLocs, *DAG.getContext());
2522 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2524 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2527 // Copy all of the result registers out of their specified physreg.
2528 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2529 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2530 RVLocs[i].getLocVT(), InFlag);
2531 Chain = Val.getValue(1);
2532 InFlag = Val.getValue(2);
2534 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2535 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2537 InVals.push_back(Val);
2543 //===----------------------------------------------------------------------===//
2544 // Formal Arguments Calling Convention Implementation
2545 //===----------------------------------------------------------------------===//
2546 /// LowerFormalArguments - transform physical registers into virtual registers
2547 /// and generate load operations for arguments places on the stack.
2549 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2550 CallingConv::ID CallConv,
2552 const SmallVectorImpl<ISD::InputArg> &Ins,
2553 SDLoc DL, SelectionDAG &DAG,
2554 SmallVectorImpl<SDValue> &InVals)
2556 MachineFunction &MF = DAG.getMachineFunction();
2557 MachineFrameInfo *MFI = MF.getFrameInfo();
2558 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2560 MipsFI->setVarArgsFrameIndex(0);
2562 // Used with vargs to acumulate store chains.
2563 std::vector<SDValue> OutChains;
2565 // Assign locations to all of the incoming arguments.
2566 SmallVector<CCValAssign, 16> ArgLocs;
2567 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2568 getTargetMachine(), ArgLocs, *DAG.getContext());
2569 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2570 Function::const_arg_iterator FuncArg =
2571 DAG.getMachineFunction().getFunction()->arg_begin();
2572 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2574 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2575 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2576 MipsCCInfo.hasByValArg());
2578 unsigned CurArgIdx = 0;
2579 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2581 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2582 CCValAssign &VA = ArgLocs[i];
2583 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2584 CurArgIdx = Ins[i].OrigArgIndex;
2585 EVT ValVT = VA.getValVT();
2586 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2587 bool IsRegLoc = VA.isRegLoc();
2589 if (Flags.isByVal()) {
2590 assert(Flags.getByValSize() &&
2591 "ByVal args of size 0 should have been ignored by front-end.");
2592 assert(ByValArg != MipsCCInfo.byval_end());
2593 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2594 MipsCCInfo, *ByValArg);
2599 // Arguments stored on registers
2601 EVT RegVT = VA.getLocVT();
2602 unsigned ArgReg = VA.getLocReg();
2603 const TargetRegisterClass *RC;
2605 if (RegVT == MVT::i32)
2606 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2607 &Mips::GPR32RegClass;
2608 else if (RegVT == MVT::i64)
2609 RC = &Mips::GPR64RegClass;
2610 else if (RegVT == MVT::f32)
2611 RC = &Mips::FGR32RegClass;
2612 else if (RegVT == MVT::f64)
2613 RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2614 &Mips::AFGR64RegClass;
2616 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2618 // Transform the arguments stored on
2619 // physical registers into virtual ones
2620 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2621 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2623 // If this is an 8 or 16-bit value, it has been passed promoted
2624 // to 32 bits. Insert an assert[sz]ext to capture this, then
2625 // truncate to the right size.
2626 if (VA.getLocInfo() != CCValAssign::Full) {
2627 unsigned Opcode = 0;
2628 if (VA.getLocInfo() == CCValAssign::SExt)
2629 Opcode = ISD::AssertSext;
2630 else if (VA.getLocInfo() == CCValAssign::ZExt)
2631 Opcode = ISD::AssertZext;
2633 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2634 DAG.getValueType(ValVT));
2635 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2638 // Handle floating point arguments passed in integer registers and
2639 // long double arguments passed in floating point registers.
2640 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2641 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2642 (RegVT == MVT::f64 && ValVT == MVT::i64))
2643 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2644 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2645 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2646 getNextIntArgReg(ArgReg), RC);
2647 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2648 if (!Subtarget->isLittle())
2649 std::swap(ArgValue, ArgValue2);
2650 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2651 ArgValue, ArgValue2);
2654 InVals.push_back(ArgValue);
2655 } else { // VA.isRegLoc()
2658 assert(VA.isMemLoc());
2660 // The stack pointer offset is relative to the caller stack frame.
2661 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2662 VA.getLocMemOffset(), true);
2664 // Create load nodes to retrieve arguments from the stack
2665 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2666 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2667 MachinePointerInfo::getFixedStack(FI),
2668 false, false, false, 0));
2672 // The mips ABIs for returning structs by value requires that we copy
2673 // the sret argument into $v0 for the return. Save the argument into
2674 // a virtual register so that we can access it from the return points.
2675 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2676 unsigned Reg = MipsFI->getSRetReturnReg();
2678 Reg = MF.getRegInfo().
2679 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2680 MipsFI->setSRetReturnReg(Reg);
2682 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2683 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2687 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2689 // All stores are grouped in one node to allow the matching between
2690 // the size of Ins and InVals. This only happens when on varg functions
2691 if (!OutChains.empty()) {
2692 OutChains.push_back(Chain);
2693 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2694 &OutChains[0], OutChains.size());
2700 //===----------------------------------------------------------------------===//
2701 // Return Value Calling Convention Implementation
2702 //===----------------------------------------------------------------------===//
2705 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2706 MachineFunction &MF, bool IsVarArg,
2707 const SmallVectorImpl<ISD::OutputArg> &Outs,
2708 LLVMContext &Context) const {
2709 SmallVector<CCValAssign, 16> RVLocs;
2710 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2712 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2716 MipsTargetLowering::LowerReturn(SDValue Chain,
2717 CallingConv::ID CallConv, bool IsVarArg,
2718 const SmallVectorImpl<ISD::OutputArg> &Outs,
2719 const SmallVectorImpl<SDValue> &OutVals,
2720 SDLoc DL, SelectionDAG &DAG) const {
2721 // CCValAssign - represent the assignment of
2722 // the return value to a location
2723 SmallVector<CCValAssign, 16> RVLocs;
2724 MachineFunction &MF = DAG.getMachineFunction();
2726 // CCState - Info about the registers and stack slot.
2727 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2729 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2731 // Analyze return values.
2732 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2733 MF.getFunction()->getReturnType());
2736 SmallVector<SDValue, 4> RetOps(1, Chain);
2738 // Copy the result values into the output registers.
2739 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2740 SDValue Val = OutVals[i];
2741 CCValAssign &VA = RVLocs[i];
2742 assert(VA.isRegLoc() && "Can only return in registers!");
2744 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2745 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2747 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2749 // Guarantee that all emitted copies are stuck together with flags.
2750 Flag = Chain.getValue(1);
2751 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2754 // The mips ABIs for returning structs by value requires that we copy
2755 // the sret argument into $v0 for the return. We saved the argument into
2756 // a virtual register in the entry block, so now we copy the value out
2758 if (MF.getFunction()->hasStructRetAttr()) {
2759 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2760 unsigned Reg = MipsFI->getSRetReturnReg();
2763 llvm_unreachable("sret virtual register not created in the entry block");
2764 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2765 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2767 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2768 Flag = Chain.getValue(1);
2769 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2772 RetOps[0] = Chain; // Update chain.
2774 // Add the flag if we have it.
2776 RetOps.push_back(Flag);
2778 // Return on Mips is always a "jr $ra"
2779 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2782 //===----------------------------------------------------------------------===//
2783 // Mips Inline Assembly Support
2784 //===----------------------------------------------------------------------===//
2786 /// getConstraintType - Given a constraint letter, return the type of
2787 /// constraint it is for this target.
2788 MipsTargetLowering::ConstraintType MipsTargetLowering::
2789 getConstraintType(const std::string &Constraint) const
2791 // Mips specific constrainy
2792 // GCC config/mips/constraints.md
2794 // 'd' : An address register. Equivalent to r
2795 // unless generating MIPS16 code.
2796 // 'y' : Equivalent to r; retained for
2797 // backwards compatibility.
2798 // 'c' : A register suitable for use in an indirect
2799 // jump. This will always be $25 for -mabicalls.
2800 // 'l' : The lo register. 1 word storage.
2801 // 'x' : The hilo register pair. Double word storage.
2802 if (Constraint.size() == 1) {
2803 switch (Constraint[0]) {
2811 return C_RegisterClass;
2816 return TargetLowering::getConstraintType(Constraint);
2819 /// Examine constraint type and operand type and determine a weight value.
2820 /// This object must already have been set up with the operand type
2821 /// and the current alternative constraint selected.
2822 TargetLowering::ConstraintWeight
2823 MipsTargetLowering::getSingleConstraintMatchWeight(
2824 AsmOperandInfo &info, const char *constraint) const {
2825 ConstraintWeight weight = CW_Invalid;
2826 Value *CallOperandVal = info.CallOperandVal;
2827 // If we don't have a value, we can't do a match,
2828 // but allow it at the lowest weight.
2829 if (CallOperandVal == NULL)
2831 Type *type = CallOperandVal->getType();
2832 // Look at the constraint type.
2833 switch (*constraint) {
2835 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2839 if (type->isIntegerTy())
2840 weight = CW_Register;
2843 if (type->isFloatTy())
2844 weight = CW_Register;
2846 case 'c': // $25 for indirect jumps
2847 case 'l': // lo register
2848 case 'x': // hilo register pair
2849 if (type->isIntegerTy())
2850 weight = CW_SpecificReg;
2852 case 'I': // signed 16 bit immediate
2853 case 'J': // integer zero
2854 case 'K': // unsigned 16 bit immediate
2855 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2856 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2857 case 'O': // signed 15 bit immediate (+- 16383)
2858 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2859 if (isa<ConstantInt>(CallOperandVal))
2860 weight = CW_Constant;
2869 /// This is a helper function to parse a physical register string and split it
2870 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2871 /// that is returned indicates whether parsing was successful. The second flag
2872 /// is true if the numeric part exists.
2873 static std::pair<bool, bool>
2874 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2875 unsigned long long &Reg) {
2876 if (C.front() != '{' || C.back() != '}')
2877 return std::make_pair(false, false);
2879 // Search for the first numeric character.
2880 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2881 I = std::find_if(B, E, std::ptr_fun(isdigit));
2883 Prefix.assign(B, I - B);
2885 // The second flag is set to false if no numeric characters were found.
2887 return std::make_pair(true, false);
2889 // Parse the numeric characters.
2890 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2894 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2895 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2896 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2897 const TargetRegisterClass *RC;
2899 unsigned long long Reg;
2901 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2904 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2906 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2907 // No numeric characters follow "hi" or "lo".
2909 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2911 RC = TRI->getRegClass(Prefix == "hi" ?
2912 Mips::HI32RegClassID : Mips::LO32RegClassID);
2913 return std::make_pair(*(RC->begin()), RC);
2917 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2919 if (Prefix == "$f") { // Parse $f0-$f31.
2920 // If the size of FP registers is 64-bit or Reg is an even number, select
2921 // the 64-bit register class. Otherwise, select the 32-bit register class.
2922 if (VT == MVT::Other)
2923 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2925 RC= getRegClassFor(VT);
2927 if (RC == &Mips::AFGR64RegClass) {
2928 assert(Reg % 2 == 0);
2931 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2932 RC = TRI->getRegClass(Mips::FCCRegClassID);
2933 } else { // Parse $0-$31.
2934 assert(Prefix == "$");
2935 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2938 assert(Reg < RC->getNumRegs());
2939 return std::make_pair(*(RC->begin() + Reg), RC);
2942 /// Given a register class constraint, like 'r', if this corresponds directly
2943 /// to an LLVM register class, return a register of 0 and the register class
2945 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2946 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2948 if (Constraint.size() == 1) {
2949 switch (Constraint[0]) {
2950 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2951 case 'y': // Same as 'r'. Exists for compatibility.
2953 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2954 if (Subtarget->inMips16Mode())
2955 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2956 return std::make_pair(0U, &Mips::GPR32RegClass);
2958 if (VT == MVT::i64 && !HasMips64)
2959 return std::make_pair(0U, &Mips::GPR32RegClass);
2960 if (VT == MVT::i64 && HasMips64)
2961 return std::make_pair(0U, &Mips::GPR64RegClass);
2962 // This will generate an error message
2963 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2966 return std::make_pair(0U, &Mips::FGR32RegClass);
2967 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2968 if (Subtarget->isFP64bit())
2969 return std::make_pair(0U, &Mips::FGR64RegClass);
2970 return std::make_pair(0U, &Mips::AFGR64RegClass);
2973 case 'c': // register suitable for indirect jump
2975 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2976 assert(VT == MVT::i64 && "Unexpected type.");
2977 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2978 case 'l': // register suitable for indirect jump
2980 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2981 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2982 case 'x': // register suitable for indirect jump
2983 // Fixme: Not triggering the use of both hi and low
2984 // This will generate an error message
2985 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2989 std::pair<unsigned, const TargetRegisterClass *> R;
2990 R = parseRegForInlineAsmConstraint(Constraint, VT);
2995 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2998 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2999 /// vector. If it is invalid, don't add anything to Ops.
3000 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3001 std::string &Constraint,
3002 std::vector<SDValue>&Ops,
3003 SelectionDAG &DAG) const {
3004 SDValue Result(0, 0);
3006 // Only support length 1 constraints for now.
3007 if (Constraint.length() > 1) return;
3009 char ConstraintLetter = Constraint[0];
3010 switch (ConstraintLetter) {
3011 default: break; // This will fall through to the generic implementation
3012 case 'I': // Signed 16 bit constant
3013 // If this fails, the parent routine will give an error
3014 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3015 EVT Type = Op.getValueType();
3016 int64_t Val = C->getSExtValue();
3017 if (isInt<16>(Val)) {
3018 Result = DAG.getTargetConstant(Val, Type);
3023 case 'J': // integer zero
3024 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3025 EVT Type = Op.getValueType();
3026 int64_t Val = C->getZExtValue();
3028 Result = DAG.getTargetConstant(0, Type);
3033 case 'K': // unsigned 16 bit immediate
3034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3035 EVT Type = Op.getValueType();
3036 uint64_t Val = (uint64_t)C->getZExtValue();
3037 if (isUInt<16>(Val)) {
3038 Result = DAG.getTargetConstant(Val, Type);
3043 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3045 EVT Type = Op.getValueType();
3046 int64_t Val = C->getSExtValue();
3047 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3048 Result = DAG.getTargetConstant(Val, Type);
3053 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3055 EVT Type = Op.getValueType();
3056 int64_t Val = C->getSExtValue();
3057 if ((Val >= -65535) && (Val <= -1)) {
3058 Result = DAG.getTargetConstant(Val, Type);
3063 case 'O': // signed 15 bit immediate
3064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3065 EVT Type = Op.getValueType();
3066 int64_t Val = C->getSExtValue();
3067 if ((isInt<15>(Val))) {
3068 Result = DAG.getTargetConstant(Val, Type);
3073 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3075 EVT Type = Op.getValueType();
3076 int64_t Val = C->getSExtValue();
3077 if ((Val <= 65535) && (Val >= 1)) {
3078 Result = DAG.getTargetConstant(Val, Type);
3085 if (Result.getNode()) {
3086 Ops.push_back(Result);
3090 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3094 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3095 // No global is ever allowed as a base.
3100 case 0: // "r+i" or just "i", depending on HasBaseReg.
3103 if (!AM.HasBaseReg) // allow "r+i".
3105 return false; // disallow "r+r" or "r+r+i".
3114 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3115 // The Mips target isn't yet aware of offsets.
3119 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3121 bool IsMemset, bool ZeroMemset,
3123 MachineFunction &MF) const {
3124 if (Subtarget->hasMips64())
3130 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3131 if (VT != MVT::f32 && VT != MVT::f64)
3133 if (Imm.isNegZero())
3135 return Imm.isZero();
3138 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3140 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3142 return TargetLowering::getJumpTableEncoding();
3145 /// This function returns true if CallSym is a long double emulation routine.
3146 static bool isF128SoftLibCall(const char *CallSym) {
3147 const char *const LibCalls[] =
3148 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3149 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3150 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3151 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3152 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3153 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3154 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3155 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3158 const char * const *End = LibCalls + array_lengthof(LibCalls);
3160 // Check that LibCalls is sorted alphabetically.
3161 MipsTargetLowering::LTStr Comp;
3164 for (const char * const *I = LibCalls; I < End - 1; ++I)
3165 assert(Comp(*I, *(I + 1)));
3168 return std::binary_search(LibCalls, End, CallSym, Comp);
3171 /// This function returns true if Ty is fp128 or i128 which was originally a
3173 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3174 if (Ty->isFP128Ty())
3177 const ExternalSymbolSDNode *ES =
3178 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3180 // If the Ty is i128 and the function being called is a long double emulation
3181 // routine, then the original type is f128.
3182 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3185 MipsTargetLowering::MipsCC::SpecialCallingConvType
3186 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3187 MipsCC::SpecialCallingConvType SpecialCallingConv =
3188 MipsCC::NoSpecialCallingConv;;
3189 if (Subtarget->inMips16HardFloat()) {
3190 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3191 llvm::StringRef Sym = G->getGlobal()->getName();
3192 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3193 if (F->hasFnAttribute("__Mips16RetHelper")) {
3194 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3198 return SpecialCallingConv;
3201 MipsTargetLowering::MipsCC::MipsCC(
3202 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3203 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3204 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3205 SpecialCallingConv(SpecialCallingConv_){
3206 // Pre-allocate reserved argument area.
3207 CCInfo.AllocateStack(reservedArgArea(), 1);
3211 void MipsTargetLowering::MipsCC::
3212 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3213 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3214 std::vector<ArgListEntry> &FuncArgs) {
3215 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3216 "CallingConv::Fast shouldn't be used for vararg functions.");
3218 unsigned NumOpnds = Args.size();
3219 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3221 for (unsigned I = 0; I != NumOpnds; ++I) {
3222 MVT ArgVT = Args[I].VT;
3223 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3226 if (ArgFlags.isByVal()) {
3227 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3231 if (IsVarArg && !Args[I].IsFixed)
3232 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3234 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3236 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3241 dbgs() << "Call operand #" << I << " has unhandled type "
3242 << EVT(ArgVT).getEVTString();
3244 llvm_unreachable(0);
3249 void MipsTargetLowering::MipsCC::
3250 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3251 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3252 unsigned NumArgs = Args.size();
3253 llvm::CCAssignFn *FixedFn = fixedArgFn();
3254 unsigned CurArgIdx = 0;
3256 for (unsigned I = 0; I != NumArgs; ++I) {
3257 MVT ArgVT = Args[I].VT;
3258 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3259 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3260 CurArgIdx = Args[I].OrigArgIndex;
3262 if (ArgFlags.isByVal()) {
3263 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3267 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3269 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3273 dbgs() << "Formal Arg #" << I << " has unhandled type "
3274 << EVT(ArgVT).getEVTString();
3276 llvm_unreachable(0);
3280 template<typename Ty>
3281 void MipsTargetLowering::MipsCC::
3282 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3283 const SDNode *CallNode, const Type *RetTy) const {
3286 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3287 Fn = RetCC_F128Soft;
3291 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3292 MVT VT = RetVals[I].VT;
3293 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3294 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3296 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3298 dbgs() << "Call result #" << I << " has unhandled type "
3299 << EVT(VT).getEVTString() << '\n';
3301 llvm_unreachable(0);
3306 void MipsTargetLowering::MipsCC::
3307 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3308 const SDNode *CallNode, const Type *RetTy) const {
3309 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3312 void MipsTargetLowering::MipsCC::
3313 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3314 const Type *RetTy) const {
3315 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3319 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3321 CCValAssign::LocInfo LocInfo,
3322 ISD::ArgFlagsTy ArgFlags) {
3323 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3325 struct ByValArgInfo ByVal;
3326 unsigned RegSize = regSize();
3327 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3328 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3331 if (useRegsForByval())
3332 allocateRegs(ByVal, ByValSize, Align);
3334 // Allocate space on caller's stack.
3335 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3337 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3339 ByValArgs.push_back(ByVal);
3342 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3343 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3346 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3347 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3350 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3351 return IsO32 ? O32IntRegs : Mips64IntRegs;
3354 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3355 if (CallConv == CallingConv::Fast)
3356 return CC_Mips_FastCC;
3358 if (SpecialCallingConv == Mips16RetHelperConv)
3359 return CC_Mips16RetHelper;
3360 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3363 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3364 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3367 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3368 return IsO32 ? O32IntRegs : Mips64DPRegs;
3371 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3374 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3375 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3376 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3377 "Byval argument's size and alignment should be a multiple of"
3380 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3382 // If Align > RegSize, the first arg register must be even.
3383 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3384 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3388 // Mark the registers allocated.
3389 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3390 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3391 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3394 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3395 const SDNode *CallNode,
3396 bool IsSoftFloat) const {
3397 if (IsSoftFloat || IsO32)
3400 // Check if the original type was fp128.
3401 if (originalTypeIsF128(OrigTy, CallNode)) {
3402 assert(VT == MVT::i64);
3409 void MipsTargetLowering::
3410 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3411 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3412 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3413 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3414 MachineFunction &MF = DAG.getMachineFunction();
3415 MachineFrameInfo *MFI = MF.getFrameInfo();
3416 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3417 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3421 FrameObjOffset = (int)CC.reservedArgArea() -
3422 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3424 FrameObjOffset = ByVal.Address;
3426 // Create frame object.
3427 EVT PtrTy = getPointerTy();
3428 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3429 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3430 InVals.push_back(FIN);
3435 // Copy arg registers.
3436 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3437 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3439 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3440 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3441 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3442 unsigned Offset = I * CC.regSize();
3443 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3444 DAG.getConstant(Offset, PtrTy));
3445 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3446 StorePtr, MachinePointerInfo(FuncArg, Offset),
3448 OutChains.push_back(Store);
3452 // Copy byVal arg to registers and stack.
3453 void MipsTargetLowering::
3454 passByValArg(SDValue Chain, SDLoc DL,
3455 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3456 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3457 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3458 const MipsCC &CC, const ByValArgInfo &ByVal,
3459 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3460 unsigned ByValSize = Flags.getByValSize();
3461 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3462 unsigned RegSize = CC.regSize();
3463 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3464 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3466 if (ByVal.NumRegs) {
3467 const uint16_t *ArgRegs = CC.intArgRegs();
3468 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3471 // Copy words to registers.
3472 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3473 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3474 DAG.getConstant(Offset, PtrTy));
3475 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3476 MachinePointerInfo(), false, false, false,
3478 MemOpChains.push_back(LoadVal.getValue(1));
3479 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3480 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3483 // Return if the struct has been fully copied.
3484 if (ByValSize == Offset)
3487 // Copy the remainder of the byval argument with sub-word loads and shifts.
3488 if (LeftoverBytes) {
3489 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3490 "Size of the remainder should be smaller than RegSize.");
3493 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3494 Offset < ByValSize; LoadSize /= 2) {
3495 unsigned RemSize = ByValSize - Offset;
3497 if (RemSize < LoadSize)
3501 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3502 DAG.getConstant(Offset, PtrTy));
3504 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3505 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3506 false, false, Alignment);
3507 MemOpChains.push_back(LoadVal.getValue(1));
3509 // Shift the loaded value.
3513 Shamt = TotalSizeLoaded;
3515 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3517 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3518 DAG.getConstant(Shamt, MVT::i32));
3521 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3526 TotalSizeLoaded += LoadSize;
3527 Alignment = std::min(Alignment, LoadSize);
3530 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3531 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3536 // Copy remainder of byval arg to it with memcpy.
3537 unsigned MemCpySize = ByValSize - Offset;
3538 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3539 DAG.getConstant(Offset, PtrTy));
3540 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3541 DAG.getIntPtrConstant(ByVal.Address));
3542 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3543 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3544 /*isVolatile=*/false, /*AlwaysInline=*/false,
3545 MachinePointerInfo(0), MachinePointerInfo(0));
3546 MemOpChains.push_back(Chain);
3550 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3551 const MipsCC &CC, SDValue Chain,
3552 SDLoc DL, SelectionDAG &DAG) const {
3553 unsigned NumRegs = CC.numIntArgRegs();
3554 const uint16_t *ArgRegs = CC.intArgRegs();
3555 const CCState &CCInfo = CC.getCCInfo();
3556 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3557 unsigned RegSize = CC.regSize();
3558 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3559 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3560 MachineFunction &MF = DAG.getMachineFunction();
3561 MachineFrameInfo *MFI = MF.getFrameInfo();
3562 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3564 // Offset of the first variable argument from stack pointer.
3568 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3571 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3573 // Record the frame index of the first variable argument
3574 // which is a value necessary to VASTART.
3575 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3576 MipsFI->setVarArgsFrameIndex(FI);
3578 // Copy the integer registers that have not been used for argument passing
3579 // to the argument register save area. For O32, the save area is allocated
3580 // in the caller's stack frame, while for N32/64, it is allocated in the
3581 // callee's stack frame.
3582 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3583 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3584 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3585 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3586 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3587 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3588 MachinePointerInfo(), false, false, 0);
3589 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3590 OutChains.push_back(Store);