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/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NumTailCalls, "Number of tail calls");
45 LargeGOT("mxgot", cl::Hidden,
46 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
49 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
50 cl::desc("MIPS: Don't trap on integer division by zero."),
54 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
55 cl::desc("Allow mips-fast-isel to be used"),
58 static const MCPhysReg O32IntRegs[4] = {
59 Mips::A0, Mips::A1, Mips::A2, Mips::A3
62 static const MCPhysReg Mips64IntRegs[8] = {
63 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
64 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
67 static const MCPhysReg Mips64DPRegs[8] = {
68 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
69 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
72 // If I is a shifted mask, set the size (Size) and the first bit of the
73 // mask (Pos), and return true.
74 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
75 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
76 if (!isShiftedMask_64(I))
79 Size = CountPopulation_64(I);
80 Pos = countTrailingZeros(I);
84 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
85 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
86 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
89 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
91 unsigned Flag) const {
92 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
95 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
97 unsigned Flag) const {
98 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
101 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
103 unsigned Flag) const {
104 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
107 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
109 unsigned Flag) const {
110 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
113 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
115 unsigned Flag) const {
116 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
117 N->getOffset(), Flag);
120 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
122 case MipsISD::JmpLink: return "MipsISD::JmpLink";
123 case MipsISD::TailCall: return "MipsISD::TailCall";
124 case MipsISD::Hi: return "MipsISD::Hi";
125 case MipsISD::Lo: return "MipsISD::Lo";
126 case MipsISD::GPRel: return "MipsISD::GPRel";
127 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
128 case MipsISD::Ret: return "MipsISD::Ret";
129 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
130 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
131 case MipsISD::FPCmp: return "MipsISD::FPCmp";
132 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
133 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
134 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
135 case MipsISD::MFHI: return "MipsISD::MFHI";
136 case MipsISD::MFLO: return "MipsISD::MFLO";
137 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
138 case MipsISD::Mult: return "MipsISD::Mult";
139 case MipsISD::Multu: return "MipsISD::Multu";
140 case MipsISD::MAdd: return "MipsISD::MAdd";
141 case MipsISD::MAddu: return "MipsISD::MAddu";
142 case MipsISD::MSub: return "MipsISD::MSub";
143 case MipsISD::MSubu: return "MipsISD::MSubu";
144 case MipsISD::DivRem: return "MipsISD::DivRem";
145 case MipsISD::DivRemU: return "MipsISD::DivRemU";
146 case MipsISD::DivRem16: return "MipsISD::DivRem16";
147 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
148 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
149 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
150 case MipsISD::Wrapper: return "MipsISD::Wrapper";
151 case MipsISD::Sync: return "MipsISD::Sync";
152 case MipsISD::Ext: return "MipsISD::Ext";
153 case MipsISD::Ins: return "MipsISD::Ins";
154 case MipsISD::LWL: return "MipsISD::LWL";
155 case MipsISD::LWR: return "MipsISD::LWR";
156 case MipsISD::SWL: return "MipsISD::SWL";
157 case MipsISD::SWR: return "MipsISD::SWR";
158 case MipsISD::LDL: return "MipsISD::LDL";
159 case MipsISD::LDR: return "MipsISD::LDR";
160 case MipsISD::SDL: return "MipsISD::SDL";
161 case MipsISD::SDR: return "MipsISD::SDR";
162 case MipsISD::EXTP: return "MipsISD::EXTP";
163 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
164 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
165 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
166 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
167 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
168 case MipsISD::SHILO: return "MipsISD::SHILO";
169 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
170 case MipsISD::MULT: return "MipsISD::MULT";
171 case MipsISD::MULTU: return "MipsISD::MULTU";
172 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
173 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
174 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
175 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
176 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
177 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
178 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
179 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
180 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
181 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
182 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
183 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
184 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
185 case MipsISD::VCEQ: return "MipsISD::VCEQ";
186 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
187 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
188 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
189 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
190 case MipsISD::VSMAX: return "MipsISD::VSMAX";
191 case MipsISD::VSMIN: return "MipsISD::VSMIN";
192 case MipsISD::VUMAX: return "MipsISD::VUMAX";
193 case MipsISD::VUMIN: return "MipsISD::VUMIN";
194 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
195 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
196 case MipsISD::VNOR: return "MipsISD::VNOR";
197 case MipsISD::VSHF: return "MipsISD::VSHF";
198 case MipsISD::SHF: return "MipsISD::SHF";
199 case MipsISD::ILVEV: return "MipsISD::ILVEV";
200 case MipsISD::ILVOD: return "MipsISD::ILVOD";
201 case MipsISD::ILVL: return "MipsISD::ILVL";
202 case MipsISD::ILVR: return "MipsISD::ILVR";
203 case MipsISD::PCKEV: return "MipsISD::PCKEV";
204 case MipsISD::PCKOD: return "MipsISD::PCKOD";
205 case MipsISD::INSVE: return "MipsISD::INSVE";
206 default: return NULL;
210 MipsTargetLowering::MipsTargetLowering(MipsTargetMachine &TM)
211 : TargetLowering(TM, new MipsTargetObjectFile()),
212 Subtarget(&TM.getSubtarget<MipsSubtarget>()) {
213 // Mips does not have i1 type, so use i32 for
214 // setcc operations results (slt, sgt, ...).
215 setBooleanContents(ZeroOrOneBooleanContent);
216 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
218 // Load extented operations for i1 types must be promoted
219 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
220 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
221 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
223 // MIPS doesn't have extending float->double load/store
224 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
225 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
227 // Used by legalize types to correctly generate the setcc result.
228 // Without this, every float setcc comes with a AND/OR with the result,
229 // we don't want this, since the fpcmp result goes to a flag register,
230 // which is used implicitly by brcond and select operations.
231 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
233 // Mips Custom Operations
234 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
235 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
236 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
237 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
238 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
239 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
240 setOperationAction(ISD::SELECT, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT, MVT::f64, Custom);
242 setOperationAction(ISD::SELECT, MVT::i32, Custom);
243 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
244 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
245 setOperationAction(ISD::SETCC, MVT::f32, Custom);
246 setOperationAction(ISD::SETCC, MVT::f64, Custom);
247 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
248 setOperationAction(ISD::VASTART, MVT::Other, Custom);
249 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
251 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
254 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
255 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
256 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
257 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
258 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
259 setOperationAction(ISD::SELECT, MVT::i64, Custom);
260 setOperationAction(ISD::LOAD, MVT::i64, Custom);
261 setOperationAction(ISD::STORE, MVT::i64, Custom);
262 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
266 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
267 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
268 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
271 setOperationAction(ISD::ADD, MVT::i32, Custom);
273 setOperationAction(ISD::ADD, MVT::i64, Custom);
275 setOperationAction(ISD::SDIV, MVT::i32, Expand);
276 setOperationAction(ISD::SREM, MVT::i32, Expand);
277 setOperationAction(ISD::UDIV, MVT::i32, Expand);
278 setOperationAction(ISD::UREM, MVT::i32, Expand);
279 setOperationAction(ISD::SDIV, MVT::i64, Expand);
280 setOperationAction(ISD::SREM, MVT::i64, Expand);
281 setOperationAction(ISD::UDIV, MVT::i64, Expand);
282 setOperationAction(ISD::UREM, MVT::i64, Expand);
284 // Operations not directly supported by Mips.
285 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
286 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
287 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
288 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
289 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
290 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
291 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
292 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
293 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
294 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
295 if (Subtarget->hasCnMips()) {
296 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
297 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
299 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
300 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
302 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
303 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
304 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
305 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
306 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
307 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
308 setOperationAction(ISD::ROTL, MVT::i32, Expand);
309 setOperationAction(ISD::ROTL, MVT::i64, Expand);
310 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
313 if (!Subtarget->hasMips32r2())
314 setOperationAction(ISD::ROTR, MVT::i32, Expand);
316 if (!Subtarget->hasMips64r2())
317 setOperationAction(ISD::ROTR, MVT::i64, Expand);
319 setOperationAction(ISD::FSIN, MVT::f32, Expand);
320 setOperationAction(ISD::FSIN, MVT::f64, Expand);
321 setOperationAction(ISD::FCOS, MVT::f32, Expand);
322 setOperationAction(ISD::FCOS, MVT::f64, Expand);
323 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
324 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
325 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
326 setOperationAction(ISD::FPOW, MVT::f32, Expand);
327 setOperationAction(ISD::FPOW, MVT::f64, Expand);
328 setOperationAction(ISD::FLOG, MVT::f32, Expand);
329 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
330 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
331 setOperationAction(ISD::FEXP, MVT::f32, Expand);
332 setOperationAction(ISD::FMA, MVT::f32, Expand);
333 setOperationAction(ISD::FMA, MVT::f64, Expand);
334 setOperationAction(ISD::FREM, MVT::f32, Expand);
335 setOperationAction(ISD::FREM, MVT::f64, Expand);
337 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
339 setOperationAction(ISD::VAARG, MVT::Other, Expand);
340 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
341 setOperationAction(ISD::VAEND, MVT::Other, Expand);
343 // Use the default for now
344 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
345 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
347 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
348 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
349 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
350 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
352 setInsertFencesForAtomic(true);
354 if (!Subtarget->hasSEInReg()) {
355 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
359 if (!Subtarget->hasBitCount()) {
360 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
361 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
364 if (!Subtarget->hasSwap()) {
365 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
366 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
370 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
371 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
372 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
373 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
376 setOperationAction(ISD::TRAP, MVT::Other, Legal);
378 setTargetDAGCombine(ISD::SDIVREM);
379 setTargetDAGCombine(ISD::UDIVREM);
380 setTargetDAGCombine(ISD::SELECT);
381 setTargetDAGCombine(ISD::AND);
382 setTargetDAGCombine(ISD::OR);
383 setTargetDAGCombine(ISD::ADD);
385 setMinFunctionAlignment(isGP64bit() ? 3 : 2);
387 setStackPointerRegisterToSaveRestore(isN64() ? Mips::SP_64 : Mips::SP);
389 setExceptionPointerRegister(isN64() ? Mips::A0_64 : Mips::A0);
390 setExceptionSelectorRegister(isN64() ? Mips::A1_64 : Mips::A1);
392 MaxStoresPerMemcpy = 16;
394 isMicroMips = Subtarget->inMicroMipsMode();
397 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
398 if (TM.getSubtargetImpl()->inMips16Mode())
399 return llvm::createMips16TargetLowering(TM);
401 return llvm::createMipsSETargetLowering(TM);
404 // Create a fast isel object.
406 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
407 const TargetLibraryInfo *libInfo) const {
408 if (!EnableMipsFastISel)
409 return TargetLowering::createFastISel(funcInfo, libInfo);
410 return Mips::createFastISel(funcInfo, libInfo);
413 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
416 return VT.changeVectorElementTypeToInteger();
419 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
420 TargetLowering::DAGCombinerInfo &DCI,
421 const MipsSubtarget *Subtarget) {
422 if (DCI.isBeforeLegalizeOps())
425 EVT Ty = N->getValueType(0);
426 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
427 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
428 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
432 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
433 N->getOperand(0), N->getOperand(1));
434 SDValue InChain = DAG.getEntryNode();
435 SDValue InGlue = DivRem;
438 if (N->hasAnyUseOfValue(0)) {
439 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
442 InChain = CopyFromLo.getValue(1);
443 InGlue = CopyFromLo.getValue(2);
447 if (N->hasAnyUseOfValue(1)) {
448 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
456 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
458 default: llvm_unreachable("Unknown fp condition code!");
460 case ISD::SETOEQ: return Mips::FCOND_OEQ;
461 case ISD::SETUNE: return Mips::FCOND_UNE;
463 case ISD::SETOLT: return Mips::FCOND_OLT;
465 case ISD::SETOGT: return Mips::FCOND_OGT;
467 case ISD::SETOLE: return Mips::FCOND_OLE;
469 case ISD::SETOGE: return Mips::FCOND_OGE;
470 case ISD::SETULT: return Mips::FCOND_ULT;
471 case ISD::SETULE: return Mips::FCOND_ULE;
472 case ISD::SETUGT: return Mips::FCOND_UGT;
473 case ISD::SETUGE: return Mips::FCOND_UGE;
474 case ISD::SETUO: return Mips::FCOND_UN;
475 case ISD::SETO: return Mips::FCOND_OR;
477 case ISD::SETONE: return Mips::FCOND_ONE;
478 case ISD::SETUEQ: return Mips::FCOND_UEQ;
483 /// This function returns true if the floating point conditional branches and
484 /// conditional moves which use condition code CC should be inverted.
485 static bool invertFPCondCodeUser(Mips::CondCode CC) {
486 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
489 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
490 "Illegal Condition Code");
495 // Creates and returns an FPCmp node from a setcc node.
496 // Returns Op if setcc is not a floating point comparison.
497 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
498 // must be a SETCC node
499 if (Op.getOpcode() != ISD::SETCC)
502 SDValue LHS = Op.getOperand(0);
504 if (!LHS.getValueType().isFloatingPoint())
507 SDValue RHS = Op.getOperand(1);
510 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
511 // node if necessary.
512 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
514 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
515 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
518 // Creates and returns a CMovFPT/F node.
519 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
520 SDValue False, SDLoc DL) {
521 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
522 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
523 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
525 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
526 True.getValueType(), True, FCC0, False, Cond);
529 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
530 TargetLowering::DAGCombinerInfo &DCI,
531 const MipsSubtarget *Subtarget) {
532 if (DCI.isBeforeLegalizeOps())
535 SDValue SetCC = N->getOperand(0);
537 if ((SetCC.getOpcode() != ISD::SETCC) ||
538 !SetCC.getOperand(0).getValueType().isInteger())
541 SDValue False = N->getOperand(2);
542 EVT FalseTy = False.getValueType();
544 if (!FalseTy.isInteger())
547 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
549 // If the RHS (False) is 0, we swap the order of the operands
550 // of ISD::SELECT (obviously also inverting the condition) so that we can
551 // take advantage of conditional moves using the $0 register.
553 // return (a != 0) ? x : 0;
561 if (!FalseC->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 // If both operands are integer constants there's a possibility that we
572 // can do some interesting optimizations.
573 SDValue True = N->getOperand(1);
574 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
576 if (!TrueC || !True.getValueType().isInteger())
579 // We'll also ignore MVT::i64 operands as this optimizations proves
580 // to be ineffective because of the required sign extensions as the result
581 // of a SETCC operator is always MVT::i32 for non-vector types.
582 if (True.getValueType() == MVT::i64)
585 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
587 // 1) (a < x) ? y : y-1
589 // addiu $reg2, $reg1, y-1
591 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
593 // 2) (a < x) ? y-1 : y
595 // xor $reg1, $reg1, 1
596 // addiu $reg2, $reg1, y-1
598 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
599 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
600 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
601 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
604 // Couldn't optimize.
608 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
609 TargetLowering::DAGCombinerInfo &DCI,
610 const MipsSubtarget *Subtarget) {
611 // Pattern match EXT.
612 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
613 // => ext $dst, $src, size, pos
614 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
617 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
618 unsigned ShiftRightOpc = ShiftRight.getOpcode();
620 // Op's first operand must be a shift right.
621 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
624 // The second operand of the shift must be an immediate.
626 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
629 uint64_t Pos = CN->getZExtValue();
630 uint64_t SMPos, SMSize;
632 // Op's second operand must be a shifted mask.
633 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
634 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
637 // Return if the shifted mask does not start at bit 0 or the sum of its size
638 // and Pos exceeds the word's size.
639 EVT ValTy = N->getValueType(0);
640 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
643 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
644 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
645 DAG.getConstant(SMSize, MVT::i32));
648 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
649 TargetLowering::DAGCombinerInfo &DCI,
650 const MipsSubtarget *Subtarget) {
651 // Pattern match INS.
652 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
653 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
654 // => ins $dst, $src, size, pos, $src1
655 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
658 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
659 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
662 // See if Op's first operand matches (and $src1 , mask0).
663 if (And0.getOpcode() != ISD::AND)
666 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
667 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
670 // See if Op's second operand matches (and (shl $src, pos), mask1).
671 if (And1.getOpcode() != ISD::AND)
674 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
675 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
678 // The shift masks must have the same position and size.
679 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
682 SDValue Shl = And1.getOperand(0);
683 if (Shl.getOpcode() != ISD::SHL)
686 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
689 unsigned Shamt = CN->getZExtValue();
691 // Return if the shift amount and the first bit position of mask are not the
693 EVT ValTy = N->getValueType(0);
694 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
697 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
698 DAG.getConstant(SMPos0, MVT::i32),
699 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
702 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
703 TargetLowering::DAGCombinerInfo &DCI,
704 const MipsSubtarget *Subtarget) {
705 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
707 if (DCI.isBeforeLegalizeOps())
710 SDValue Add = N->getOperand(1);
712 if (Add.getOpcode() != ISD::ADD)
715 SDValue Lo = Add.getOperand(1);
717 if ((Lo.getOpcode() != MipsISD::Lo) ||
718 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
721 EVT ValTy = N->getValueType(0);
724 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
726 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
729 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
731 SelectionDAG &DAG = DCI.DAG;
732 unsigned Opc = N->getOpcode();
738 return performDivRemCombine(N, DAG, DCI, Subtarget);
740 return performSELECTCombine(N, DAG, DCI, Subtarget);
742 return performANDCombine(N, DAG, DCI, Subtarget);
744 return performORCombine(N, DAG, DCI, Subtarget);
746 return performADDCombine(N, DAG, DCI, Subtarget);
753 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
754 SmallVectorImpl<SDValue> &Results,
755 SelectionDAG &DAG) const {
756 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
758 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
759 Results.push_back(Res.getValue(I));
763 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
764 SmallVectorImpl<SDValue> &Results,
765 SelectionDAG &DAG) const {
766 return LowerOperationWrapper(N, Results, DAG);
769 SDValue MipsTargetLowering::
770 LowerOperation(SDValue Op, SelectionDAG &DAG) const
772 switch (Op.getOpcode())
774 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
775 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
776 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
777 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
778 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
779 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
780 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
781 case ISD::SELECT: return lowerSELECT(Op, DAG);
782 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
783 case ISD::SETCC: return lowerSETCC(Op, DAG);
784 case ISD::VASTART: return lowerVASTART(Op, DAG);
785 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
786 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
787 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
788 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
789 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
790 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
791 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
792 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
793 case ISD::LOAD: return lowerLOAD(Op, DAG);
794 case ISD::STORE: return lowerSTORE(Op, DAG);
795 case ISD::ADD: return lowerADD(Op, DAG);
796 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
801 //===----------------------------------------------------------------------===//
802 // Lower helper functions
803 //===----------------------------------------------------------------------===//
805 // addLiveIn - This helper function adds the specified physical register to the
806 // MachineFunction as a live in value. It also creates a corresponding
807 // virtual register for it.
809 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
811 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
812 MF.getRegInfo().addLiveIn(PReg, VReg);
816 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
817 MachineBasicBlock &MBB,
818 const TargetInstrInfo &TII,
823 // Insert instruction "teq $divisor_reg, $zero, 7".
824 MachineBasicBlock::iterator I(MI);
825 MachineInstrBuilder MIB;
826 MachineOperand &Divisor = MI->getOperand(2);
827 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
828 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
829 .addReg(Mips::ZERO).addImm(7);
831 // Use the 32-bit sub-register if this is a 64-bit division.
833 MIB->getOperand(0).setSubReg(Mips::sub_32);
835 // Clear Divisor's kill flag.
836 Divisor.setIsKill(false);
841 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
842 MachineBasicBlock *BB) const {
843 switch (MI->getOpcode()) {
845 llvm_unreachable("Unexpected instr type to insert");
846 case Mips::ATOMIC_LOAD_ADD_I8:
847 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
848 case Mips::ATOMIC_LOAD_ADD_I16:
849 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
850 case Mips::ATOMIC_LOAD_ADD_I32:
851 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
852 case Mips::ATOMIC_LOAD_ADD_I64:
853 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
855 case Mips::ATOMIC_LOAD_AND_I8:
856 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
857 case Mips::ATOMIC_LOAD_AND_I16:
858 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
859 case Mips::ATOMIC_LOAD_AND_I32:
860 return emitAtomicBinary(MI, BB, 4, Mips::AND);
861 case Mips::ATOMIC_LOAD_AND_I64:
862 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
864 case Mips::ATOMIC_LOAD_OR_I8:
865 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
866 case Mips::ATOMIC_LOAD_OR_I16:
867 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
868 case Mips::ATOMIC_LOAD_OR_I32:
869 return emitAtomicBinary(MI, BB, 4, Mips::OR);
870 case Mips::ATOMIC_LOAD_OR_I64:
871 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
873 case Mips::ATOMIC_LOAD_XOR_I8:
874 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
875 case Mips::ATOMIC_LOAD_XOR_I16:
876 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
877 case Mips::ATOMIC_LOAD_XOR_I32:
878 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
879 case Mips::ATOMIC_LOAD_XOR_I64:
880 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
882 case Mips::ATOMIC_LOAD_NAND_I8:
883 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
884 case Mips::ATOMIC_LOAD_NAND_I16:
885 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
886 case Mips::ATOMIC_LOAD_NAND_I32:
887 return emitAtomicBinary(MI, BB, 4, 0, true);
888 case Mips::ATOMIC_LOAD_NAND_I64:
889 return emitAtomicBinary(MI, BB, 8, 0, true);
891 case Mips::ATOMIC_LOAD_SUB_I8:
892 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
893 case Mips::ATOMIC_LOAD_SUB_I16:
894 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
895 case Mips::ATOMIC_LOAD_SUB_I32:
896 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
897 case Mips::ATOMIC_LOAD_SUB_I64:
898 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
900 case Mips::ATOMIC_SWAP_I8:
901 return emitAtomicBinaryPartword(MI, BB, 1, 0);
902 case Mips::ATOMIC_SWAP_I16:
903 return emitAtomicBinaryPartword(MI, BB, 2, 0);
904 case Mips::ATOMIC_SWAP_I32:
905 return emitAtomicBinary(MI, BB, 4, 0);
906 case Mips::ATOMIC_SWAP_I64:
907 return emitAtomicBinary(MI, BB, 8, 0);
909 case Mips::ATOMIC_CMP_SWAP_I8:
910 return emitAtomicCmpSwapPartword(MI, BB, 1);
911 case Mips::ATOMIC_CMP_SWAP_I16:
912 return emitAtomicCmpSwapPartword(MI, BB, 2);
913 case Mips::ATOMIC_CMP_SWAP_I32:
914 return emitAtomicCmpSwap(MI, BB, 4);
915 case Mips::ATOMIC_CMP_SWAP_I64:
916 return emitAtomicCmpSwap(MI, BB, 8);
917 case Mips::PseudoSDIV:
918 case Mips::PseudoUDIV:
919 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
920 case Mips::PseudoDSDIV:
921 case Mips::PseudoDUDIV:
922 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
926 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
927 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
929 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
930 unsigned Size, unsigned BinOpcode,
932 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
934 MachineFunction *MF = BB->getParent();
935 MachineRegisterInfo &RegInfo = MF->getRegInfo();
936 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
937 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
938 DebugLoc DL = MI->getDebugLoc();
939 unsigned LL, SC, AND, NOR, ZERO, BEQ;
942 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
943 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
954 ZERO = Mips::ZERO_64;
958 unsigned OldVal = MI->getOperand(0).getReg();
959 unsigned Ptr = MI->getOperand(1).getReg();
960 unsigned Incr = MI->getOperand(2).getReg();
962 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
963 unsigned AndRes = RegInfo.createVirtualRegister(RC);
964 unsigned Success = RegInfo.createVirtualRegister(RC);
966 // insert new blocks after the current block
967 const BasicBlock *LLVM_BB = BB->getBasicBlock();
968 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
969 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
970 MachineFunction::iterator It = BB;
972 MF->insert(It, loopMBB);
973 MF->insert(It, exitMBB);
975 // Transfer the remainder of BB and its successor edges to exitMBB.
976 exitMBB->splice(exitMBB->begin(), BB,
977 std::next(MachineBasicBlock::iterator(MI)), BB->end());
978 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
982 // fallthrough --> loopMBB
983 BB->addSuccessor(loopMBB);
984 loopMBB->addSuccessor(loopMBB);
985 loopMBB->addSuccessor(exitMBB);
989 // <binop> storeval, oldval, incr
990 // sc success, storeval, 0(ptr)
991 // beq success, $0, loopMBB
993 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
995 // and andres, oldval, incr
996 // nor storeval, $0, andres
997 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
998 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
999 } else if (BinOpcode) {
1000 // <binop> storeval, oldval, incr
1001 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1005 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1006 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1008 MI->eraseFromParent(); // The instruction is gone now.
1014 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1015 MachineBasicBlock *BB,
1016 unsigned Size, unsigned BinOpcode,
1018 assert((Size == 1 || Size == 2) &&
1019 "Unsupported size for EmitAtomicBinaryPartial.");
1021 MachineFunction *MF = BB->getParent();
1022 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1023 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1024 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1025 DebugLoc DL = MI->getDebugLoc();
1027 unsigned Dest = MI->getOperand(0).getReg();
1028 unsigned Ptr = MI->getOperand(1).getReg();
1029 unsigned Incr = MI->getOperand(2).getReg();
1031 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1032 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1033 unsigned Mask = RegInfo.createVirtualRegister(RC);
1034 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1035 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1036 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1037 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1038 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1039 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1040 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1041 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1042 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1043 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1044 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1045 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1046 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1047 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1048 unsigned Success = RegInfo.createVirtualRegister(RC);
1050 // insert new blocks after the current block
1051 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1052 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1053 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1054 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1055 MachineFunction::iterator It = BB;
1057 MF->insert(It, loopMBB);
1058 MF->insert(It, sinkMBB);
1059 MF->insert(It, exitMBB);
1061 // Transfer the remainder of BB and its successor edges to exitMBB.
1062 exitMBB->splice(exitMBB->begin(), BB,
1063 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1064 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1066 BB->addSuccessor(loopMBB);
1067 loopMBB->addSuccessor(loopMBB);
1068 loopMBB->addSuccessor(sinkMBB);
1069 sinkMBB->addSuccessor(exitMBB);
1072 // addiu masklsb2,$0,-4 # 0xfffffffc
1073 // and alignedaddr,ptr,masklsb2
1074 // andi ptrlsb2,ptr,3
1075 // sll shiftamt,ptrlsb2,3
1076 // ori maskupper,$0,255 # 0xff
1077 // sll mask,maskupper,shiftamt
1078 // nor mask2,$0,mask
1079 // sll incr2,incr,shiftamt
1081 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1082 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1083 .addReg(Mips::ZERO).addImm(-4);
1084 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1085 .addReg(Ptr).addReg(MaskLSB2);
1086 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1087 if (Subtarget->isLittle()) {
1088 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1090 unsigned Off = RegInfo.createVirtualRegister(RC);
1091 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1092 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1093 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1095 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1096 .addReg(Mips::ZERO).addImm(MaskImm);
1097 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1098 .addReg(MaskUpper).addReg(ShiftAmt);
1099 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1100 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1102 // atomic.load.binop
1104 // ll oldval,0(alignedaddr)
1105 // binop binopres,oldval,incr2
1106 // and newval,binopres,mask
1107 // and maskedoldval0,oldval,mask2
1108 // or storeval,maskedoldval0,newval
1109 // sc success,storeval,0(alignedaddr)
1110 // beq success,$0,loopMBB
1114 // ll oldval,0(alignedaddr)
1115 // and newval,incr2,mask
1116 // and maskedoldval0,oldval,mask2
1117 // or storeval,maskedoldval0,newval
1118 // sc success,storeval,0(alignedaddr)
1119 // beq success,$0,loopMBB
1122 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1124 // and andres, oldval, incr2
1125 // nor binopres, $0, andres
1126 // and newval, binopres, mask
1127 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1128 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1129 .addReg(Mips::ZERO).addReg(AndRes);
1130 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1131 } else if (BinOpcode) {
1132 // <binop> binopres, oldval, incr2
1133 // and newval, binopres, mask
1134 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1135 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1136 } else { // atomic.swap
1137 // and newval, incr2, mask
1138 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1141 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1142 .addReg(OldVal).addReg(Mask2);
1143 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1144 .addReg(MaskedOldVal0).addReg(NewVal);
1145 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1146 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1147 BuildMI(BB, DL, TII->get(Mips::BEQ))
1148 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1151 // and maskedoldval1,oldval,mask
1152 // srl srlres,maskedoldval1,shiftamt
1153 // sll sllres,srlres,24
1154 // sra dest,sllres,24
1156 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1158 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1159 .addReg(OldVal).addReg(Mask);
1160 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1161 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1162 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1163 .addReg(SrlRes).addImm(ShiftImm);
1164 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1165 .addReg(SllRes).addImm(ShiftImm);
1167 MI->eraseFromParent(); // The instruction is gone now.
1172 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1173 MachineBasicBlock *BB,
1174 unsigned Size) const {
1175 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1177 MachineFunction *MF = BB->getParent();
1178 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1179 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1180 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1181 DebugLoc DL = MI->getDebugLoc();
1182 unsigned LL, SC, ZERO, BNE, BEQ;
1185 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1186 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1193 ZERO = Mips::ZERO_64;
1198 unsigned Dest = MI->getOperand(0).getReg();
1199 unsigned Ptr = MI->getOperand(1).getReg();
1200 unsigned OldVal = MI->getOperand(2).getReg();
1201 unsigned NewVal = MI->getOperand(3).getReg();
1203 unsigned Success = RegInfo.createVirtualRegister(RC);
1205 // insert new blocks after the current block
1206 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1207 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1208 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1209 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1210 MachineFunction::iterator It = BB;
1212 MF->insert(It, loop1MBB);
1213 MF->insert(It, loop2MBB);
1214 MF->insert(It, exitMBB);
1216 // Transfer the remainder of BB and its successor edges to exitMBB.
1217 exitMBB->splice(exitMBB->begin(), BB,
1218 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1219 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1223 // fallthrough --> loop1MBB
1224 BB->addSuccessor(loop1MBB);
1225 loop1MBB->addSuccessor(exitMBB);
1226 loop1MBB->addSuccessor(loop2MBB);
1227 loop2MBB->addSuccessor(loop1MBB);
1228 loop2MBB->addSuccessor(exitMBB);
1232 // bne dest, oldval, exitMBB
1234 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1235 BuildMI(BB, DL, TII->get(BNE))
1236 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1239 // sc success, newval, 0(ptr)
1240 // beq success, $0, loop1MBB
1242 BuildMI(BB, DL, TII->get(SC), Success)
1243 .addReg(NewVal).addReg(Ptr).addImm(0);
1244 BuildMI(BB, DL, TII->get(BEQ))
1245 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1247 MI->eraseFromParent(); // The instruction is gone now.
1253 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1254 MachineBasicBlock *BB,
1255 unsigned Size) const {
1256 assert((Size == 1 || Size == 2) &&
1257 "Unsupported size for EmitAtomicCmpSwapPartial.");
1259 MachineFunction *MF = BB->getParent();
1260 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1261 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1262 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1263 DebugLoc DL = MI->getDebugLoc();
1265 unsigned Dest = MI->getOperand(0).getReg();
1266 unsigned Ptr = MI->getOperand(1).getReg();
1267 unsigned CmpVal = MI->getOperand(2).getReg();
1268 unsigned NewVal = MI->getOperand(3).getReg();
1270 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1271 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1272 unsigned Mask = RegInfo.createVirtualRegister(RC);
1273 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1274 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1275 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1276 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1277 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1278 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1279 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1280 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1281 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1282 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1283 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1284 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1285 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1286 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1287 unsigned Success = RegInfo.createVirtualRegister(RC);
1289 // insert new blocks after the current block
1290 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1291 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1292 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1293 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1294 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1295 MachineFunction::iterator It = BB;
1297 MF->insert(It, loop1MBB);
1298 MF->insert(It, loop2MBB);
1299 MF->insert(It, sinkMBB);
1300 MF->insert(It, exitMBB);
1302 // Transfer the remainder of BB and its successor edges to exitMBB.
1303 exitMBB->splice(exitMBB->begin(), BB,
1304 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1305 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1307 BB->addSuccessor(loop1MBB);
1308 loop1MBB->addSuccessor(sinkMBB);
1309 loop1MBB->addSuccessor(loop2MBB);
1310 loop2MBB->addSuccessor(loop1MBB);
1311 loop2MBB->addSuccessor(sinkMBB);
1312 sinkMBB->addSuccessor(exitMBB);
1314 // FIXME: computation of newval2 can be moved to loop2MBB.
1316 // addiu masklsb2,$0,-4 # 0xfffffffc
1317 // and alignedaddr,ptr,masklsb2
1318 // andi ptrlsb2,ptr,3
1319 // sll shiftamt,ptrlsb2,3
1320 // ori maskupper,$0,255 # 0xff
1321 // sll mask,maskupper,shiftamt
1322 // nor mask2,$0,mask
1323 // andi maskedcmpval,cmpval,255
1324 // sll shiftedcmpval,maskedcmpval,shiftamt
1325 // andi maskednewval,newval,255
1326 // sll shiftednewval,maskednewval,shiftamt
1327 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1328 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1329 .addReg(Mips::ZERO).addImm(-4);
1330 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1331 .addReg(Ptr).addReg(MaskLSB2);
1332 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1333 if (Subtarget->isLittle()) {
1334 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1336 unsigned Off = RegInfo.createVirtualRegister(RC);
1337 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1338 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1339 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1341 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1342 .addReg(Mips::ZERO).addImm(MaskImm);
1343 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1344 .addReg(MaskUpper).addReg(ShiftAmt);
1345 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1346 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1347 .addReg(CmpVal).addImm(MaskImm);
1348 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1349 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1350 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1351 .addReg(NewVal).addImm(MaskImm);
1352 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1353 .addReg(MaskedNewVal).addReg(ShiftAmt);
1356 // ll oldval,0(alginedaddr)
1357 // and maskedoldval0,oldval,mask
1358 // bne maskedoldval0,shiftedcmpval,sinkMBB
1360 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1361 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1362 .addReg(OldVal).addReg(Mask);
1363 BuildMI(BB, DL, TII->get(Mips::BNE))
1364 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1367 // and maskedoldval1,oldval,mask2
1368 // or storeval,maskedoldval1,shiftednewval
1369 // sc success,storeval,0(alignedaddr)
1370 // beq success,$0,loop1MBB
1372 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1373 .addReg(OldVal).addReg(Mask2);
1374 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1375 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1376 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1377 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1378 BuildMI(BB, DL, TII->get(Mips::BEQ))
1379 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1382 // srl srlres,maskedoldval0,shiftamt
1383 // sll sllres,srlres,24
1384 // sra dest,sllres,24
1386 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1388 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1389 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1390 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1391 .addReg(SrlRes).addImm(ShiftImm);
1392 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1393 .addReg(SllRes).addImm(ShiftImm);
1395 MI->eraseFromParent(); // The instruction is gone now.
1400 //===----------------------------------------------------------------------===//
1401 // Misc Lower Operation implementation
1402 //===----------------------------------------------------------------------===//
1403 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1404 SDValue Chain = Op.getOperand(0);
1405 SDValue Table = Op.getOperand(1);
1406 SDValue Index = Op.getOperand(2);
1408 EVT PTy = getPointerTy();
1409 unsigned EntrySize =
1410 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1412 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1413 DAG.getConstant(EntrySize, PTy));
1414 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1416 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1417 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1418 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1420 Chain = Addr.getValue(1);
1422 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || isN64()) {
1423 // For PIC, the sequence is:
1424 // BRIND(load(Jumptable + index) + RelocBase)
1425 // RelocBase can be JumpTable, GOT or some sort of global base.
1426 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1427 getPICJumpTableRelocBase(Table, DAG));
1430 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1433 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1434 // The first operand is the chain, the second is the condition, the third is
1435 // the block to branch to if the condition is true.
1436 SDValue Chain = Op.getOperand(0);
1437 SDValue Dest = Op.getOperand(2);
1440 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1442 // Return if flag is not set by a floating point comparison.
1443 if (CondRes.getOpcode() != MipsISD::FPCmp)
1446 SDValue CCNode = CondRes.getOperand(2);
1448 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1449 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1450 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1451 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1452 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1453 FCC0, Dest, CondRes);
1456 SDValue MipsTargetLowering::
1457 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1459 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1461 // Return if flag is not set by a floating point comparison.
1462 if (Cond.getOpcode() != MipsISD::FPCmp)
1465 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1469 SDValue MipsTargetLowering::
1470 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1473 EVT Ty = Op.getOperand(0).getValueType();
1474 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1475 getSetCCResultType(*DAG.getContext(), Ty),
1476 Op.getOperand(0), Op.getOperand(1),
1479 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1483 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1484 SDValue Cond = createFPCmp(DAG, Op);
1486 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1487 "Floating point operand expected.");
1489 SDValue True = DAG.getConstant(1, MVT::i32);
1490 SDValue False = DAG.getConstant(0, MVT::i32);
1492 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1495 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1496 SelectionDAG &DAG) const {
1497 // FIXME there isn't actually debug info here
1499 EVT Ty = Op.getValueType();
1500 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1501 const GlobalValue *GV = N->getGlobal();
1503 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64()) {
1504 const MipsTargetObjectFile &TLOF =
1505 (const MipsTargetObjectFile&)getObjFileLowering();
1507 // %gp_rel relocation
1508 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1509 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1511 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1512 DAG.getVTList(MVT::i32), &GA, 1);
1513 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1514 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1517 // %hi/%lo relocation
1518 return getAddrNonPIC(N, Ty, DAG);
1521 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1522 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1525 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1526 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1527 MachinePointerInfo::getGOT());
1529 return getAddrGlobal(N, Ty, DAG, (isN32() || isN64()) ? MipsII::MO_GOT_DISP
1531 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1534 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1535 SelectionDAG &DAG) const {
1536 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1537 EVT Ty = Op.getValueType();
1539 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1540 return getAddrNonPIC(N, Ty, DAG);
1542 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1545 SDValue MipsTargetLowering::
1546 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1548 // If the relocation model is PIC, use the General Dynamic TLS Model or
1549 // Local Dynamic TLS model, otherwise use the Initial Exec or
1550 // Local Exec TLS Model.
1552 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1554 const GlobalValue *GV = GA->getGlobal();
1555 EVT PtrVT = getPointerTy();
1557 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1559 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1560 // General Dynamic and Local Dynamic TLS Model.
1561 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1564 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1565 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1566 getGlobalReg(DAG, PtrVT), TGA);
1567 unsigned PtrSize = PtrVT.getSizeInBits();
1568 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1570 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1574 Entry.Node = Argument;
1576 Args.push_back(Entry);
1578 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1579 false, false, false, false, 0, CallingConv::C,
1580 /*IsTailCall=*/false, /*doesNotRet=*/false,
1581 /*isReturnValueUsed=*/true,
1582 TlsGetAddr, Args, DAG, DL);
1583 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1585 SDValue Ret = CallResult.first;
1587 if (model != TLSModel::LocalDynamic)
1590 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1591 MipsII::MO_DTPREL_HI);
1592 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1593 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1594 MipsII::MO_DTPREL_LO);
1595 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1596 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1597 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1601 if (model == TLSModel::InitialExec) {
1602 // Initial Exec TLS Model
1603 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1604 MipsII::MO_GOTTPREL);
1605 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1607 Offset = DAG.getLoad(PtrVT, DL,
1608 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1609 false, false, false, 0);
1611 // Local Exec TLS Model
1612 assert(model == TLSModel::LocalExec);
1613 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1614 MipsII::MO_TPREL_HI);
1615 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1616 MipsII::MO_TPREL_LO);
1617 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1618 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1619 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1622 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1623 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1626 SDValue MipsTargetLowering::
1627 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1629 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1630 EVT Ty = Op.getValueType();
1632 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1633 return getAddrNonPIC(N, Ty, DAG);
1635 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1638 SDValue MipsTargetLowering::
1639 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1641 // gp_rel relocation
1642 // FIXME: we should reference the constant pool using small data sections,
1643 // but the asm printer currently doesn't support this feature without
1644 // hacking it. This feature should come soon so we can uncomment the
1646 //if (IsInSmallSection(C->getType())) {
1647 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1648 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1649 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1650 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1651 EVT Ty = Op.getValueType();
1653 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1654 return getAddrNonPIC(N, Ty, DAG);
1656 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1659 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1660 MachineFunction &MF = DAG.getMachineFunction();
1661 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1664 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1667 // vastart just stores the address of the VarArgsFrameIndex slot into the
1668 // memory location argument.
1669 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1670 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1671 MachinePointerInfo(SV), false, false, 0);
1674 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1675 bool HasExtractInsert) {
1676 EVT TyX = Op.getOperand(0).getValueType();
1677 EVT TyY = Op.getOperand(1).getValueType();
1678 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1679 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1683 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1685 SDValue X = (TyX == MVT::f32) ?
1686 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1687 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1689 SDValue Y = (TyY == MVT::f32) ?
1690 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1691 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1694 if (HasExtractInsert) {
1695 // ext E, Y, 31, 1 ; extract bit31 of Y
1696 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1697 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1698 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1701 // srl SrlX, SllX, 1
1703 // sll SllY, SrlX, 31
1704 // or Or, SrlX, SllY
1705 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1706 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1707 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1708 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1709 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1712 if (TyX == MVT::f32)
1713 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1715 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1716 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1717 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1720 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1721 bool HasExtractInsert) {
1722 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1723 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1724 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1725 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1728 // Bitcast to integer nodes.
1729 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1730 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1732 if (HasExtractInsert) {
1733 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1734 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1735 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1736 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1738 if (WidthX > WidthY)
1739 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1740 else if (WidthY > WidthX)
1741 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1743 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1744 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1745 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1748 // (d)sll SllX, X, 1
1749 // (d)srl SrlX, SllX, 1
1750 // (d)srl SrlY, Y, width(Y)-1
1751 // (d)sll SllY, SrlX, width(Y)-1
1752 // or Or, SrlX, SllY
1753 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1754 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1755 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1756 DAG.getConstant(WidthY - 1, MVT::i32));
1758 if (WidthX > WidthY)
1759 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1760 else if (WidthY > WidthX)
1761 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1763 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1764 DAG.getConstant(WidthX - 1, MVT::i32));
1765 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1766 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1770 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1771 if (Subtarget->isGP64bit())
1772 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1774 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1777 SDValue MipsTargetLowering::
1778 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1780 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1781 "Frame address can only be determined for current frame.");
1783 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1784 MFI->setFrameAddressIsTaken(true);
1785 EVT VT = Op.getValueType();
1787 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1788 isN64() ? Mips::FP_64 : Mips::FP, VT);
1792 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1793 SelectionDAG &DAG) const {
1794 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1798 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1799 "Return address can be determined only for current frame.");
1801 MachineFunction &MF = DAG.getMachineFunction();
1802 MachineFrameInfo *MFI = MF.getFrameInfo();
1803 MVT VT = Op.getSimpleValueType();
1804 unsigned RA = isN64() ? Mips::RA_64 : Mips::RA;
1805 MFI->setReturnAddressIsTaken(true);
1807 // Return RA, which contains the return address. Mark it an implicit live-in.
1808 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1809 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1812 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1813 // generated from __builtin_eh_return (offset, handler)
1814 // The effect of this is to adjust the stack pointer by "offset"
1815 // and then branch to "handler".
1816 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1818 MachineFunction &MF = DAG.getMachineFunction();
1819 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1821 MipsFI->setCallsEhReturn();
1822 SDValue Chain = Op.getOperand(0);
1823 SDValue Offset = Op.getOperand(1);
1824 SDValue Handler = Op.getOperand(2);
1826 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
1828 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1829 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1830 unsigned OffsetReg = isN64() ? Mips::V1_64 : Mips::V1;
1831 unsigned AddrReg = isN64() ? Mips::V0_64 : Mips::V0;
1832 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1833 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1834 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1835 DAG.getRegister(OffsetReg, Ty),
1836 DAG.getRegister(AddrReg, getPointerTy()),
1840 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1841 SelectionDAG &DAG) const {
1842 // FIXME: Need pseudo-fence for 'singlethread' fences
1843 // FIXME: Set SType for weaker fences where supported/appropriate.
1846 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1847 DAG.getConstant(SType, MVT::i32));
1850 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1851 SelectionDAG &DAG) const {
1853 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1854 SDValue Shamt = Op.getOperand(2);
1857 // lo = (shl lo, shamt)
1858 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1861 // hi = (shl lo, shamt[4:0])
1862 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1863 DAG.getConstant(-1, MVT::i32));
1864 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1865 DAG.getConstant(1, MVT::i32));
1866 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1868 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1869 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1870 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1871 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1872 DAG.getConstant(0x20, MVT::i32));
1873 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1874 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1875 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1877 SDValue Ops[2] = {Lo, Hi};
1878 return DAG.getMergeValues(Ops, 2, DL);
1881 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1884 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1885 SDValue Shamt = Op.getOperand(2);
1888 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1890 // hi = (sra hi, shamt)
1892 // hi = (srl hi, shamt)
1895 // lo = (sra hi, shamt[4:0])
1896 // hi = (sra hi, 31)
1898 // lo = (srl hi, shamt[4:0])
1900 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1901 DAG.getConstant(-1, MVT::i32));
1902 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1903 DAG.getConstant(1, MVT::i32));
1904 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1905 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1906 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1907 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1909 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1910 DAG.getConstant(0x20, MVT::i32));
1911 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1912 DAG.getConstant(31, MVT::i32));
1913 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1914 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1915 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1918 SDValue Ops[2] = {Lo, Hi};
1919 return DAG.getMergeValues(Ops, 2, DL);
1922 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1923 SDValue Chain, SDValue Src, unsigned Offset) {
1924 SDValue Ptr = LD->getBasePtr();
1925 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1926 EVT BasePtrVT = Ptr.getValueType();
1928 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1931 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1932 DAG.getConstant(Offset, BasePtrVT));
1934 SDValue Ops[] = { Chain, Ptr, Src };
1935 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1936 LD->getMemOperand());
1939 // Expand an unaligned 32 or 64-bit integer load node.
1940 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1941 LoadSDNode *LD = cast<LoadSDNode>(Op);
1942 EVT MemVT = LD->getMemoryVT();
1944 // Return if load is aligned or if MemVT is neither i32 nor i64.
1945 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1946 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1949 bool IsLittle = Subtarget->isLittle();
1950 EVT VT = Op.getValueType();
1951 ISD::LoadExtType ExtType = LD->getExtensionType();
1952 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1954 assert((VT == MVT::i32) || (VT == MVT::i64));
1957 // (set dst, (i64 (load baseptr)))
1959 // (set tmp, (ldl (add baseptr, 7), undef))
1960 // (set dst, (ldr baseptr, tmp))
1961 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1962 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1964 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1968 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1970 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1974 // (set dst, (i32 (load baseptr))) or
1975 // (set dst, (i64 (sextload baseptr))) or
1976 // (set dst, (i64 (extload baseptr)))
1978 // (set tmp, (lwl (add baseptr, 3), undef))
1979 // (set dst, (lwr baseptr, tmp))
1980 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1981 (ExtType == ISD::EXTLOAD))
1984 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1987 // (set dst, (i64 (zextload baseptr)))
1989 // (set tmp0, (lwl (add baseptr, 3), undef))
1990 // (set tmp1, (lwr baseptr, tmp0))
1991 // (set tmp2, (shl tmp1, 32))
1992 // (set dst, (srl tmp2, 32))
1994 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1995 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1996 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1997 SDValue Ops[] = { SRL, LWR.getValue(1) };
1998 return DAG.getMergeValues(Ops, 2, DL);
2001 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2002 SDValue Chain, unsigned Offset) {
2003 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2004 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2006 SDVTList VTList = DAG.getVTList(MVT::Other);
2009 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2010 DAG.getConstant(Offset, BasePtrVT));
2012 SDValue Ops[] = { Chain, Value, Ptr };
2013 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2014 SD->getMemOperand());
2017 // Expand an unaligned 32 or 64-bit integer store node.
2018 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2020 SDValue Value = SD->getValue(), Chain = SD->getChain();
2021 EVT VT = Value.getValueType();
2024 // (store val, baseptr) or
2025 // (truncstore val, baseptr)
2027 // (swl val, (add baseptr, 3))
2028 // (swr val, baseptr)
2029 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2030 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2032 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2035 assert(VT == MVT::i64);
2038 // (store val, baseptr)
2040 // (sdl val, (add baseptr, 7))
2041 // (sdr val, baseptr)
2042 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2043 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2046 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2047 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2048 SDValue Val = SD->getValue();
2050 if (Val.getOpcode() != ISD::FP_TO_SINT)
2053 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2054 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2057 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2058 SD->getPointerInfo(), SD->isVolatile(),
2059 SD->isNonTemporal(), SD->getAlignment());
2062 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2063 StoreSDNode *SD = cast<StoreSDNode>(Op);
2064 EVT MemVT = SD->getMemoryVT();
2066 // Lower unaligned integer stores.
2067 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2068 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2069 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2071 return lowerFP_TO_SINT_STORE(SD, DAG);
2074 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2075 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2076 || cast<ConstantSDNode>
2077 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2078 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2082 // (add (frameaddr 0), (frame_to_args_offset))
2083 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2084 // (add FrameObject, 0)
2085 // where FrameObject is a fixed StackObject with offset 0 which points to
2086 // the old stack pointer.
2087 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2088 EVT ValTy = Op->getValueType(0);
2089 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2090 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2091 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2092 DAG.getConstant(0, ValTy));
2095 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2096 SelectionDAG &DAG) const {
2097 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2098 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2100 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2103 //===----------------------------------------------------------------------===//
2104 // Calling Convention Implementation
2105 //===----------------------------------------------------------------------===//
2107 //===----------------------------------------------------------------------===//
2108 // TODO: Implement a generic logic using tblgen that can support this.
2109 // Mips O32 ABI rules:
2111 // i32 - Passed in A0, A1, A2, A3 and stack
2112 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2113 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2114 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2115 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2116 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2119 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2120 //===----------------------------------------------------------------------===//
2122 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2123 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2124 CCState &State, const MCPhysReg *F64Regs) {
2126 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2128 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2129 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2131 // Do not process byval args here.
2132 if (ArgFlags.isByVal())
2135 // Promote i8 and i16
2136 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2138 if (ArgFlags.isSExt())
2139 LocInfo = CCValAssign::SExt;
2140 else if (ArgFlags.isZExt())
2141 LocInfo = CCValAssign::ZExt;
2143 LocInfo = CCValAssign::AExt;
2148 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2149 // is true: function is vararg, argument is 3rd or higher, there is previous
2150 // argument which is not f32 or f64.
2151 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2152 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2153 unsigned OrigAlign = ArgFlags.getOrigAlign();
2154 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2156 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2157 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2158 // If this is the first part of an i64 arg,
2159 // the allocated register must be either A0 or A2.
2160 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2161 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2163 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2164 // Allocate int register and shadow next int register. If first
2165 // available register is Mips::A1 or Mips::A3, shadow it too.
2166 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2167 if (Reg == Mips::A1 || Reg == Mips::A3)
2168 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2169 State.AllocateReg(IntRegs, IntRegsSize);
2171 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2172 // we are guaranteed to find an available float register
2173 if (ValVT == MVT::f32) {
2174 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2175 // Shadow int register
2176 State.AllocateReg(IntRegs, IntRegsSize);
2178 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2179 // Shadow int registers
2180 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2181 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2182 State.AllocateReg(IntRegs, IntRegsSize);
2183 State.AllocateReg(IntRegs, IntRegsSize);
2186 llvm_unreachable("Cannot handle this ValVT.");
2189 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2191 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2193 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2198 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2199 MVT LocVT, CCValAssign::LocInfo LocInfo,
2200 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2201 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2203 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2206 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2207 MVT LocVT, CCValAssign::LocInfo LocInfo,
2208 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2209 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2211 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2214 #include "MipsGenCallingConv.inc"
2216 //===----------------------------------------------------------------------===//
2217 // Call Calling Convention Implementation
2218 //===----------------------------------------------------------------------===//
2220 // Return next O32 integer argument register.
2221 static unsigned getNextIntArgReg(unsigned Reg) {
2222 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2223 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2227 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2228 SDValue Chain, SDValue Arg, SDLoc DL,
2229 bool IsTailCall, SelectionDAG &DAG) const {
2231 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2232 DAG.getIntPtrConstant(Offset));
2233 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2237 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2238 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2239 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2240 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2241 /*isVolatile=*/ true, false, 0);
2244 void MipsTargetLowering::
2245 getOpndList(SmallVectorImpl<SDValue> &Ops,
2246 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2247 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2248 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2249 // Insert node "GP copy globalreg" before call to function.
2251 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2252 // in PIC mode) allow symbols to be resolved via lazy binding.
2253 // The lazy binding stub requires GP to point to the GOT.
2254 if (IsPICCall && !InternalLinkage) {
2255 unsigned GPReg = isN64() ? Mips::GP_64 : Mips::GP;
2256 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
2257 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2260 // Build a sequence of copy-to-reg nodes chained together with token
2261 // chain and flag operands which copy the outgoing args into registers.
2262 // The InFlag in necessary since all emitted instructions must be
2266 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2267 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2268 RegsToPass[i].second, InFlag);
2269 InFlag = Chain.getValue(1);
2272 // Add argument registers to the end of the list so that they are
2273 // known live into the call.
2274 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2275 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2276 RegsToPass[i].second.getValueType()));
2278 // Add a register mask operand representing the call-preserved registers.
2279 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2280 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2281 assert(Mask && "Missing call preserved mask for calling convention");
2282 if (Subtarget->inMips16HardFloat()) {
2283 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2284 llvm::StringRef Sym = G->getGlobal()->getName();
2285 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2286 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2287 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2291 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2293 if (InFlag.getNode())
2294 Ops.push_back(InFlag);
2297 /// LowerCall - functions arguments are copied from virtual regs to
2298 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2300 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2301 SmallVectorImpl<SDValue> &InVals) const {
2302 SelectionDAG &DAG = CLI.DAG;
2304 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2305 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2306 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2307 SDValue Chain = CLI.Chain;
2308 SDValue Callee = CLI.Callee;
2309 bool &IsTailCall = CLI.IsTailCall;
2310 CallingConv::ID CallConv = CLI.CallConv;
2311 bool IsVarArg = CLI.IsVarArg;
2313 MachineFunction &MF = DAG.getMachineFunction();
2314 MachineFrameInfo *MFI = MF.getFrameInfo();
2315 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2316 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2317 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2319 // Analyze operands of the call, assigning locations to each operand.
2320 SmallVector<CCValAssign, 16> ArgLocs;
2321 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2322 getTargetMachine(), ArgLocs, *DAG.getContext());
2323 MipsCC::SpecialCallingConvType SpecialCallingConv =
2324 getSpecialCallingConv(Callee);
2325 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo,
2326 SpecialCallingConv);
2328 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2329 Subtarget->mipsSEUsesSoftFloat(),
2330 Callee.getNode(), CLI.Args);
2332 // Get a count of how many bytes are to be pushed on the stack.
2333 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2335 // Check if it's really possible to do a tail call.
2338 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2339 *MF.getInfo<MipsFunctionInfo>());
2344 // Chain is the output chain of the last Load/Store or CopyToReg node.
2345 // ByValChain is the output chain of the last Memcpy node created for copying
2346 // byval arguments to the stack.
2347 unsigned StackAlignment = TFL->getStackAlignment();
2348 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2349 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2352 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2354 SDValue StackPtr = DAG.getCopyFromReg(
2355 Chain, DL, isN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2357 // With EABI is it possible to have 16 args on registers.
2358 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2359 SmallVector<SDValue, 8> MemOpChains;
2360 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2362 // Walk the register/memloc assignments, inserting copies/loads.
2363 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2364 SDValue Arg = OutVals[i];
2365 CCValAssign &VA = ArgLocs[i];
2366 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2367 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2370 if (Flags.isByVal()) {
2371 assert(Flags.getByValSize() &&
2372 "ByVal args of size 0 should have been ignored by front-end.");
2373 assert(ByValArg != MipsCCInfo.byval_end());
2374 assert(!IsTailCall &&
2375 "Do not tail-call optimize if there is a byval argument.");
2376 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2377 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2382 // Promote the value if needed.
2383 switch (VA.getLocInfo()) {
2384 default: llvm_unreachable("Unknown loc info!");
2385 case CCValAssign::Full:
2386 if (VA.isRegLoc()) {
2387 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2388 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2389 (ValVT == MVT::i64 && LocVT == MVT::f64))
2390 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2391 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2392 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2393 Arg, DAG.getConstant(0, MVT::i32));
2394 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2395 Arg, DAG.getConstant(1, MVT::i32));
2396 if (!Subtarget->isLittle())
2398 unsigned LocRegLo = VA.getLocReg();
2399 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2400 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2401 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2406 case CCValAssign::SExt:
2407 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2409 case CCValAssign::ZExt:
2410 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2412 case CCValAssign::AExt:
2413 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2417 // Arguments that can be passed on register must be kept at
2418 // RegsToPass vector
2419 if (VA.isRegLoc()) {
2420 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2424 // Register can't get to this point...
2425 assert(VA.isMemLoc());
2427 // emit ISD::STORE whichs stores the
2428 // parameter value to a stack Location
2429 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2430 Chain, Arg, DL, IsTailCall, DAG));
2433 // Transform all store nodes into one single node because all store
2434 // nodes are independent of each other.
2435 if (!MemOpChains.empty())
2436 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2437 &MemOpChains[0], MemOpChains.size());
2439 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2440 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2441 // node so that legalize doesn't hack it.
2442 bool IsPICCall = (isN64() || IsPIC); // true if calls are translated to
2444 bool GlobalOrExternal = false, InternalLinkage = false;
2446 EVT Ty = Callee.getValueType();
2448 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2450 const GlobalValue *Val = G->getGlobal();
2451 InternalLinkage = Val->hasInternalLinkage();
2453 if (InternalLinkage)
2454 Callee = getAddrLocal(G, Ty, DAG, isN32() || isN64());
2456 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2457 MipsII::MO_CALL_LO16, Chain,
2458 FuncInfo->callPtrInfo(Val));
2460 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2461 FuncInfo->callPtrInfo(Val));
2463 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2464 MipsII::MO_NO_FLAG);
2465 GlobalOrExternal = true;
2467 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2468 const char *Sym = S->getSymbol();
2470 if (!isN64() && !IsPIC) // !N64 && static
2471 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2472 MipsII::MO_NO_FLAG);
2474 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2475 MipsII::MO_CALL_LO16, Chain,
2476 FuncInfo->callPtrInfo(Sym));
2478 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2479 FuncInfo->callPtrInfo(Sym));
2481 GlobalOrExternal = true;
2484 SmallVector<SDValue, 8> Ops(1, Chain);
2485 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2487 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2488 CLI, Callee, Chain);
2491 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2493 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2494 SDValue InFlag = Chain.getValue(1);
2496 // Create the CALLSEQ_END node.
2497 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2498 DAG.getIntPtrConstant(0, true), InFlag, DL);
2499 InFlag = Chain.getValue(1);
2501 // Handle result values, copying them out of physregs into vregs that we
2503 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2504 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2507 /// LowerCallResult - Lower the result values of a call into the
2508 /// appropriate copies out of appropriate physical registers.
2510 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2511 CallingConv::ID CallConv, bool IsVarArg,
2512 const SmallVectorImpl<ISD::InputArg> &Ins,
2513 SDLoc DL, SelectionDAG &DAG,
2514 SmallVectorImpl<SDValue> &InVals,
2515 const SDNode *CallNode,
2516 const Type *RetTy) const {
2517 // Assign locations to each value returned by this call.
2518 SmallVector<CCValAssign, 16> RVLocs;
2519 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2520 getTargetMachine(), RVLocs, *DAG.getContext());
2521 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2523 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2526 // Copy all of the result registers out of their specified physreg.
2527 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2528 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2529 RVLocs[i].getLocVT(), InFlag);
2530 Chain = Val.getValue(1);
2531 InFlag = Val.getValue(2);
2533 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2534 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2536 InVals.push_back(Val);
2542 //===----------------------------------------------------------------------===//
2543 // Formal Arguments Calling Convention Implementation
2544 //===----------------------------------------------------------------------===//
2545 /// LowerFormalArguments - transform physical registers into virtual registers
2546 /// and generate load operations for arguments places on the stack.
2548 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2549 CallingConv::ID CallConv,
2551 const SmallVectorImpl<ISD::InputArg> &Ins,
2552 SDLoc DL, SelectionDAG &DAG,
2553 SmallVectorImpl<SDValue> &InVals)
2555 MachineFunction &MF = DAG.getMachineFunction();
2556 MachineFrameInfo *MFI = MF.getFrameInfo();
2557 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2559 MipsFI->setVarArgsFrameIndex(0);
2561 // Used with vargs to acumulate store chains.
2562 std::vector<SDValue> OutChains;
2564 // Assign locations to all of the incoming arguments.
2565 SmallVector<CCValAssign, 16> ArgLocs;
2566 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2567 getTargetMachine(), ArgLocs, *DAG.getContext());
2568 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2569 Function::const_arg_iterator FuncArg =
2570 DAG.getMachineFunction().getFunction()->arg_begin();
2571 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2573 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2574 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2575 MipsCCInfo.hasByValArg());
2577 unsigned CurArgIdx = 0;
2578 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2580 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2581 CCValAssign &VA = ArgLocs[i];
2582 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2583 CurArgIdx = Ins[i].OrigArgIndex;
2584 EVT ValVT = VA.getValVT();
2585 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2586 bool IsRegLoc = VA.isRegLoc();
2588 if (Flags.isByVal()) {
2589 assert(Flags.getByValSize() &&
2590 "ByVal args of size 0 should have been ignored by front-end.");
2591 assert(ByValArg != MipsCCInfo.byval_end());
2592 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2593 MipsCCInfo, *ByValArg);
2598 // Arguments stored on registers
2600 MVT RegVT = VA.getLocVT();
2601 unsigned ArgReg = VA.getLocReg();
2602 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2604 // Transform the arguments stored on
2605 // physical registers into virtual ones
2606 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2607 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2609 // If this is an 8 or 16-bit value, it has been passed promoted
2610 // to 32 bits. Insert an assert[sz]ext to capture this, then
2611 // truncate to the right size.
2612 if (VA.getLocInfo() != CCValAssign::Full) {
2613 unsigned Opcode = 0;
2614 if (VA.getLocInfo() == CCValAssign::SExt)
2615 Opcode = ISD::AssertSext;
2616 else if (VA.getLocInfo() == CCValAssign::ZExt)
2617 Opcode = ISD::AssertZext;
2619 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2620 DAG.getValueType(ValVT));
2621 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2624 // Handle floating point arguments passed in integer registers and
2625 // long double arguments passed in floating point registers.
2626 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2627 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2628 (RegVT == MVT::f64 && ValVT == MVT::i64))
2629 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2630 else if (isO32() && RegVT == MVT::i32 && ValVT == MVT::f64) {
2631 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2632 getNextIntArgReg(ArgReg), RC);
2633 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2634 if (!Subtarget->isLittle())
2635 std::swap(ArgValue, ArgValue2);
2636 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2637 ArgValue, ArgValue2);
2640 InVals.push_back(ArgValue);
2641 } else { // VA.isRegLoc()
2644 assert(VA.isMemLoc());
2646 // The stack pointer offset is relative to the caller stack frame.
2647 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2648 VA.getLocMemOffset(), true);
2650 // Create load nodes to retrieve arguments from the stack
2651 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2652 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2653 MachinePointerInfo::getFixedStack(FI),
2654 false, false, false, 0);
2655 InVals.push_back(Load);
2656 OutChains.push_back(Load.getValue(1));
2660 // The mips ABIs for returning structs by value requires that we copy
2661 // the sret argument into $v0 for the return. Save the argument into
2662 // a virtual register so that we can access it from the return points.
2663 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2664 unsigned Reg = MipsFI->getSRetReturnReg();
2666 Reg = MF.getRegInfo().createVirtualRegister(
2667 getRegClassFor(isN64() ? MVT::i64 : MVT::i32));
2668 MipsFI->setSRetReturnReg(Reg);
2670 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2671 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2675 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2677 // All stores are grouped in one node to allow the matching between
2678 // the size of Ins and InVals. This only happens when on varg functions
2679 if (!OutChains.empty()) {
2680 OutChains.push_back(Chain);
2681 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2682 &OutChains[0], OutChains.size());
2688 //===----------------------------------------------------------------------===//
2689 // Return Value Calling Convention Implementation
2690 //===----------------------------------------------------------------------===//
2693 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2694 MachineFunction &MF, bool IsVarArg,
2695 const SmallVectorImpl<ISD::OutputArg> &Outs,
2696 LLVMContext &Context) const {
2697 SmallVector<CCValAssign, 16> RVLocs;
2698 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2700 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2704 MipsTargetLowering::LowerReturn(SDValue Chain,
2705 CallingConv::ID CallConv, bool IsVarArg,
2706 const SmallVectorImpl<ISD::OutputArg> &Outs,
2707 const SmallVectorImpl<SDValue> &OutVals,
2708 SDLoc DL, SelectionDAG &DAG) const {
2709 // CCValAssign - represent the assignment of
2710 // the return value to a location
2711 SmallVector<CCValAssign, 16> RVLocs;
2712 MachineFunction &MF = DAG.getMachineFunction();
2714 // CCState - Info about the registers and stack slot.
2715 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2717 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2719 // Analyze return values.
2720 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2721 MF.getFunction()->getReturnType());
2724 SmallVector<SDValue, 4> RetOps(1, Chain);
2726 // Copy the result values into the output registers.
2727 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2728 SDValue Val = OutVals[i];
2729 CCValAssign &VA = RVLocs[i];
2730 assert(VA.isRegLoc() && "Can only return in registers!");
2732 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2733 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2735 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2737 // Guarantee that all emitted copies are stuck together with flags.
2738 Flag = Chain.getValue(1);
2739 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2742 // The mips ABIs for returning structs by value requires that we copy
2743 // the sret argument into $v0 for the return. We saved the argument into
2744 // a virtual register in the entry block, so now we copy the value out
2746 if (MF.getFunction()->hasStructRetAttr()) {
2747 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2748 unsigned Reg = MipsFI->getSRetReturnReg();
2751 llvm_unreachable("sret virtual register not created in the entry block");
2752 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2753 unsigned V0 = isN64() ? Mips::V0_64 : Mips::V0;
2755 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2756 Flag = Chain.getValue(1);
2757 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2760 RetOps[0] = Chain; // Update chain.
2762 // Add the flag if we have it.
2764 RetOps.push_back(Flag);
2766 // Return on Mips is always a "jr $ra"
2767 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2770 //===----------------------------------------------------------------------===//
2771 // Mips Inline Assembly Support
2772 //===----------------------------------------------------------------------===//
2774 /// getConstraintType - Given a constraint letter, return the type of
2775 /// constraint it is for this target.
2776 MipsTargetLowering::ConstraintType MipsTargetLowering::
2777 getConstraintType(const std::string &Constraint) const
2779 // Mips specific constraints
2780 // GCC config/mips/constraints.md
2782 // 'd' : An address register. Equivalent to r
2783 // unless generating MIPS16 code.
2784 // 'y' : Equivalent to r; retained for
2785 // backwards compatibility.
2786 // 'c' : A register suitable for use in an indirect
2787 // jump. This will always be $25 for -mabicalls.
2788 // 'l' : The lo register. 1 word storage.
2789 // 'x' : The hilo register pair. Double word storage.
2790 if (Constraint.size() == 1) {
2791 switch (Constraint[0]) {
2799 return C_RegisterClass;
2804 return TargetLowering::getConstraintType(Constraint);
2807 /// Examine constraint type and operand type and determine a weight value.
2808 /// This object must already have been set up with the operand type
2809 /// and the current alternative constraint selected.
2810 TargetLowering::ConstraintWeight
2811 MipsTargetLowering::getSingleConstraintMatchWeight(
2812 AsmOperandInfo &info, const char *constraint) const {
2813 ConstraintWeight weight = CW_Invalid;
2814 Value *CallOperandVal = info.CallOperandVal;
2815 // If we don't have a value, we can't do a match,
2816 // but allow it at the lowest weight.
2817 if (CallOperandVal == NULL)
2819 Type *type = CallOperandVal->getType();
2820 // Look at the constraint type.
2821 switch (*constraint) {
2823 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2827 if (type->isIntegerTy())
2828 weight = CW_Register;
2830 case 'f': // FPU or MSA register
2831 if (Subtarget->hasMSA() && type->isVectorTy() &&
2832 cast<VectorType>(type)->getBitWidth() == 128)
2833 weight = CW_Register;
2834 else if (type->isFloatTy())
2835 weight = CW_Register;
2837 case 'c': // $25 for indirect jumps
2838 case 'l': // lo register
2839 case 'x': // hilo register pair
2840 if (type->isIntegerTy())
2841 weight = CW_SpecificReg;
2843 case 'I': // signed 16 bit immediate
2844 case 'J': // integer zero
2845 case 'K': // unsigned 16 bit immediate
2846 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2847 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2848 case 'O': // signed 15 bit immediate (+- 16383)
2849 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2850 if (isa<ConstantInt>(CallOperandVal))
2851 weight = CW_Constant;
2860 /// This is a helper function to parse a physical register string and split it
2861 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2862 /// that is returned indicates whether parsing was successful. The second flag
2863 /// is true if the numeric part exists.
2864 static std::pair<bool, bool>
2865 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2866 unsigned long long &Reg) {
2867 if (C.front() != '{' || C.back() != '}')
2868 return std::make_pair(false, false);
2870 // Search for the first numeric character.
2871 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2872 I = std::find_if(B, E, std::ptr_fun(isdigit));
2874 Prefix.assign(B, I - B);
2876 // The second flag is set to false if no numeric characters were found.
2878 return std::make_pair(true, false);
2880 // Parse the numeric characters.
2881 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2885 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2886 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2887 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2888 const TargetRegisterClass *RC;
2890 unsigned long long Reg;
2892 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2895 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2897 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2898 // No numeric characters follow "hi" or "lo".
2900 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2902 RC = TRI->getRegClass(Prefix == "hi" ?
2903 Mips::HI32RegClassID : Mips::LO32RegClassID);
2904 return std::make_pair(*(RC->begin()), RC);
2905 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2906 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2908 // No numeric characters follow the name.
2910 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2912 Reg = StringSwitch<unsigned long long>(Prefix)
2913 .Case("$msair", Mips::MSAIR)
2914 .Case("$msacsr", Mips::MSACSR)
2915 .Case("$msaaccess", Mips::MSAAccess)
2916 .Case("$msasave", Mips::MSASave)
2917 .Case("$msamodify", Mips::MSAModify)
2918 .Case("$msarequest", Mips::MSARequest)
2919 .Case("$msamap", Mips::MSAMap)
2920 .Case("$msaunmap", Mips::MSAUnmap)
2924 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2926 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2927 return std::make_pair(Reg, RC);
2931 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2933 if (Prefix == "$f") { // Parse $f0-$f31.
2934 // If the size of FP registers is 64-bit or Reg is an even number, select
2935 // the 64-bit register class. Otherwise, select the 32-bit register class.
2936 if (VT == MVT::Other)
2937 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2939 RC = getRegClassFor(VT);
2941 if (RC == &Mips::AFGR64RegClass) {
2942 assert(Reg % 2 == 0);
2945 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2946 RC = TRI->getRegClass(Mips::FCCRegClassID);
2947 else if (Prefix == "$w") { // Parse $w0-$w31.
2948 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2949 } else { // Parse $0-$31.
2950 assert(Prefix == "$");
2951 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2954 assert(Reg < RC->getNumRegs());
2955 return std::make_pair(*(RC->begin() + Reg), RC);
2958 /// Given a register class constraint, like 'r', if this corresponds directly
2959 /// to an LLVM register class, return a register of 0 and the register class
2961 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2962 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2964 if (Constraint.size() == 1) {
2965 switch (Constraint[0]) {
2966 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2967 case 'y': // Same as 'r'. Exists for compatibility.
2969 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2970 if (Subtarget->inMips16Mode())
2971 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2972 return std::make_pair(0U, &Mips::GPR32RegClass);
2974 if (VT == MVT::i64 && !isGP64bit())
2975 return std::make_pair(0U, &Mips::GPR32RegClass);
2976 if (VT == MVT::i64 && isGP64bit())
2977 return std::make_pair(0U, &Mips::GPR64RegClass);
2978 // This will generate an error message
2979 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2980 case 'f': // FPU or MSA register
2981 if (VT == MVT::v16i8)
2982 return std::make_pair(0U, &Mips::MSA128BRegClass);
2983 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
2984 return std::make_pair(0U, &Mips::MSA128HRegClass);
2985 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2986 return std::make_pair(0U, &Mips::MSA128WRegClass);
2987 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2988 return std::make_pair(0U, &Mips::MSA128DRegClass);
2989 else if (VT == MVT::f32)
2990 return std::make_pair(0U, &Mips::FGR32RegClass);
2991 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2992 if (Subtarget->isFP64bit())
2993 return std::make_pair(0U, &Mips::FGR64RegClass);
2994 return std::make_pair(0U, &Mips::AFGR64RegClass);
2997 case 'c': // register suitable for indirect jump
2999 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3000 assert(VT == MVT::i64 && "Unexpected type.");
3001 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3002 case 'l': // register suitable for indirect jump
3004 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3005 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3006 case 'x': // register suitable for indirect jump
3007 // Fixme: Not triggering the use of both hi and low
3008 // This will generate an error message
3009 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3013 std::pair<unsigned, const TargetRegisterClass *> R;
3014 R = parseRegForInlineAsmConstraint(Constraint, VT);
3019 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3022 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3023 /// vector. If it is invalid, don't add anything to Ops.
3024 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3025 std::string &Constraint,
3026 std::vector<SDValue>&Ops,
3027 SelectionDAG &DAG) const {
3028 SDValue Result(0, 0);
3030 // Only support length 1 constraints for now.
3031 if (Constraint.length() > 1) return;
3033 char ConstraintLetter = Constraint[0];
3034 switch (ConstraintLetter) {
3035 default: break; // This will fall through to the generic implementation
3036 case 'I': // Signed 16 bit constant
3037 // If this fails, the parent routine will give an error
3038 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3039 EVT Type = Op.getValueType();
3040 int64_t Val = C->getSExtValue();
3041 if (isInt<16>(Val)) {
3042 Result = DAG.getTargetConstant(Val, Type);
3047 case 'J': // integer zero
3048 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3049 EVT Type = Op.getValueType();
3050 int64_t Val = C->getZExtValue();
3052 Result = DAG.getTargetConstant(0, Type);
3057 case 'K': // unsigned 16 bit immediate
3058 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3059 EVT Type = Op.getValueType();
3060 uint64_t Val = (uint64_t)C->getZExtValue();
3061 if (isUInt<16>(Val)) {
3062 Result = DAG.getTargetConstant(Val, Type);
3067 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3068 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3069 EVT Type = Op.getValueType();
3070 int64_t Val = C->getSExtValue();
3071 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3072 Result = DAG.getTargetConstant(Val, Type);
3077 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3078 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3079 EVT Type = Op.getValueType();
3080 int64_t Val = C->getSExtValue();
3081 if ((Val >= -65535) && (Val <= -1)) {
3082 Result = DAG.getTargetConstant(Val, Type);
3087 case 'O': // signed 15 bit immediate
3088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3089 EVT Type = Op.getValueType();
3090 int64_t Val = C->getSExtValue();
3091 if ((isInt<15>(Val))) {
3092 Result = DAG.getTargetConstant(Val, Type);
3097 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3098 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3099 EVT Type = Op.getValueType();
3100 int64_t Val = C->getSExtValue();
3101 if ((Val <= 65535) && (Val >= 1)) {
3102 Result = DAG.getTargetConstant(Val, Type);
3109 if (Result.getNode()) {
3110 Ops.push_back(Result);
3114 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3117 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3119 // No global is ever allowed as a base.
3124 case 0: // "r+i" or just "i", depending on HasBaseReg.
3127 if (!AM.HasBaseReg) // allow "r+i".
3129 return false; // disallow "r+r" or "r+r+i".
3138 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3139 // The Mips target isn't yet aware of offsets.
3143 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3145 bool IsMemset, bool ZeroMemset,
3147 MachineFunction &MF) const {
3148 if (Subtarget->hasMips64())
3154 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3155 if (VT != MVT::f32 && VT != MVT::f64)
3157 if (Imm.isNegZero())
3159 return Imm.isZero();
3162 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3164 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3166 return TargetLowering::getJumpTableEncoding();
3169 /// This function returns true if CallSym is a long double emulation routine.
3170 static bool isF128SoftLibCall(const char *CallSym) {
3171 const char *const LibCalls[] =
3172 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3173 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3174 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3175 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3176 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3177 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3178 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3179 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3182 const char *const *End = LibCalls + array_lengthof(LibCalls);
3184 // Check that LibCalls is sorted alphabetically.
3185 MipsTargetLowering::LTStr Comp;
3188 for (const char *const *I = LibCalls; I < End - 1; ++I)
3189 assert(Comp(*I, *(I + 1)));
3192 return std::binary_search(LibCalls, End, CallSym, Comp);
3195 /// This function returns true if Ty is fp128 or i128 which was originally a
3197 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3198 if (Ty->isFP128Ty())
3201 const ExternalSymbolSDNode *ES =
3202 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3204 // If the Ty is i128 and the function being called is a long double emulation
3205 // routine, then the original type is f128.
3206 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3209 MipsTargetLowering::MipsCC::SpecialCallingConvType
3210 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3211 MipsCC::SpecialCallingConvType SpecialCallingConv =
3212 MipsCC::NoSpecialCallingConv;;
3213 if (Subtarget->inMips16HardFloat()) {
3214 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3215 llvm::StringRef Sym = G->getGlobal()->getName();
3216 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3217 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3218 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3222 return SpecialCallingConv;
3225 MipsTargetLowering::MipsCC::MipsCC(
3226 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3227 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3228 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3229 SpecialCallingConv(SpecialCallingConv_){
3230 // Pre-allocate reserved argument area.
3231 CCInfo.AllocateStack(reservedArgArea(), 1);
3235 void MipsTargetLowering::MipsCC::
3236 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3237 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3238 std::vector<ArgListEntry> &FuncArgs) {
3239 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3240 "CallingConv::Fast shouldn't be used for vararg functions.");
3242 unsigned NumOpnds = Args.size();
3243 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3245 for (unsigned I = 0; I != NumOpnds; ++I) {
3246 MVT ArgVT = Args[I].VT;
3247 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3250 if (ArgFlags.isByVal()) {
3251 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3255 if (IsVarArg && !Args[I].IsFixed)
3256 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3258 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3260 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3265 dbgs() << "Call operand #" << I << " has unhandled type "
3266 << EVT(ArgVT).getEVTString();
3268 llvm_unreachable(0);
3273 void MipsTargetLowering::MipsCC::
3274 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3275 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3276 unsigned NumArgs = Args.size();
3277 llvm::CCAssignFn *FixedFn = fixedArgFn();
3278 unsigned CurArgIdx = 0;
3280 for (unsigned I = 0; I != NumArgs; ++I) {
3281 MVT ArgVT = Args[I].VT;
3282 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3283 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3284 CurArgIdx = Args[I].OrigArgIndex;
3286 if (ArgFlags.isByVal()) {
3287 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3291 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3293 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3297 dbgs() << "Formal Arg #" << I << " has unhandled type "
3298 << EVT(ArgVT).getEVTString();
3300 llvm_unreachable(0);
3304 template<typename Ty>
3305 void MipsTargetLowering::MipsCC::
3306 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3307 const SDNode *CallNode, const Type *RetTy) const {
3310 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3311 Fn = RetCC_F128Soft;
3315 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3316 MVT VT = RetVals[I].VT;
3317 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3318 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3320 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3322 dbgs() << "Call result #" << I << " has unhandled type "
3323 << EVT(VT).getEVTString() << '\n';
3325 llvm_unreachable(0);
3330 void MipsTargetLowering::MipsCC::
3331 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3332 const SDNode *CallNode, const Type *RetTy) const {
3333 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3336 void MipsTargetLowering::MipsCC::
3337 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3338 const Type *RetTy) const {
3339 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3342 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3344 CCValAssign::LocInfo LocInfo,
3345 ISD::ArgFlagsTy ArgFlags) {
3346 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3348 struct ByValArgInfo ByVal;
3349 unsigned RegSize = regSize();
3350 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3351 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3354 if (useRegsForByval())
3355 allocateRegs(ByVal, ByValSize, Align);
3357 // Allocate space on caller's stack.
3358 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3360 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3362 ByValArgs.push_back(ByVal);
3365 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3366 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3369 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3370 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3373 const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
3374 return IsO32 ? O32IntRegs : Mips64IntRegs;
3377 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3378 if (CallConv == CallingConv::Fast)
3379 return CC_Mips_FastCC;
3381 if (SpecialCallingConv == Mips16RetHelperConv)
3382 return CC_Mips16RetHelper;
3383 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3386 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3387 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3390 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3391 return IsO32 ? O32IntRegs : Mips64DPRegs;
3394 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3397 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3398 const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3399 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3400 "Byval argument's size and alignment should be a multiple of"
3403 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3405 // If Align > RegSize, the first arg register must be even.
3406 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3407 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3411 // Mark the registers allocated.
3412 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3413 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3414 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3417 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3418 const SDNode *CallNode,
3419 bool IsSoftFloat) const {
3420 if (IsSoftFloat || IsO32)
3423 // Check if the original type was fp128.
3424 if (originalTypeIsF128(OrigTy, CallNode)) {
3425 assert(VT == MVT::i64);
3432 void MipsTargetLowering::
3433 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3434 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3435 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3436 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3437 MachineFunction &MF = DAG.getMachineFunction();
3438 MachineFrameInfo *MFI = MF.getFrameInfo();
3439 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3440 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3444 FrameObjOffset = (int)CC.reservedArgArea() -
3445 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3447 FrameObjOffset = ByVal.Address;
3449 // Create frame object.
3450 EVT PtrTy = getPointerTy();
3451 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3452 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3453 InVals.push_back(FIN);
3458 // Copy arg registers.
3459 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3460 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3462 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3463 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3464 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3465 unsigned Offset = I * CC.regSize();
3466 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3467 DAG.getConstant(Offset, PtrTy));
3468 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3469 StorePtr, MachinePointerInfo(FuncArg, Offset),
3471 OutChains.push_back(Store);
3475 // Copy byVal arg to registers and stack.
3476 void MipsTargetLowering::
3477 passByValArg(SDValue Chain, SDLoc DL,
3478 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3479 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3480 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3481 const MipsCC &CC, const ByValArgInfo &ByVal,
3482 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3483 unsigned ByValSize = Flags.getByValSize();
3484 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3485 unsigned RegSize = CC.regSize();
3486 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3487 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3489 if (ByVal.NumRegs) {
3490 const MCPhysReg *ArgRegs = CC.intArgRegs();
3491 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3494 // Copy words to registers.
3495 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3496 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3497 DAG.getConstant(Offset, PtrTy));
3498 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3499 MachinePointerInfo(), false, false, false,
3501 MemOpChains.push_back(LoadVal.getValue(1));
3502 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3503 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3506 // Return if the struct has been fully copied.
3507 if (ByValSize == Offset)
3510 // Copy the remainder of the byval argument with sub-word loads and shifts.
3511 if (LeftoverBytes) {
3512 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3513 "Size of the remainder should be smaller than RegSize.");
3516 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3517 Offset < ByValSize; LoadSize /= 2) {
3518 unsigned RemSize = ByValSize - Offset;
3520 if (RemSize < LoadSize)
3524 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3525 DAG.getConstant(Offset, PtrTy));
3527 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3528 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3529 false, false, Alignment);
3530 MemOpChains.push_back(LoadVal.getValue(1));
3532 // Shift the loaded value.
3536 Shamt = TotalSizeLoaded;
3538 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3540 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3541 DAG.getConstant(Shamt, MVT::i32));
3544 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3549 TotalSizeLoaded += LoadSize;
3550 Alignment = std::min(Alignment, LoadSize);
3553 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3554 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3559 // Copy remainder of byval arg to it with memcpy.
3560 unsigned MemCpySize = ByValSize - Offset;
3561 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3562 DAG.getConstant(Offset, PtrTy));
3563 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3564 DAG.getIntPtrConstant(ByVal.Address));
3565 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3566 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3567 MachinePointerInfo(), MachinePointerInfo());
3568 MemOpChains.push_back(Chain);
3571 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3572 const MipsCC &CC, SDValue Chain,
3573 SDLoc DL, SelectionDAG &DAG) const {
3574 unsigned NumRegs = CC.numIntArgRegs();
3575 const MCPhysReg *ArgRegs = CC.intArgRegs();
3576 const CCState &CCInfo = CC.getCCInfo();
3577 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3578 unsigned RegSize = CC.regSize();
3579 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3580 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3581 MachineFunction &MF = DAG.getMachineFunction();
3582 MachineFrameInfo *MFI = MF.getFrameInfo();
3583 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3585 // Offset of the first variable argument from stack pointer.
3589 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3591 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3593 // Record the frame index of the first variable argument
3594 // which is a value necessary to VASTART.
3595 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3596 MipsFI->setVarArgsFrameIndex(FI);
3598 // Copy the integer registers that have not been used for argument passing
3599 // to the argument register save area. For O32, the save area is allocated
3600 // in the caller's stack frame, while for N32/64, it is allocated in the
3601 // callee's stack frame.
3602 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3603 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3604 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3605 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3606 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3607 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3608 MachinePointerInfo(), false, false, 0);
3609 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue((Value*)0);
3610 OutChains.push_back(Store);