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."),
53 static const uint16_t O32IntRegs[4] = {
54 Mips::A0, Mips::A1, Mips::A2, Mips::A3
57 static const uint16_t Mips64IntRegs[8] = {
58 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
59 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
62 static const uint16_t Mips64DPRegs[8] = {
63 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
64 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
67 // If I is a shifted mask, set the size (Size) and the first bit of the
68 // mask (Pos), and return true.
69 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
70 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
71 if (!isShiftedMask_64(I))
74 Size = CountPopulation_64(I);
75 Pos = countTrailingZeros(I);
79 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
80 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
81 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
84 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
86 unsigned Flag) const {
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
90 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
96 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
102 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
108 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
112 N->getOffset(), Flag);
115 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
117 case MipsISD::JmpLink: return "MipsISD::JmpLink";
118 case MipsISD::TailCall: return "MipsISD::TailCall";
119 case MipsISD::Hi: return "MipsISD::Hi";
120 case MipsISD::Lo: return "MipsISD::Lo";
121 case MipsISD::GPRel: return "MipsISD::GPRel";
122 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
123 case MipsISD::Ret: return "MipsISD::Ret";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::Sync: return "MipsISD::Sync";
147 case MipsISD::Ext: return "MipsISD::Ext";
148 case MipsISD::Ins: return "MipsISD::Ins";
149 case MipsISD::LWL: return "MipsISD::LWL";
150 case MipsISD::LWR: return "MipsISD::LWR";
151 case MipsISD::SWL: return "MipsISD::SWL";
152 case MipsISD::SWR: return "MipsISD::SWR";
153 case MipsISD::LDL: return "MipsISD::LDL";
154 case MipsISD::LDR: return "MipsISD::LDR";
155 case MipsISD::SDL: return "MipsISD::SDL";
156 case MipsISD::SDR: return "MipsISD::SDR";
157 case MipsISD::EXTP: return "MipsISD::EXTP";
158 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
159 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
160 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
161 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
162 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
163 case MipsISD::SHILO: return "MipsISD::SHILO";
164 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
165 case MipsISD::MULT: return "MipsISD::MULT";
166 case MipsISD::MULTU: return "MipsISD::MULTU";
167 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
168 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
169 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
170 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
171 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
172 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
173 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
174 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
175 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
176 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
177 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
178 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
179 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
180 case MipsISD::VCEQ: return "MipsISD::VCEQ";
181 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
182 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
183 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
184 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
185 case MipsISD::VSMAX: return "MipsISD::VSMAX";
186 case MipsISD::VSMIN: return "MipsISD::VSMIN";
187 case MipsISD::VUMAX: return "MipsISD::VUMAX";
188 case MipsISD::VUMIN: return "MipsISD::VUMIN";
189 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
190 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
191 case MipsISD::VNOR: return "MipsISD::VNOR";
192 case MipsISD::VSHF: return "MipsISD::VSHF";
193 case MipsISD::SHF: return "MipsISD::SHF";
194 case MipsISD::ILVEV: return "MipsISD::ILVEV";
195 case MipsISD::ILVOD: return "MipsISD::ILVOD";
196 case MipsISD::ILVL: return "MipsISD::ILVL";
197 case MipsISD::ILVR: return "MipsISD::ILVR";
198 case MipsISD::PCKEV: return "MipsISD::PCKEV";
199 case MipsISD::PCKOD: return "MipsISD::PCKOD";
200 default: return NULL;
205 MipsTargetLowering(MipsTargetMachine &TM)
206 : TargetLowering(TM, new MipsTargetObjectFile()),
207 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
208 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
209 IsO32(Subtarget->isABI_O32()) {
210 // Mips does not have i1 type, so use i32 for
211 // setcc operations results (slt, sgt, ...).
212 setBooleanContents(ZeroOrOneBooleanContent);
213 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
215 // Load extented operations for i1 types must be promoted
216 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
217 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
218 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
220 // MIPS doesn't have extending float->double load/store
221 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
222 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224 // Used by legalize types to correctly generate the setcc result.
225 // Without this, every float setcc comes with a AND/OR with the result,
226 // we don't want this, since the fpcmp result goes to a flag register,
227 // which is used implicitly by brcond and select operations.
228 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
230 // Mips Custom Operations
231 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
232 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
233 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
234 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
235 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
236 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
237 setOperationAction(ISD::SELECT, MVT::f32, Custom);
238 setOperationAction(ISD::SELECT, MVT::f64, Custom);
239 setOperationAction(ISD::SELECT, MVT::i32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 setOperationAction(ISD::SETCC, MVT::f32, Custom);
243 setOperationAction(ISD::SETCC, MVT::f64, Custom);
244 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
245 setOperationAction(ISD::VASTART, MVT::Other, Custom);
246 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
247 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 if (!TM.Options.NoNaNsFPMath) {
251 setOperationAction(ISD::FABS, MVT::f32, Custom);
252 setOperationAction(ISD::FABS, MVT::f64, Custom);
256 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
257 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
259 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
260 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
261 setOperationAction(ISD::SELECT, MVT::i64, Custom);
262 setOperationAction(ISD::LOAD, MVT::i64, Custom);
263 setOperationAction(ISD::STORE, MVT::i64, Custom);
264 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
268 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
270 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
273 setOperationAction(ISD::ADD, MVT::i32, Custom);
275 setOperationAction(ISD::ADD, MVT::i64, Custom);
277 setOperationAction(ISD::SDIV, MVT::i32, Expand);
278 setOperationAction(ISD::SREM, MVT::i32, Expand);
279 setOperationAction(ISD::UDIV, MVT::i32, Expand);
280 setOperationAction(ISD::UREM, MVT::i32, Expand);
281 setOperationAction(ISD::SDIV, MVT::i64, Expand);
282 setOperationAction(ISD::SREM, MVT::i64, Expand);
283 setOperationAction(ISD::UDIV, MVT::i64, Expand);
284 setOperationAction(ISD::UREM, MVT::i64, Expand);
286 // Operations not directly supported by Mips.
287 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
291 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
292 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
293 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
294 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
296 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
297 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
298 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
299 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
300 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
301 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
302 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
303 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
304 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
305 setOperationAction(ISD::ROTL, MVT::i32, Expand);
306 setOperationAction(ISD::ROTL, MVT::i64, Expand);
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
310 if (!Subtarget->hasMips32r2())
311 setOperationAction(ISD::ROTR, MVT::i32, Expand);
313 if (!Subtarget->hasMips64r2())
314 setOperationAction(ISD::ROTR, MVT::i64, Expand);
316 setOperationAction(ISD::FSIN, MVT::f32, Expand);
317 setOperationAction(ISD::FSIN, MVT::f64, Expand);
318 setOperationAction(ISD::FCOS, MVT::f32, Expand);
319 setOperationAction(ISD::FCOS, MVT::f64, Expand);
320 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
321 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
322 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
323 setOperationAction(ISD::FPOW, MVT::f32, Expand);
324 setOperationAction(ISD::FPOW, MVT::f64, Expand);
325 setOperationAction(ISD::FLOG, MVT::f32, Expand);
326 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
327 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
328 setOperationAction(ISD::FEXP, MVT::f32, Expand);
329 setOperationAction(ISD::FMA, MVT::f32, Expand);
330 setOperationAction(ISD::FMA, MVT::f64, Expand);
331 setOperationAction(ISD::FREM, MVT::f32, Expand);
332 setOperationAction(ISD::FREM, MVT::f64, Expand);
334 if (!TM.Options.NoNaNsFPMath) {
335 setOperationAction(ISD::FNEG, MVT::f32, Expand);
336 setOperationAction(ISD::FNEG, MVT::f64, Expand);
339 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
341 setOperationAction(ISD::VAARG, MVT::Other, Expand);
342 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
343 setOperationAction(ISD::VAEND, MVT::Other, Expand);
345 // Use the default for now
346 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
347 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
349 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
350 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
351 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
352 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
354 setInsertFencesForAtomic(true);
356 if (!Subtarget->hasSEInReg()) {
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
358 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
361 if (!Subtarget->hasBitCount()) {
362 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
363 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
366 if (!Subtarget->hasSwap()) {
367 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
368 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
372 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
374 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
375 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
378 setOperationAction(ISD::TRAP, MVT::Other, Legal);
380 setTargetDAGCombine(ISD::SDIVREM);
381 setTargetDAGCombine(ISD::UDIVREM);
382 setTargetDAGCombine(ISD::SELECT);
383 setTargetDAGCombine(ISD::AND);
384 setTargetDAGCombine(ISD::OR);
385 setTargetDAGCombine(ISD::ADD);
387 setMinFunctionAlignment(HasMips64 ? 3 : 2);
389 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
391 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
392 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
394 MaxStoresPerMemcpy = 16;
397 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
398 if (TM.getSubtargetImpl()->inMips16Mode())
399 return llvm::createMips16TargetLowering(TM);
401 return llvm::createMipsSETargetLowering(TM);
404 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
407 return VT.changeVectorElementTypeToInteger();
410 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
411 TargetLowering::DAGCombinerInfo &DCI,
412 const MipsSubtarget *Subtarget) {
413 if (DCI.isBeforeLegalizeOps())
416 EVT Ty = N->getValueType(0);
417 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
418 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
419 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
423 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
424 N->getOperand(0), N->getOperand(1));
425 SDValue InChain = DAG.getEntryNode();
426 SDValue InGlue = DivRem;
429 if (N->hasAnyUseOfValue(0)) {
430 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
432 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
433 InChain = CopyFromLo.getValue(1);
434 InGlue = CopyFromLo.getValue(2);
438 if (N->hasAnyUseOfValue(1)) {
439 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
447 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
449 default: llvm_unreachable("Unknown fp condition code!");
451 case ISD::SETOEQ: return Mips::FCOND_OEQ;
452 case ISD::SETUNE: return Mips::FCOND_UNE;
454 case ISD::SETOLT: return Mips::FCOND_OLT;
456 case ISD::SETOGT: return Mips::FCOND_OGT;
458 case ISD::SETOLE: return Mips::FCOND_OLE;
460 case ISD::SETOGE: return Mips::FCOND_OGE;
461 case ISD::SETULT: return Mips::FCOND_ULT;
462 case ISD::SETULE: return Mips::FCOND_ULE;
463 case ISD::SETUGT: return Mips::FCOND_UGT;
464 case ISD::SETUGE: return Mips::FCOND_UGE;
465 case ISD::SETUO: return Mips::FCOND_UN;
466 case ISD::SETO: return Mips::FCOND_OR;
468 case ISD::SETONE: return Mips::FCOND_ONE;
469 case ISD::SETUEQ: return Mips::FCOND_UEQ;
474 /// This function returns true if the floating point conditional branches and
475 /// conditional moves which use condition code CC should be inverted.
476 static bool invertFPCondCodeUser(Mips::CondCode CC) {
477 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
480 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
481 "Illegal Condition Code");
486 // Creates and returns an FPCmp node from a setcc node.
487 // Returns Op if setcc is not a floating point comparison.
488 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
489 // must be a SETCC node
490 if (Op.getOpcode() != ISD::SETCC)
493 SDValue LHS = Op.getOperand(0);
495 if (!LHS.getValueType().isFloatingPoint())
498 SDValue RHS = Op.getOperand(1);
501 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
502 // node if necessary.
503 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
505 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
506 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
509 // Creates and returns a CMovFPT/F node.
510 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
511 SDValue False, SDLoc DL) {
512 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
513 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
514 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
516 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
517 True.getValueType(), True, FCC0, False, Cond);
520 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
521 TargetLowering::DAGCombinerInfo &DCI,
522 const MipsSubtarget *Subtarget) {
523 if (DCI.isBeforeLegalizeOps())
526 SDValue SetCC = N->getOperand(0);
528 if ((SetCC.getOpcode() != ISD::SETCC) ||
529 !SetCC.getOperand(0).getValueType().isInteger())
532 SDValue False = N->getOperand(2);
533 EVT FalseTy = False.getValueType();
535 if (!FalseTy.isInteger())
538 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
540 // If the RHS (False) is 0, we swap the order of the operands
541 // of ISD::SELECT (obviously also inverting the condition) so that we can
542 // take advantage of conditional moves using the $0 register.
544 // return (a != 0) ? x : 0;
552 if (!FalseC->getZExtValue()) {
553 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
554 SDValue True = N->getOperand(1);
556 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
557 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
559 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
562 // Couldn't optimize.
566 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
567 TargetLowering::DAGCombinerInfo &DCI,
568 const MipsSubtarget *Subtarget) {
569 // Pattern match EXT.
570 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
571 // => ext $dst, $src, size, pos
572 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
575 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
576 unsigned ShiftRightOpc = ShiftRight.getOpcode();
578 // Op's first operand must be a shift right.
579 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
582 // The second operand of the shift must be an immediate.
584 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
587 uint64_t Pos = CN->getZExtValue();
588 uint64_t SMPos, SMSize;
590 // Op's second operand must be a shifted mask.
591 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
592 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
595 // Return if the shifted mask does not start at bit 0 or the sum of its size
596 // and Pos exceeds the word's size.
597 EVT ValTy = N->getValueType(0);
598 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
601 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
602 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
603 DAG.getConstant(SMSize, MVT::i32));
606 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
607 TargetLowering::DAGCombinerInfo &DCI,
608 const MipsSubtarget *Subtarget) {
609 // Pattern match INS.
610 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
611 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
612 // => ins $dst, $src, size, pos, $src1
613 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
616 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
617 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
620 // See if Op's first operand matches (and $src1 , mask0).
621 if (And0.getOpcode() != ISD::AND)
624 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
625 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
628 // See if Op's second operand matches (and (shl $src, pos), mask1).
629 if (And1.getOpcode() != ISD::AND)
632 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
633 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
636 // The shift masks must have the same position and size.
637 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
640 SDValue Shl = And1.getOperand(0);
641 if (Shl.getOpcode() != ISD::SHL)
644 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
647 unsigned Shamt = CN->getZExtValue();
649 // Return if the shift amount and the first bit position of mask are not the
651 EVT ValTy = N->getValueType(0);
652 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
655 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
656 DAG.getConstant(SMPos0, MVT::i32),
657 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
660 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
661 TargetLowering::DAGCombinerInfo &DCI,
662 const MipsSubtarget *Subtarget) {
663 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
665 if (DCI.isBeforeLegalizeOps())
668 SDValue Add = N->getOperand(1);
670 if (Add.getOpcode() != ISD::ADD)
673 SDValue Lo = Add.getOperand(1);
675 if ((Lo.getOpcode() != MipsISD::Lo) ||
676 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
679 EVT ValTy = N->getValueType(0);
682 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
684 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
687 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
689 SelectionDAG &DAG = DCI.DAG;
690 unsigned Opc = N->getOpcode();
696 return performDivRemCombine(N, DAG, DCI, Subtarget);
698 return performSELECTCombine(N, DAG, DCI, Subtarget);
700 return performANDCombine(N, DAG, DCI, Subtarget);
702 return performORCombine(N, DAG, DCI, Subtarget);
704 return performADDCombine(N, DAG, DCI, Subtarget);
711 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
712 SmallVectorImpl<SDValue> &Results,
713 SelectionDAG &DAG) const {
714 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
716 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
717 Results.push_back(Res.getValue(I));
721 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
722 SmallVectorImpl<SDValue> &Results,
723 SelectionDAG &DAG) const {
724 return LowerOperationWrapper(N, Results, DAG);
727 SDValue MipsTargetLowering::
728 LowerOperation(SDValue Op, SelectionDAG &DAG) const
730 switch (Op.getOpcode())
732 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
733 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
734 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
735 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
736 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
737 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
738 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
739 case ISD::SELECT: return lowerSELECT(Op, DAG);
740 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
741 case ISD::SETCC: return lowerSETCC(Op, DAG);
742 case ISD::VASTART: return lowerVASTART(Op, DAG);
743 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
744 case ISD::FABS: return lowerFABS(Op, DAG);
745 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
746 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
747 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
748 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
749 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
750 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
751 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
752 case ISD::LOAD: return lowerLOAD(Op, DAG);
753 case ISD::STORE: return lowerSTORE(Op, DAG);
754 case ISD::ADD: return lowerADD(Op, DAG);
755 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
760 //===----------------------------------------------------------------------===//
761 // Lower helper functions
762 //===----------------------------------------------------------------------===//
764 // addLiveIn - This helper function adds the specified physical register to the
765 // MachineFunction as a live in value. It also creates a corresponding
766 // virtual register for it.
768 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
770 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
771 MF.getRegInfo().addLiveIn(PReg, VReg);
775 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
776 MachineBasicBlock &MBB,
777 const TargetInstrInfo &TII,
782 // Insert instruction "teq $divisor_reg, $zero, 7".
783 MachineBasicBlock::iterator I(MI);
784 MachineInstrBuilder MIB;
785 MachineOperand &Divisor = MI->getOperand(2);
786 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
787 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
788 .addReg(Mips::ZERO).addImm(7);
790 // Use the 32-bit sub-register if this is a 64-bit division.
792 MIB->getOperand(0).setSubReg(Mips::sub_32);
794 // Clear Divisor's kill flag.
795 Divisor.setIsKill(false);
800 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
801 MachineBasicBlock *BB) const {
802 switch (MI->getOpcode()) {
804 llvm_unreachable("Unexpected instr type to insert");
805 case Mips::ATOMIC_LOAD_ADD_I8:
806 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
807 case Mips::ATOMIC_LOAD_ADD_I16:
808 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
809 case Mips::ATOMIC_LOAD_ADD_I32:
810 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
811 case Mips::ATOMIC_LOAD_ADD_I64:
812 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
814 case Mips::ATOMIC_LOAD_AND_I8:
815 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
816 case Mips::ATOMIC_LOAD_AND_I16:
817 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
818 case Mips::ATOMIC_LOAD_AND_I32:
819 return emitAtomicBinary(MI, BB, 4, Mips::AND);
820 case Mips::ATOMIC_LOAD_AND_I64:
821 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
823 case Mips::ATOMIC_LOAD_OR_I8:
824 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
825 case Mips::ATOMIC_LOAD_OR_I16:
826 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
827 case Mips::ATOMIC_LOAD_OR_I32:
828 return emitAtomicBinary(MI, BB, 4, Mips::OR);
829 case Mips::ATOMIC_LOAD_OR_I64:
830 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
832 case Mips::ATOMIC_LOAD_XOR_I8:
833 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
834 case Mips::ATOMIC_LOAD_XOR_I16:
835 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
836 case Mips::ATOMIC_LOAD_XOR_I32:
837 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
838 case Mips::ATOMIC_LOAD_XOR_I64:
839 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
841 case Mips::ATOMIC_LOAD_NAND_I8:
842 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
843 case Mips::ATOMIC_LOAD_NAND_I16:
844 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
845 case Mips::ATOMIC_LOAD_NAND_I32:
846 return emitAtomicBinary(MI, BB, 4, 0, true);
847 case Mips::ATOMIC_LOAD_NAND_I64:
848 return emitAtomicBinary(MI, BB, 8, 0, true);
850 case Mips::ATOMIC_LOAD_SUB_I8:
851 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
852 case Mips::ATOMIC_LOAD_SUB_I16:
853 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
854 case Mips::ATOMIC_LOAD_SUB_I32:
855 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
856 case Mips::ATOMIC_LOAD_SUB_I64:
857 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
859 case Mips::ATOMIC_SWAP_I8:
860 return emitAtomicBinaryPartword(MI, BB, 1, 0);
861 case Mips::ATOMIC_SWAP_I16:
862 return emitAtomicBinaryPartword(MI, BB, 2, 0);
863 case Mips::ATOMIC_SWAP_I32:
864 return emitAtomicBinary(MI, BB, 4, 0);
865 case Mips::ATOMIC_SWAP_I64:
866 return emitAtomicBinary(MI, BB, 8, 0);
868 case Mips::ATOMIC_CMP_SWAP_I8:
869 return emitAtomicCmpSwapPartword(MI, BB, 1);
870 case Mips::ATOMIC_CMP_SWAP_I16:
871 return emitAtomicCmpSwapPartword(MI, BB, 2);
872 case Mips::ATOMIC_CMP_SWAP_I32:
873 return emitAtomicCmpSwap(MI, BB, 4);
874 case Mips::ATOMIC_CMP_SWAP_I64:
875 return emitAtomicCmpSwap(MI, BB, 8);
876 case Mips::PseudoSDIV:
877 case Mips::PseudoUDIV:
878 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
879 case Mips::PseudoDSDIV:
880 case Mips::PseudoDUDIV:
881 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
885 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
886 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
888 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
889 unsigned Size, unsigned BinOpcode,
891 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
893 MachineFunction *MF = BB->getParent();
894 MachineRegisterInfo &RegInfo = MF->getRegInfo();
895 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
896 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
897 DebugLoc DL = MI->getDebugLoc();
898 unsigned LL, SC, AND, NOR, ZERO, BEQ;
913 ZERO = Mips::ZERO_64;
917 unsigned OldVal = MI->getOperand(0).getReg();
918 unsigned Ptr = MI->getOperand(1).getReg();
919 unsigned Incr = MI->getOperand(2).getReg();
921 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
922 unsigned AndRes = RegInfo.createVirtualRegister(RC);
923 unsigned Success = RegInfo.createVirtualRegister(RC);
925 // insert new blocks after the current block
926 const BasicBlock *LLVM_BB = BB->getBasicBlock();
927 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
928 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
929 MachineFunction::iterator It = BB;
931 MF->insert(It, loopMBB);
932 MF->insert(It, exitMBB);
934 // Transfer the remainder of BB and its successor edges to exitMBB.
935 exitMBB->splice(exitMBB->begin(), BB,
936 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
937 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
941 // fallthrough --> loopMBB
942 BB->addSuccessor(loopMBB);
943 loopMBB->addSuccessor(loopMBB);
944 loopMBB->addSuccessor(exitMBB);
948 // <binop> storeval, oldval, incr
949 // sc success, storeval, 0(ptr)
950 // beq success, $0, loopMBB
952 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
954 // and andres, oldval, incr
955 // nor storeval, $0, andres
956 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
957 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
958 } else if (BinOpcode) {
959 // <binop> storeval, oldval, incr
960 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
964 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
965 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
967 MI->eraseFromParent(); // The instruction is gone now.
973 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
974 MachineBasicBlock *BB,
975 unsigned Size, unsigned BinOpcode,
977 assert((Size == 1 || Size == 2) &&
978 "Unsupported size for EmitAtomicBinaryPartial.");
980 MachineFunction *MF = BB->getParent();
981 MachineRegisterInfo &RegInfo = MF->getRegInfo();
982 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
983 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
984 DebugLoc DL = MI->getDebugLoc();
986 unsigned Dest = MI->getOperand(0).getReg();
987 unsigned Ptr = MI->getOperand(1).getReg();
988 unsigned Incr = MI->getOperand(2).getReg();
990 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
991 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
992 unsigned Mask = RegInfo.createVirtualRegister(RC);
993 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
994 unsigned NewVal = RegInfo.createVirtualRegister(RC);
995 unsigned OldVal = RegInfo.createVirtualRegister(RC);
996 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
997 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
998 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
999 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1000 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1001 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1002 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1003 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1004 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1005 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1006 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1007 unsigned Success = RegInfo.createVirtualRegister(RC);
1009 // insert new blocks after the current block
1010 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1011 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1012 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1013 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1014 MachineFunction::iterator It = BB;
1016 MF->insert(It, loopMBB);
1017 MF->insert(It, sinkMBB);
1018 MF->insert(It, exitMBB);
1020 // Transfer the remainder of BB and its successor edges to exitMBB.
1021 exitMBB->splice(exitMBB->begin(), BB,
1022 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1023 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1025 BB->addSuccessor(loopMBB);
1026 loopMBB->addSuccessor(loopMBB);
1027 loopMBB->addSuccessor(sinkMBB);
1028 sinkMBB->addSuccessor(exitMBB);
1031 // addiu masklsb2,$0,-4 # 0xfffffffc
1032 // and alignedaddr,ptr,masklsb2
1033 // andi ptrlsb2,ptr,3
1034 // sll shiftamt,ptrlsb2,3
1035 // ori maskupper,$0,255 # 0xff
1036 // sll mask,maskupper,shiftamt
1037 // nor mask2,$0,mask
1038 // sll incr2,incr,shiftamt
1040 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1041 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1042 .addReg(Mips::ZERO).addImm(-4);
1043 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1044 .addReg(Ptr).addReg(MaskLSB2);
1045 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1046 if (Subtarget->isLittle()) {
1047 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1049 unsigned Off = RegInfo.createVirtualRegister(RC);
1050 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1051 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1052 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1054 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1055 .addReg(Mips::ZERO).addImm(MaskImm);
1056 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1057 .addReg(MaskUpper).addReg(ShiftAmt);
1058 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1059 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1061 // atomic.load.binop
1063 // ll oldval,0(alignedaddr)
1064 // binop binopres,oldval,incr2
1065 // and newval,binopres,mask
1066 // and maskedoldval0,oldval,mask2
1067 // or storeval,maskedoldval0,newval
1068 // sc success,storeval,0(alignedaddr)
1069 // beq success,$0,loopMBB
1073 // ll oldval,0(alignedaddr)
1074 // and newval,incr2,mask
1075 // and maskedoldval0,oldval,mask2
1076 // or storeval,maskedoldval0,newval
1077 // sc success,storeval,0(alignedaddr)
1078 // beq success,$0,loopMBB
1081 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1083 // and andres, oldval, incr2
1084 // nor binopres, $0, andres
1085 // and newval, binopres, mask
1086 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1087 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1088 .addReg(Mips::ZERO).addReg(AndRes);
1089 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1090 } else if (BinOpcode) {
1091 // <binop> binopres, oldval, incr2
1092 // and newval, binopres, mask
1093 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1094 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1095 } else { // atomic.swap
1096 // and newval, incr2, mask
1097 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1100 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1101 .addReg(OldVal).addReg(Mask2);
1102 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1103 .addReg(MaskedOldVal0).addReg(NewVal);
1104 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1105 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1106 BuildMI(BB, DL, TII->get(Mips::BEQ))
1107 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1110 // and maskedoldval1,oldval,mask
1111 // srl srlres,maskedoldval1,shiftamt
1112 // sll sllres,srlres,24
1113 // sra dest,sllres,24
1115 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1117 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1118 .addReg(OldVal).addReg(Mask);
1119 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1120 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1121 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1122 .addReg(SrlRes).addImm(ShiftImm);
1123 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1124 .addReg(SllRes).addImm(ShiftImm);
1126 MI->eraseFromParent(); // The instruction is gone now.
1131 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1132 MachineBasicBlock *BB,
1133 unsigned Size) const {
1134 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1136 MachineFunction *MF = BB->getParent();
1137 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1138 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1139 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1140 DebugLoc DL = MI->getDebugLoc();
1141 unsigned LL, SC, ZERO, BNE, BEQ;
1152 ZERO = Mips::ZERO_64;
1157 unsigned Dest = MI->getOperand(0).getReg();
1158 unsigned Ptr = MI->getOperand(1).getReg();
1159 unsigned OldVal = MI->getOperand(2).getReg();
1160 unsigned NewVal = MI->getOperand(3).getReg();
1162 unsigned Success = RegInfo.createVirtualRegister(RC);
1164 // insert new blocks after the current block
1165 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1166 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1167 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1168 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1169 MachineFunction::iterator It = BB;
1171 MF->insert(It, loop1MBB);
1172 MF->insert(It, loop2MBB);
1173 MF->insert(It, exitMBB);
1175 // Transfer the remainder of BB and its successor edges to exitMBB.
1176 exitMBB->splice(exitMBB->begin(), BB,
1177 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1178 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1182 // fallthrough --> loop1MBB
1183 BB->addSuccessor(loop1MBB);
1184 loop1MBB->addSuccessor(exitMBB);
1185 loop1MBB->addSuccessor(loop2MBB);
1186 loop2MBB->addSuccessor(loop1MBB);
1187 loop2MBB->addSuccessor(exitMBB);
1191 // bne dest, oldval, exitMBB
1193 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1194 BuildMI(BB, DL, TII->get(BNE))
1195 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1198 // sc success, newval, 0(ptr)
1199 // beq success, $0, loop1MBB
1201 BuildMI(BB, DL, TII->get(SC), Success)
1202 .addReg(NewVal).addReg(Ptr).addImm(0);
1203 BuildMI(BB, DL, TII->get(BEQ))
1204 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1206 MI->eraseFromParent(); // The instruction is gone now.
1212 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1213 MachineBasicBlock *BB,
1214 unsigned Size) const {
1215 assert((Size == 1 || Size == 2) &&
1216 "Unsupported size for EmitAtomicCmpSwapPartial.");
1218 MachineFunction *MF = BB->getParent();
1219 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1220 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1221 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1222 DebugLoc DL = MI->getDebugLoc();
1224 unsigned Dest = MI->getOperand(0).getReg();
1225 unsigned Ptr = MI->getOperand(1).getReg();
1226 unsigned CmpVal = MI->getOperand(2).getReg();
1227 unsigned NewVal = MI->getOperand(3).getReg();
1229 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1230 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1231 unsigned Mask = RegInfo.createVirtualRegister(RC);
1232 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1233 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1234 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1235 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1236 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1237 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1238 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1239 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1240 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1241 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1242 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1243 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1244 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1245 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1246 unsigned Success = RegInfo.createVirtualRegister(RC);
1248 // insert new blocks after the current block
1249 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1250 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1251 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1252 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1253 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1254 MachineFunction::iterator It = BB;
1256 MF->insert(It, loop1MBB);
1257 MF->insert(It, loop2MBB);
1258 MF->insert(It, sinkMBB);
1259 MF->insert(It, exitMBB);
1261 // Transfer the remainder of BB and its successor edges to exitMBB.
1262 exitMBB->splice(exitMBB->begin(), BB,
1263 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1264 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1266 BB->addSuccessor(loop1MBB);
1267 loop1MBB->addSuccessor(sinkMBB);
1268 loop1MBB->addSuccessor(loop2MBB);
1269 loop2MBB->addSuccessor(loop1MBB);
1270 loop2MBB->addSuccessor(sinkMBB);
1271 sinkMBB->addSuccessor(exitMBB);
1273 // FIXME: computation of newval2 can be moved to loop2MBB.
1275 // addiu masklsb2,$0,-4 # 0xfffffffc
1276 // and alignedaddr,ptr,masklsb2
1277 // andi ptrlsb2,ptr,3
1278 // sll shiftamt,ptrlsb2,3
1279 // ori maskupper,$0,255 # 0xff
1280 // sll mask,maskupper,shiftamt
1281 // nor mask2,$0,mask
1282 // andi maskedcmpval,cmpval,255
1283 // sll shiftedcmpval,maskedcmpval,shiftamt
1284 // andi maskednewval,newval,255
1285 // sll shiftednewval,maskednewval,shiftamt
1286 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1287 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1288 .addReg(Mips::ZERO).addImm(-4);
1289 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1290 .addReg(Ptr).addReg(MaskLSB2);
1291 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1292 if (Subtarget->isLittle()) {
1293 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1295 unsigned Off = RegInfo.createVirtualRegister(RC);
1296 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1297 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1298 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1300 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1301 .addReg(Mips::ZERO).addImm(MaskImm);
1302 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1303 .addReg(MaskUpper).addReg(ShiftAmt);
1304 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1305 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1306 .addReg(CmpVal).addImm(MaskImm);
1307 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1308 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1309 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1310 .addReg(NewVal).addImm(MaskImm);
1311 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1312 .addReg(MaskedNewVal).addReg(ShiftAmt);
1315 // ll oldval,0(alginedaddr)
1316 // and maskedoldval0,oldval,mask
1317 // bne maskedoldval0,shiftedcmpval,sinkMBB
1319 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1320 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1321 .addReg(OldVal).addReg(Mask);
1322 BuildMI(BB, DL, TII->get(Mips::BNE))
1323 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1326 // and maskedoldval1,oldval,mask2
1327 // or storeval,maskedoldval1,shiftednewval
1328 // sc success,storeval,0(alignedaddr)
1329 // beq success,$0,loop1MBB
1331 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1332 .addReg(OldVal).addReg(Mask2);
1333 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1334 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1335 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1336 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1337 BuildMI(BB, DL, TII->get(Mips::BEQ))
1338 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1341 // srl srlres,maskedoldval0,shiftamt
1342 // sll sllres,srlres,24
1343 // sra dest,sllres,24
1345 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1347 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1348 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1349 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1350 .addReg(SrlRes).addImm(ShiftImm);
1351 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1352 .addReg(SllRes).addImm(ShiftImm);
1354 MI->eraseFromParent(); // The instruction is gone now.
1359 //===----------------------------------------------------------------------===//
1360 // Misc Lower Operation implementation
1361 //===----------------------------------------------------------------------===//
1362 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1363 SDValue Chain = Op.getOperand(0);
1364 SDValue Table = Op.getOperand(1);
1365 SDValue Index = Op.getOperand(2);
1367 EVT PTy = getPointerTy();
1368 unsigned EntrySize =
1369 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1371 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1372 DAG.getConstant(EntrySize, PTy));
1373 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1375 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1376 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1377 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1379 Chain = Addr.getValue(1);
1381 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1382 // For PIC, the sequence is:
1383 // BRIND(load(Jumptable + index) + RelocBase)
1384 // RelocBase can be JumpTable, GOT or some sort of global base.
1385 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1386 getPICJumpTableRelocBase(Table, DAG));
1389 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1392 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1393 // The first operand is the chain, the second is the condition, the third is
1394 // the block to branch to if the condition is true.
1395 SDValue Chain = Op.getOperand(0);
1396 SDValue Dest = Op.getOperand(2);
1399 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1401 // Return if flag is not set by a floating point comparison.
1402 if (CondRes.getOpcode() != MipsISD::FPCmp)
1405 SDValue CCNode = CondRes.getOperand(2);
1407 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1408 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1409 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1410 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1411 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1412 FCC0, Dest, CondRes);
1415 SDValue MipsTargetLowering::
1416 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1418 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1420 // Return if flag is not set by a floating point comparison.
1421 if (Cond.getOpcode() != MipsISD::FPCmp)
1424 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1428 SDValue MipsTargetLowering::
1429 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1432 EVT Ty = Op.getOperand(0).getValueType();
1433 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1434 getSetCCResultType(*DAG.getContext(), Ty),
1435 Op.getOperand(0), Op.getOperand(1),
1438 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1442 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1443 SDValue Cond = createFPCmp(DAG, Op);
1445 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1446 "Floating point operand expected.");
1448 SDValue True = DAG.getConstant(1, MVT::i32);
1449 SDValue False = DAG.getConstant(0, MVT::i32);
1451 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1454 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1455 SelectionDAG &DAG) const {
1456 // FIXME there isn't actually debug info here
1458 EVT Ty = Op.getValueType();
1459 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1460 const GlobalValue *GV = N->getGlobal();
1462 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1463 const MipsTargetObjectFile &TLOF =
1464 (const MipsTargetObjectFile&)getObjFileLowering();
1466 // %gp_rel relocation
1467 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1468 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1470 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1471 DAG.getVTList(MVT::i32), &GA, 1);
1472 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1473 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1476 // %hi/%lo relocation
1477 return getAddrNonPIC(N, Ty, DAG);
1480 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1481 return getAddrLocal(N, Ty, DAG, HasMips64);
1484 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1485 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1486 MachinePointerInfo::getGOT());
1488 return getAddrGlobal(N, Ty, DAG,
1489 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1490 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1493 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1494 SelectionDAG &DAG) const {
1495 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1496 EVT Ty = Op.getValueType();
1498 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1499 return getAddrNonPIC(N, Ty, DAG);
1501 return getAddrLocal(N, Ty, DAG, HasMips64);
1504 SDValue MipsTargetLowering::
1505 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1507 // If the relocation model is PIC, use the General Dynamic TLS Model or
1508 // Local Dynamic TLS model, otherwise use the Initial Exec or
1509 // Local Exec TLS Model.
1511 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1513 const GlobalValue *GV = GA->getGlobal();
1514 EVT PtrVT = getPointerTy();
1516 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1518 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1519 // General Dynamic and Local Dynamic TLS Model.
1520 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1523 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1524 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1525 getGlobalReg(DAG, PtrVT), TGA);
1526 unsigned PtrSize = PtrVT.getSizeInBits();
1527 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1529 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1533 Entry.Node = Argument;
1535 Args.push_back(Entry);
1537 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1538 false, false, false, false, 0, CallingConv::C,
1539 /*IsTailCall=*/false, /*doesNotRet=*/false,
1540 /*isReturnValueUsed=*/true,
1541 TlsGetAddr, Args, DAG, DL);
1542 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1544 SDValue Ret = CallResult.first;
1546 if (model != TLSModel::LocalDynamic)
1549 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1550 MipsII::MO_DTPREL_HI);
1551 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1552 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1553 MipsII::MO_DTPREL_LO);
1554 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1555 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1556 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1560 if (model == TLSModel::InitialExec) {
1561 // Initial Exec TLS Model
1562 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1563 MipsII::MO_GOTTPREL);
1564 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1566 Offset = DAG.getLoad(PtrVT, DL,
1567 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1568 false, false, false, 0);
1570 // Local Exec TLS Model
1571 assert(model == TLSModel::LocalExec);
1572 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1573 MipsII::MO_TPREL_HI);
1574 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1575 MipsII::MO_TPREL_LO);
1576 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1577 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1578 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1581 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1582 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1585 SDValue MipsTargetLowering::
1586 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1588 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1589 EVT Ty = Op.getValueType();
1591 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1592 return getAddrNonPIC(N, Ty, DAG);
1594 return getAddrLocal(N, Ty, DAG, HasMips64);
1597 SDValue MipsTargetLowering::
1598 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1600 // gp_rel relocation
1601 // FIXME: we should reference the constant pool using small data sections,
1602 // but the asm printer currently doesn't support this feature without
1603 // hacking it. This feature should come soon so we can uncomment the
1605 //if (IsInSmallSection(C->getType())) {
1606 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1607 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1608 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1609 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1610 EVT Ty = Op.getValueType();
1612 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1613 return getAddrNonPIC(N, Ty, DAG);
1615 return getAddrLocal(N, Ty, DAG, HasMips64);
1618 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1619 MachineFunction &MF = DAG.getMachineFunction();
1620 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1623 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1626 // vastart just stores the address of the VarArgsFrameIndex slot into the
1627 // memory location argument.
1628 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1629 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1630 MachinePointerInfo(SV), false, false, 0);
1633 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1634 bool HasExtractInsert) {
1635 EVT TyX = Op.getOperand(0).getValueType();
1636 EVT TyY = Op.getOperand(1).getValueType();
1637 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1638 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1642 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1644 SDValue X = (TyX == MVT::f32) ?
1645 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1646 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1648 SDValue Y = (TyY == MVT::f32) ?
1649 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1650 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1653 if (HasExtractInsert) {
1654 // ext E, Y, 31, 1 ; extract bit31 of Y
1655 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1656 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1657 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1660 // srl SrlX, SllX, 1
1662 // sll SllY, SrlX, 31
1663 // or Or, SrlX, SllY
1664 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1665 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1666 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1667 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1668 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1671 if (TyX == MVT::f32)
1672 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1674 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1675 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1676 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1679 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1680 bool HasExtractInsert) {
1681 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1682 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1683 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1684 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1687 // Bitcast to integer nodes.
1688 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1689 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1691 if (HasExtractInsert) {
1692 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1693 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1694 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1695 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1697 if (WidthX > WidthY)
1698 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1699 else if (WidthY > WidthX)
1700 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1702 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1703 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1704 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1707 // (d)sll SllX, X, 1
1708 // (d)srl SrlX, SllX, 1
1709 // (d)srl SrlY, Y, width(Y)-1
1710 // (d)sll SllY, SrlX, width(Y)-1
1711 // or Or, SrlX, SllY
1712 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1713 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1714 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1715 DAG.getConstant(WidthY - 1, MVT::i32));
1717 if (WidthX > WidthY)
1718 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1719 else if (WidthY > WidthX)
1720 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1722 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1723 DAG.getConstant(WidthX - 1, MVT::i32));
1724 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1725 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1729 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1730 if (Subtarget->hasMips64())
1731 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1733 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1736 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
1737 bool HasExtractInsert) {
1738 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1741 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1743 SDValue X = (Op.getValueType() == MVT::f32) ?
1744 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1745 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1749 if (HasExtractInsert)
1750 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1751 DAG.getRegister(Mips::ZERO, MVT::i32),
1752 DAG.getConstant(31, MVT::i32), Const1, X);
1754 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1755 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1758 if (Op.getValueType() == MVT::f32)
1759 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1761 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1762 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1763 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1766 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
1767 bool HasExtractInsert) {
1768 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1771 // Bitcast to integer node.
1772 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1775 if (HasExtractInsert)
1776 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1777 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1778 DAG.getConstant(63, MVT::i32), Const1, X);
1780 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1781 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1784 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1788 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1789 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1790 return lowerFABS64(Op, DAG, Subtarget->hasExtractInsert());
1792 return lowerFABS32(Op, DAG, Subtarget->hasExtractInsert());
1795 SDValue MipsTargetLowering::
1796 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1798 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1799 "Frame address can only be determined for current frame.");
1801 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1802 MFI->setFrameAddressIsTaken(true);
1803 EVT VT = Op.getValueType();
1805 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1806 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1810 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1811 SelectionDAG &DAG) const {
1813 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1814 "Return address can be determined only for current frame.");
1816 MachineFunction &MF = DAG.getMachineFunction();
1817 MachineFrameInfo *MFI = MF.getFrameInfo();
1818 MVT VT = Op.getSimpleValueType();
1819 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1820 MFI->setReturnAddressIsTaken(true);
1822 // Return RA, which contains the return address. Mark it an implicit live-in.
1823 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1824 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1827 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1828 // generated from __builtin_eh_return (offset, handler)
1829 // The effect of this is to adjust the stack pointer by "offset"
1830 // and then branch to "handler".
1831 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1833 MachineFunction &MF = DAG.getMachineFunction();
1834 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1836 MipsFI->setCallsEhReturn();
1837 SDValue Chain = Op.getOperand(0);
1838 SDValue Offset = Op.getOperand(1);
1839 SDValue Handler = Op.getOperand(2);
1841 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1843 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1844 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1845 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1846 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1847 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1848 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1849 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1850 DAG.getRegister(OffsetReg, Ty),
1851 DAG.getRegister(AddrReg, getPointerTy()),
1855 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1856 SelectionDAG &DAG) const {
1857 // FIXME: Need pseudo-fence for 'singlethread' fences
1858 // FIXME: Set SType for weaker fences where supported/appropriate.
1861 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1862 DAG.getConstant(SType, MVT::i32));
1865 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1866 SelectionDAG &DAG) const {
1868 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1869 SDValue Shamt = Op.getOperand(2);
1872 // lo = (shl lo, shamt)
1873 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1876 // hi = (shl lo, shamt[4:0])
1877 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1878 DAG.getConstant(-1, MVT::i32));
1879 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1880 DAG.getConstant(1, MVT::i32));
1881 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1883 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1884 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1885 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1886 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1887 DAG.getConstant(0x20, MVT::i32));
1888 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1889 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1890 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1892 SDValue Ops[2] = {Lo, Hi};
1893 return DAG.getMergeValues(Ops, 2, DL);
1896 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1899 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1900 SDValue Shamt = Op.getOperand(2);
1903 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1905 // hi = (sra hi, shamt)
1907 // hi = (srl hi, shamt)
1910 // lo = (sra hi, shamt[4:0])
1911 // hi = (sra hi, 31)
1913 // lo = (srl hi, shamt[4:0])
1915 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1916 DAG.getConstant(-1, MVT::i32));
1917 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1918 DAG.getConstant(1, MVT::i32));
1919 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1920 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1921 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1922 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1924 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1925 DAG.getConstant(0x20, MVT::i32));
1926 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1927 DAG.getConstant(31, MVT::i32));
1928 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1929 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1930 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1933 SDValue Ops[2] = {Lo, Hi};
1934 return DAG.getMergeValues(Ops, 2, DL);
1937 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1938 SDValue Chain, SDValue Src, unsigned Offset) {
1939 SDValue Ptr = LD->getBasePtr();
1940 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1941 EVT BasePtrVT = Ptr.getValueType();
1943 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1946 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1947 DAG.getConstant(Offset, BasePtrVT));
1949 SDValue Ops[] = { Chain, Ptr, Src };
1950 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1951 LD->getMemOperand());
1954 // Expand an unaligned 32 or 64-bit integer load node.
1955 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1956 LoadSDNode *LD = cast<LoadSDNode>(Op);
1957 EVT MemVT = LD->getMemoryVT();
1959 // Return if load is aligned or if MemVT is neither i32 nor i64.
1960 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1961 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1964 bool IsLittle = Subtarget->isLittle();
1965 EVT VT = Op.getValueType();
1966 ISD::LoadExtType ExtType = LD->getExtensionType();
1967 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1969 assert((VT == MVT::i32) || (VT == MVT::i64));
1972 // (set dst, (i64 (load baseptr)))
1974 // (set tmp, (ldl (add baseptr, 7), undef))
1975 // (set dst, (ldr baseptr, tmp))
1976 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1977 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1979 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1983 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1985 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1989 // (set dst, (i32 (load baseptr))) or
1990 // (set dst, (i64 (sextload baseptr))) or
1991 // (set dst, (i64 (extload baseptr)))
1993 // (set tmp, (lwl (add baseptr, 3), undef))
1994 // (set dst, (lwr baseptr, tmp))
1995 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1996 (ExtType == ISD::EXTLOAD))
1999 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2002 // (set dst, (i64 (zextload baseptr)))
2004 // (set tmp0, (lwl (add baseptr, 3), undef))
2005 // (set tmp1, (lwr baseptr, tmp0))
2006 // (set tmp2, (shl tmp1, 32))
2007 // (set dst, (srl tmp2, 32))
2009 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2010 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2011 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2012 SDValue Ops[] = { SRL, LWR.getValue(1) };
2013 return DAG.getMergeValues(Ops, 2, DL);
2016 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2017 SDValue Chain, unsigned Offset) {
2018 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2019 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2021 SDVTList VTList = DAG.getVTList(MVT::Other);
2024 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2025 DAG.getConstant(Offset, BasePtrVT));
2027 SDValue Ops[] = { Chain, Value, Ptr };
2028 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2029 SD->getMemOperand());
2032 // Expand an unaligned 32 or 64-bit integer store node.
2033 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2035 SDValue Value = SD->getValue(), Chain = SD->getChain();
2036 EVT VT = Value.getValueType();
2039 // (store val, baseptr) or
2040 // (truncstore val, baseptr)
2042 // (swl val, (add baseptr, 3))
2043 // (swr val, baseptr)
2044 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2045 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2047 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2050 assert(VT == MVT::i64);
2053 // (store val, baseptr)
2055 // (sdl val, (add baseptr, 7))
2056 // (sdr val, baseptr)
2057 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2058 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2061 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2062 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2063 SDValue Val = SD->getValue();
2065 if (Val.getOpcode() != ISD::FP_TO_SINT)
2068 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2069 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2072 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2073 SD->getPointerInfo(), SD->isVolatile(),
2074 SD->isNonTemporal(), SD->getAlignment());
2077 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2078 StoreSDNode *SD = cast<StoreSDNode>(Op);
2079 EVT MemVT = SD->getMemoryVT();
2081 // Lower unaligned integer stores.
2082 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2083 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2084 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2086 return lowerFP_TO_SINT_STORE(SD, DAG);
2089 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2090 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2091 || cast<ConstantSDNode>
2092 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2093 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2097 // (add (frameaddr 0), (frame_to_args_offset))
2098 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2099 // (add FrameObject, 0)
2100 // where FrameObject is a fixed StackObject with offset 0 which points to
2101 // the old stack pointer.
2102 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2103 EVT ValTy = Op->getValueType(0);
2104 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2105 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2106 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2107 DAG.getConstant(0, ValTy));
2110 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2111 SelectionDAG &DAG) const {
2112 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2113 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2115 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2118 //===----------------------------------------------------------------------===//
2119 // Calling Convention Implementation
2120 //===----------------------------------------------------------------------===//
2122 //===----------------------------------------------------------------------===//
2123 // TODO: Implement a generic logic using tblgen that can support this.
2124 // Mips O32 ABI rules:
2126 // i32 - Passed in A0, A1, A2, A3 and stack
2127 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2128 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2129 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2130 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2131 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2134 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2135 //===----------------------------------------------------------------------===//
2137 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2138 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2139 CCState &State, const uint16_t *F64Regs) {
2141 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2143 static const uint16_t IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2144 static const uint16_t F32Regs[] = { Mips::F12, Mips::F14 };
2146 // Do not process byval args here.
2147 if (ArgFlags.isByVal())
2150 // Promote i8 and i16
2151 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2153 if (ArgFlags.isSExt())
2154 LocInfo = CCValAssign::SExt;
2155 else if (ArgFlags.isZExt())
2156 LocInfo = CCValAssign::ZExt;
2158 LocInfo = CCValAssign::AExt;
2163 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2164 // is true: function is vararg, argument is 3rd or higher, there is previous
2165 // argument which is not f32 or f64.
2166 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2167 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2168 unsigned OrigAlign = ArgFlags.getOrigAlign();
2169 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2171 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2172 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2173 // If this is the first part of an i64 arg,
2174 // the allocated register must be either A0 or A2.
2175 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2176 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2178 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2179 // Allocate int register and shadow next int register. If first
2180 // available register is Mips::A1 or Mips::A3, shadow it too.
2181 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2182 if (Reg == Mips::A1 || Reg == Mips::A3)
2183 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2184 State.AllocateReg(IntRegs, IntRegsSize);
2186 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2187 // we are guaranteed to find an available float register
2188 if (ValVT == MVT::f32) {
2189 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2190 // Shadow int register
2191 State.AllocateReg(IntRegs, IntRegsSize);
2193 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2194 // Shadow int registers
2195 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2196 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2197 State.AllocateReg(IntRegs, IntRegsSize);
2198 State.AllocateReg(IntRegs, IntRegsSize);
2201 llvm_unreachable("Cannot handle this ValVT.");
2204 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2206 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2208 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2213 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2214 MVT LocVT, CCValAssign::LocInfo LocInfo,
2215 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2216 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2218 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2221 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2222 MVT LocVT, CCValAssign::LocInfo LocInfo,
2223 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2224 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2226 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2229 #include "MipsGenCallingConv.inc"
2231 //===----------------------------------------------------------------------===//
2232 // Call Calling Convention Implementation
2233 //===----------------------------------------------------------------------===//
2235 // Return next O32 integer argument register.
2236 static unsigned getNextIntArgReg(unsigned Reg) {
2237 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2238 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2242 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2243 SDValue Chain, SDValue Arg, SDLoc DL,
2244 bool IsTailCall, SelectionDAG &DAG) const {
2246 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2247 DAG.getIntPtrConstant(Offset));
2248 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2252 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2253 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2254 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2255 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2256 /*isVolatile=*/ true, false, 0);
2259 void MipsTargetLowering::
2260 getOpndList(SmallVectorImpl<SDValue> &Ops,
2261 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2262 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2263 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2264 // Insert node "GP copy globalreg" before call to function.
2266 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2267 // in PIC mode) allow symbols to be resolved via lazy binding.
2268 // The lazy binding stub requires GP to point to the GOT.
2269 if (IsPICCall && !InternalLinkage) {
2270 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2271 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2272 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2275 // Build a sequence of copy-to-reg nodes chained together with token
2276 // chain and flag operands which copy the outgoing args into registers.
2277 // The InFlag in necessary since all emitted instructions must be
2281 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2282 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2283 RegsToPass[i].second, InFlag);
2284 InFlag = Chain.getValue(1);
2287 // Add argument registers to the end of the list so that they are
2288 // known live into the call.
2289 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2290 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2291 RegsToPass[i].second.getValueType()));
2293 // Add a register mask operand representing the call-preserved registers.
2294 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2295 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2296 assert(Mask && "Missing call preserved mask for calling convention");
2297 if (Subtarget->inMips16HardFloat()) {
2298 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2299 llvm::StringRef Sym = G->getGlobal()->getName();
2300 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2301 if (F->hasFnAttribute("__Mips16RetHelper")) {
2302 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2306 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2308 if (InFlag.getNode())
2309 Ops.push_back(InFlag);
2312 /// LowerCall - functions arguments are copied from virtual regs to
2313 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2315 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2316 SmallVectorImpl<SDValue> &InVals) const {
2317 SelectionDAG &DAG = CLI.DAG;
2319 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2320 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2321 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2322 SDValue Chain = CLI.Chain;
2323 SDValue Callee = CLI.Callee;
2324 bool &IsTailCall = CLI.IsTailCall;
2325 CallingConv::ID CallConv = CLI.CallConv;
2326 bool IsVarArg = CLI.IsVarArg;
2328 MachineFunction &MF = DAG.getMachineFunction();
2329 MachineFrameInfo *MFI = MF.getFrameInfo();
2330 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2331 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2332 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2334 // Analyze operands of the call, assigning locations to each operand.
2335 SmallVector<CCValAssign, 16> ArgLocs;
2336 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2337 getTargetMachine(), ArgLocs, *DAG.getContext());
2338 MipsCC::SpecialCallingConvType SpecialCallingConv =
2339 getSpecialCallingConv(Callee);
2340 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2341 SpecialCallingConv);
2343 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2344 Subtarget->mipsSEUsesSoftFloat(),
2345 Callee.getNode(), CLI.Args);
2347 // Get a count of how many bytes are to be pushed on the stack.
2348 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2350 // Check if it's really possible to do a tail call.
2353 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2354 *MF.getInfo<MipsFunctionInfo>());
2359 // Chain is the output chain of the last Load/Store or CopyToReg node.
2360 // ByValChain is the output chain of the last Memcpy node created for copying
2361 // byval arguments to the stack.
2362 unsigned StackAlignment = TFL->getStackAlignment();
2363 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2364 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2367 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2369 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2370 IsN64 ? Mips::SP_64 : Mips::SP,
2373 // With EABI is it possible to have 16 args on registers.
2374 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2375 SmallVector<SDValue, 8> MemOpChains;
2376 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2378 // Walk the register/memloc assignments, inserting copies/loads.
2379 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2380 SDValue Arg = OutVals[i];
2381 CCValAssign &VA = ArgLocs[i];
2382 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2383 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2386 if (Flags.isByVal()) {
2387 assert(Flags.getByValSize() &&
2388 "ByVal args of size 0 should have been ignored by front-end.");
2389 assert(ByValArg != MipsCCInfo.byval_end());
2390 assert(!IsTailCall &&
2391 "Do not tail-call optimize if there is a byval argument.");
2392 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2393 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2398 // Promote the value if needed.
2399 switch (VA.getLocInfo()) {
2400 default: llvm_unreachable("Unknown loc info!");
2401 case CCValAssign::Full:
2402 if (VA.isRegLoc()) {
2403 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2404 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2405 (ValVT == MVT::i64 && LocVT == MVT::f64))
2406 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2407 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2408 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2409 Arg, DAG.getConstant(0, MVT::i32));
2410 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2411 Arg, DAG.getConstant(1, MVT::i32));
2412 if (!Subtarget->isLittle())
2414 unsigned LocRegLo = VA.getLocReg();
2415 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2416 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2417 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2422 case CCValAssign::SExt:
2423 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2425 case CCValAssign::ZExt:
2426 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2428 case CCValAssign::AExt:
2429 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2433 // Arguments that can be passed on register must be kept at
2434 // RegsToPass vector
2435 if (VA.isRegLoc()) {
2436 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2440 // Register can't get to this point...
2441 assert(VA.isMemLoc());
2443 // emit ISD::STORE whichs stores the
2444 // parameter value to a stack Location
2445 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2446 Chain, Arg, DL, IsTailCall, DAG));
2449 // Transform all store nodes into one single node because all store
2450 // nodes are independent of each other.
2451 if (!MemOpChains.empty())
2452 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2453 &MemOpChains[0], MemOpChains.size());
2455 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2456 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2457 // node so that legalize doesn't hack it.
2458 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2459 bool GlobalOrExternal = false, InternalLinkage = false;
2461 EVT Ty = Callee.getValueType();
2463 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2465 const GlobalValue *Val = G->getGlobal();
2466 InternalLinkage = Val->hasInternalLinkage();
2468 if (InternalLinkage)
2469 Callee = getAddrLocal(G, Ty, DAG, HasMips64);
2471 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2472 MipsII::MO_CALL_LO16, Chain,
2473 FuncInfo->callPtrInfo(Val));
2475 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2476 FuncInfo->callPtrInfo(Val));
2478 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2479 MipsII::MO_NO_FLAG);
2480 GlobalOrExternal = true;
2482 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2483 const char *Sym = S->getSymbol();
2485 if (!IsN64 && !IsPIC) // !N64 && static
2486 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2487 MipsII::MO_NO_FLAG);
2489 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2490 MipsII::MO_CALL_LO16, Chain,
2491 FuncInfo->callPtrInfo(Sym));
2493 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2494 FuncInfo->callPtrInfo(Sym));
2496 GlobalOrExternal = true;
2499 SmallVector<SDValue, 8> Ops(1, Chain);
2500 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2502 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2503 CLI, Callee, Chain);
2506 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2508 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2509 SDValue InFlag = Chain.getValue(1);
2511 // Create the CALLSEQ_END node.
2512 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2513 DAG.getIntPtrConstant(0, true), InFlag, DL);
2514 InFlag = Chain.getValue(1);
2516 // Handle result values, copying them out of physregs into vregs that we
2518 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2519 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2522 /// LowerCallResult - Lower the result values of a call into the
2523 /// appropriate copies out of appropriate physical registers.
2525 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2526 CallingConv::ID CallConv, bool IsVarArg,
2527 const SmallVectorImpl<ISD::InputArg> &Ins,
2528 SDLoc DL, SelectionDAG &DAG,
2529 SmallVectorImpl<SDValue> &InVals,
2530 const SDNode *CallNode,
2531 const Type *RetTy) const {
2532 // Assign locations to each value returned by this call.
2533 SmallVector<CCValAssign, 16> RVLocs;
2534 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2535 getTargetMachine(), RVLocs, *DAG.getContext());
2536 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2538 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2541 // Copy all of the result registers out of their specified physreg.
2542 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2543 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2544 RVLocs[i].getLocVT(), InFlag);
2545 Chain = Val.getValue(1);
2546 InFlag = Val.getValue(2);
2548 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2549 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2551 InVals.push_back(Val);
2557 //===----------------------------------------------------------------------===//
2558 // Formal Arguments Calling Convention Implementation
2559 //===----------------------------------------------------------------------===//
2560 /// LowerFormalArguments - transform physical registers into virtual registers
2561 /// and generate load operations for arguments places on the stack.
2563 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2564 CallingConv::ID CallConv,
2566 const SmallVectorImpl<ISD::InputArg> &Ins,
2567 SDLoc DL, SelectionDAG &DAG,
2568 SmallVectorImpl<SDValue> &InVals)
2570 MachineFunction &MF = DAG.getMachineFunction();
2571 MachineFrameInfo *MFI = MF.getFrameInfo();
2572 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2574 MipsFI->setVarArgsFrameIndex(0);
2576 // Used with vargs to acumulate store chains.
2577 std::vector<SDValue> OutChains;
2579 // Assign locations to all of the incoming arguments.
2580 SmallVector<CCValAssign, 16> ArgLocs;
2581 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2582 getTargetMachine(), ArgLocs, *DAG.getContext());
2583 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2584 Function::const_arg_iterator FuncArg =
2585 DAG.getMachineFunction().getFunction()->arg_begin();
2586 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2588 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2589 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2590 MipsCCInfo.hasByValArg());
2592 unsigned CurArgIdx = 0;
2593 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2595 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2596 CCValAssign &VA = ArgLocs[i];
2597 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2598 CurArgIdx = Ins[i].OrigArgIndex;
2599 EVT ValVT = VA.getValVT();
2600 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2601 bool IsRegLoc = VA.isRegLoc();
2603 if (Flags.isByVal()) {
2604 assert(Flags.getByValSize() &&
2605 "ByVal args of size 0 should have been ignored by front-end.");
2606 assert(ByValArg != MipsCCInfo.byval_end());
2607 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2608 MipsCCInfo, *ByValArg);
2613 // Arguments stored on registers
2615 MVT RegVT = VA.getLocVT();
2616 unsigned ArgReg = VA.getLocReg();
2617 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2619 // Transform the arguments stored on
2620 // physical registers into virtual ones
2621 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2622 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2624 // If this is an 8 or 16-bit value, it has been passed promoted
2625 // to 32 bits. Insert an assert[sz]ext to capture this, then
2626 // truncate to the right size.
2627 if (VA.getLocInfo() != CCValAssign::Full) {
2628 unsigned Opcode = 0;
2629 if (VA.getLocInfo() == CCValAssign::SExt)
2630 Opcode = ISD::AssertSext;
2631 else if (VA.getLocInfo() == CCValAssign::ZExt)
2632 Opcode = ISD::AssertZext;
2634 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2635 DAG.getValueType(ValVT));
2636 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2639 // Handle floating point arguments passed in integer registers and
2640 // long double arguments passed in floating point registers.
2641 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2642 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2643 (RegVT == MVT::f64 && ValVT == MVT::i64))
2644 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2645 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2646 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2647 getNextIntArgReg(ArgReg), RC);
2648 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2649 if (!Subtarget->isLittle())
2650 std::swap(ArgValue, ArgValue2);
2651 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2652 ArgValue, ArgValue2);
2655 InVals.push_back(ArgValue);
2656 } else { // VA.isRegLoc()
2659 assert(VA.isMemLoc());
2661 // The stack pointer offset is relative to the caller stack frame.
2662 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2663 VA.getLocMemOffset(), true);
2665 // Create load nodes to retrieve arguments from the stack
2666 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2667 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2668 MachinePointerInfo::getFixedStack(FI),
2669 false, false, false, 0);
2670 InVals.push_back(Load);
2671 OutChains.push_back(Load.getValue(1));
2675 // The mips ABIs for returning structs by value requires that we copy
2676 // the sret argument into $v0 for the return. Save the argument into
2677 // a virtual register so that we can access it from the return points.
2678 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2679 unsigned Reg = MipsFI->getSRetReturnReg();
2681 Reg = MF.getRegInfo().
2682 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2683 MipsFI->setSRetReturnReg(Reg);
2685 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2686 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2690 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2692 // All stores are grouped in one node to allow the matching between
2693 // the size of Ins and InVals. This only happens when on varg functions
2694 if (!OutChains.empty()) {
2695 OutChains.push_back(Chain);
2696 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2697 &OutChains[0], OutChains.size());
2703 //===----------------------------------------------------------------------===//
2704 // Return Value Calling Convention Implementation
2705 //===----------------------------------------------------------------------===//
2708 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2709 MachineFunction &MF, bool IsVarArg,
2710 const SmallVectorImpl<ISD::OutputArg> &Outs,
2711 LLVMContext &Context) const {
2712 SmallVector<CCValAssign, 16> RVLocs;
2713 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2715 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2719 MipsTargetLowering::LowerReturn(SDValue Chain,
2720 CallingConv::ID CallConv, bool IsVarArg,
2721 const SmallVectorImpl<ISD::OutputArg> &Outs,
2722 const SmallVectorImpl<SDValue> &OutVals,
2723 SDLoc DL, SelectionDAG &DAG) const {
2724 // CCValAssign - represent the assignment of
2725 // the return value to a location
2726 SmallVector<CCValAssign, 16> RVLocs;
2727 MachineFunction &MF = DAG.getMachineFunction();
2729 // CCState - Info about the registers and stack slot.
2730 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2732 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2734 // Analyze return values.
2735 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2736 MF.getFunction()->getReturnType());
2739 SmallVector<SDValue, 4> RetOps(1, Chain);
2741 // Copy the result values into the output registers.
2742 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2743 SDValue Val = OutVals[i];
2744 CCValAssign &VA = RVLocs[i];
2745 assert(VA.isRegLoc() && "Can only return in registers!");
2747 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2748 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2750 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2752 // Guarantee that all emitted copies are stuck together with flags.
2753 Flag = Chain.getValue(1);
2754 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2757 // The mips ABIs for returning structs by value requires that we copy
2758 // the sret argument into $v0 for the return. We saved the argument into
2759 // a virtual register in the entry block, so now we copy the value out
2761 if (MF.getFunction()->hasStructRetAttr()) {
2762 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2763 unsigned Reg = MipsFI->getSRetReturnReg();
2766 llvm_unreachable("sret virtual register not created in the entry block");
2767 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2768 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2770 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2771 Flag = Chain.getValue(1);
2772 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2775 RetOps[0] = Chain; // Update chain.
2777 // Add the flag if we have it.
2779 RetOps.push_back(Flag);
2781 // Return on Mips is always a "jr $ra"
2782 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2785 //===----------------------------------------------------------------------===//
2786 // Mips Inline Assembly Support
2787 //===----------------------------------------------------------------------===//
2789 /// getConstraintType - Given a constraint letter, return the type of
2790 /// constraint it is for this target.
2791 MipsTargetLowering::ConstraintType MipsTargetLowering::
2792 getConstraintType(const std::string &Constraint) const
2794 // Mips specific constraints
2795 // GCC config/mips/constraints.md
2797 // 'd' : An address register. Equivalent to r
2798 // unless generating MIPS16 code.
2799 // 'y' : Equivalent to r; retained for
2800 // backwards compatibility.
2801 // 'c' : A register suitable for use in an indirect
2802 // jump. This will always be $25 for -mabicalls.
2803 // 'l' : The lo register. 1 word storage.
2804 // 'x' : The hilo register pair. Double word storage.
2805 if (Constraint.size() == 1) {
2806 switch (Constraint[0]) {
2814 return C_RegisterClass;
2819 return TargetLowering::getConstraintType(Constraint);
2822 /// Examine constraint type and operand type and determine a weight value.
2823 /// This object must already have been set up with the operand type
2824 /// and the current alternative constraint selected.
2825 TargetLowering::ConstraintWeight
2826 MipsTargetLowering::getSingleConstraintMatchWeight(
2827 AsmOperandInfo &info, const char *constraint) const {
2828 ConstraintWeight weight = CW_Invalid;
2829 Value *CallOperandVal = info.CallOperandVal;
2830 // If we don't have a value, we can't do a match,
2831 // but allow it at the lowest weight.
2832 if (CallOperandVal == NULL)
2834 Type *type = CallOperandVal->getType();
2835 // Look at the constraint type.
2836 switch (*constraint) {
2838 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2842 if (type->isIntegerTy())
2843 weight = CW_Register;
2845 case 'f': // FPU or MSA register
2846 if (Subtarget->hasMSA() && type->isVectorTy() &&
2847 cast<VectorType>(type)->getBitWidth() == 128)
2848 weight = CW_Register;
2849 else if (type->isFloatTy())
2850 weight = CW_Register;
2852 case 'c': // $25 for indirect jumps
2853 case 'l': // lo register
2854 case 'x': // hilo register pair
2855 if (type->isIntegerTy())
2856 weight = CW_SpecificReg;
2858 case 'I': // signed 16 bit immediate
2859 case 'J': // integer zero
2860 case 'K': // unsigned 16 bit immediate
2861 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2862 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2863 case 'O': // signed 15 bit immediate (+- 16383)
2864 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2865 if (isa<ConstantInt>(CallOperandVal))
2866 weight = CW_Constant;
2875 /// This is a helper function to parse a physical register string and split it
2876 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2877 /// that is returned indicates whether parsing was successful. The second flag
2878 /// is true if the numeric part exists.
2879 static std::pair<bool, bool>
2880 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2881 unsigned long long &Reg) {
2882 if (C.front() != '{' || C.back() != '}')
2883 return std::make_pair(false, false);
2885 // Search for the first numeric character.
2886 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2887 I = std::find_if(B, E, std::ptr_fun(isdigit));
2889 Prefix.assign(B, I - B);
2891 // The second flag is set to false if no numeric characters were found.
2893 return std::make_pair(true, false);
2895 // Parse the numeric characters.
2896 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2900 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2901 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2902 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2903 const TargetRegisterClass *RC;
2905 unsigned long long Reg;
2907 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2910 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2912 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2913 // No numeric characters follow "hi" or "lo".
2915 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2917 RC = TRI->getRegClass(Prefix == "hi" ?
2918 Mips::HI32RegClassID : Mips::LO32RegClassID);
2919 return std::make_pair(*(RC->begin()), RC);
2920 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2921 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2923 // No numeric characters follow the name.
2925 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2927 Reg = StringSwitch<unsigned long long>(Prefix)
2928 .Case("$msair", Mips::MSAIR)
2929 .Case("$msacsr", Mips::MSACSR)
2930 .Case("$msaaccess", Mips::MSAAccess)
2931 .Case("$msasave", Mips::MSASave)
2932 .Case("$msamodify", Mips::MSAModify)
2933 .Case("$msarequest", Mips::MSARequest)
2934 .Case("$msamap", Mips::MSAMap)
2935 .Case("$msaunmap", Mips::MSAUnmap)
2939 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2941 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2942 return std::make_pair(Reg, RC);
2946 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2948 if (Prefix == "$f") { // Parse $f0-$f31.
2949 // If the size of FP registers is 64-bit or Reg is an even number, select
2950 // the 64-bit register class. Otherwise, select the 32-bit register class.
2951 if (VT == MVT::Other)
2952 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2954 RC = getRegClassFor(VT);
2956 if (RC == &Mips::AFGR64RegClass) {
2957 assert(Reg % 2 == 0);
2960 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2961 RC = TRI->getRegClass(Mips::FCCRegClassID);
2962 else if (Prefix == "$w") { // Parse $w0-$w31.
2963 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2964 } else { // Parse $0-$31.
2965 assert(Prefix == "$");
2966 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2969 assert(Reg < RC->getNumRegs());
2970 return std::make_pair(*(RC->begin() + Reg), RC);
2973 /// Given a register class constraint, like 'r', if this corresponds directly
2974 /// to an LLVM register class, return a register of 0 and the register class
2976 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2977 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2979 if (Constraint.size() == 1) {
2980 switch (Constraint[0]) {
2981 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2982 case 'y': // Same as 'r'. Exists for compatibility.
2984 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2985 if (Subtarget->inMips16Mode())
2986 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2987 return std::make_pair(0U, &Mips::GPR32RegClass);
2989 if (VT == MVT::i64 && !HasMips64)
2990 return std::make_pair(0U, &Mips::GPR32RegClass);
2991 if (VT == MVT::i64 && HasMips64)
2992 return std::make_pair(0U, &Mips::GPR64RegClass);
2993 // This will generate an error message
2994 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2995 case 'f': // FPU or MSA register
2996 if (VT == MVT::v16i8)
2997 return std::make_pair(0U, &Mips::MSA128BRegClass);
2998 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
2999 return std::make_pair(0U, &Mips::MSA128HRegClass);
3000 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3001 return std::make_pair(0U, &Mips::MSA128WRegClass);
3002 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3003 return std::make_pair(0U, &Mips::MSA128DRegClass);
3004 else if (VT == MVT::f32)
3005 return std::make_pair(0U, &Mips::FGR32RegClass);
3006 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3007 if (Subtarget->isFP64bit())
3008 return std::make_pair(0U, &Mips::FGR64RegClass);
3009 return std::make_pair(0U, &Mips::AFGR64RegClass);
3012 case 'c': // register suitable for indirect jump
3014 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3015 assert(VT == MVT::i64 && "Unexpected type.");
3016 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3017 case 'l': // register suitable for indirect jump
3019 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3020 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3021 case 'x': // register suitable for indirect jump
3022 // Fixme: Not triggering the use of both hi and low
3023 // This will generate an error message
3024 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3028 std::pair<unsigned, const TargetRegisterClass *> R;
3029 R = parseRegForInlineAsmConstraint(Constraint, VT);
3034 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3037 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3038 /// vector. If it is invalid, don't add anything to Ops.
3039 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3040 std::string &Constraint,
3041 std::vector<SDValue>&Ops,
3042 SelectionDAG &DAG) const {
3043 SDValue Result(0, 0);
3045 // Only support length 1 constraints for now.
3046 if (Constraint.length() > 1) return;
3048 char ConstraintLetter = Constraint[0];
3049 switch (ConstraintLetter) {
3050 default: break; // This will fall through to the generic implementation
3051 case 'I': // Signed 16 bit constant
3052 // If this fails, the parent routine will give an error
3053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3054 EVT Type = Op.getValueType();
3055 int64_t Val = C->getSExtValue();
3056 if (isInt<16>(Val)) {
3057 Result = DAG.getTargetConstant(Val, Type);
3062 case 'J': // integer zero
3063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3064 EVT Type = Op.getValueType();
3065 int64_t Val = C->getZExtValue();
3067 Result = DAG.getTargetConstant(0, Type);
3072 case 'K': // unsigned 16 bit immediate
3073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3074 EVT Type = Op.getValueType();
3075 uint64_t Val = (uint64_t)C->getZExtValue();
3076 if (isUInt<16>(Val)) {
3077 Result = DAG.getTargetConstant(Val, Type);
3082 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3084 EVT Type = Op.getValueType();
3085 int64_t Val = C->getSExtValue();
3086 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3087 Result = DAG.getTargetConstant(Val, Type);
3092 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3094 EVT Type = Op.getValueType();
3095 int64_t Val = C->getSExtValue();
3096 if ((Val >= -65535) && (Val <= -1)) {
3097 Result = DAG.getTargetConstant(Val, Type);
3102 case 'O': // signed 15 bit immediate
3103 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3104 EVT Type = Op.getValueType();
3105 int64_t Val = C->getSExtValue();
3106 if ((isInt<15>(Val))) {
3107 Result = DAG.getTargetConstant(Val, Type);
3112 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3113 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3114 EVT Type = Op.getValueType();
3115 int64_t Val = C->getSExtValue();
3116 if ((Val <= 65535) && (Val >= 1)) {
3117 Result = DAG.getTargetConstant(Val, Type);
3124 if (Result.getNode()) {
3125 Ops.push_back(Result);
3129 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3132 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3134 // No global is ever allowed as a base.
3139 case 0: // "r+i" or just "i", depending on HasBaseReg.
3142 if (!AM.HasBaseReg) // allow "r+i".
3144 return false; // disallow "r+r" or "r+r+i".
3153 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3154 // The Mips target isn't yet aware of offsets.
3158 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3160 bool IsMemset, bool ZeroMemset,
3162 MachineFunction &MF) const {
3163 if (Subtarget->hasMips64())
3169 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3170 if (VT != MVT::f32 && VT != MVT::f64)
3172 if (Imm.isNegZero())
3174 return Imm.isZero();
3177 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3179 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3181 return TargetLowering::getJumpTableEncoding();
3184 /// This function returns true if CallSym is a long double emulation routine.
3185 static bool isF128SoftLibCall(const char *CallSym) {
3186 const char *const LibCalls[] =
3187 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3188 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3189 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3190 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3191 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3192 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3193 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3194 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3197 const char *const *End = LibCalls + array_lengthof(LibCalls);
3199 // Check that LibCalls is sorted alphabetically.
3200 MipsTargetLowering::LTStr Comp;
3203 for (const char *const *I = LibCalls; I < End - 1; ++I)
3204 assert(Comp(*I, *(I + 1)));
3207 return std::binary_search(LibCalls, End, CallSym, Comp);
3210 /// This function returns true if Ty is fp128 or i128 which was originally a
3212 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3213 if (Ty->isFP128Ty())
3216 const ExternalSymbolSDNode *ES =
3217 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3219 // If the Ty is i128 and the function being called is a long double emulation
3220 // routine, then the original type is f128.
3221 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3224 MipsTargetLowering::MipsCC::SpecialCallingConvType
3225 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3226 MipsCC::SpecialCallingConvType SpecialCallingConv =
3227 MipsCC::NoSpecialCallingConv;;
3228 if (Subtarget->inMips16HardFloat()) {
3229 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3230 llvm::StringRef Sym = G->getGlobal()->getName();
3231 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3232 if (F->hasFnAttribute("__Mips16RetHelper")) {
3233 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3237 return SpecialCallingConv;
3240 MipsTargetLowering::MipsCC::MipsCC(
3241 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3242 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3243 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3244 SpecialCallingConv(SpecialCallingConv_){
3245 // Pre-allocate reserved argument area.
3246 CCInfo.AllocateStack(reservedArgArea(), 1);
3250 void MipsTargetLowering::MipsCC::
3251 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3252 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3253 std::vector<ArgListEntry> &FuncArgs) {
3254 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3255 "CallingConv::Fast shouldn't be used for vararg functions.");
3257 unsigned NumOpnds = Args.size();
3258 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3260 for (unsigned I = 0; I != NumOpnds; ++I) {
3261 MVT ArgVT = Args[I].VT;
3262 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3265 if (ArgFlags.isByVal()) {
3266 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3270 if (IsVarArg && !Args[I].IsFixed)
3271 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3273 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3275 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3280 dbgs() << "Call operand #" << I << " has unhandled type "
3281 << EVT(ArgVT).getEVTString();
3283 llvm_unreachable(0);
3288 void MipsTargetLowering::MipsCC::
3289 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3290 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3291 unsigned NumArgs = Args.size();
3292 llvm::CCAssignFn *FixedFn = fixedArgFn();
3293 unsigned CurArgIdx = 0;
3295 for (unsigned I = 0; I != NumArgs; ++I) {
3296 MVT ArgVT = Args[I].VT;
3297 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3298 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3299 CurArgIdx = Args[I].OrigArgIndex;
3301 if (ArgFlags.isByVal()) {
3302 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3306 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3308 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3312 dbgs() << "Formal Arg #" << I << " has unhandled type "
3313 << EVT(ArgVT).getEVTString();
3315 llvm_unreachable(0);
3319 template<typename Ty>
3320 void MipsTargetLowering::MipsCC::
3321 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3322 const SDNode *CallNode, const Type *RetTy) const {
3325 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3326 Fn = RetCC_F128Soft;
3330 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3331 MVT VT = RetVals[I].VT;
3332 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3333 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3335 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3337 dbgs() << "Call result #" << I << " has unhandled type "
3338 << EVT(VT).getEVTString() << '\n';
3340 llvm_unreachable(0);
3345 void MipsTargetLowering::MipsCC::
3346 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3347 const SDNode *CallNode, const Type *RetTy) const {
3348 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3351 void MipsTargetLowering::MipsCC::
3352 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3353 const Type *RetTy) const {
3354 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3357 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3359 CCValAssign::LocInfo LocInfo,
3360 ISD::ArgFlagsTy ArgFlags) {
3361 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3363 struct ByValArgInfo ByVal;
3364 unsigned RegSize = regSize();
3365 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3366 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3369 if (useRegsForByval())
3370 allocateRegs(ByVal, ByValSize, Align);
3372 // Allocate space on caller's stack.
3373 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3375 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3377 ByValArgs.push_back(ByVal);
3380 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3381 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3384 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3385 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3388 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3389 return IsO32 ? O32IntRegs : Mips64IntRegs;
3392 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3393 if (CallConv == CallingConv::Fast)
3394 return CC_Mips_FastCC;
3396 if (SpecialCallingConv == Mips16RetHelperConv)
3397 return CC_Mips16RetHelper;
3398 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3401 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3402 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3405 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3406 return IsO32 ? O32IntRegs : Mips64DPRegs;
3409 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3412 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3413 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3414 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3415 "Byval argument's size and alignment should be a multiple of"
3418 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3420 // If Align > RegSize, the first arg register must be even.
3421 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3422 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3426 // Mark the registers allocated.
3427 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3428 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3429 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3432 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3433 const SDNode *CallNode,
3434 bool IsSoftFloat) const {
3435 if (IsSoftFloat || IsO32)
3438 // Check if the original type was fp128.
3439 if (originalTypeIsF128(OrigTy, CallNode)) {
3440 assert(VT == MVT::i64);
3447 void MipsTargetLowering::
3448 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3449 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3450 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3451 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3452 MachineFunction &MF = DAG.getMachineFunction();
3453 MachineFrameInfo *MFI = MF.getFrameInfo();
3454 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3455 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3459 FrameObjOffset = (int)CC.reservedArgArea() -
3460 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3462 FrameObjOffset = ByVal.Address;
3464 // Create frame object.
3465 EVT PtrTy = getPointerTy();
3466 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3467 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3468 InVals.push_back(FIN);
3473 // Copy arg registers.
3474 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3475 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3477 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3478 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3479 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3480 unsigned Offset = I * CC.regSize();
3481 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3482 DAG.getConstant(Offset, PtrTy));
3483 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3484 StorePtr, MachinePointerInfo(FuncArg, Offset),
3486 OutChains.push_back(Store);
3490 // Copy byVal arg to registers and stack.
3491 void MipsTargetLowering::
3492 passByValArg(SDValue Chain, SDLoc DL,
3493 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3494 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3495 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3496 const MipsCC &CC, const ByValArgInfo &ByVal,
3497 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3498 unsigned ByValSize = Flags.getByValSize();
3499 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3500 unsigned RegSize = CC.regSize();
3501 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3502 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3504 if (ByVal.NumRegs) {
3505 const uint16_t *ArgRegs = CC.intArgRegs();
3506 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3509 // Copy words to registers.
3510 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3511 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3512 DAG.getConstant(Offset, PtrTy));
3513 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3514 MachinePointerInfo(), false, false, false,
3516 MemOpChains.push_back(LoadVal.getValue(1));
3517 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3518 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3521 // Return if the struct has been fully copied.
3522 if (ByValSize == Offset)
3525 // Copy the remainder of the byval argument with sub-word loads and shifts.
3526 if (LeftoverBytes) {
3527 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3528 "Size of the remainder should be smaller than RegSize.");
3531 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3532 Offset < ByValSize; LoadSize /= 2) {
3533 unsigned RemSize = ByValSize - Offset;
3535 if (RemSize < LoadSize)
3539 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3540 DAG.getConstant(Offset, PtrTy));
3542 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3543 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3544 false, false, Alignment);
3545 MemOpChains.push_back(LoadVal.getValue(1));
3547 // Shift the loaded value.
3551 Shamt = TotalSizeLoaded;
3553 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3555 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3556 DAG.getConstant(Shamt, MVT::i32));
3559 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3564 TotalSizeLoaded += LoadSize;
3565 Alignment = std::min(Alignment, LoadSize);
3568 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3569 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3574 // Copy remainder of byval arg to it with memcpy.
3575 unsigned MemCpySize = ByValSize - Offset;
3576 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3577 DAG.getConstant(Offset, PtrTy));
3578 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3579 DAG.getIntPtrConstant(ByVal.Address));
3580 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3581 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3582 MachinePointerInfo(0), MachinePointerInfo(0));
3583 MemOpChains.push_back(Chain);
3586 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3587 const MipsCC &CC, SDValue Chain,
3588 SDLoc DL, SelectionDAG &DAG) const {
3589 unsigned NumRegs = CC.numIntArgRegs();
3590 const uint16_t *ArgRegs = CC.intArgRegs();
3591 const CCState &CCInfo = CC.getCCInfo();
3592 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3593 unsigned RegSize = CC.regSize();
3594 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3595 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3596 MachineFunction &MF = DAG.getMachineFunction();
3597 MachineFrameInfo *MFI = MF.getFrameInfo();
3598 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3600 // Offset of the first variable argument from stack pointer.
3604 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3606 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3608 // Record the frame index of the first variable argument
3609 // which is a value necessary to VASTART.
3610 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3611 MipsFI->setVarArgsFrameIndex(FI);
3613 // Copy the integer registers that have not been used for argument passing
3614 // to the argument register save area. For O32, the save area is allocated
3615 // in the caller's stack frame, while for N32/64, it is allocated in the
3616 // callee's stack frame.
3617 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3618 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3619 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3620 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3621 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3622 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3623 MachinePointerInfo(), false, false, 0);
3624 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3625 OutChains.push_back(Store);