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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "InstPrinter/MipsInstPrinter.h"
22 #include "MCTargetDesc/MipsBaseInfo.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
41 // If I is a shifted mask, set the size (Size) and the first bit of the
42 // mask (Pos), and return true.
43 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
44 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
45 if (!isShiftedMask_64(I))
48 Size = CountPopulation_64(I);
49 Pos = CountTrailingZeros_64(I);
53 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
54 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
55 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
58 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
60 case MipsISD::JmpLink: return "MipsISD::JmpLink";
61 case MipsISD::Hi: return "MipsISD::Hi";
62 case MipsISD::Lo: return "MipsISD::Lo";
63 case MipsISD::GPRel: return "MipsISD::GPRel";
64 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
65 case MipsISD::Ret: return "MipsISD::Ret";
66 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
67 case MipsISD::FPCmp: return "MipsISD::FPCmp";
68 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
69 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
70 case MipsISD::FPRound: return "MipsISD::FPRound";
71 case MipsISD::MAdd: return "MipsISD::MAdd";
72 case MipsISD::MAddu: return "MipsISD::MAddu";
73 case MipsISD::MSub: return "MipsISD::MSub";
74 case MipsISD::MSubu: return "MipsISD::MSubu";
75 case MipsISD::DivRem: return "MipsISD::DivRem";
76 case MipsISD::DivRemU: return "MipsISD::DivRemU";
77 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
78 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
79 case MipsISD::Wrapper: return "MipsISD::Wrapper";
80 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
81 case MipsISD::Sync: return "MipsISD::Sync";
82 case MipsISD::Ext: return "MipsISD::Ext";
83 case MipsISD::Ins: return "MipsISD::Ins";
89 MipsTargetLowering(MipsTargetMachine &TM)
90 : TargetLowering(TM, new MipsTargetObjectFile()),
91 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
92 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
93 IsO32(Subtarget->isABI_O32()) {
95 // Mips does not have i1 type, so use i32 for
96 // setcc operations results (slt, sgt, ...).
97 setBooleanContents(ZeroOrOneBooleanContent);
98 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
100 // Set up the register classes
101 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
104 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
106 if (Subtarget->inMips16Mode()) {
107 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
108 addRegisterClass(MVT::i32, &Mips::CPURARegRegClass);
111 if (!TM.Options.UseSoftFloat) {
112 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
114 // When dealing with single precision only, use libcalls
115 if (!Subtarget->isSingleFloat()) {
117 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
119 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
123 // Load extented operations for i1 types must be promoted
124 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
125 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
126 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
128 // MIPS doesn't have extending float->double load/store
129 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
130 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
132 // Used by legalize types to correctly generate the setcc result.
133 // Without this, every float setcc comes with a AND/OR with the result,
134 // we don't want this, since the fpcmp result goes to a flag register,
135 // which is used implicitly by brcond and select operations.
136 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
138 // Mips Custom Operations
139 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
140 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
141 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
142 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
143 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
144 setOperationAction(ISD::SELECT, MVT::f32, Custom);
145 setOperationAction(ISD::SELECT, MVT::f64, Custom);
146 setOperationAction(ISD::SELECT, MVT::i32, Custom);
147 setOperationAction(ISD::SETCC, MVT::f32, Custom);
148 setOperationAction(ISD::SETCC, MVT::f64, Custom);
149 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
150 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
151 setOperationAction(ISD::VASTART, MVT::Other, Custom);
152 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
153 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
154 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
155 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
157 if (!TM.Options.NoNaNsFPMath) {
158 setOperationAction(ISD::FABS, MVT::f32, Custom);
159 setOperationAction(ISD::FABS, MVT::f64, Custom);
163 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
164 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
165 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
166 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
167 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
168 setOperationAction(ISD::SELECT, MVT::i64, Custom);
169 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
173 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
174 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
175 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
178 setOperationAction(ISD::SDIV, MVT::i32, Expand);
179 setOperationAction(ISD::SREM, MVT::i32, Expand);
180 setOperationAction(ISD::UDIV, MVT::i32, Expand);
181 setOperationAction(ISD::UREM, MVT::i32, Expand);
182 setOperationAction(ISD::SDIV, MVT::i64, Expand);
183 setOperationAction(ISD::SREM, MVT::i64, Expand);
184 setOperationAction(ISD::UDIV, MVT::i64, Expand);
185 setOperationAction(ISD::UREM, MVT::i64, Expand);
187 // Operations not directly supported by Mips.
188 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
189 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
190 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
191 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
192 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
193 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
194 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
196 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
197 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
198 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
199 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
200 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
201 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
202 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
203 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
204 setOperationAction(ISD::ROTL, MVT::i32, Expand);
205 setOperationAction(ISD::ROTL, MVT::i64, Expand);
207 if (!Subtarget->hasMips32r2())
208 setOperationAction(ISD::ROTR, MVT::i32, Expand);
210 if (!Subtarget->hasMips64r2())
211 setOperationAction(ISD::ROTR, MVT::i64, Expand);
213 setOperationAction(ISD::FSIN, MVT::f32, Expand);
214 setOperationAction(ISD::FSIN, MVT::f64, Expand);
215 setOperationAction(ISD::FCOS, MVT::f32, Expand);
216 setOperationAction(ISD::FCOS, MVT::f64, Expand);
217 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
218 setOperationAction(ISD::FPOW, MVT::f32, Expand);
219 setOperationAction(ISD::FPOW, MVT::f64, Expand);
220 setOperationAction(ISD::FLOG, MVT::f32, Expand);
221 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
222 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
223 setOperationAction(ISD::FEXP, MVT::f32, Expand);
224 setOperationAction(ISD::FMA, MVT::f32, Expand);
225 setOperationAction(ISD::FMA, MVT::f64, Expand);
226 setOperationAction(ISD::FREM, MVT::f32, Expand);
227 setOperationAction(ISD::FREM, MVT::f64, Expand);
229 if (!TM.Options.NoNaNsFPMath) {
230 setOperationAction(ISD::FNEG, MVT::f32, Expand);
231 setOperationAction(ISD::FNEG, MVT::f64, Expand);
234 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
235 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
236 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
237 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
239 setOperationAction(ISD::VAARG, MVT::Other, Expand);
240 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
241 setOperationAction(ISD::VAEND, MVT::Other, Expand);
243 // Use the default for now
244 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
245 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
247 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
248 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
249 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
250 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
252 setInsertFencesForAtomic(true);
254 if (Subtarget->isSingleFloat())
255 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
257 if (!Subtarget->hasSEInReg()) {
258 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
259 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
262 if (!Subtarget->hasBitCount()) {
263 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
264 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
267 if (!Subtarget->hasSwap()) {
268 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
269 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
272 setTargetDAGCombine(ISD::ADDE);
273 setTargetDAGCombine(ISD::SUBE);
274 setTargetDAGCombine(ISD::SDIVREM);
275 setTargetDAGCombine(ISD::UDIVREM);
276 setTargetDAGCombine(ISD::SELECT);
277 setTargetDAGCombine(ISD::AND);
278 setTargetDAGCombine(ISD::OR);
280 setMinFunctionAlignment(HasMips64 ? 3 : 2);
282 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
283 computeRegisterProperties();
285 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
286 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
289 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
290 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
298 return Subtarget->hasMips32r2Or64();
304 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
309 // Transforms a subgraph in CurDAG if the following pattern is found:
310 // (addc multLo, Lo0), (adde multHi, Hi0),
312 // multHi/Lo: product of multiplication
313 // Lo0: initial value of Lo register
314 // Hi0: initial value of Hi register
315 // Return true if pattern matching was successful.
316 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
317 // ADDENode's second operand must be a flag output of an ADDC node in order
318 // for the matching to be successful.
319 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
321 if (ADDCNode->getOpcode() != ISD::ADDC)
324 SDValue MultHi = ADDENode->getOperand(0);
325 SDValue MultLo = ADDCNode->getOperand(0);
326 SDNode* MultNode = MultHi.getNode();
327 unsigned MultOpc = MultHi.getOpcode();
329 // MultHi and MultLo must be generated by the same node,
330 if (MultLo.getNode() != MultNode)
333 // and it must be a multiplication.
334 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
337 // MultLo amd MultHi must be the first and second output of MultNode
339 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
342 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
343 // of the values of MultNode, in which case MultNode will be removed in later
345 // If there exist users other than ADDENode or ADDCNode, this function returns
346 // here, which will result in MultNode being mapped to a single MULT
347 // instruction node rather than a pair of MULT and MADD instructions being
349 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
352 SDValue Chain = CurDAG->getEntryNode();
353 DebugLoc dl = ADDENode->getDebugLoc();
355 // create MipsMAdd(u) node
356 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
358 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
359 MultNode->getOperand(0),// Factor 0
360 MultNode->getOperand(1),// Factor 1
361 ADDCNode->getOperand(1),// Lo0
362 ADDENode->getOperand(1));// Hi0
364 // create CopyFromReg nodes
365 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
367 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
369 CopyFromLo.getValue(2));
371 // replace uses of adde and addc here
372 if (!SDValue(ADDCNode, 0).use_empty())
373 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
375 if (!SDValue(ADDENode, 0).use_empty())
376 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
382 // Transforms a subgraph in CurDAG if the following pattern is found:
383 // (addc Lo0, multLo), (sube Hi0, multHi),
385 // multHi/Lo: product of multiplication
386 // Lo0: initial value of Lo register
387 // Hi0: initial value of Hi register
388 // Return true if pattern matching was successful.
389 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
390 // SUBENode's second operand must be a flag output of an SUBC node in order
391 // for the matching to be successful.
392 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
394 if (SUBCNode->getOpcode() != ISD::SUBC)
397 SDValue MultHi = SUBENode->getOperand(1);
398 SDValue MultLo = SUBCNode->getOperand(1);
399 SDNode* MultNode = MultHi.getNode();
400 unsigned MultOpc = MultHi.getOpcode();
402 // MultHi and MultLo must be generated by the same node,
403 if (MultLo.getNode() != MultNode)
406 // and it must be a multiplication.
407 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
410 // MultLo amd MultHi must be the first and second output of MultNode
412 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
415 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
416 // of the values of MultNode, in which case MultNode will be removed in later
418 // If there exist users other than SUBENode or SUBCNode, this function returns
419 // here, which will result in MultNode being mapped to a single MULT
420 // instruction node rather than a pair of MULT and MSUB instructions being
422 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
425 SDValue Chain = CurDAG->getEntryNode();
426 DebugLoc dl = SUBENode->getDebugLoc();
428 // create MipsSub(u) node
429 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
431 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
432 MultNode->getOperand(0),// Factor 0
433 MultNode->getOperand(1),// Factor 1
434 SUBCNode->getOperand(0),// Lo0
435 SUBENode->getOperand(0));// Hi0
437 // create CopyFromReg nodes
438 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
440 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
442 CopyFromLo.getValue(2));
444 // replace uses of sube and subc here
445 if (!SDValue(SUBCNode, 0).use_empty())
446 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
448 if (!SDValue(SUBENode, 0).use_empty())
449 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
454 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
455 TargetLowering::DAGCombinerInfo &DCI,
456 const MipsSubtarget* Subtarget) {
457 if (DCI.isBeforeLegalize())
460 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
462 return SDValue(N, 0);
467 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
468 TargetLowering::DAGCombinerInfo &DCI,
469 const MipsSubtarget* Subtarget) {
470 if (DCI.isBeforeLegalize())
473 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
475 return SDValue(N, 0);
480 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
481 TargetLowering::DAGCombinerInfo &DCI,
482 const MipsSubtarget* Subtarget) {
483 if (DCI.isBeforeLegalizeOps())
486 EVT Ty = N->getValueType(0);
487 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
488 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
489 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
491 DebugLoc dl = N->getDebugLoc();
493 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
494 N->getOperand(0), N->getOperand(1));
495 SDValue InChain = DAG.getEntryNode();
496 SDValue InGlue = DivRem;
499 if (N->hasAnyUseOfValue(0)) {
500 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
502 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
503 InChain = CopyFromLo.getValue(1);
504 InGlue = CopyFromLo.getValue(2);
508 if (N->hasAnyUseOfValue(1)) {
509 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
511 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
517 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
519 default: llvm_unreachable("Unknown fp condition code!");
521 case ISD::SETOEQ: return Mips::FCOND_OEQ;
522 case ISD::SETUNE: return Mips::FCOND_UNE;
524 case ISD::SETOLT: return Mips::FCOND_OLT;
526 case ISD::SETOGT: return Mips::FCOND_OGT;
528 case ISD::SETOLE: return Mips::FCOND_OLE;
530 case ISD::SETOGE: return Mips::FCOND_OGE;
531 case ISD::SETULT: return Mips::FCOND_ULT;
532 case ISD::SETULE: return Mips::FCOND_ULE;
533 case ISD::SETUGT: return Mips::FCOND_UGT;
534 case ISD::SETUGE: return Mips::FCOND_UGE;
535 case ISD::SETUO: return Mips::FCOND_UN;
536 case ISD::SETO: return Mips::FCOND_OR;
538 case ISD::SETONE: return Mips::FCOND_ONE;
539 case ISD::SETUEQ: return Mips::FCOND_UEQ;
544 // Returns true if condition code has to be inverted.
545 static bool InvertFPCondCode(Mips::CondCode CC) {
546 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
549 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
550 "Illegal Condition Code");
555 // Creates and returns an FPCmp node from a setcc node.
556 // Returns Op if setcc is not a floating point comparison.
557 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
558 // must be a SETCC node
559 if (Op.getOpcode() != ISD::SETCC)
562 SDValue LHS = Op.getOperand(0);
564 if (!LHS.getValueType().isFloatingPoint())
567 SDValue RHS = Op.getOperand(1);
568 DebugLoc dl = Op.getDebugLoc();
570 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
571 // node if necessary.
572 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
574 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
575 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
578 // Creates and returns a CMovFPT/F node.
579 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
580 SDValue False, DebugLoc DL) {
581 bool invert = InvertFPCondCode((Mips::CondCode)
582 cast<ConstantSDNode>(Cond.getOperand(2))
585 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
586 True.getValueType(), True, False, Cond);
589 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG& DAG,
590 TargetLowering::DAGCombinerInfo &DCI,
591 const MipsSubtarget* Subtarget) {
592 if (DCI.isBeforeLegalizeOps())
595 SDValue SetCC = N->getOperand(0);
597 if ((SetCC.getOpcode() != ISD::SETCC) ||
598 !SetCC.getOperand(0).getValueType().isInteger())
601 SDValue False = N->getOperand(2);
602 EVT FalseTy = False.getValueType();
604 if (!FalseTy.isInteger())
607 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
609 if (!CN || CN->getZExtValue())
612 const DebugLoc DL = N->getDebugLoc();
613 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
614 SDValue True = N->getOperand(1);
616 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
617 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
619 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
622 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
623 TargetLowering::DAGCombinerInfo &DCI,
624 const MipsSubtarget* Subtarget) {
625 // Pattern match EXT.
626 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
627 // => ext $dst, $src, size, pos
628 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
631 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
632 unsigned ShiftRightOpc = ShiftRight.getOpcode();
634 // Op's first operand must be a shift right.
635 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
638 // The second operand of the shift must be an immediate.
640 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
643 uint64_t Pos = CN->getZExtValue();
644 uint64_t SMPos, SMSize;
646 // Op's second operand must be a shifted mask.
647 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
648 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
651 // Return if the shifted mask does not start at bit 0 or the sum of its size
652 // and Pos exceeds the word's size.
653 EVT ValTy = N->getValueType(0);
654 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
657 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
658 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
659 DAG.getConstant(SMSize, MVT::i32));
662 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
663 TargetLowering::DAGCombinerInfo &DCI,
664 const MipsSubtarget* Subtarget) {
665 // Pattern match INS.
666 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
667 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
668 // => ins $dst, $src, size, pos, $src1
669 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
672 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
673 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
676 // See if Op's first operand matches (and $src1 , mask0).
677 if (And0.getOpcode() != ISD::AND)
680 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
681 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
684 // See if Op's second operand matches (and (shl $src, pos), mask1).
685 if (And1.getOpcode() != ISD::AND)
688 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
689 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
692 // The shift masks must have the same position and size.
693 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
696 SDValue Shl = And1.getOperand(0);
697 if (Shl.getOpcode() != ISD::SHL)
700 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
703 unsigned Shamt = CN->getZExtValue();
705 // Return if the shift amount and the first bit position of mask are not the
707 EVT ValTy = N->getValueType(0);
708 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
711 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
712 DAG.getConstant(SMPos0, MVT::i32),
713 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
716 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
718 SelectionDAG &DAG = DCI.DAG;
719 unsigned opc = N->getOpcode();
724 return PerformADDECombine(N, DAG, DCI, Subtarget);
726 return PerformSUBECombine(N, DAG, DCI, Subtarget);
729 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
731 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
733 return PerformANDCombine(N, DAG, DCI, Subtarget);
735 return PerformORCombine(N, DAG, DCI, Subtarget);
741 SDValue MipsTargetLowering::
742 LowerOperation(SDValue Op, SelectionDAG &DAG) const
744 switch (Op.getOpcode())
746 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
747 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
748 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
749 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
750 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
751 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
752 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
753 case ISD::SELECT: return LowerSELECT(Op, DAG);
754 case ISD::SETCC: return LowerSETCC(Op, DAG);
755 case ISD::VASTART: return LowerVASTART(Op, DAG);
756 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
757 case ISD::FABS: return LowerFABS(Op, DAG);
758 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
759 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
760 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
761 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
762 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
763 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
768 //===----------------------------------------------------------------------===//
769 // Lower helper functions
770 //===----------------------------------------------------------------------===//
772 // AddLiveIn - This helper function adds the specified physical register to the
773 // MachineFunction as a live in value. It also creates a corresponding
774 // virtual register for it.
776 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
778 assert(RC->contains(PReg) && "Not the correct regclass!");
779 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
780 MF.getRegInfo().addLiveIn(PReg, VReg);
784 // Get fp branch code (not opcode) from condition code.
785 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
786 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
787 return Mips::BRANCH_T;
789 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
790 "Invalid CondCode.");
792 return Mips::BRANCH_F;
796 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
798 const MipsSubtarget* Subtarget,
799 const TargetInstrInfo *TII,
800 bool isFPCmp, unsigned Opc) {
801 // There is no need to expand CMov instructions if target has
802 // conditional moves.
803 if (Subtarget->hasCondMov())
806 // To "insert" a SELECT_CC instruction, we actually have to insert the
807 // diamond control-flow pattern. The incoming instruction knows the
808 // destination vreg to set, the condition code register to branch on, the
809 // true/false values to select between, and a branch opcode to use.
810 const BasicBlock *LLVM_BB = BB->getBasicBlock();
811 MachineFunction::iterator It = BB;
818 // bNE r1, r0, copy1MBB
819 // fallthrough --> copy0MBB
820 MachineBasicBlock *thisMBB = BB;
821 MachineFunction *F = BB->getParent();
822 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
823 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
824 F->insert(It, copy0MBB);
825 F->insert(It, sinkMBB);
827 // Transfer the remainder of BB and its successor edges to sinkMBB.
828 sinkMBB->splice(sinkMBB->begin(), BB,
829 llvm::next(MachineBasicBlock::iterator(MI)),
831 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
833 // Next, add the true and fallthrough blocks as its successors.
834 BB->addSuccessor(copy0MBB);
835 BB->addSuccessor(sinkMBB);
837 // Emit the right instruction according to the type of the operands compared
839 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
841 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
842 .addReg(Mips::ZERO).addMBB(sinkMBB);
846 // # fallthrough to sinkMBB
849 // Update machine-CFG edges
850 BB->addSuccessor(sinkMBB);
853 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
858 BuildMI(*BB, BB->begin(), dl,
859 TII->get(Mips::PHI), MI->getOperand(0).getReg())
860 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
861 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
863 BuildMI(*BB, BB->begin(), dl,
864 TII->get(Mips::PHI), MI->getOperand(0).getReg())
865 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
866 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
868 MI->eraseFromParent(); // The pseudo instruction is gone now.
873 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
874 MachineBasicBlock *BB) const {
875 switch (MI->getOpcode()) {
876 default: llvm_unreachable("Unexpected instr type to insert");
877 case Mips::ATOMIC_LOAD_ADD_I8:
878 case Mips::ATOMIC_LOAD_ADD_I8_P8:
879 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
880 case Mips::ATOMIC_LOAD_ADD_I16:
881 case Mips::ATOMIC_LOAD_ADD_I16_P8:
882 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
883 case Mips::ATOMIC_LOAD_ADD_I32:
884 case Mips::ATOMIC_LOAD_ADD_I32_P8:
885 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
886 case Mips::ATOMIC_LOAD_ADD_I64:
887 case Mips::ATOMIC_LOAD_ADD_I64_P8:
888 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
890 case Mips::ATOMIC_LOAD_AND_I8:
891 case Mips::ATOMIC_LOAD_AND_I8_P8:
892 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
893 case Mips::ATOMIC_LOAD_AND_I16:
894 case Mips::ATOMIC_LOAD_AND_I16_P8:
895 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
896 case Mips::ATOMIC_LOAD_AND_I32:
897 case Mips::ATOMIC_LOAD_AND_I32_P8:
898 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
899 case Mips::ATOMIC_LOAD_AND_I64:
900 case Mips::ATOMIC_LOAD_AND_I64_P8:
901 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
903 case Mips::ATOMIC_LOAD_OR_I8:
904 case Mips::ATOMIC_LOAD_OR_I8_P8:
905 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
906 case Mips::ATOMIC_LOAD_OR_I16:
907 case Mips::ATOMIC_LOAD_OR_I16_P8:
908 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
909 case Mips::ATOMIC_LOAD_OR_I32:
910 case Mips::ATOMIC_LOAD_OR_I32_P8:
911 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
912 case Mips::ATOMIC_LOAD_OR_I64:
913 case Mips::ATOMIC_LOAD_OR_I64_P8:
914 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
916 case Mips::ATOMIC_LOAD_XOR_I8:
917 case Mips::ATOMIC_LOAD_XOR_I8_P8:
918 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
919 case Mips::ATOMIC_LOAD_XOR_I16:
920 case Mips::ATOMIC_LOAD_XOR_I16_P8:
921 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
922 case Mips::ATOMIC_LOAD_XOR_I32:
923 case Mips::ATOMIC_LOAD_XOR_I32_P8:
924 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
925 case Mips::ATOMIC_LOAD_XOR_I64:
926 case Mips::ATOMIC_LOAD_XOR_I64_P8:
927 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
929 case Mips::ATOMIC_LOAD_NAND_I8:
930 case Mips::ATOMIC_LOAD_NAND_I8_P8:
931 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
932 case Mips::ATOMIC_LOAD_NAND_I16:
933 case Mips::ATOMIC_LOAD_NAND_I16_P8:
934 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
935 case Mips::ATOMIC_LOAD_NAND_I32:
936 case Mips::ATOMIC_LOAD_NAND_I32_P8:
937 return EmitAtomicBinary(MI, BB, 4, 0, true);
938 case Mips::ATOMIC_LOAD_NAND_I64:
939 case Mips::ATOMIC_LOAD_NAND_I64_P8:
940 return EmitAtomicBinary(MI, BB, 8, 0, true);
942 case Mips::ATOMIC_LOAD_SUB_I8:
943 case Mips::ATOMIC_LOAD_SUB_I8_P8:
944 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
945 case Mips::ATOMIC_LOAD_SUB_I16:
946 case Mips::ATOMIC_LOAD_SUB_I16_P8:
947 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
948 case Mips::ATOMIC_LOAD_SUB_I32:
949 case Mips::ATOMIC_LOAD_SUB_I32_P8:
950 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
951 case Mips::ATOMIC_LOAD_SUB_I64:
952 case Mips::ATOMIC_LOAD_SUB_I64_P8:
953 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
955 case Mips::ATOMIC_SWAP_I8:
956 case Mips::ATOMIC_SWAP_I8_P8:
957 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
958 case Mips::ATOMIC_SWAP_I16:
959 case Mips::ATOMIC_SWAP_I16_P8:
960 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
961 case Mips::ATOMIC_SWAP_I32:
962 case Mips::ATOMIC_SWAP_I32_P8:
963 return EmitAtomicBinary(MI, BB, 4, 0);
964 case Mips::ATOMIC_SWAP_I64:
965 case Mips::ATOMIC_SWAP_I64_P8:
966 return EmitAtomicBinary(MI, BB, 8, 0);
968 case Mips::ATOMIC_CMP_SWAP_I8:
969 case Mips::ATOMIC_CMP_SWAP_I8_P8:
970 return EmitAtomicCmpSwapPartword(MI, BB, 1);
971 case Mips::ATOMIC_CMP_SWAP_I16:
972 case Mips::ATOMIC_CMP_SWAP_I16_P8:
973 return EmitAtomicCmpSwapPartword(MI, BB, 2);
974 case Mips::ATOMIC_CMP_SWAP_I32:
975 case Mips::ATOMIC_CMP_SWAP_I32_P8:
976 return EmitAtomicCmpSwap(MI, BB, 4);
977 case Mips::ATOMIC_CMP_SWAP_I64:
978 case Mips::ATOMIC_CMP_SWAP_I64_P8:
979 return EmitAtomicCmpSwap(MI, BB, 8);
983 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
984 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
986 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
987 unsigned Size, unsigned BinOpcode,
989 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
991 MachineFunction *MF = BB->getParent();
992 MachineRegisterInfo &RegInfo = MF->getRegInfo();
993 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
994 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
995 DebugLoc dl = MI->getDebugLoc();
996 unsigned LL, SC, AND, NOR, ZERO, BEQ;
999 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1000 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1007 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1008 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1011 ZERO = Mips::ZERO_64;
1015 unsigned OldVal = MI->getOperand(0).getReg();
1016 unsigned Ptr = MI->getOperand(1).getReg();
1017 unsigned Incr = MI->getOperand(2).getReg();
1019 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1020 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1021 unsigned Success = RegInfo.createVirtualRegister(RC);
1023 // insert new blocks after the current block
1024 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1025 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1026 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1027 MachineFunction::iterator It = BB;
1029 MF->insert(It, loopMBB);
1030 MF->insert(It, exitMBB);
1032 // Transfer the remainder of BB and its successor edges to exitMBB.
1033 exitMBB->splice(exitMBB->begin(), BB,
1034 llvm::next(MachineBasicBlock::iterator(MI)),
1036 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1040 // fallthrough --> loopMBB
1041 BB->addSuccessor(loopMBB);
1042 loopMBB->addSuccessor(loopMBB);
1043 loopMBB->addSuccessor(exitMBB);
1046 // ll oldval, 0(ptr)
1047 // <binop> storeval, oldval, incr
1048 // sc success, storeval, 0(ptr)
1049 // beq success, $0, loopMBB
1051 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1053 // and andres, oldval, incr
1054 // nor storeval, $0, andres
1055 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1056 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1057 } else if (BinOpcode) {
1058 // <binop> storeval, oldval, incr
1059 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1063 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1064 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1066 MI->eraseFromParent(); // The instruction is gone now.
1072 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1073 MachineBasicBlock *BB,
1074 unsigned Size, unsigned BinOpcode,
1076 assert((Size == 1 || Size == 2) &&
1077 "Unsupported size for EmitAtomicBinaryPartial.");
1079 MachineFunction *MF = BB->getParent();
1080 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1081 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1082 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1083 DebugLoc dl = MI->getDebugLoc();
1084 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1085 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1087 unsigned Dest = MI->getOperand(0).getReg();
1088 unsigned Ptr = MI->getOperand(1).getReg();
1089 unsigned Incr = MI->getOperand(2).getReg();
1091 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1092 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1093 unsigned Mask = RegInfo.createVirtualRegister(RC);
1094 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1095 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1096 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1097 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1098 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1099 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1100 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1101 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1102 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1103 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1104 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1105 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1106 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1107 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1108 unsigned Success = RegInfo.createVirtualRegister(RC);
1110 // insert new blocks after the current block
1111 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1112 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1113 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1114 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1115 MachineFunction::iterator It = BB;
1117 MF->insert(It, loopMBB);
1118 MF->insert(It, sinkMBB);
1119 MF->insert(It, exitMBB);
1121 // Transfer the remainder of BB and its successor edges to exitMBB.
1122 exitMBB->splice(exitMBB->begin(), BB,
1123 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1124 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1126 BB->addSuccessor(loopMBB);
1127 loopMBB->addSuccessor(loopMBB);
1128 loopMBB->addSuccessor(sinkMBB);
1129 sinkMBB->addSuccessor(exitMBB);
1132 // addiu masklsb2,$0,-4 # 0xfffffffc
1133 // and alignedaddr,ptr,masklsb2
1134 // andi ptrlsb2,ptr,3
1135 // sll shiftamt,ptrlsb2,3
1136 // ori maskupper,$0,255 # 0xff
1137 // sll mask,maskupper,shiftamt
1138 // nor mask2,$0,mask
1139 // sll incr2,incr,shiftamt
1141 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1142 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1143 .addReg(Mips::ZERO).addImm(-4);
1144 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1145 .addReg(Ptr).addReg(MaskLSB2);
1146 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1147 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1148 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1149 .addReg(Mips::ZERO).addImm(MaskImm);
1150 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1151 .addReg(ShiftAmt).addReg(MaskUpper);
1152 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1153 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1155 // atomic.load.binop
1157 // ll oldval,0(alignedaddr)
1158 // binop binopres,oldval,incr2
1159 // and newval,binopres,mask
1160 // and maskedoldval0,oldval,mask2
1161 // or storeval,maskedoldval0,newval
1162 // sc success,storeval,0(alignedaddr)
1163 // beq success,$0,loopMBB
1167 // ll oldval,0(alignedaddr)
1168 // and newval,incr2,mask
1169 // and maskedoldval0,oldval,mask2
1170 // or storeval,maskedoldval0,newval
1171 // sc success,storeval,0(alignedaddr)
1172 // beq success,$0,loopMBB
1175 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1177 // and andres, oldval, incr2
1178 // nor binopres, $0, andres
1179 // and newval, binopres, mask
1180 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1181 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1182 .addReg(Mips::ZERO).addReg(AndRes);
1183 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1184 } else if (BinOpcode) {
1185 // <binop> binopres, oldval, incr2
1186 // and newval, binopres, mask
1187 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1188 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1189 } else {// atomic.swap
1190 // and newval, incr2, mask
1191 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1194 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1195 .addReg(OldVal).addReg(Mask2);
1196 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1197 .addReg(MaskedOldVal0).addReg(NewVal);
1198 BuildMI(BB, dl, TII->get(SC), Success)
1199 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1200 BuildMI(BB, dl, TII->get(Mips::BEQ))
1201 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1204 // and maskedoldval1,oldval,mask
1205 // srl srlres,maskedoldval1,shiftamt
1206 // sll sllres,srlres,24
1207 // sra dest,sllres,24
1209 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1211 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1212 .addReg(OldVal).addReg(Mask);
1213 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1214 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1215 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1216 .addReg(SrlRes).addImm(ShiftImm);
1217 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1218 .addReg(SllRes).addImm(ShiftImm);
1220 MI->eraseFromParent(); // The instruction is gone now.
1226 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1227 MachineBasicBlock *BB,
1228 unsigned Size) const {
1229 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1231 MachineFunction *MF = BB->getParent();
1232 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1233 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1234 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1235 DebugLoc dl = MI->getDebugLoc();
1236 unsigned LL, SC, ZERO, BNE, BEQ;
1239 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1240 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1246 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1247 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1248 ZERO = Mips::ZERO_64;
1253 unsigned Dest = MI->getOperand(0).getReg();
1254 unsigned Ptr = MI->getOperand(1).getReg();
1255 unsigned OldVal = MI->getOperand(2).getReg();
1256 unsigned NewVal = MI->getOperand(3).getReg();
1258 unsigned Success = RegInfo.createVirtualRegister(RC);
1260 // insert new blocks after the current block
1261 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1262 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1263 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1264 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1265 MachineFunction::iterator It = BB;
1267 MF->insert(It, loop1MBB);
1268 MF->insert(It, loop2MBB);
1269 MF->insert(It, exitMBB);
1271 // Transfer the remainder of BB and its successor edges to exitMBB.
1272 exitMBB->splice(exitMBB->begin(), BB,
1273 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1274 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1278 // fallthrough --> loop1MBB
1279 BB->addSuccessor(loop1MBB);
1280 loop1MBB->addSuccessor(exitMBB);
1281 loop1MBB->addSuccessor(loop2MBB);
1282 loop2MBB->addSuccessor(loop1MBB);
1283 loop2MBB->addSuccessor(exitMBB);
1287 // bne dest, oldval, exitMBB
1289 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1290 BuildMI(BB, dl, TII->get(BNE))
1291 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1294 // sc success, newval, 0(ptr)
1295 // beq success, $0, loop1MBB
1297 BuildMI(BB, dl, TII->get(SC), Success)
1298 .addReg(NewVal).addReg(Ptr).addImm(0);
1299 BuildMI(BB, dl, TII->get(BEQ))
1300 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1302 MI->eraseFromParent(); // The instruction is gone now.
1308 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1309 MachineBasicBlock *BB,
1310 unsigned Size) const {
1311 assert((Size == 1 || Size == 2) &&
1312 "Unsupported size for EmitAtomicCmpSwapPartial.");
1314 MachineFunction *MF = BB->getParent();
1315 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1316 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1317 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1318 DebugLoc dl = MI->getDebugLoc();
1319 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1320 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1322 unsigned Dest = MI->getOperand(0).getReg();
1323 unsigned Ptr = MI->getOperand(1).getReg();
1324 unsigned CmpVal = MI->getOperand(2).getReg();
1325 unsigned NewVal = MI->getOperand(3).getReg();
1327 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1328 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1329 unsigned Mask = RegInfo.createVirtualRegister(RC);
1330 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1331 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1332 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1333 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1334 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1335 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1336 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1337 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1338 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1339 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1340 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1341 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1342 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1343 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1344 unsigned Success = RegInfo.createVirtualRegister(RC);
1346 // insert new blocks after the current block
1347 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1348 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1349 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1350 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1351 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1352 MachineFunction::iterator It = BB;
1354 MF->insert(It, loop1MBB);
1355 MF->insert(It, loop2MBB);
1356 MF->insert(It, sinkMBB);
1357 MF->insert(It, exitMBB);
1359 // Transfer the remainder of BB and its successor edges to exitMBB.
1360 exitMBB->splice(exitMBB->begin(), BB,
1361 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1362 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1364 BB->addSuccessor(loop1MBB);
1365 loop1MBB->addSuccessor(sinkMBB);
1366 loop1MBB->addSuccessor(loop2MBB);
1367 loop2MBB->addSuccessor(loop1MBB);
1368 loop2MBB->addSuccessor(sinkMBB);
1369 sinkMBB->addSuccessor(exitMBB);
1371 // FIXME: computation of newval2 can be moved to loop2MBB.
1373 // addiu masklsb2,$0,-4 # 0xfffffffc
1374 // and alignedaddr,ptr,masklsb2
1375 // andi ptrlsb2,ptr,3
1376 // sll shiftamt,ptrlsb2,3
1377 // ori maskupper,$0,255 # 0xff
1378 // sll mask,maskupper,shiftamt
1379 // nor mask2,$0,mask
1380 // andi maskedcmpval,cmpval,255
1381 // sll shiftedcmpval,maskedcmpval,shiftamt
1382 // andi maskednewval,newval,255
1383 // sll shiftednewval,maskednewval,shiftamt
1384 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1385 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1386 .addReg(Mips::ZERO).addImm(-4);
1387 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1388 .addReg(Ptr).addReg(MaskLSB2);
1389 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1390 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1391 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1392 .addReg(Mips::ZERO).addImm(MaskImm);
1393 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1394 .addReg(ShiftAmt).addReg(MaskUpper);
1395 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1396 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1397 .addReg(CmpVal).addImm(MaskImm);
1398 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1399 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1400 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1401 .addReg(NewVal).addImm(MaskImm);
1402 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1403 .addReg(ShiftAmt).addReg(MaskedNewVal);
1406 // ll oldval,0(alginedaddr)
1407 // and maskedoldval0,oldval,mask
1408 // bne maskedoldval0,shiftedcmpval,sinkMBB
1410 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1411 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1412 .addReg(OldVal).addReg(Mask);
1413 BuildMI(BB, dl, TII->get(Mips::BNE))
1414 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1417 // and maskedoldval1,oldval,mask2
1418 // or storeval,maskedoldval1,shiftednewval
1419 // sc success,storeval,0(alignedaddr)
1420 // beq success,$0,loop1MBB
1422 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1423 .addReg(OldVal).addReg(Mask2);
1424 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1425 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1426 BuildMI(BB, dl, TII->get(SC), Success)
1427 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1428 BuildMI(BB, dl, TII->get(Mips::BEQ))
1429 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1432 // srl srlres,maskedoldval0,shiftamt
1433 // sll sllres,srlres,24
1434 // sra dest,sllres,24
1436 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1438 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1439 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1440 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1441 .addReg(SrlRes).addImm(ShiftImm);
1442 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1443 .addReg(SllRes).addImm(ShiftImm);
1445 MI->eraseFromParent(); // The instruction is gone now.
1450 //===----------------------------------------------------------------------===//
1451 // Misc Lower Operation implementation
1452 //===----------------------------------------------------------------------===//
1453 SDValue MipsTargetLowering::
1454 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1456 MachineFunction &MF = DAG.getMachineFunction();
1457 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1458 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1460 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1461 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1462 "Cannot lower if the alignment of the allocated space is larger than \
1463 that of the stack.");
1465 SDValue Chain = Op.getOperand(0);
1466 SDValue Size = Op.getOperand(1);
1467 DebugLoc dl = Op.getDebugLoc();
1469 // Get a reference from Mips stack pointer
1470 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1472 // Subtract the dynamic size from the actual stack size to
1473 // obtain the new stack size.
1474 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1476 // The Sub result contains the new stack start address, so it
1477 // must be placed in the stack pointer register.
1478 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1480 // This node always has two return values: a new stack pointer
1481 // value and a chain
1482 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1483 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1484 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1486 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1489 SDValue MipsTargetLowering::
1490 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1492 // The first operand is the chain, the second is the condition, the third is
1493 // the block to branch to if the condition is true.
1494 SDValue Chain = Op.getOperand(0);
1495 SDValue Dest = Op.getOperand(2);
1496 DebugLoc dl = Op.getDebugLoc();
1498 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1500 // Return if flag is not set by a floating point comparison.
1501 if (CondRes.getOpcode() != MipsISD::FPCmp)
1504 SDValue CCNode = CondRes.getOperand(2);
1506 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1507 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1509 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1513 SDValue MipsTargetLowering::
1514 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1516 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1518 // Return if flag is not set by a floating point comparison.
1519 if (Cond.getOpcode() != MipsISD::FPCmp)
1522 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1526 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1527 SDValue Cond = CreateFPCmp(DAG, Op);
1529 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1530 "Floating point operand expected.");
1532 SDValue True = DAG.getConstant(1, MVT::i32);
1533 SDValue False = DAG.getConstant(0, MVT::i32);
1535 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1538 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1539 SelectionDAG &DAG) const {
1540 // FIXME there isn't actually debug info here
1541 DebugLoc dl = Op.getDebugLoc();
1542 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1544 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1545 SDVTList VTs = DAG.getVTList(MVT::i32);
1547 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1549 // %gp_rel relocation
1550 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1551 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1553 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1554 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1555 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1557 // %hi/%lo relocation
1558 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1560 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1562 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1563 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1564 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1567 EVT ValTy = Op.getValueType();
1568 bool HasGotOfst = (GV->hasInternalLinkage() ||
1569 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1570 unsigned GotFlag = HasMips64 ?
1571 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1572 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1573 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1574 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1575 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1576 MachinePointerInfo(), false, false, false, 0);
1577 // On functions and global targets not internal linked only
1578 // a load from got/GP is necessary for PIC to work.
1581 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1582 HasMips64 ? MipsII::MO_GOT_OFST :
1584 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1585 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1588 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1589 SelectionDAG &DAG) const {
1590 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1591 // FIXME there isn't actually debug info here
1592 DebugLoc dl = Op.getDebugLoc();
1594 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1595 // %hi/%lo relocation
1596 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1597 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1598 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1599 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1600 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1603 EVT ValTy = Op.getValueType();
1604 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1605 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1606 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1607 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1608 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1609 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1610 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1611 MachinePointerInfo(), false, false, false, 0);
1612 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1613 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1616 SDValue MipsTargetLowering::
1617 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1619 // If the relocation model is PIC, use the General Dynamic TLS Model or
1620 // Local Dynamic TLS model, otherwise use the Initial Exec or
1621 // Local Exec TLS Model.
1623 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1624 DebugLoc dl = GA->getDebugLoc();
1625 const GlobalValue *GV = GA->getGlobal();
1626 EVT PtrVT = getPointerTy();
1628 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1630 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1631 // General Dynamic TLS Model
1632 bool LocalDynamic = GV->hasInternalLinkage();
1633 unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1634 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1635 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1636 GetGlobalReg(DAG, PtrVT), TGA);
1637 unsigned PtrSize = PtrVT.getSizeInBits();
1638 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1640 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1644 Entry.Node = Argument;
1646 Args.push_back(Entry);
1648 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1649 false, false, false, false, 0, CallingConv::C,
1650 /*isTailCall=*/false, /*doesNotRet=*/false,
1651 /*isReturnValueUsed=*/true,
1652 TlsGetAddr, Args, DAG, dl);
1653 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1655 SDValue Ret = CallResult.first;
1657 if (model != TLSModel::LocalDynamic)
1660 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1661 MipsII::MO_DTPREL_HI);
1662 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1663 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1664 MipsII::MO_DTPREL_LO);
1665 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1666 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1667 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1671 if (model == TLSModel::InitialExec) {
1672 // Initial Exec TLS Model
1673 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1674 MipsII::MO_GOTTPREL);
1675 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1677 Offset = DAG.getLoad(PtrVT, dl,
1678 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1679 false, false, false, 0);
1681 // Local Exec TLS Model
1682 assert(model == TLSModel::LocalExec);
1683 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1684 MipsII::MO_TPREL_HI);
1685 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1686 MipsII::MO_TPREL_LO);
1687 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1688 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1689 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1692 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1693 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1696 SDValue MipsTargetLowering::
1697 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1699 SDValue HiPart, JTI, JTILo;
1700 // FIXME there isn't actually debug info here
1701 DebugLoc dl = Op.getDebugLoc();
1702 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1703 EVT PtrVT = Op.getValueType();
1704 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1706 if (!IsPIC && !IsN64) {
1707 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1708 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1709 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1710 } else {// Emit Load from Global Pointer
1711 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1712 unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1713 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1714 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1716 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1717 MachinePointerInfo(), false, false, false, 0);
1718 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1721 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1722 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1725 SDValue MipsTargetLowering::
1726 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1729 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1730 const Constant *C = N->getConstVal();
1731 // FIXME there isn't actually debug info here
1732 DebugLoc dl = Op.getDebugLoc();
1734 // gp_rel relocation
1735 // FIXME: we should reference the constant pool using small data sections,
1736 // but the asm printer currently doesn't support this feature without
1737 // hacking it. This feature should come soon so we can uncomment the
1739 //if (IsInSmallSection(C->getType())) {
1740 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1741 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1742 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1744 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1745 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1746 N->getOffset(), MipsII::MO_ABS_HI);
1747 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1748 N->getOffset(), MipsII::MO_ABS_LO);
1749 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1750 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1751 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1753 EVT ValTy = Op.getValueType();
1754 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1755 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1756 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1757 N->getOffset(), GOTFlag);
1758 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1759 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1760 MachinePointerInfo::getConstantPool(), false,
1762 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1763 N->getOffset(), OFSTFlag);
1764 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1765 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1771 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1772 MachineFunction &MF = DAG.getMachineFunction();
1773 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1775 DebugLoc dl = Op.getDebugLoc();
1776 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1779 // vastart just stores the address of the VarArgsFrameIndex slot into the
1780 // memory location argument.
1781 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1782 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1783 MachinePointerInfo(SV), false, false, 0);
1786 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1787 EVT TyX = Op.getOperand(0).getValueType();
1788 EVT TyY = Op.getOperand(1).getValueType();
1789 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1790 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1791 DebugLoc DL = Op.getDebugLoc();
1794 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1796 SDValue X = (TyX == MVT::f32) ?
1797 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1798 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1800 SDValue Y = (TyY == MVT::f32) ?
1801 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1802 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1806 // ext E, Y, 31, 1 ; extract bit31 of Y
1807 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1808 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1809 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1812 // srl SrlX, SllX, 1
1814 // sll SllY, SrlX, 31
1815 // or Or, SrlX, SllY
1816 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1817 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1818 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1819 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1820 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1823 if (TyX == MVT::f32)
1824 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1826 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1827 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1828 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1831 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1832 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1833 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1834 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1835 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1836 DebugLoc DL = Op.getDebugLoc();
1838 // Bitcast to integer nodes.
1839 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1840 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1843 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1844 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1845 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1846 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1848 if (WidthX > WidthY)
1849 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1850 else if (WidthY > WidthX)
1851 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1853 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1854 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1855 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1858 // (d)sll SllX, X, 1
1859 // (d)srl SrlX, SllX, 1
1860 // (d)srl SrlY, Y, width(Y)-1
1861 // (d)sll SllY, SrlX, width(Y)-1
1862 // or Or, SrlX, SllY
1863 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1864 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1865 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1866 DAG.getConstant(WidthY - 1, MVT::i32));
1868 if (WidthX > WidthY)
1869 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1870 else if (WidthY > WidthX)
1871 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1873 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1874 DAG.getConstant(WidthX - 1, MVT::i32));
1875 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1876 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1880 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1881 if (Subtarget->hasMips64())
1882 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1884 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1887 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1888 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1889 DebugLoc DL = Op.getDebugLoc();
1891 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1893 SDValue X = (Op.getValueType() == MVT::f32) ?
1894 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1895 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1900 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1901 DAG.getRegister(Mips::ZERO, MVT::i32),
1902 DAG.getConstant(31, MVT::i32), Const1, X);
1904 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1905 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1908 if (Op.getValueType() == MVT::f32)
1909 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1911 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1912 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1913 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1916 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1917 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1918 DebugLoc DL = Op.getDebugLoc();
1920 // Bitcast to integer node.
1921 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1925 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1926 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1927 DAG.getConstant(63, MVT::i32), Const1, X);
1929 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1930 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1933 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1937 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
1938 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1939 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1941 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1944 SDValue MipsTargetLowering::
1945 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1947 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1948 "Frame address can only be determined for current frame.");
1950 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1951 MFI->setFrameAddressIsTaken(true);
1952 EVT VT = Op.getValueType();
1953 DebugLoc dl = Op.getDebugLoc();
1954 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1955 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1959 // TODO: set SType according to the desired memory barrier behavior.
1961 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1963 DebugLoc dl = Op.getDebugLoc();
1964 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1965 DAG.getConstant(SType, MVT::i32));
1968 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1969 SelectionDAG& DAG) const {
1970 // FIXME: Need pseudo-fence for 'singlethread' fences
1971 // FIXME: Set SType for weaker fences where supported/appropriate.
1973 DebugLoc dl = Op.getDebugLoc();
1974 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1975 DAG.getConstant(SType, MVT::i32));
1978 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
1979 SelectionDAG& DAG) const {
1980 DebugLoc DL = Op.getDebugLoc();
1981 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1982 SDValue Shamt = Op.getOperand(2);
1985 // lo = (shl lo, shamt)
1986 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1989 // hi = (shl lo, shamt[4:0])
1990 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1991 DAG.getConstant(-1, MVT::i32));
1992 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1993 DAG.getConstant(1, MVT::i32));
1994 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1996 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1997 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1998 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1999 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2000 DAG.getConstant(0x20, MVT::i32));
2001 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, DAG.getConstant(0, MVT::i32),
2003 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2005 SDValue Ops[2] = {Lo, Hi};
2006 return DAG.getMergeValues(Ops, 2, DL);
2009 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG& DAG,
2011 DebugLoc DL = Op.getDebugLoc();
2012 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2013 SDValue Shamt = Op.getOperand(2);
2016 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2018 // hi = (sra hi, shamt)
2020 // hi = (srl hi, shamt)
2023 // lo = (sra hi, shamt[4:0])
2024 // hi = (sra hi, 31)
2026 // lo = (srl hi, shamt[4:0])
2028 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2029 DAG.getConstant(-1, MVT::i32));
2030 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2031 DAG.getConstant(1, MVT::i32));
2032 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2033 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2034 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2035 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2037 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2038 DAG.getConstant(0x20, MVT::i32));
2039 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2040 DAG.getConstant(31, MVT::i32));
2041 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2042 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2043 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2046 SDValue Ops[2] = {Lo, Hi};
2047 return DAG.getMergeValues(Ops, 2, DL);
2050 //===----------------------------------------------------------------------===//
2051 // Calling Convention Implementation
2052 //===----------------------------------------------------------------------===//
2054 //===----------------------------------------------------------------------===//
2055 // TODO: Implement a generic logic using tblgen that can support this.
2056 // Mips O32 ABI rules:
2058 // i32 - Passed in A0, A1, A2, A3 and stack
2059 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2060 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2061 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2062 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2063 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2066 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2067 //===----------------------------------------------------------------------===//
2069 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2070 MVT LocVT, CCValAssign::LocInfo LocInfo,
2071 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2073 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2075 static const uint16_t IntRegs[] = {
2076 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2078 static const uint16_t F32Regs[] = {
2079 Mips::F12, Mips::F14
2081 static const uint16_t F64Regs[] = {
2086 if (ArgFlags.isByVal()) {
2087 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
2088 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
2089 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
2090 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
2091 r < std::min(IntRegsSize, NextReg); ++r)
2092 State.AllocateReg(IntRegs[r]);
2096 // Promote i8 and i16
2097 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2099 if (ArgFlags.isSExt())
2100 LocInfo = CCValAssign::SExt;
2101 else if (ArgFlags.isZExt())
2102 LocInfo = CCValAssign::ZExt;
2104 LocInfo = CCValAssign::AExt;
2109 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2110 // is true: function is vararg, argument is 3rd or higher, there is previous
2111 // argument which is not f32 or f64.
2112 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2113 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2114 unsigned OrigAlign = ArgFlags.getOrigAlign();
2115 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2117 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2118 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2119 // If this is the first part of an i64 arg,
2120 // the allocated register must be either A0 or A2.
2121 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2122 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2124 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2125 // Allocate int register and shadow next int register. If first
2126 // available register is Mips::A1 or Mips::A3, shadow it too.
2127 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2128 if (Reg == Mips::A1 || Reg == Mips::A3)
2129 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2130 State.AllocateReg(IntRegs, IntRegsSize);
2132 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2133 // we are guaranteed to find an available float register
2134 if (ValVT == MVT::f32) {
2135 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2136 // Shadow int register
2137 State.AllocateReg(IntRegs, IntRegsSize);
2139 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2140 // Shadow int registers
2141 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2142 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2143 State.AllocateReg(IntRegs, IntRegsSize);
2144 State.AllocateReg(IntRegs, IntRegsSize);
2147 llvm_unreachable("Cannot handle this ValVT.");
2149 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
2150 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
2153 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2155 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2157 return false; // CC must always match
2160 static const uint16_t Mips64IntRegs[8] =
2161 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
2162 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
2163 static const uint16_t Mips64DPRegs[8] =
2164 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
2165 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
2167 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
2168 CCValAssign::LocInfo LocInfo,
2169 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2170 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
2171 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
2172 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
2174 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
2176 // If byval is 16-byte aligned, the first arg register must be even.
2177 if ((Align == 16) && (FirstIdx % 2)) {
2178 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
2182 // Mark the registers allocated.
2183 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
2184 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
2186 // Allocate space on caller's stack.
2187 unsigned Offset = State.AllocateStack(Size, Align);
2190 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
2193 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2198 #include "MipsGenCallingConv.inc"
2201 AnalyzeMips64CallOperands(CCState &CCInfo,
2202 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2203 unsigned NumOps = Outs.size();
2204 for (unsigned i = 0; i != NumOps; ++i) {
2205 MVT ArgVT = Outs[i].VT;
2206 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2209 if (Outs[i].IsFixed)
2210 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2212 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2216 dbgs() << "Call operand #" << i << " has unhandled type "
2217 << EVT(ArgVT).getEVTString();
2219 llvm_unreachable(0);
2224 //===----------------------------------------------------------------------===//
2225 // Call Calling Convention Implementation
2226 //===----------------------------------------------------------------------===//
2228 static const unsigned O32IntRegsSize = 4;
2230 static const uint16_t O32IntRegs[] = {
2231 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2234 // Return next O32 integer argument register.
2235 static unsigned getNextIntArgReg(unsigned Reg) {
2236 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2237 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2240 // Write ByVal Arg to arg registers and stack.
2242 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2243 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2244 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2245 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2246 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2247 MVT PtrType, bool isLittle) {
2248 unsigned LocMemOffset = VA.getLocMemOffset();
2249 unsigned Offset = 0;
2250 uint32_t RemainingSize = Flags.getByValSize();
2251 unsigned ByValAlign = Flags.getByValAlign();
2253 // Copy the first 4 words of byval arg to registers A0 - A3.
2254 // FIXME: Use a stricter alignment if it enables better optimization in passes
2256 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2257 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2258 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2259 DAG.getConstant(Offset, MVT::i32));
2260 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2261 MachinePointerInfo(), false, false, false,
2262 std::min(ByValAlign, (unsigned )4));
2263 MemOpChains.push_back(LoadVal.getValue(1));
2264 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2265 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2268 if (RemainingSize == 0)
2271 // If there still is a register available for argument passing, write the
2272 // remaining part of the structure to it using subword loads and shifts.
2273 if (LocMemOffset < 4 * 4) {
2274 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2275 "There must be one to three bytes remaining.");
2276 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2277 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2278 DAG.getConstant(Offset, MVT::i32));
2279 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2280 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2281 LoadPtr, MachinePointerInfo(),
2282 MVT::getIntegerVT(LoadSize * 8), false,
2284 MemOpChains.push_back(LoadVal.getValue(1));
2286 // If target is big endian, shift it to the most significant half-word or
2289 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2290 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2293 RemainingSize -= LoadSize;
2295 // Read second subword if necessary.
2296 if (RemainingSize != 0) {
2297 assert(RemainingSize == 1 && "There must be one byte remaining.");
2298 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2299 DAG.getConstant(Offset, MVT::i32));
2300 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2301 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2302 LoadPtr, MachinePointerInfo(),
2303 MVT::i8, false, false, Alignment);
2304 MemOpChains.push_back(Subword.getValue(1));
2305 // Insert the loaded byte to LoadVal.
2306 // FIXME: Use INS if supported by target.
2307 unsigned ShiftAmt = isLittle ? 16 : 8;
2308 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2309 DAG.getConstant(ShiftAmt, MVT::i32));
2310 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2313 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2314 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2318 // Create a fixed object on stack at offset LocMemOffset and copy
2319 // remaining part of byval arg to it using memcpy.
2320 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2321 DAG.getConstant(Offset, MVT::i32));
2322 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2323 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2324 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2325 DAG.getConstant(RemainingSize, MVT::i32),
2326 std::min(ByValAlign, (unsigned)4),
2327 /*isVolatile=*/false, /*AlwaysInline=*/false,
2328 MachinePointerInfo(0), MachinePointerInfo(0));
2331 // Copy Mips64 byVal arg to registers and stack.
2333 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2334 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2335 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2336 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2337 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2338 EVT PtrTy, bool isLittle) {
2339 unsigned ByValSize = Flags.getByValSize();
2340 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2341 bool IsRegLoc = VA.isRegLoc();
2342 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2343 unsigned LocMemOffset = 0;
2344 unsigned MemCpySize = ByValSize;
2347 LocMemOffset = VA.getLocMemOffset();
2349 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2351 const uint16_t *RegEnd = Mips64IntRegs + 8;
2353 // Copy double words to registers.
2354 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2355 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2356 DAG.getConstant(Offset, PtrTy));
2357 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2358 MachinePointerInfo(), false, false, false,
2360 MemOpChains.push_back(LoadVal.getValue(1));
2361 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2364 // Return if the struct has been fully copied.
2365 if (!(MemCpySize = ByValSize - Offset))
2368 // If there is an argument register available, copy the remainder of the
2369 // byval argument with sub-doubleword loads and shifts.
2370 if (Reg != RegEnd) {
2371 assert((ByValSize < Offset + 8) &&
2372 "Size of the remainder should be smaller than 8-byte.");
2374 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2375 unsigned RemSize = ByValSize - Offset;
2377 if (RemSize < LoadSize)
2380 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2381 DAG.getConstant(Offset, PtrTy));
2383 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2384 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2385 false, false, Alignment);
2386 MemOpChains.push_back(LoadVal.getValue(1));
2388 // Offset in number of bits from double word boundary.
2389 unsigned OffsetDW = (Offset % 8) * 8;
2390 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2391 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2392 DAG.getConstant(Shamt, MVT::i32));
2394 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2397 Alignment = std::min(Alignment, LoadSize);
2400 RegsToPass.push_back(std::make_pair(*Reg, Val));
2405 assert(MemCpySize && "MemCpySize must not be zero.");
2407 // Create a fixed object on stack at offset LocMemOffset and copy
2408 // remainder of byval arg to it with memcpy.
2409 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2410 DAG.getConstant(Offset, PtrTy));
2411 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2412 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2413 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2414 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2415 /*isVolatile=*/false, /*AlwaysInline=*/false,
2416 MachinePointerInfo(0), MachinePointerInfo(0));
2419 /// LowerCall - functions arguments are copied from virtual regs to
2420 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2421 /// TODO: isTailCall.
2423 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2424 SmallVectorImpl<SDValue> &InVals) const {
2425 SelectionDAG &DAG = CLI.DAG;
2426 DebugLoc &dl = CLI.DL;
2427 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2428 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2429 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2430 SDValue InChain = CLI.Chain;
2431 SDValue Callee = CLI.Callee;
2432 bool &isTailCall = CLI.IsTailCall;
2433 CallingConv::ID CallConv = CLI.CallConv;
2434 bool isVarArg = CLI.IsVarArg;
2436 // MIPs target does not yet support tail call optimization.
2439 MachineFunction &MF = DAG.getMachineFunction();
2440 MachineFrameInfo *MFI = MF.getFrameInfo();
2441 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2442 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2443 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2445 // Analyze operands of the call, assigning locations to each operand.
2446 SmallVector<CCValAssign, 16> ArgLocs;
2447 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2448 getTargetMachine(), ArgLocs, *DAG.getContext());
2451 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2453 AnalyzeMips64CallOperands(CCInfo, Outs);
2455 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2457 // Get a count of how many bytes are to be pushed on the stack.
2458 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2460 // Chain is the output chain of the last Load/Store or CopyToReg node.
2461 // ByValChain is the output chain of the last Memcpy node created for copying
2462 // byval arguments to the stack.
2463 SDValue Chain, CallSeqStart, ByValChain;
2464 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2465 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2466 ByValChain = InChain;
2468 // Get the frame index of the stack frame object that points to the location
2469 // of dynamically allocated area on the stack.
2470 int DynAllocFI = MipsFI->getDynAllocFI();
2472 // Update size of the maximum argument space.
2473 // For O32, a minimum of four words (16 bytes) of argument space is
2476 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2478 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2480 if (MaxCallFrameSize < NextStackOffset) {
2481 MipsFI->setMaxCallFrameSize(NextStackOffset);
2483 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2484 // allocated stack space. These offsets must be aligned to a boundary
2485 // determined by the stack alignment of the ABI.
2486 unsigned StackAlignment = TFL->getStackAlignment();
2487 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2488 StackAlignment * StackAlignment;
2490 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2493 // With EABI is it possible to have 16 args on registers.
2494 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2495 SmallVector<SDValue, 8> MemOpChains;
2497 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2499 // Walk the register/memloc assignments, inserting copies/loads.
2500 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2501 SDValue Arg = OutVals[i];
2502 CCValAssign &VA = ArgLocs[i];
2503 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2504 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2507 if (Flags.isByVal()) {
2508 assert(Flags.getByValSize() &&
2509 "ByVal args of size 0 should have been ignored by front-end.");
2511 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2512 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2513 Subtarget->isLittle());
2515 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2516 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2517 Subtarget->isLittle());
2521 // Promote the value if needed.
2522 switch (VA.getLocInfo()) {
2523 default: llvm_unreachable("Unknown loc info!");
2524 case CCValAssign::Full:
2525 if (VA.isRegLoc()) {
2526 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2527 (ValVT == MVT::f64 && LocVT == MVT::i64))
2528 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2529 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2530 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2531 Arg, DAG.getConstant(0, MVT::i32));
2532 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2533 Arg, DAG.getConstant(1, MVT::i32));
2534 if (!Subtarget->isLittle())
2536 unsigned LocRegLo = VA.getLocReg();
2537 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2538 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2539 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2544 case CCValAssign::SExt:
2545 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2547 case CCValAssign::ZExt:
2548 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2550 case CCValAssign::AExt:
2551 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2555 // Arguments that can be passed on register must be kept at
2556 // RegsToPass vector
2557 if (VA.isRegLoc()) {
2558 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2562 // Register can't get to this point...
2563 assert(VA.isMemLoc());
2565 // Create the frame index object for this incoming parameter
2566 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2567 VA.getLocMemOffset(), true);
2568 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2570 // emit ISD::STORE whichs stores the
2571 // parameter value to a stack Location
2572 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2573 MachinePointerInfo(), false, false, 0));
2576 // Extend range of indices of frame objects for outgoing arguments that were
2577 // created during this function call. Skip this step if no such objects were
2580 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2582 // If a memcpy has been created to copy a byval arg to a stack, replace the
2583 // chain input of CallSeqStart with ByValChain.
2584 if (InChain != ByValChain)
2585 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2586 NextStackOffsetVal);
2588 // Transform all store nodes into one single node because all store
2589 // nodes are independent of each other.
2590 if (!MemOpChains.empty())
2591 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2592 &MemOpChains[0], MemOpChains.size());
2594 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2595 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2596 // node so that legalize doesn't hack it.
2597 unsigned char OpFlag;
2598 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2599 bool GlobalOrExternal = false;
2602 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2603 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2604 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2605 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2606 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2608 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2611 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2612 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2613 getPointerTy(), 0, OpFlag);
2616 GlobalOrExternal = true;
2618 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2619 if (IsN64 || (!IsO32 && IsPIC))
2620 OpFlag = MipsII::MO_GOT_DISP;
2621 else if (!IsPIC) // !N64 && static
2622 OpFlag = MipsII::MO_NO_FLAG;
2624 OpFlag = MipsII::MO_GOT_CALL;
2625 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2627 GlobalOrExternal = true;
2632 // Create nodes that load address of callee and copy it to T9
2634 if (GlobalOrExternal) {
2635 // Load callee address
2636 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2637 GetGlobalReg(DAG, getPointerTy()), Callee);
2638 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2639 Callee, MachinePointerInfo::getGOT(),
2640 false, false, false, 0);
2642 // Use GOT+LO if callee has internal linkage.
2643 if (CalleeLo.getNode()) {
2644 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2645 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2651 // T9 should contain the address of the callee function if
2652 // -reloction-model=pic or it is an indirect call.
2653 if (IsPICCall || !GlobalOrExternal) {
2655 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2656 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2657 InFlag = Chain.getValue(1);
2658 Callee = DAG.getRegister(T9Reg, getPointerTy());
2661 // Insert node "GP copy globalreg" before call to function.
2662 // Lazy-binding stubs require GP to point to the GOT.
2664 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2665 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2666 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2669 // Build a sequence of copy-to-reg nodes chained together with token
2670 // chain and flag operands which copy the outgoing args into registers.
2671 // The InFlag in necessary since all emitted instructions must be
2673 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2674 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2675 RegsToPass[i].second, InFlag);
2676 InFlag = Chain.getValue(1);
2679 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2680 // = Chain, Callee, Reg#1, Reg#2, ...
2682 // Returns a chain & a flag for retval copy to use.
2683 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2684 SmallVector<SDValue, 8> Ops;
2685 Ops.push_back(Chain);
2686 Ops.push_back(Callee);
2688 // Add argument registers to the end of the list so that they are
2689 // known live into the call.
2690 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2691 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2692 RegsToPass[i].second.getValueType()));
2694 // Add a register mask operand representing the call-preserved registers.
2695 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2696 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2697 assert(Mask && "Missing call preserved mask for calling convention");
2698 Ops.push_back(DAG.getRegisterMask(Mask));
2700 if (InFlag.getNode())
2701 Ops.push_back(InFlag);
2703 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2704 InFlag = Chain.getValue(1);
2706 // Create the CALLSEQ_END node.
2707 Chain = DAG.getCALLSEQ_END(Chain,
2708 DAG.getIntPtrConstant(NextStackOffset, true),
2709 DAG.getIntPtrConstant(0, true), InFlag);
2710 InFlag = Chain.getValue(1);
2712 // Handle result values, copying them out of physregs into vregs that we
2714 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2715 Ins, dl, DAG, InVals);
2718 /// LowerCallResult - Lower the result values of a call into the
2719 /// appropriate copies out of appropriate physical registers.
2721 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2722 CallingConv::ID CallConv, bool isVarArg,
2723 const SmallVectorImpl<ISD::InputArg> &Ins,
2724 DebugLoc dl, SelectionDAG &DAG,
2725 SmallVectorImpl<SDValue> &InVals) const {
2726 // Assign locations to each value returned by this call.
2727 SmallVector<CCValAssign, 16> RVLocs;
2728 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2729 getTargetMachine(), RVLocs, *DAG.getContext());
2731 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2733 // Copy all of the result registers out of their specified physreg.
2734 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2735 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2736 RVLocs[i].getValVT(), InFlag).getValue(1);
2737 InFlag = Chain.getValue(2);
2738 InVals.push_back(Chain.getValue(0));
2744 //===----------------------------------------------------------------------===//
2745 // Formal Arguments Calling Convention Implementation
2746 //===----------------------------------------------------------------------===//
2747 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2748 std::vector<SDValue>& OutChains,
2749 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2750 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2751 const Argument *FuncArg) {
2752 unsigned LocMem = VA.getLocMemOffset();
2753 unsigned FirstWord = LocMem / 4;
2755 // copy register A0 - A3 to frame object
2756 for (unsigned i = 0; i < NumWords; ++i) {
2757 unsigned CurWord = FirstWord + i;
2758 if (CurWord >= O32IntRegsSize)
2761 unsigned SrcReg = O32IntRegs[CurWord];
2762 unsigned Reg = AddLiveIn(MF, SrcReg, &Mips::CPURegsRegClass);
2763 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2764 DAG.getConstant(i * 4, MVT::i32));
2765 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2766 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2768 OutChains.push_back(Store);
2772 // Create frame object on stack and copy registers used for byval passing to it.
2774 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2775 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2776 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2777 MachineFrameInfo *MFI, bool IsRegLoc,
2778 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2779 EVT PtrTy, const Argument *FuncArg) {
2780 const uint16_t *Reg = Mips64IntRegs + 8;
2781 int FOOffset; // Frame object offset from virtual frame pointer.
2784 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2785 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2788 FOOffset = VA.getLocMemOffset();
2790 // Create frame object.
2791 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2792 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2793 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2794 InVals.push_back(FIN);
2796 // Copy arg registers.
2797 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2799 unsigned VReg = AddLiveIn(MF, *Reg, &Mips::CPU64RegsRegClass);
2800 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2801 DAG.getConstant(I * 8, PtrTy));
2802 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2803 StorePtr, MachinePointerInfo(FuncArg, I * 8),
2805 OutChains.push_back(Store);
2811 /// LowerFormalArguments - transform physical registers into virtual registers
2812 /// and generate load operations for arguments places on the stack.
2814 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2815 CallingConv::ID CallConv,
2817 const SmallVectorImpl<ISD::InputArg> &Ins,
2818 DebugLoc dl, SelectionDAG &DAG,
2819 SmallVectorImpl<SDValue> &InVals)
2821 MachineFunction &MF = DAG.getMachineFunction();
2822 MachineFrameInfo *MFI = MF.getFrameInfo();
2823 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2825 MipsFI->setVarArgsFrameIndex(0);
2827 // Used with vargs to acumulate store chains.
2828 std::vector<SDValue> OutChains;
2830 // Assign locations to all of the incoming arguments.
2831 SmallVector<CCValAssign, 16> ArgLocs;
2832 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2833 getTargetMachine(), ArgLocs, *DAG.getContext());
2836 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2838 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2840 Function::const_arg_iterator FuncArg =
2841 DAG.getMachineFunction().getFunction()->arg_begin();
2842 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2844 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
2845 CCValAssign &VA = ArgLocs[i];
2846 EVT ValVT = VA.getValVT();
2847 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2848 bool IsRegLoc = VA.isRegLoc();
2850 if (Flags.isByVal()) {
2851 assert(Flags.getByValSize() &&
2852 "ByVal args of size 0 should have been ignored by front-end.");
2854 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2855 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2857 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2858 InVals.push_back(FIN);
2859 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
2862 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2863 MFI, IsRegLoc, InVals, MipsFI,
2864 getPointerTy(), &*FuncArg);
2868 // Arguments stored on registers
2870 EVT RegVT = VA.getLocVT();
2871 unsigned ArgReg = VA.getLocReg();
2872 const TargetRegisterClass *RC;
2874 if (RegVT == MVT::i32)
2875 RC = &Mips::CPURegsRegClass;
2876 else if (RegVT == MVT::i64)
2877 RC = &Mips::CPU64RegsRegClass;
2878 else if (RegVT == MVT::f32)
2879 RC = &Mips::FGR32RegClass;
2880 else if (RegVT == MVT::f64)
2881 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2883 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2885 // Transform the arguments stored on
2886 // physical registers into virtual ones
2887 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2888 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2890 // If this is an 8 or 16-bit value, it has been passed promoted
2891 // to 32 bits. Insert an assert[sz]ext to capture this, then
2892 // truncate to the right size.
2893 if (VA.getLocInfo() != CCValAssign::Full) {
2894 unsigned Opcode = 0;
2895 if (VA.getLocInfo() == CCValAssign::SExt)
2896 Opcode = ISD::AssertSext;
2897 else if (VA.getLocInfo() == CCValAssign::ZExt)
2898 Opcode = ISD::AssertZext;
2900 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2901 DAG.getValueType(ValVT));
2902 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2905 // Handle floating point arguments passed in integer registers.
2906 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2907 (RegVT == MVT::i64 && ValVT == MVT::f64))
2908 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2909 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2910 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2911 getNextIntArgReg(ArgReg), RC);
2912 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2913 if (!Subtarget->isLittle())
2914 std::swap(ArgValue, ArgValue2);
2915 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2916 ArgValue, ArgValue2);
2919 InVals.push_back(ArgValue);
2920 } else { // VA.isRegLoc()
2923 assert(VA.isMemLoc());
2925 // The stack pointer offset is relative to the caller stack frame.
2926 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2927 VA.getLocMemOffset(), true);
2929 // Create load nodes to retrieve arguments from the stack
2930 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2931 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2932 MachinePointerInfo::getFixedStack(LastFI),
2933 false, false, false, 0));
2937 // The mips ABIs for returning structs by value requires that we copy
2938 // the sret argument into $v0 for the return. Save the argument into
2939 // a virtual register so that we can access it from the return points.
2940 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2941 unsigned Reg = MipsFI->getSRetReturnReg();
2943 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2944 MipsFI->setSRetReturnReg(Reg);
2946 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2947 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2951 unsigned NumOfRegs = IsO32 ? 4 : 8;
2952 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2953 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2954 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2955 const TargetRegisterClass *RC = IsO32 ?
2956 (const TargetRegisterClass*)&Mips::CPURegsRegClass :
2957 (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
2958 unsigned RegSize = RC->getSize();
2959 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2961 // Offset of the first variable argument from stack pointer.
2962 int FirstVaArgOffset;
2964 if (IsO32 || (Idx == NumOfRegs)) {
2966 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2968 FirstVaArgOffset = RegSlotOffset;
2970 // Record the frame index of the first variable argument
2971 // which is a value necessary to VASTART.
2972 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2973 MipsFI->setVarArgsFrameIndex(LastFI);
2975 // Copy the integer registers that have not been used for argument passing
2976 // to the argument register save area. For O32, the save area is allocated
2977 // in the caller's stack frame, while for N32/64, it is allocated in the
2978 // callee's stack frame.
2979 for (int StackOffset = RegSlotOffset;
2980 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2981 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2982 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2983 MVT::getIntegerVT(RegSize * 8));
2984 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2985 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2986 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2987 MachinePointerInfo(), false, false, 0));
2991 MipsFI->setLastInArgFI(LastFI);
2993 // All stores are grouped in one node to allow the matching between
2994 // the size of Ins and InVals. This only happens when on varg functions
2995 if (!OutChains.empty()) {
2996 OutChains.push_back(Chain);
2997 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2998 &OutChains[0], OutChains.size());
3004 //===----------------------------------------------------------------------===//
3005 // Return Value Calling Convention Implementation
3006 //===----------------------------------------------------------------------===//
3009 MipsTargetLowering::LowerReturn(SDValue Chain,
3010 CallingConv::ID CallConv, bool isVarArg,
3011 const SmallVectorImpl<ISD::OutputArg> &Outs,
3012 const SmallVectorImpl<SDValue> &OutVals,
3013 DebugLoc dl, SelectionDAG &DAG) const {
3015 // CCValAssign - represent the assignment of
3016 // the return value to a location
3017 SmallVector<CCValAssign, 16> RVLocs;
3019 // CCState - Info about the registers and stack slot.
3020 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3021 getTargetMachine(), RVLocs, *DAG.getContext());
3023 // Analize return values.
3024 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3026 // If this is the first return lowered for this function, add
3027 // the regs to the liveout set for the function.
3028 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3029 for (unsigned i = 0; i != RVLocs.size(); ++i)
3030 if (RVLocs[i].isRegLoc())
3031 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3036 // Copy the result values into the output registers.
3037 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3038 CCValAssign &VA = RVLocs[i];
3039 assert(VA.isRegLoc() && "Can only return in registers!");
3041 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3043 // guarantee that all emitted copies are
3044 // stuck together, avoiding something bad
3045 Flag = Chain.getValue(1);
3048 // The mips ABIs for returning structs by value requires that we copy
3049 // the sret argument into $v0 for the return. We saved the argument into
3050 // a virtual register in the entry block, so now we copy the value out
3052 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3053 MachineFunction &MF = DAG.getMachineFunction();
3054 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3055 unsigned Reg = MipsFI->getSRetReturnReg();
3058 llvm_unreachable("sret virtual register not created in the entry block");
3059 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3061 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
3062 Flag = Chain.getValue(1);
3065 // Return on Mips is always a "jr $ra"
3067 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3068 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
3070 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3071 Chain, DAG.getRegister(Mips::RA, MVT::i32));
3074 //===----------------------------------------------------------------------===//
3075 // Mips Inline Assembly Support
3076 //===----------------------------------------------------------------------===//
3078 /// getConstraintType - Given a constraint letter, return the type of
3079 /// constraint it is for this target.
3080 MipsTargetLowering::ConstraintType MipsTargetLowering::
3081 getConstraintType(const std::string &Constraint) const
3083 // Mips specific constrainy
3084 // GCC config/mips/constraints.md
3086 // 'd' : An address register. Equivalent to r
3087 // unless generating MIPS16 code.
3088 // 'y' : Equivalent to r; retained for
3089 // backwards compatibility.
3090 // 'c' : A register suitable for use in an indirect
3091 // jump. This will always be $25 for -mabicalls.
3092 // 'l' : The lo register. 1 word storage.
3093 // 'x' : The hilo register pair. Double word storage.
3094 if (Constraint.size() == 1) {
3095 switch (Constraint[0]) {
3103 return C_RegisterClass;
3106 return TargetLowering::getConstraintType(Constraint);
3109 /// Examine constraint type and operand type and determine a weight value.
3110 /// This object must already have been set up with the operand type
3111 /// and the current alternative constraint selected.
3112 TargetLowering::ConstraintWeight
3113 MipsTargetLowering::getSingleConstraintMatchWeight(
3114 AsmOperandInfo &info, const char *constraint) const {
3115 ConstraintWeight weight = CW_Invalid;
3116 Value *CallOperandVal = info.CallOperandVal;
3117 // If we don't have a value, we can't do a match,
3118 // but allow it at the lowest weight.
3119 if (CallOperandVal == NULL)
3121 Type *type = CallOperandVal->getType();
3122 // Look at the constraint type.
3123 switch (*constraint) {
3125 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3129 if (type->isIntegerTy())
3130 weight = CW_Register;
3133 if (type->isFloatTy())
3134 weight = CW_Register;
3136 case 'c': // $25 for indirect jumps
3137 case 'l': // lo register
3138 case 'x': // hilo register pair
3139 if (type->isIntegerTy())
3140 weight = CW_SpecificReg;
3142 case 'I': // signed 16 bit immediate
3143 case 'J': // integer zero
3144 case 'K': // unsigned 16 bit immediate
3145 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3146 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3147 case 'O': // signed 15 bit immediate (+- 16383)
3148 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3149 if (isa<ConstantInt>(CallOperandVal))
3150 weight = CW_Constant;
3156 /// Given a register class constraint, like 'r', if this corresponds directly
3157 /// to an LLVM register class, return a register of 0 and the register class
3159 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3160 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3162 if (Constraint.size() == 1) {
3163 switch (Constraint[0]) {
3164 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3165 case 'y': // Same as 'r'. Exists for compatibility.
3167 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
3168 return std::make_pair(0U, &Mips::CPURegsRegClass);
3169 if (VT == MVT::i64 && HasMips64)
3170 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3171 // This will generate an error message
3172 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3175 return std::make_pair(0U, &Mips::FGR32RegClass);
3176 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3177 if (Subtarget->isFP64bit())
3178 return std::make_pair(0U, &Mips::FGR64RegClass);
3179 return std::make_pair(0U, &Mips::AFGR64RegClass);
3182 case 'c': // register suitable for indirect jump
3184 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3185 assert(VT == MVT::i64 && "Unexpected type.");
3186 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3187 case 'l': // register suitable for indirect jump
3189 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3190 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3191 case 'x': // register suitable for indirect jump
3192 // Fixme: Not triggering the use of both hi and low
3193 // This will generate an error message
3194 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3197 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3200 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3201 /// vector. If it is invalid, don't add anything to Ops.
3202 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3203 std::string &Constraint,
3204 std::vector<SDValue>&Ops,
3205 SelectionDAG &DAG) const {
3206 SDValue Result(0, 0);
3208 // Only support length 1 constraints for now.
3209 if (Constraint.length() > 1) return;
3211 char ConstraintLetter = Constraint[0];
3212 switch (ConstraintLetter) {
3213 default: break; // This will fall through to the generic implementation
3214 case 'I': // Signed 16 bit constant
3215 // If this fails, the parent routine will give an error
3216 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3217 EVT Type = Op.getValueType();
3218 int64_t Val = C->getSExtValue();
3219 if (isInt<16>(Val)) {
3220 Result = DAG.getTargetConstant(Val, Type);
3225 case 'J': // integer zero
3226 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3227 EVT Type = Op.getValueType();
3228 int64_t Val = C->getZExtValue();
3230 Result = DAG.getTargetConstant(0, Type);
3235 case 'K': // unsigned 16 bit immediate
3236 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3237 EVT Type = Op.getValueType();
3238 uint64_t Val = (uint64_t)C->getZExtValue();
3239 if (isUInt<16>(Val)) {
3240 Result = DAG.getTargetConstant(Val, Type);
3245 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3246 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3247 EVT Type = Op.getValueType();
3248 int64_t Val = C->getSExtValue();
3249 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3250 Result = DAG.getTargetConstant(Val, Type);
3255 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3256 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3257 EVT Type = Op.getValueType();
3258 int64_t Val = C->getSExtValue();
3259 if ((Val >= -65535) && (Val <= -1)) {
3260 Result = DAG.getTargetConstant(Val, Type);
3265 case 'O': // signed 15 bit immediate
3266 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3267 EVT Type = Op.getValueType();
3268 int64_t Val = C->getSExtValue();
3269 if ((isInt<15>(Val))) {
3270 Result = DAG.getTargetConstant(Val, Type);
3275 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3276 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3277 EVT Type = Op.getValueType();
3278 int64_t Val = C->getSExtValue();
3279 if ((Val <= 65535) && (Val >= 1)) {
3280 Result = DAG.getTargetConstant(Val, Type);
3287 if (Result.getNode()) {
3288 Ops.push_back(Result);
3292 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3296 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3297 // The Mips target isn't yet aware of offsets.
3301 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3302 if (VT != MVT::f32 && VT != MVT::f64)
3304 if (Imm.isNegZero())
3306 return Imm.isZero();
3309 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3311 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3313 return TargetLowering::getJumpTableEncoding();