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"
39 // If I is a shifted mask, set the size (Size) and the first bit of the
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43 if (!isShiftedMask_64(I))
46 Size = CountPopulation_64(I);
47 Pos = CountTrailingZeros_64(I);
51 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
52 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
53 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
56 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
58 case MipsISD::JmpLink: return "MipsISD::JmpLink";
59 case MipsISD::Hi: return "MipsISD::Hi";
60 case MipsISD::Lo: return "MipsISD::Lo";
61 case MipsISD::GPRel: return "MipsISD::GPRel";
62 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
63 case MipsISD::Ret: return "MipsISD::Ret";
64 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
65 case MipsISD::FPCmp: return "MipsISD::FPCmp";
66 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
67 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
68 case MipsISD::FPRound: return "MipsISD::FPRound";
69 case MipsISD::MAdd: return "MipsISD::MAdd";
70 case MipsISD::MAddu: return "MipsISD::MAddu";
71 case MipsISD::MSub: return "MipsISD::MSub";
72 case MipsISD::MSubu: return "MipsISD::MSubu";
73 case MipsISD::DivRem: return "MipsISD::DivRem";
74 case MipsISD::DivRemU: return "MipsISD::DivRemU";
75 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
76 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
77 case MipsISD::Wrapper: return "MipsISD::Wrapper";
78 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
79 case MipsISD::Sync: return "MipsISD::Sync";
80 case MipsISD::Ext: return "MipsISD::Ext";
81 case MipsISD::Ins: return "MipsISD::Ins";
87 MipsTargetLowering(MipsTargetMachine &TM)
88 : TargetLowering(TM, new MipsTargetObjectFile()),
89 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
90 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
91 IsO32(Subtarget->isABI_O32()) {
93 // Mips does not have i1 type, so use i32 for
94 // setcc operations results (slt, sgt, ...).
95 setBooleanContents(ZeroOrOneBooleanContent);
96 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
98 // Set up the register classes
99 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
102 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
104 if (!TM.Options.UseSoftFloat) {
105 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
107 // When dealing with single precision only, use libcalls
108 if (!Subtarget->isSingleFloat()) {
110 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
112 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
116 // Load extented operations for i1 types must be promoted
117 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
118 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
119 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
121 // MIPS doesn't have extending float->double load/store
122 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
123 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
125 // Used by legalize types to correctly generate the setcc result.
126 // Without this, every float setcc comes with a AND/OR with the result,
127 // we don't want this, since the fpcmp result goes to a flag register,
128 // which is used implicitly by brcond and select operations.
129 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
131 // Mips Custom Operations
132 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
133 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
134 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
135 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
136 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
137 setOperationAction(ISD::SELECT, MVT::f32, Custom);
138 setOperationAction(ISD::SELECT, MVT::f64, Custom);
139 setOperationAction(ISD::SELECT, MVT::i32, Custom);
140 setOperationAction(ISD::SETCC, MVT::f32, Custom);
141 setOperationAction(ISD::SETCC, MVT::f64, Custom);
142 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
143 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
144 setOperationAction(ISD::VASTART, MVT::Other, Custom);
145 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
146 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
147 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
148 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
151 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
152 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
153 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
154 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
155 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
156 setOperationAction(ISD::SELECT, MVT::i64, Custom);
157 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
160 setOperationAction(ISD::SDIV, MVT::i32, Expand);
161 setOperationAction(ISD::SREM, MVT::i32, Expand);
162 setOperationAction(ISD::UDIV, MVT::i32, Expand);
163 setOperationAction(ISD::UREM, MVT::i32, Expand);
164 setOperationAction(ISD::SDIV, MVT::i64, Expand);
165 setOperationAction(ISD::SREM, MVT::i64, Expand);
166 setOperationAction(ISD::UDIV, MVT::i64, Expand);
167 setOperationAction(ISD::UREM, MVT::i64, Expand);
169 // Operations not directly supported by Mips.
170 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
171 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
172 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
173 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
174 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
175 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
176 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
177 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
178 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
179 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
180 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
181 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
182 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
183 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
184 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
185 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
186 setOperationAction(ISD::ROTL, MVT::i32, Expand);
187 setOperationAction(ISD::ROTL, MVT::i64, Expand);
189 if (!Subtarget->hasMips32r2())
190 setOperationAction(ISD::ROTR, MVT::i32, Expand);
192 if (!Subtarget->hasMips64r2())
193 setOperationAction(ISD::ROTR, MVT::i64, Expand);
195 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
196 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
197 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
198 setOperationAction(ISD::FSIN, MVT::f32, Expand);
199 setOperationAction(ISD::FSIN, MVT::f64, Expand);
200 setOperationAction(ISD::FCOS, MVT::f32, Expand);
201 setOperationAction(ISD::FCOS, MVT::f64, Expand);
202 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
203 setOperationAction(ISD::FPOW, MVT::f32, Expand);
204 setOperationAction(ISD::FPOW, MVT::f64, Expand);
205 setOperationAction(ISD::FLOG, MVT::f32, Expand);
206 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
207 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
208 setOperationAction(ISD::FEXP, MVT::f32, Expand);
209 setOperationAction(ISD::FMA, MVT::f32, Expand);
210 setOperationAction(ISD::FMA, MVT::f64, Expand);
212 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
213 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
214 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
215 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
217 setOperationAction(ISD::VAARG, MVT::Other, Expand);
218 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
219 setOperationAction(ISD::VAEND, MVT::Other, Expand);
221 // Use the default for now
222 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
223 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
225 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
226 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
227 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
228 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
230 setInsertFencesForAtomic(true);
232 if (Subtarget->isSingleFloat())
233 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
235 if (!Subtarget->hasSEInReg()) {
236 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
237 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
240 if (!Subtarget->hasBitCount()) {
241 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
242 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
245 if (!Subtarget->hasSwap()) {
246 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
247 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
250 setTargetDAGCombine(ISD::ADDE);
251 setTargetDAGCombine(ISD::SUBE);
252 setTargetDAGCombine(ISD::SDIVREM);
253 setTargetDAGCombine(ISD::UDIVREM);
254 setTargetDAGCombine(ISD::SELECT);
255 setTargetDAGCombine(ISD::AND);
256 setTargetDAGCombine(ISD::OR);
258 setMinFunctionAlignment(HasMips64 ? 3 : 2);
260 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
261 computeRegisterProperties();
263 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
264 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
267 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
268 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
276 return Subtarget->hasMips32r2Or64();
282 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
287 // Transforms a subgraph in CurDAG if the following pattern is found:
288 // (addc multLo, Lo0), (adde multHi, Hi0),
290 // multHi/Lo: product of multiplication
291 // Lo0: initial value of Lo register
292 // Hi0: initial value of Hi register
293 // Return true if pattern matching was successful.
294 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
295 // ADDENode's second operand must be a flag output of an ADDC node in order
296 // for the matching to be successful.
297 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
299 if (ADDCNode->getOpcode() != ISD::ADDC)
302 SDValue MultHi = ADDENode->getOperand(0);
303 SDValue MultLo = ADDCNode->getOperand(0);
304 SDNode* MultNode = MultHi.getNode();
305 unsigned MultOpc = MultHi.getOpcode();
307 // MultHi and MultLo must be generated by the same node,
308 if (MultLo.getNode() != MultNode)
311 // and it must be a multiplication.
312 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
315 // MultLo amd MultHi must be the first and second output of MultNode
317 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
320 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
321 // of the values of MultNode, in which case MultNode will be removed in later
323 // If there exist users other than ADDENode or ADDCNode, this function returns
324 // here, which will result in MultNode being mapped to a single MULT
325 // instruction node rather than a pair of MULT and MADD instructions being
327 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
330 SDValue Chain = CurDAG->getEntryNode();
331 DebugLoc dl = ADDENode->getDebugLoc();
333 // create MipsMAdd(u) node
334 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
336 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
337 MultNode->getOperand(0),// Factor 0
338 MultNode->getOperand(1),// Factor 1
339 ADDCNode->getOperand(1),// Lo0
340 ADDENode->getOperand(1));// Hi0
342 // create CopyFromReg nodes
343 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
345 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
347 CopyFromLo.getValue(2));
349 // replace uses of adde and addc here
350 if (!SDValue(ADDCNode, 0).use_empty())
351 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
353 if (!SDValue(ADDENode, 0).use_empty())
354 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
360 // Transforms a subgraph in CurDAG if the following pattern is found:
361 // (addc Lo0, multLo), (sube Hi0, multHi),
363 // multHi/Lo: product of multiplication
364 // Lo0: initial value of Lo register
365 // Hi0: initial value of Hi register
366 // Return true if pattern matching was successful.
367 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
368 // SUBENode's second operand must be a flag output of an SUBC node in order
369 // for the matching to be successful.
370 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
372 if (SUBCNode->getOpcode() != ISD::SUBC)
375 SDValue MultHi = SUBENode->getOperand(1);
376 SDValue MultLo = SUBCNode->getOperand(1);
377 SDNode* MultNode = MultHi.getNode();
378 unsigned MultOpc = MultHi.getOpcode();
380 // MultHi and MultLo must be generated by the same node,
381 if (MultLo.getNode() != MultNode)
384 // and it must be a multiplication.
385 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
388 // MultLo amd MultHi must be the first and second output of MultNode
390 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
393 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
394 // of the values of MultNode, in which case MultNode will be removed in later
396 // If there exist users other than SUBENode or SUBCNode, this function returns
397 // here, which will result in MultNode being mapped to a single MULT
398 // instruction node rather than a pair of MULT and MSUB instructions being
400 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
403 SDValue Chain = CurDAG->getEntryNode();
404 DebugLoc dl = SUBENode->getDebugLoc();
406 // create MipsSub(u) node
407 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
409 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
410 MultNode->getOperand(0),// Factor 0
411 MultNode->getOperand(1),// Factor 1
412 SUBCNode->getOperand(0),// Lo0
413 SUBENode->getOperand(0));// Hi0
415 // create CopyFromReg nodes
416 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
418 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
420 CopyFromLo.getValue(2));
422 // replace uses of sube and subc here
423 if (!SDValue(SUBCNode, 0).use_empty())
424 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
426 if (!SDValue(SUBENode, 0).use_empty())
427 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
432 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
433 TargetLowering::DAGCombinerInfo &DCI,
434 const MipsSubtarget* Subtarget) {
435 if (DCI.isBeforeLegalize())
438 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
440 return SDValue(N, 0);
445 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
446 TargetLowering::DAGCombinerInfo &DCI,
447 const MipsSubtarget* Subtarget) {
448 if (DCI.isBeforeLegalize())
451 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
453 return SDValue(N, 0);
458 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
459 TargetLowering::DAGCombinerInfo &DCI,
460 const MipsSubtarget* Subtarget) {
461 if (DCI.isBeforeLegalizeOps())
464 EVT Ty = N->getValueType(0);
465 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
466 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
467 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
469 DebugLoc dl = N->getDebugLoc();
471 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
472 N->getOperand(0), N->getOperand(1));
473 SDValue InChain = DAG.getEntryNode();
474 SDValue InGlue = DivRem;
477 if (N->hasAnyUseOfValue(0)) {
478 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
480 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
481 InChain = CopyFromLo.getValue(1);
482 InGlue = CopyFromLo.getValue(2);
486 if (N->hasAnyUseOfValue(1)) {
487 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
489 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
495 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
497 default: llvm_unreachable("Unknown fp condition code!");
499 case ISD::SETOEQ: return Mips::FCOND_OEQ;
500 case ISD::SETUNE: return Mips::FCOND_UNE;
502 case ISD::SETOLT: return Mips::FCOND_OLT;
504 case ISD::SETOGT: return Mips::FCOND_OGT;
506 case ISD::SETOLE: return Mips::FCOND_OLE;
508 case ISD::SETOGE: return Mips::FCOND_OGE;
509 case ISD::SETULT: return Mips::FCOND_ULT;
510 case ISD::SETULE: return Mips::FCOND_ULE;
511 case ISD::SETUGT: return Mips::FCOND_UGT;
512 case ISD::SETUGE: return Mips::FCOND_UGE;
513 case ISD::SETUO: return Mips::FCOND_UN;
514 case ISD::SETO: return Mips::FCOND_OR;
516 case ISD::SETONE: return Mips::FCOND_ONE;
517 case ISD::SETUEQ: return Mips::FCOND_UEQ;
522 // Returns true if condition code has to be inverted.
523 static bool InvertFPCondCode(Mips::CondCode CC) {
524 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
527 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
528 "Illegal Condition Code");
533 // Creates and returns an FPCmp node from a setcc node.
534 // Returns Op if setcc is not a floating point comparison.
535 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
536 // must be a SETCC node
537 if (Op.getOpcode() != ISD::SETCC)
540 SDValue LHS = Op.getOperand(0);
542 if (!LHS.getValueType().isFloatingPoint())
545 SDValue RHS = Op.getOperand(1);
546 DebugLoc dl = Op.getDebugLoc();
548 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
549 // node if necessary.
550 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
552 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
553 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
556 // Creates and returns a CMovFPT/F node.
557 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
558 SDValue False, DebugLoc DL) {
559 bool invert = InvertFPCondCode((Mips::CondCode)
560 cast<ConstantSDNode>(Cond.getOperand(2))
563 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
564 True.getValueType(), True, False, Cond);
567 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG& DAG,
568 TargetLowering::DAGCombinerInfo &DCI,
569 const MipsSubtarget* Subtarget) {
570 if (DCI.isBeforeLegalizeOps())
573 SDValue SetCC = N->getOperand(0);
575 if ((SetCC.getOpcode() != ISD::SETCC) ||
576 !SetCC.getOperand(0).getValueType().isInteger())
579 SDValue False = N->getOperand(2);
580 EVT FalseTy = False.getValueType();
582 if (!FalseTy.isInteger())
585 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
587 if (!CN || CN->getZExtValue())
590 const DebugLoc DL = N->getDebugLoc();
591 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
592 SDValue True = N->getOperand(1);
594 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
595 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
597 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
600 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
601 TargetLowering::DAGCombinerInfo &DCI,
602 const MipsSubtarget* Subtarget) {
603 // Pattern match EXT.
604 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
605 // => ext $dst, $src, size, pos
606 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
609 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
610 unsigned ShiftRightOpc = ShiftRight.getOpcode();
612 // Op's first operand must be a shift right.
613 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
616 // The second operand of the shift must be an immediate.
618 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
621 uint64_t Pos = CN->getZExtValue();
622 uint64_t SMPos, SMSize;
624 // Op's second operand must be a shifted mask.
625 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
626 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
629 // Return if the shifted mask does not start at bit 0 or the sum of its size
630 // and Pos exceeds the word's size.
631 EVT ValTy = N->getValueType(0);
632 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
635 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
636 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
637 DAG.getConstant(SMSize, MVT::i32));
640 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
641 TargetLowering::DAGCombinerInfo &DCI,
642 const MipsSubtarget* Subtarget) {
643 // Pattern match INS.
644 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
645 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
646 // => ins $dst, $src, size, pos, $src1
647 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
650 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
651 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
654 // See if Op's first operand matches (and $src1 , mask0).
655 if (And0.getOpcode() != ISD::AND)
658 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
659 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
662 // See if Op's second operand matches (and (shl $src, pos), mask1).
663 if (And1.getOpcode() != ISD::AND)
666 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
667 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
670 // The shift masks must have the same position and size.
671 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
674 SDValue Shl = And1.getOperand(0);
675 if (Shl.getOpcode() != ISD::SHL)
678 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
681 unsigned Shamt = CN->getZExtValue();
683 // Return if the shift amount and the first bit position of mask are not the
685 EVT ValTy = N->getValueType(0);
686 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
689 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
690 DAG.getConstant(SMPos0, MVT::i32),
691 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
694 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
696 SelectionDAG &DAG = DCI.DAG;
697 unsigned opc = N->getOpcode();
702 return PerformADDECombine(N, DAG, DCI, Subtarget);
704 return PerformSUBECombine(N, DAG, DCI, Subtarget);
707 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
709 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
711 return PerformANDCombine(N, DAG, DCI, Subtarget);
713 return PerformORCombine(N, DAG, DCI, Subtarget);
719 SDValue MipsTargetLowering::
720 LowerOperation(SDValue Op, SelectionDAG &DAG) const
722 switch (Op.getOpcode())
724 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
725 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
726 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
727 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
728 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
729 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
730 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
731 case ISD::SELECT: return LowerSELECT(Op, DAG);
732 case ISD::SETCC: return LowerSETCC(Op, DAG);
733 case ISD::VASTART: return LowerVASTART(Op, DAG);
734 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
735 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
736 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
737 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
742 //===----------------------------------------------------------------------===//
743 // Lower helper functions
744 //===----------------------------------------------------------------------===//
746 // AddLiveIn - This helper function adds the specified physical register to the
747 // MachineFunction as a live in value. It also creates a corresponding
748 // virtual register for it.
750 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
752 assert(RC->contains(PReg) && "Not the correct regclass!");
753 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
754 MF.getRegInfo().addLiveIn(PReg, VReg);
758 // Get fp branch code (not opcode) from condition code.
759 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
760 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
761 return Mips::BRANCH_T;
763 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
764 "Invalid CondCode.");
766 return Mips::BRANCH_F;
770 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
772 const MipsSubtarget* Subtarget,
773 const TargetInstrInfo *TII,
774 bool isFPCmp, unsigned Opc) {
775 // There is no need to expand CMov instructions if target has
776 // conditional moves.
777 if (Subtarget->hasCondMov())
780 // To "insert" a SELECT_CC instruction, we actually have to insert the
781 // diamond control-flow pattern. The incoming instruction knows the
782 // destination vreg to set, the condition code register to branch on, the
783 // true/false values to select between, and a branch opcode to use.
784 const BasicBlock *LLVM_BB = BB->getBasicBlock();
785 MachineFunction::iterator It = BB;
792 // bNE r1, r0, copy1MBB
793 // fallthrough --> copy0MBB
794 MachineBasicBlock *thisMBB = BB;
795 MachineFunction *F = BB->getParent();
796 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
797 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
798 F->insert(It, copy0MBB);
799 F->insert(It, sinkMBB);
801 // Transfer the remainder of BB and its successor edges to sinkMBB.
802 sinkMBB->splice(sinkMBB->begin(), BB,
803 llvm::next(MachineBasicBlock::iterator(MI)),
805 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
807 // Next, add the true and fallthrough blocks as its successors.
808 BB->addSuccessor(copy0MBB);
809 BB->addSuccessor(sinkMBB);
811 // Emit the right instruction according to the type of the operands compared
813 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
815 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
816 .addReg(Mips::ZERO).addMBB(sinkMBB);
820 // # fallthrough to sinkMBB
823 // Update machine-CFG edges
824 BB->addSuccessor(sinkMBB);
827 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
832 BuildMI(*BB, BB->begin(), dl,
833 TII->get(Mips::PHI), MI->getOperand(0).getReg())
834 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
835 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
837 BuildMI(*BB, BB->begin(), dl,
838 TII->get(Mips::PHI), MI->getOperand(0).getReg())
839 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
840 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
842 MI->eraseFromParent(); // The pseudo instruction is gone now.
847 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
848 MachineBasicBlock *BB) const {
849 switch (MI->getOpcode()) {
850 default: llvm_unreachable("Unexpected instr type to insert");
851 case Mips::ATOMIC_LOAD_ADD_I8:
852 case Mips::ATOMIC_LOAD_ADD_I8_P8:
853 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
854 case Mips::ATOMIC_LOAD_ADD_I16:
855 case Mips::ATOMIC_LOAD_ADD_I16_P8:
856 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
857 case Mips::ATOMIC_LOAD_ADD_I32:
858 case Mips::ATOMIC_LOAD_ADD_I32_P8:
859 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
860 case Mips::ATOMIC_LOAD_ADD_I64:
861 case Mips::ATOMIC_LOAD_ADD_I64_P8:
862 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
864 case Mips::ATOMIC_LOAD_AND_I8:
865 case Mips::ATOMIC_LOAD_AND_I8_P8:
866 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
867 case Mips::ATOMIC_LOAD_AND_I16:
868 case Mips::ATOMIC_LOAD_AND_I16_P8:
869 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
870 case Mips::ATOMIC_LOAD_AND_I32:
871 case Mips::ATOMIC_LOAD_AND_I32_P8:
872 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
873 case Mips::ATOMIC_LOAD_AND_I64:
874 case Mips::ATOMIC_LOAD_AND_I64_P8:
875 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
877 case Mips::ATOMIC_LOAD_OR_I8:
878 case Mips::ATOMIC_LOAD_OR_I8_P8:
879 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
880 case Mips::ATOMIC_LOAD_OR_I16:
881 case Mips::ATOMIC_LOAD_OR_I16_P8:
882 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
883 case Mips::ATOMIC_LOAD_OR_I32:
884 case Mips::ATOMIC_LOAD_OR_I32_P8:
885 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
886 case Mips::ATOMIC_LOAD_OR_I64:
887 case Mips::ATOMIC_LOAD_OR_I64_P8:
888 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
890 case Mips::ATOMIC_LOAD_XOR_I8:
891 case Mips::ATOMIC_LOAD_XOR_I8_P8:
892 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
893 case Mips::ATOMIC_LOAD_XOR_I16:
894 case Mips::ATOMIC_LOAD_XOR_I16_P8:
895 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
896 case Mips::ATOMIC_LOAD_XOR_I32:
897 case Mips::ATOMIC_LOAD_XOR_I32_P8:
898 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
899 case Mips::ATOMIC_LOAD_XOR_I64:
900 case Mips::ATOMIC_LOAD_XOR_I64_P8:
901 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
903 case Mips::ATOMIC_LOAD_NAND_I8:
904 case Mips::ATOMIC_LOAD_NAND_I8_P8:
905 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
906 case Mips::ATOMIC_LOAD_NAND_I16:
907 case Mips::ATOMIC_LOAD_NAND_I16_P8:
908 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
909 case Mips::ATOMIC_LOAD_NAND_I32:
910 case Mips::ATOMIC_LOAD_NAND_I32_P8:
911 return EmitAtomicBinary(MI, BB, 4, 0, true);
912 case Mips::ATOMIC_LOAD_NAND_I64:
913 case Mips::ATOMIC_LOAD_NAND_I64_P8:
914 return EmitAtomicBinary(MI, BB, 8, 0, true);
916 case Mips::ATOMIC_LOAD_SUB_I8:
917 case Mips::ATOMIC_LOAD_SUB_I8_P8:
918 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
919 case Mips::ATOMIC_LOAD_SUB_I16:
920 case Mips::ATOMIC_LOAD_SUB_I16_P8:
921 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
922 case Mips::ATOMIC_LOAD_SUB_I32:
923 case Mips::ATOMIC_LOAD_SUB_I32_P8:
924 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
925 case Mips::ATOMIC_LOAD_SUB_I64:
926 case Mips::ATOMIC_LOAD_SUB_I64_P8:
927 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
929 case Mips::ATOMIC_SWAP_I8:
930 case Mips::ATOMIC_SWAP_I8_P8:
931 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
932 case Mips::ATOMIC_SWAP_I16:
933 case Mips::ATOMIC_SWAP_I16_P8:
934 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
935 case Mips::ATOMIC_SWAP_I32:
936 case Mips::ATOMIC_SWAP_I32_P8:
937 return EmitAtomicBinary(MI, BB, 4, 0);
938 case Mips::ATOMIC_SWAP_I64:
939 case Mips::ATOMIC_SWAP_I64_P8:
940 return EmitAtomicBinary(MI, BB, 8, 0);
942 case Mips::ATOMIC_CMP_SWAP_I8:
943 case Mips::ATOMIC_CMP_SWAP_I8_P8:
944 return EmitAtomicCmpSwapPartword(MI, BB, 1);
945 case Mips::ATOMIC_CMP_SWAP_I16:
946 case Mips::ATOMIC_CMP_SWAP_I16_P8:
947 return EmitAtomicCmpSwapPartword(MI, BB, 2);
948 case Mips::ATOMIC_CMP_SWAP_I32:
949 case Mips::ATOMIC_CMP_SWAP_I32_P8:
950 return EmitAtomicCmpSwap(MI, BB, 4);
951 case Mips::ATOMIC_CMP_SWAP_I64:
952 case Mips::ATOMIC_CMP_SWAP_I64_P8:
953 return EmitAtomicCmpSwap(MI, BB, 8);
957 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
958 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
960 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
961 unsigned Size, unsigned BinOpcode,
963 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
965 MachineFunction *MF = BB->getParent();
966 MachineRegisterInfo &RegInfo = MF->getRegInfo();
967 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
968 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
969 DebugLoc dl = MI->getDebugLoc();
970 unsigned LL, SC, AND, NOR, ZERO, BEQ;
973 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
974 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
981 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
982 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
985 ZERO = Mips::ZERO_64;
989 unsigned OldVal = MI->getOperand(0).getReg();
990 unsigned Ptr = MI->getOperand(1).getReg();
991 unsigned Incr = MI->getOperand(2).getReg();
993 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
994 unsigned AndRes = RegInfo.createVirtualRegister(RC);
995 unsigned Success = RegInfo.createVirtualRegister(RC);
997 // insert new blocks after the current block
998 const BasicBlock *LLVM_BB = BB->getBasicBlock();
999 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1000 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1001 MachineFunction::iterator It = BB;
1003 MF->insert(It, loopMBB);
1004 MF->insert(It, exitMBB);
1006 // Transfer the remainder of BB and its successor edges to exitMBB.
1007 exitMBB->splice(exitMBB->begin(), BB,
1008 llvm::next(MachineBasicBlock::iterator(MI)),
1010 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1014 // fallthrough --> loopMBB
1015 BB->addSuccessor(loopMBB);
1016 loopMBB->addSuccessor(loopMBB);
1017 loopMBB->addSuccessor(exitMBB);
1020 // ll oldval, 0(ptr)
1021 // <binop> storeval, oldval, incr
1022 // sc success, storeval, 0(ptr)
1023 // beq success, $0, loopMBB
1025 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1027 // and andres, oldval, incr
1028 // nor storeval, $0, andres
1029 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1030 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1031 } else if (BinOpcode) {
1032 // <binop> storeval, oldval, incr
1033 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1037 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1038 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1040 MI->eraseFromParent(); // The instruction is gone now.
1046 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1047 MachineBasicBlock *BB,
1048 unsigned Size, unsigned BinOpcode,
1050 assert((Size == 1 || Size == 2) &&
1051 "Unsupported size for EmitAtomicBinaryPartial.");
1053 MachineFunction *MF = BB->getParent();
1054 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1055 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1056 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1057 DebugLoc dl = MI->getDebugLoc();
1058 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1059 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1061 unsigned Dest = MI->getOperand(0).getReg();
1062 unsigned Ptr = MI->getOperand(1).getReg();
1063 unsigned Incr = MI->getOperand(2).getReg();
1065 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1066 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1067 unsigned Mask = RegInfo.createVirtualRegister(RC);
1068 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1069 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1070 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1071 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1072 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1073 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1074 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1075 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1076 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1077 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1078 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1079 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1080 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1081 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1082 unsigned Success = RegInfo.createVirtualRegister(RC);
1084 // insert new blocks after the current block
1085 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1086 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1087 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1088 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1089 MachineFunction::iterator It = BB;
1091 MF->insert(It, loopMBB);
1092 MF->insert(It, sinkMBB);
1093 MF->insert(It, exitMBB);
1095 // Transfer the remainder of BB and its successor edges to exitMBB.
1096 exitMBB->splice(exitMBB->begin(), BB,
1097 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1098 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1100 BB->addSuccessor(loopMBB);
1101 loopMBB->addSuccessor(loopMBB);
1102 loopMBB->addSuccessor(sinkMBB);
1103 sinkMBB->addSuccessor(exitMBB);
1106 // addiu masklsb2,$0,-4 # 0xfffffffc
1107 // and alignedaddr,ptr,masklsb2
1108 // andi ptrlsb2,ptr,3
1109 // sll shiftamt,ptrlsb2,3
1110 // ori maskupper,$0,255 # 0xff
1111 // sll mask,maskupper,shiftamt
1112 // nor mask2,$0,mask
1113 // sll incr2,incr,shiftamt
1115 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1116 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1117 .addReg(Mips::ZERO).addImm(-4);
1118 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1119 .addReg(Ptr).addReg(MaskLSB2);
1120 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1121 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1122 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1123 .addReg(Mips::ZERO).addImm(MaskImm);
1124 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1125 .addReg(ShiftAmt).addReg(MaskUpper);
1126 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1127 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1129 // atomic.load.binop
1131 // ll oldval,0(alignedaddr)
1132 // binop binopres,oldval,incr2
1133 // and newval,binopres,mask
1134 // and maskedoldval0,oldval,mask2
1135 // or storeval,maskedoldval0,newval
1136 // sc success,storeval,0(alignedaddr)
1137 // beq success,$0,loopMBB
1141 // ll oldval,0(alignedaddr)
1142 // and newval,incr2,mask
1143 // and maskedoldval0,oldval,mask2
1144 // or storeval,maskedoldval0,newval
1145 // sc success,storeval,0(alignedaddr)
1146 // beq success,$0,loopMBB
1149 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1151 // and andres, oldval, incr2
1152 // nor binopres, $0, andres
1153 // and newval, binopres, mask
1154 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1155 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1156 .addReg(Mips::ZERO).addReg(AndRes);
1157 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1158 } else if (BinOpcode) {
1159 // <binop> binopres, oldval, incr2
1160 // and newval, binopres, mask
1161 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1162 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1163 } else {// atomic.swap
1164 // and newval, incr2, mask
1165 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1168 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1169 .addReg(OldVal).addReg(Mask2);
1170 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1171 .addReg(MaskedOldVal0).addReg(NewVal);
1172 BuildMI(BB, dl, TII->get(SC), Success)
1173 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1174 BuildMI(BB, dl, TII->get(Mips::BEQ))
1175 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1178 // and maskedoldval1,oldval,mask
1179 // srl srlres,maskedoldval1,shiftamt
1180 // sll sllres,srlres,24
1181 // sra dest,sllres,24
1183 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1185 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1186 .addReg(OldVal).addReg(Mask);
1187 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1188 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1189 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1190 .addReg(SrlRes).addImm(ShiftImm);
1191 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1192 .addReg(SllRes).addImm(ShiftImm);
1194 MI->eraseFromParent(); // The instruction is gone now.
1200 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1201 MachineBasicBlock *BB,
1202 unsigned Size) const {
1203 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1205 MachineFunction *MF = BB->getParent();
1206 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1207 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1208 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1209 DebugLoc dl = MI->getDebugLoc();
1210 unsigned LL, SC, ZERO, BNE, BEQ;
1213 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1214 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1220 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1221 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1222 ZERO = Mips::ZERO_64;
1227 unsigned Dest = MI->getOperand(0).getReg();
1228 unsigned Ptr = MI->getOperand(1).getReg();
1229 unsigned OldVal = MI->getOperand(2).getReg();
1230 unsigned NewVal = MI->getOperand(3).getReg();
1232 unsigned Success = RegInfo.createVirtualRegister(RC);
1234 // insert new blocks after the current block
1235 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1236 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1237 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1238 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1239 MachineFunction::iterator It = BB;
1241 MF->insert(It, loop1MBB);
1242 MF->insert(It, loop2MBB);
1243 MF->insert(It, exitMBB);
1245 // Transfer the remainder of BB and its successor edges to exitMBB.
1246 exitMBB->splice(exitMBB->begin(), BB,
1247 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1248 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1252 // fallthrough --> loop1MBB
1253 BB->addSuccessor(loop1MBB);
1254 loop1MBB->addSuccessor(exitMBB);
1255 loop1MBB->addSuccessor(loop2MBB);
1256 loop2MBB->addSuccessor(loop1MBB);
1257 loop2MBB->addSuccessor(exitMBB);
1261 // bne dest, oldval, exitMBB
1263 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1264 BuildMI(BB, dl, TII->get(BNE))
1265 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1268 // sc success, newval, 0(ptr)
1269 // beq success, $0, loop1MBB
1271 BuildMI(BB, dl, TII->get(SC), Success)
1272 .addReg(NewVal).addReg(Ptr).addImm(0);
1273 BuildMI(BB, dl, TII->get(BEQ))
1274 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1276 MI->eraseFromParent(); // The instruction is gone now.
1282 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1283 MachineBasicBlock *BB,
1284 unsigned Size) const {
1285 assert((Size == 1 || Size == 2) &&
1286 "Unsupported size for EmitAtomicCmpSwapPartial.");
1288 MachineFunction *MF = BB->getParent();
1289 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1290 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1291 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1292 DebugLoc dl = MI->getDebugLoc();
1293 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1294 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1296 unsigned Dest = MI->getOperand(0).getReg();
1297 unsigned Ptr = MI->getOperand(1).getReg();
1298 unsigned CmpVal = MI->getOperand(2).getReg();
1299 unsigned NewVal = MI->getOperand(3).getReg();
1301 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1302 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1303 unsigned Mask = RegInfo.createVirtualRegister(RC);
1304 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1305 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1306 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1307 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1308 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1309 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1310 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1311 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1312 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1313 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1314 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1315 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1316 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1317 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1318 unsigned Success = RegInfo.createVirtualRegister(RC);
1320 // insert new blocks after the current block
1321 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1322 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1323 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1324 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1325 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1326 MachineFunction::iterator It = BB;
1328 MF->insert(It, loop1MBB);
1329 MF->insert(It, loop2MBB);
1330 MF->insert(It, sinkMBB);
1331 MF->insert(It, exitMBB);
1333 // Transfer the remainder of BB and its successor edges to exitMBB.
1334 exitMBB->splice(exitMBB->begin(), BB,
1335 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1336 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1338 BB->addSuccessor(loop1MBB);
1339 loop1MBB->addSuccessor(sinkMBB);
1340 loop1MBB->addSuccessor(loop2MBB);
1341 loop2MBB->addSuccessor(loop1MBB);
1342 loop2MBB->addSuccessor(sinkMBB);
1343 sinkMBB->addSuccessor(exitMBB);
1345 // FIXME: computation of newval2 can be moved to loop2MBB.
1347 // addiu masklsb2,$0,-4 # 0xfffffffc
1348 // and alignedaddr,ptr,masklsb2
1349 // andi ptrlsb2,ptr,3
1350 // sll shiftamt,ptrlsb2,3
1351 // ori maskupper,$0,255 # 0xff
1352 // sll mask,maskupper,shiftamt
1353 // nor mask2,$0,mask
1354 // andi maskedcmpval,cmpval,255
1355 // sll shiftedcmpval,maskedcmpval,shiftamt
1356 // andi maskednewval,newval,255
1357 // sll shiftednewval,maskednewval,shiftamt
1358 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1359 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1360 .addReg(Mips::ZERO).addImm(-4);
1361 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1362 .addReg(Ptr).addReg(MaskLSB2);
1363 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1364 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1365 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1366 .addReg(Mips::ZERO).addImm(MaskImm);
1367 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1368 .addReg(ShiftAmt).addReg(MaskUpper);
1369 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1370 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1371 .addReg(CmpVal).addImm(MaskImm);
1372 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1373 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1374 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1375 .addReg(NewVal).addImm(MaskImm);
1376 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1377 .addReg(ShiftAmt).addReg(MaskedNewVal);
1380 // ll oldval,0(alginedaddr)
1381 // and maskedoldval0,oldval,mask
1382 // bne maskedoldval0,shiftedcmpval,sinkMBB
1384 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1385 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1386 .addReg(OldVal).addReg(Mask);
1387 BuildMI(BB, dl, TII->get(Mips::BNE))
1388 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1391 // and maskedoldval1,oldval,mask2
1392 // or storeval,maskedoldval1,shiftednewval
1393 // sc success,storeval,0(alignedaddr)
1394 // beq success,$0,loop1MBB
1396 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1397 .addReg(OldVal).addReg(Mask2);
1398 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1399 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1400 BuildMI(BB, dl, TII->get(SC), Success)
1401 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1402 BuildMI(BB, dl, TII->get(Mips::BEQ))
1403 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1406 // srl srlres,maskedoldval0,shiftamt
1407 // sll sllres,srlres,24
1408 // sra dest,sllres,24
1410 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1412 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1413 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1414 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1415 .addReg(SrlRes).addImm(ShiftImm);
1416 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1417 .addReg(SllRes).addImm(ShiftImm);
1419 MI->eraseFromParent(); // The instruction is gone now.
1424 //===----------------------------------------------------------------------===//
1425 // Misc Lower Operation implementation
1426 //===----------------------------------------------------------------------===//
1427 SDValue MipsTargetLowering::
1428 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1430 MachineFunction &MF = DAG.getMachineFunction();
1431 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1432 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1434 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1435 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1436 "Cannot lower if the alignment of the allocated space is larger than \
1437 that of the stack.");
1439 SDValue Chain = Op.getOperand(0);
1440 SDValue Size = Op.getOperand(1);
1441 DebugLoc dl = Op.getDebugLoc();
1443 // Get a reference from Mips stack pointer
1444 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1446 // Subtract the dynamic size from the actual stack size to
1447 // obtain the new stack size.
1448 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1450 // The Sub result contains the new stack start address, so it
1451 // must be placed in the stack pointer register.
1452 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1454 // This node always has two return values: a new stack pointer
1455 // value and a chain
1456 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1457 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1458 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1460 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1463 SDValue MipsTargetLowering::
1464 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1466 // The first operand is the chain, the second is the condition, the third is
1467 // the block to branch to if the condition is true.
1468 SDValue Chain = Op.getOperand(0);
1469 SDValue Dest = Op.getOperand(2);
1470 DebugLoc dl = Op.getDebugLoc();
1472 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1474 // Return if flag is not set by a floating point comparison.
1475 if (CondRes.getOpcode() != MipsISD::FPCmp)
1478 SDValue CCNode = CondRes.getOperand(2);
1480 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1481 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1483 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1487 SDValue MipsTargetLowering::
1488 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1490 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1492 // Return if flag is not set by a floating point comparison.
1493 if (Cond.getOpcode() != MipsISD::FPCmp)
1496 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1500 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1501 SDValue Cond = CreateFPCmp(DAG, Op);
1503 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1504 "Floating point operand expected.");
1506 SDValue True = DAG.getConstant(1, MVT::i32);
1507 SDValue False = DAG.getConstant(0, MVT::i32);
1509 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1512 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1513 SelectionDAG &DAG) const {
1514 // FIXME there isn't actually debug info here
1515 DebugLoc dl = Op.getDebugLoc();
1516 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1518 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1519 SDVTList VTs = DAG.getVTList(MVT::i32);
1521 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1523 // %gp_rel relocation
1524 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1525 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1527 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1528 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1529 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1531 // %hi/%lo relocation
1532 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1534 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1536 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1537 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1538 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1541 EVT ValTy = Op.getValueType();
1542 bool HasGotOfst = (GV->hasInternalLinkage() ||
1543 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1544 unsigned GotFlag = IsN64 ?
1545 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1546 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1547 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1548 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1549 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1550 MachinePointerInfo(), false, false, false, 0);
1551 // On functions and global targets not internal linked only
1552 // a load from got/GP is necessary for PIC to work.
1555 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1556 IsN64 ? MipsII::MO_GOT_OFST :
1558 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1559 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1562 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1563 SelectionDAG &DAG) const {
1564 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1565 // FIXME there isn't actually debug info here
1566 DebugLoc dl = Op.getDebugLoc();
1568 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1569 // %hi/%lo relocation
1570 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1571 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1572 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1573 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1574 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1577 EVT ValTy = Op.getValueType();
1578 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1579 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1580 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1581 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1582 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1583 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1584 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1585 MachinePointerInfo(), false, false, false, 0);
1586 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1587 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1590 SDValue MipsTargetLowering::
1591 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1593 // If the relocation model is PIC, use the General Dynamic TLS Model or
1594 // Local Dynamic TLS model, otherwise use the Initial Exec or
1595 // Local Exec TLS Model.
1597 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1598 DebugLoc dl = GA->getDebugLoc();
1599 const GlobalValue *GV = GA->getGlobal();
1600 EVT PtrVT = getPointerTy();
1602 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1603 // General Dynamic TLS Model
1604 bool LocalDynamic = GV->hasInternalLinkage();
1605 unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1606 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1607 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1608 GetGlobalReg(DAG, PtrVT), TGA);
1609 unsigned PtrSize = PtrVT.getSizeInBits();
1610 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1612 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1616 Entry.Node = Argument;
1618 Args.push_back(Entry);
1620 std::pair<SDValue, SDValue> CallResult =
1621 LowerCallTo(DAG.getEntryNode(), PtrTy,
1622 false, false, false, false, 0, CallingConv::C,
1623 /*isTailCall=*/false, /*doesNotRet=*/false,
1624 /*isReturnValueUsed=*/true,
1625 TlsGetAddr, Args, DAG, dl);
1627 SDValue Ret = CallResult.first;
1632 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1633 MipsII::MO_DTPREL_HI);
1634 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1635 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1636 MipsII::MO_DTPREL_LO);
1637 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1638 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1639 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1643 if (GV->isDeclaration()) {
1644 // Initial Exec TLS Model
1645 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1646 MipsII::MO_GOTTPREL);
1647 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1649 Offset = DAG.getLoad(PtrVT, dl,
1650 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1651 false, false, false, 0);
1653 // Local Exec TLS Model
1654 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1655 MipsII::MO_TPREL_HI);
1656 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1657 MipsII::MO_TPREL_LO);
1658 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1659 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1660 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1663 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1664 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1667 SDValue MipsTargetLowering::
1668 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1670 SDValue HiPart, JTI, JTILo;
1671 // FIXME there isn't actually debug info here
1672 DebugLoc dl = Op.getDebugLoc();
1673 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1674 EVT PtrVT = Op.getValueType();
1675 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1677 if (!IsPIC && !IsN64) {
1678 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1679 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1680 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1681 } else {// Emit Load from Global Pointer
1682 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1683 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1684 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1685 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1687 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1688 MachinePointerInfo(), false, false, false, 0);
1689 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1692 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1693 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1696 SDValue MipsTargetLowering::
1697 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1700 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1701 const Constant *C = N->getConstVal();
1702 // FIXME there isn't actually debug info here
1703 DebugLoc dl = Op.getDebugLoc();
1705 // gp_rel relocation
1706 // FIXME: we should reference the constant pool using small data sections,
1707 // but the asm printer currently doesn't support this feature without
1708 // hacking it. This feature should come soon so we can uncomment the
1710 //if (IsInSmallSection(C->getType())) {
1711 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1712 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1713 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1715 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1716 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1717 N->getOffset(), MipsII::MO_ABS_HI);
1718 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1719 N->getOffset(), MipsII::MO_ABS_LO);
1720 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1721 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1722 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1724 EVT ValTy = Op.getValueType();
1725 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1726 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1727 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1728 N->getOffset(), GOTFlag);
1729 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1730 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1731 MachinePointerInfo::getConstantPool(), false,
1733 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1734 N->getOffset(), OFSTFlag);
1735 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1736 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1742 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1743 MachineFunction &MF = DAG.getMachineFunction();
1744 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1746 DebugLoc dl = Op.getDebugLoc();
1747 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1750 // vastart just stores the address of the VarArgsFrameIndex slot into the
1751 // memory location argument.
1752 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1753 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1754 MachinePointerInfo(SV), false, false, 0);
1757 // Called if the size of integer registers is large enough to hold the whole
1758 // floating point number.
1759 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1760 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1761 EVT ValTy = Op.getValueType();
1762 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1763 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1764 DebugLoc dl = Op.getDebugLoc();
1765 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1766 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1767 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1768 DAG.getConstant(Mask - 1, IntValTy));
1769 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1770 DAG.getConstant(Mask, IntValTy));
1771 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1772 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1775 // Called if the size of integer registers is not large enough to hold the whole
1776 // floating point number (e.g. f64 & 32-bit integer register).
1778 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1780 // Use ext/ins instructions if target architecture is Mips32r2.
1781 // Eliminate redundant mfc1 and mtc1 instructions.
1782 unsigned LoIdx = 0, HiIdx = 1;
1785 std::swap(LoIdx, HiIdx);
1787 DebugLoc dl = Op.getDebugLoc();
1788 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1790 DAG.getConstant(LoIdx, MVT::i32));
1791 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1792 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1793 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1794 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1795 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1796 DAG.getConstant(0x7fffffff, MVT::i32));
1797 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1798 DAG.getConstant(0x80000000, MVT::i32));
1799 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1802 std::swap(Word0, Word1);
1804 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1808 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1809 EVT Ty = Op.getValueType();
1811 assert(Ty == MVT::f32 || Ty == MVT::f64);
1813 if (Ty == MVT::f32 || HasMips64)
1814 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1816 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1819 SDValue MipsTargetLowering::
1820 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1822 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1823 "Frame address can only be determined for current frame.");
1825 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1826 MFI->setFrameAddressIsTaken(true);
1827 EVT VT = Op.getValueType();
1828 DebugLoc dl = Op.getDebugLoc();
1829 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1830 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1834 // TODO: set SType according to the desired memory barrier behavior.
1836 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1838 DebugLoc dl = Op.getDebugLoc();
1839 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1840 DAG.getConstant(SType, MVT::i32));
1843 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1844 SelectionDAG& DAG) const {
1845 // FIXME: Need pseudo-fence for 'singlethread' fences
1846 // FIXME: Set SType for weaker fences where supported/appropriate.
1848 DebugLoc dl = Op.getDebugLoc();
1849 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1850 DAG.getConstant(SType, MVT::i32));
1853 //===----------------------------------------------------------------------===//
1854 // Calling Convention Implementation
1855 //===----------------------------------------------------------------------===//
1857 //===----------------------------------------------------------------------===//
1858 // TODO: Implement a generic logic using tblgen that can support this.
1859 // Mips O32 ABI rules:
1861 // i32 - Passed in A0, A1, A2, A3 and stack
1862 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1863 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1864 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1865 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1866 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1869 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1870 //===----------------------------------------------------------------------===//
1872 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1873 MVT LocVT, CCValAssign::LocInfo LocInfo,
1874 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1876 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1878 static const uint16_t IntRegs[] = {
1879 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1881 static const uint16_t F32Regs[] = {
1882 Mips::F12, Mips::F14
1884 static const uint16_t F64Regs[] = {
1889 if (ArgFlags.isByVal()) {
1890 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1891 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1892 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1893 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1894 r < std::min(IntRegsSize, NextReg); ++r)
1895 State.AllocateReg(IntRegs[r]);
1899 // Promote i8 and i16
1900 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1902 if (ArgFlags.isSExt())
1903 LocInfo = CCValAssign::SExt;
1904 else if (ArgFlags.isZExt())
1905 LocInfo = CCValAssign::ZExt;
1907 LocInfo = CCValAssign::AExt;
1912 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1913 // is true: function is vararg, argument is 3rd or higher, there is previous
1914 // argument which is not f32 or f64.
1915 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1916 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1917 unsigned OrigAlign = ArgFlags.getOrigAlign();
1918 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1920 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1921 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1922 // If this is the first part of an i64 arg,
1923 // the allocated register must be either A0 or A2.
1924 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1925 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1927 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1928 // Allocate int register and shadow next int register. If first
1929 // available register is Mips::A1 or Mips::A3, shadow it too.
1930 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1931 if (Reg == Mips::A1 || Reg == Mips::A3)
1932 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1933 State.AllocateReg(IntRegs, IntRegsSize);
1935 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1936 // we are guaranteed to find an available float register
1937 if (ValVT == MVT::f32) {
1938 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1939 // Shadow int register
1940 State.AllocateReg(IntRegs, IntRegsSize);
1942 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1943 // Shadow int registers
1944 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1945 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1946 State.AllocateReg(IntRegs, IntRegsSize);
1947 State.AllocateReg(IntRegs, IntRegsSize);
1950 llvm_unreachable("Cannot handle this ValVT.");
1952 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1953 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1956 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1958 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1960 return false; // CC must always match
1963 static const uint16_t Mips64IntRegs[8] =
1964 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1965 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1966 static const uint16_t Mips64DPRegs[8] =
1967 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1968 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1970 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1971 CCValAssign::LocInfo LocInfo,
1972 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1973 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1974 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1975 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1977 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1979 // If byval is 16-byte aligned, the first arg register must be even.
1980 if ((Align == 16) && (FirstIdx % 2)) {
1981 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1985 // Mark the registers allocated.
1986 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1987 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1989 // Allocate space on caller's stack.
1990 unsigned Offset = State.AllocateStack(Size, Align);
1993 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1996 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2001 #include "MipsGenCallingConv.inc"
2004 AnalyzeMips64CallOperands(CCState &CCInfo,
2005 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2006 unsigned NumOps = Outs.size();
2007 for (unsigned i = 0; i != NumOps; ++i) {
2008 MVT ArgVT = Outs[i].VT;
2009 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2012 if (Outs[i].IsFixed)
2013 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2015 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2019 dbgs() << "Call operand #" << i << " has unhandled type "
2020 << EVT(ArgVT).getEVTString();
2022 llvm_unreachable(0);
2027 //===----------------------------------------------------------------------===//
2028 // Call Calling Convention Implementation
2029 //===----------------------------------------------------------------------===//
2031 static const unsigned O32IntRegsSize = 4;
2033 static const uint16_t O32IntRegs[] = {
2034 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2037 // Return next O32 integer argument register.
2038 static unsigned getNextIntArgReg(unsigned Reg) {
2039 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2040 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2043 // Write ByVal Arg to arg registers and stack.
2045 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2046 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2047 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2048 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2049 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2050 MVT PtrType, bool isLittle) {
2051 unsigned LocMemOffset = VA.getLocMemOffset();
2052 unsigned Offset = 0;
2053 uint32_t RemainingSize = Flags.getByValSize();
2054 unsigned ByValAlign = Flags.getByValAlign();
2056 // Copy the first 4 words of byval arg to registers A0 - A3.
2057 // FIXME: Use a stricter alignment if it enables better optimization in passes
2059 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2060 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2061 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2062 DAG.getConstant(Offset, MVT::i32));
2063 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2064 MachinePointerInfo(), false, false, false,
2065 std::min(ByValAlign, (unsigned )4));
2066 MemOpChains.push_back(LoadVal.getValue(1));
2067 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2068 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2071 if (RemainingSize == 0)
2074 // If there still is a register available for argument passing, write the
2075 // remaining part of the structure to it using subword loads and shifts.
2076 if (LocMemOffset < 4 * 4) {
2077 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2078 "There must be one to three bytes remaining.");
2079 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2080 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2081 DAG.getConstant(Offset, MVT::i32));
2082 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2083 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2084 LoadPtr, MachinePointerInfo(),
2085 MVT::getIntegerVT(LoadSize * 8), false,
2087 MemOpChains.push_back(LoadVal.getValue(1));
2089 // If target is big endian, shift it to the most significant half-word or
2092 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2093 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2096 RemainingSize -= LoadSize;
2098 // Read second subword if necessary.
2099 if (RemainingSize != 0) {
2100 assert(RemainingSize == 1 && "There must be one byte remaining.");
2101 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2102 DAG.getConstant(Offset, MVT::i32));
2103 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2104 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2105 LoadPtr, MachinePointerInfo(),
2106 MVT::i8, false, false, Alignment);
2107 MemOpChains.push_back(Subword.getValue(1));
2108 // Insert the loaded byte to LoadVal.
2109 // FIXME: Use INS if supported by target.
2110 unsigned ShiftAmt = isLittle ? 16 : 8;
2111 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2112 DAG.getConstant(ShiftAmt, MVT::i32));
2113 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2116 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2117 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2121 // Create a fixed object on stack at offset LocMemOffset and copy
2122 // remaining part of byval arg to it using memcpy.
2123 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2124 DAG.getConstant(Offset, MVT::i32));
2125 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2126 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2127 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2128 DAG.getConstant(RemainingSize, MVT::i32),
2129 std::min(ByValAlign, (unsigned)4),
2130 /*isVolatile=*/false, /*AlwaysInline=*/false,
2131 MachinePointerInfo(0), MachinePointerInfo(0));
2134 // Copy Mips64 byVal arg to registers and stack.
2136 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2137 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2138 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2139 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2140 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2141 EVT PtrTy, bool isLittle) {
2142 unsigned ByValSize = Flags.getByValSize();
2143 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2144 bool IsRegLoc = VA.isRegLoc();
2145 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2146 unsigned LocMemOffset = 0;
2147 unsigned MemCpySize = ByValSize;
2150 LocMemOffset = VA.getLocMemOffset();
2152 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2154 const uint16_t *RegEnd = Mips64IntRegs + 8;
2156 // Copy double words to registers.
2157 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2158 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2159 DAG.getConstant(Offset, PtrTy));
2160 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2161 MachinePointerInfo(), false, false, false,
2163 MemOpChains.push_back(LoadVal.getValue(1));
2164 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2167 // Return if the struct has been fully copied.
2168 if (!(MemCpySize = ByValSize - Offset))
2171 // If there is an argument register available, copy the remainder of the
2172 // byval argument with sub-doubleword loads and shifts.
2173 if (Reg != RegEnd) {
2174 assert((ByValSize < Offset + 8) &&
2175 "Size of the remainder should be smaller than 8-byte.");
2177 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2178 unsigned RemSize = ByValSize - Offset;
2180 if (RemSize < LoadSize)
2183 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2184 DAG.getConstant(Offset, PtrTy));
2186 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2187 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2188 false, false, Alignment);
2189 MemOpChains.push_back(LoadVal.getValue(1));
2191 // Offset in number of bits from double word boundary.
2192 unsigned OffsetDW = (Offset % 8) * 8;
2193 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2194 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2195 DAG.getConstant(Shamt, MVT::i32));
2197 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2200 Alignment = std::min(Alignment, LoadSize);
2203 RegsToPass.push_back(std::make_pair(*Reg, Val));
2208 assert(MemCpySize && "MemCpySize must not be zero.");
2210 // Create a fixed object on stack at offset LocMemOffset and copy
2211 // remainder of byval arg to it with memcpy.
2212 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2213 DAG.getConstant(Offset, PtrTy));
2214 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2215 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2216 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2217 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2218 /*isVolatile=*/false, /*AlwaysInline=*/false,
2219 MachinePointerInfo(0), MachinePointerInfo(0));
2222 /// LowerCall - functions arguments are copied from virtual regs to
2223 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2224 /// TODO: isTailCall.
2226 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2227 CallingConv::ID CallConv, bool isVarArg,
2228 bool doesNotRet, bool &isTailCall,
2229 const SmallVectorImpl<ISD::OutputArg> &Outs,
2230 const SmallVectorImpl<SDValue> &OutVals,
2231 const SmallVectorImpl<ISD::InputArg> &Ins,
2232 DebugLoc dl, SelectionDAG &DAG,
2233 SmallVectorImpl<SDValue> &InVals) const {
2234 // MIPs target does not yet support tail call optimization.
2237 MachineFunction &MF = DAG.getMachineFunction();
2238 MachineFrameInfo *MFI = MF.getFrameInfo();
2239 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2240 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2241 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2243 // Analyze operands of the call, assigning locations to each operand.
2244 SmallVector<CCValAssign, 16> ArgLocs;
2245 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2246 getTargetMachine(), ArgLocs, *DAG.getContext());
2249 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2251 AnalyzeMips64CallOperands(CCInfo, Outs);
2253 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2255 // Get a count of how many bytes are to be pushed on the stack.
2256 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2258 // Chain is the output chain of the last Load/Store or CopyToReg node.
2259 // ByValChain is the output chain of the last Memcpy node created for copying
2260 // byval arguments to the stack.
2261 SDValue Chain, CallSeqStart, ByValChain;
2262 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2263 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2264 ByValChain = InChain;
2266 // If this is the first call, create a stack frame object that points to
2267 // a location to which .cprestore saves $gp.
2268 if (IsO32 && IsPIC && MipsFI->globalBaseRegFixed() && !MipsFI->getGPFI())
2269 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2271 // Get the frame index of the stack frame object that points to the location
2272 // of dynamically allocated area on the stack.
2273 int DynAllocFI = MipsFI->getDynAllocFI();
2275 // Update size of the maximum argument space.
2276 // For O32, a minimum of four words (16 bytes) of argument space is
2279 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2281 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2283 if (MaxCallFrameSize < NextStackOffset) {
2284 MipsFI->setMaxCallFrameSize(NextStackOffset);
2286 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2287 // allocated stack space. These offsets must be aligned to a boundary
2288 // determined by the stack alignment of the ABI.
2289 unsigned StackAlignment = TFL->getStackAlignment();
2290 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2291 StackAlignment * StackAlignment;
2293 if (MipsFI->needGPSaveRestore())
2294 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2296 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2299 // With EABI is it possible to have 16 args on registers.
2300 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2301 SmallVector<SDValue, 8> MemOpChains;
2303 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2305 // Walk the register/memloc assignments, inserting copies/loads.
2306 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2307 SDValue Arg = OutVals[i];
2308 CCValAssign &VA = ArgLocs[i];
2309 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2310 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2313 if (Flags.isByVal()) {
2314 assert(Flags.getByValSize() &&
2315 "ByVal args of size 0 should have been ignored by front-end.");
2317 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2318 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2319 Subtarget->isLittle());
2321 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2322 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2323 Subtarget->isLittle());
2327 // Promote the value if needed.
2328 switch (VA.getLocInfo()) {
2329 default: llvm_unreachable("Unknown loc info!");
2330 case CCValAssign::Full:
2331 if (VA.isRegLoc()) {
2332 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2333 (ValVT == MVT::f64 && LocVT == MVT::i64))
2334 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2335 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2336 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2337 Arg, DAG.getConstant(0, MVT::i32));
2338 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2339 Arg, DAG.getConstant(1, MVT::i32));
2340 if (!Subtarget->isLittle())
2342 unsigned LocRegLo = VA.getLocReg();
2343 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2344 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2345 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2350 case CCValAssign::SExt:
2351 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2353 case CCValAssign::ZExt:
2354 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2356 case CCValAssign::AExt:
2357 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2361 // Arguments that can be passed on register must be kept at
2362 // RegsToPass vector
2363 if (VA.isRegLoc()) {
2364 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2368 // Register can't get to this point...
2369 assert(VA.isMemLoc());
2371 // Create the frame index object for this incoming parameter
2372 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2373 VA.getLocMemOffset(), true);
2374 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2376 // emit ISD::STORE whichs stores the
2377 // parameter value to a stack Location
2378 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2379 MachinePointerInfo(), false, false, 0));
2382 // Extend range of indices of frame objects for outgoing arguments that were
2383 // created during this function call. Skip this step if no such objects were
2386 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2388 // If a memcpy has been created to copy a byval arg to a stack, replace the
2389 // chain input of CallSeqStart with ByValChain.
2390 if (InChain != ByValChain)
2391 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2392 NextStackOffsetVal);
2394 // Transform all store nodes into one single node because all store
2395 // nodes are independent of each other.
2396 if (!MemOpChains.empty())
2397 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2398 &MemOpChains[0], MemOpChains.size());
2400 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2401 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2402 // node so that legalize doesn't hack it.
2403 unsigned char OpFlag;
2404 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2405 bool GlobalOrExternal = false;
2408 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2409 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2410 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2411 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2412 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2414 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2417 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2418 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2419 getPointerTy(), 0, OpFlag);
2422 GlobalOrExternal = true;
2424 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2425 if (IsN64 || (!IsO32 && IsPIC))
2426 OpFlag = MipsII::MO_GOT_DISP;
2427 else if (!IsPIC) // !N64 && static
2428 OpFlag = MipsII::MO_NO_FLAG;
2430 OpFlag = MipsII::MO_GOT_CALL;
2431 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2433 GlobalOrExternal = true;
2438 // Create nodes that load address of callee and copy it to T9
2440 if (GlobalOrExternal) {
2441 // Load callee address
2442 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2443 GetGlobalReg(DAG, getPointerTy()), Callee);
2444 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2445 Callee, MachinePointerInfo::getGOT(),
2446 false, false, false, 0);
2448 // Use GOT+LO if callee has internal linkage.
2449 if (CalleeLo.getNode()) {
2450 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2451 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2457 // T9 should contain the address of the callee function if
2458 // -reloction-model=pic or it is an indirect call.
2459 if (IsPICCall || !GlobalOrExternal) {
2461 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2462 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2463 InFlag = Chain.getValue(1);
2464 Callee = DAG.getRegister(T9Reg, getPointerTy());
2467 // Build a sequence of copy-to-reg nodes chained together with token
2468 // chain and flag operands which copy the outgoing args into registers.
2469 // The InFlag in necessary since all emitted instructions must be
2471 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2472 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2473 RegsToPass[i].second, InFlag);
2474 InFlag = Chain.getValue(1);
2477 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2478 // = Chain, Callee, Reg#1, Reg#2, ...
2480 // Returns a chain & a flag for retval copy to use.
2481 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2482 SmallVector<SDValue, 8> Ops;
2483 Ops.push_back(Chain);
2484 Ops.push_back(Callee);
2486 // Add argument registers to the end of the list so that they are
2487 // known live into the call.
2488 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2489 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2490 RegsToPass[i].second.getValueType()));
2492 // Add a register mask operand representing the call-preserved registers.
2493 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2494 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2495 assert(Mask && "Missing call preserved mask for calling convention");
2496 Ops.push_back(DAG.getRegisterMask(Mask));
2498 if (InFlag.getNode())
2499 Ops.push_back(InFlag);
2501 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2502 InFlag = Chain.getValue(1);
2504 // Create the CALLSEQ_END node.
2505 Chain = DAG.getCALLSEQ_END(Chain,
2506 DAG.getIntPtrConstant(NextStackOffset, true),
2507 DAG.getIntPtrConstant(0, true), InFlag);
2508 InFlag = Chain.getValue(1);
2510 // Handle result values, copying them out of physregs into vregs that we
2512 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2513 Ins, dl, DAG, InVals);
2516 /// LowerCallResult - Lower the result values of a call into the
2517 /// appropriate copies out of appropriate physical registers.
2519 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2520 CallingConv::ID CallConv, bool isVarArg,
2521 const SmallVectorImpl<ISD::InputArg> &Ins,
2522 DebugLoc dl, SelectionDAG &DAG,
2523 SmallVectorImpl<SDValue> &InVals) const {
2524 // Assign locations to each value returned by this call.
2525 SmallVector<CCValAssign, 16> RVLocs;
2526 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2527 getTargetMachine(), RVLocs, *DAG.getContext());
2529 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2531 // Copy all of the result registers out of their specified physreg.
2532 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2533 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2534 RVLocs[i].getValVT(), InFlag).getValue(1);
2535 InFlag = Chain.getValue(2);
2536 InVals.push_back(Chain.getValue(0));
2542 //===----------------------------------------------------------------------===//
2543 // Formal Arguments Calling Convention Implementation
2544 //===----------------------------------------------------------------------===//
2545 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2546 std::vector<SDValue>& OutChains,
2547 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2548 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2549 const Argument *FuncArg) {
2550 unsigned LocMem = VA.getLocMemOffset();
2551 unsigned FirstWord = LocMem / 4;
2553 // copy register A0 - A3 to frame object
2554 for (unsigned i = 0; i < NumWords; ++i) {
2555 unsigned CurWord = FirstWord + i;
2556 if (CurWord >= O32IntRegsSize)
2559 unsigned SrcReg = O32IntRegs[CurWord];
2560 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2561 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2562 DAG.getConstant(i * 4, MVT::i32));
2563 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2564 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2566 OutChains.push_back(Store);
2570 // Create frame object on stack and copy registers used for byval passing to it.
2572 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2573 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2574 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2575 MachineFrameInfo *MFI, bool IsRegLoc,
2576 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2577 EVT PtrTy, const Argument *FuncArg) {
2578 const uint16_t *Reg = Mips64IntRegs + 8;
2579 int FOOffset; // Frame object offset from virtual frame pointer.
2582 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2583 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2586 FOOffset = VA.getLocMemOffset();
2588 // Create frame object.
2589 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2590 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2591 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2592 InVals.push_back(FIN);
2594 // Copy arg registers.
2595 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2597 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2598 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2599 DAG.getConstant(I * 8, PtrTy));
2600 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2601 StorePtr, MachinePointerInfo(FuncArg, I * 8),
2603 OutChains.push_back(Store);
2609 /// LowerFormalArguments - transform physical registers into virtual registers
2610 /// and generate load operations for arguments places on the stack.
2612 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2613 CallingConv::ID CallConv,
2615 const SmallVectorImpl<ISD::InputArg> &Ins,
2616 DebugLoc dl, SelectionDAG &DAG,
2617 SmallVectorImpl<SDValue> &InVals)
2619 MachineFunction &MF = DAG.getMachineFunction();
2620 MachineFrameInfo *MFI = MF.getFrameInfo();
2621 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2623 MipsFI->setVarArgsFrameIndex(0);
2625 // Used with vargs to acumulate store chains.
2626 std::vector<SDValue> OutChains;
2628 // Assign locations to all of the incoming arguments.
2629 SmallVector<CCValAssign, 16> ArgLocs;
2630 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2631 getTargetMachine(), ArgLocs, *DAG.getContext());
2634 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2636 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2638 Function::const_arg_iterator FuncArg =
2639 DAG.getMachineFunction().getFunction()->arg_begin();
2640 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2642 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
2643 CCValAssign &VA = ArgLocs[i];
2644 EVT ValVT = VA.getValVT();
2645 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2646 bool IsRegLoc = VA.isRegLoc();
2648 if (Flags.isByVal()) {
2649 assert(Flags.getByValSize() &&
2650 "ByVal args of size 0 should have been ignored by front-end.");
2652 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2653 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2655 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2656 InVals.push_back(FIN);
2657 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
2660 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2661 MFI, IsRegLoc, InVals, MipsFI,
2662 getPointerTy(), &*FuncArg);
2666 // Arguments stored on registers
2668 EVT RegVT = VA.getLocVT();
2669 unsigned ArgReg = VA.getLocReg();
2670 const TargetRegisterClass *RC;
2672 if (RegVT == MVT::i32)
2673 RC = Mips::CPURegsRegisterClass;
2674 else if (RegVT == MVT::i64)
2675 RC = Mips::CPU64RegsRegisterClass;
2676 else if (RegVT == MVT::f32)
2677 RC = Mips::FGR32RegisterClass;
2678 else if (RegVT == MVT::f64)
2679 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2681 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2683 // Transform the arguments stored on
2684 // physical registers into virtual ones
2685 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2686 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2688 // If this is an 8 or 16-bit value, it has been passed promoted
2689 // to 32 bits. Insert an assert[sz]ext to capture this, then
2690 // truncate to the right size.
2691 if (VA.getLocInfo() != CCValAssign::Full) {
2692 unsigned Opcode = 0;
2693 if (VA.getLocInfo() == CCValAssign::SExt)
2694 Opcode = ISD::AssertSext;
2695 else if (VA.getLocInfo() == CCValAssign::ZExt)
2696 Opcode = ISD::AssertZext;
2698 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2699 DAG.getValueType(ValVT));
2700 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2703 // Handle floating point arguments passed in integer registers.
2704 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2705 (RegVT == MVT::i64 && ValVT == MVT::f64))
2706 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2707 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2708 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2709 getNextIntArgReg(ArgReg), RC);
2710 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2711 if (!Subtarget->isLittle())
2712 std::swap(ArgValue, ArgValue2);
2713 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2714 ArgValue, ArgValue2);
2717 InVals.push_back(ArgValue);
2718 } else { // VA.isRegLoc()
2721 assert(VA.isMemLoc());
2723 // The stack pointer offset is relative to the caller stack frame.
2724 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2725 VA.getLocMemOffset(), true);
2727 // Create load nodes to retrieve arguments from the stack
2728 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2729 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2730 MachinePointerInfo::getFixedStack(LastFI),
2731 false, false, false, 0));
2735 // The mips ABIs for returning structs by value requires that we copy
2736 // the sret argument into $v0 for the return. Save the argument into
2737 // a virtual register so that we can access it from the return points.
2738 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2739 unsigned Reg = MipsFI->getSRetReturnReg();
2741 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2742 MipsFI->setSRetReturnReg(Reg);
2744 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2745 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2749 unsigned NumOfRegs = IsO32 ? 4 : 8;
2750 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2751 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2752 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2753 const TargetRegisterClass *RC
2754 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2755 unsigned RegSize = RC->getSize();
2756 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2758 // Offset of the first variable argument from stack pointer.
2759 int FirstVaArgOffset;
2761 if (IsO32 || (Idx == NumOfRegs)) {
2763 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2765 FirstVaArgOffset = RegSlotOffset;
2767 // Record the frame index of the first variable argument
2768 // which is a value necessary to VASTART.
2769 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2770 MipsFI->setVarArgsFrameIndex(LastFI);
2772 // Copy the integer registers that have not been used for argument passing
2773 // to the argument register save area. For O32, the save area is allocated
2774 // in the caller's stack frame, while for N32/64, it is allocated in the
2775 // callee's stack frame.
2776 for (int StackOffset = RegSlotOffset;
2777 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2778 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2779 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2780 MVT::getIntegerVT(RegSize * 8));
2781 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2782 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2783 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2784 MachinePointerInfo(), false, false, 0));
2788 MipsFI->setLastInArgFI(LastFI);
2790 // All stores are grouped in one node to allow the matching between
2791 // the size of Ins and InVals. This only happens when on varg functions
2792 if (!OutChains.empty()) {
2793 OutChains.push_back(Chain);
2794 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2795 &OutChains[0], OutChains.size());
2801 //===----------------------------------------------------------------------===//
2802 // Return Value Calling Convention Implementation
2803 //===----------------------------------------------------------------------===//
2806 MipsTargetLowering::LowerReturn(SDValue Chain,
2807 CallingConv::ID CallConv, bool isVarArg,
2808 const SmallVectorImpl<ISD::OutputArg> &Outs,
2809 const SmallVectorImpl<SDValue> &OutVals,
2810 DebugLoc dl, SelectionDAG &DAG) const {
2812 // CCValAssign - represent the assignment of
2813 // the return value to a location
2814 SmallVector<CCValAssign, 16> RVLocs;
2816 // CCState - Info about the registers and stack slot.
2817 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2818 getTargetMachine(), RVLocs, *DAG.getContext());
2820 // Analize return values.
2821 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2823 // If this is the first return lowered for this function, add
2824 // the regs to the liveout set for the function.
2825 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2826 for (unsigned i = 0; i != RVLocs.size(); ++i)
2827 if (RVLocs[i].isRegLoc())
2828 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2833 // Copy the result values into the output registers.
2834 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2835 CCValAssign &VA = RVLocs[i];
2836 assert(VA.isRegLoc() && "Can only return in registers!");
2838 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2840 // guarantee that all emitted copies are
2841 // stuck together, avoiding something bad
2842 Flag = Chain.getValue(1);
2845 // The mips ABIs for returning structs by value requires that we copy
2846 // the sret argument into $v0 for the return. We saved the argument into
2847 // a virtual register in the entry block, so now we copy the value out
2849 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2850 MachineFunction &MF = DAG.getMachineFunction();
2851 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2852 unsigned Reg = MipsFI->getSRetReturnReg();
2855 llvm_unreachable("sret virtual register not created in the entry block");
2856 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2858 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2859 Flag = Chain.getValue(1);
2862 // Return on Mips is always a "jr $ra"
2864 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2865 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2867 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2868 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2871 //===----------------------------------------------------------------------===//
2872 // Mips Inline Assembly Support
2873 //===----------------------------------------------------------------------===//
2875 /// getConstraintType - Given a constraint letter, return the type of
2876 /// constraint it is for this target.
2877 MipsTargetLowering::ConstraintType MipsTargetLowering::
2878 getConstraintType(const std::string &Constraint) const
2880 // Mips specific constrainy
2881 // GCC config/mips/constraints.md
2883 // 'd' : An address register. Equivalent to r
2884 // unless generating MIPS16 code.
2885 // 'y' : Equivalent to r; retained for
2886 // backwards compatibility.
2887 // 'f' : Floating Point registers.
2888 if (Constraint.size() == 1) {
2889 switch (Constraint[0]) {
2894 return C_RegisterClass;
2897 return TargetLowering::getConstraintType(Constraint);
2900 /// Examine constraint type and operand type and determine a weight value.
2901 /// This object must already have been set up with the operand type
2902 /// and the current alternative constraint selected.
2903 TargetLowering::ConstraintWeight
2904 MipsTargetLowering::getSingleConstraintMatchWeight(
2905 AsmOperandInfo &info, const char *constraint) const {
2906 ConstraintWeight weight = CW_Invalid;
2907 Value *CallOperandVal = info.CallOperandVal;
2908 // If we don't have a value, we can't do a match,
2909 // but allow it at the lowest weight.
2910 if (CallOperandVal == NULL)
2912 Type *type = CallOperandVal->getType();
2913 // Look at the constraint type.
2914 switch (*constraint) {
2916 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2920 if (type->isIntegerTy())
2921 weight = CW_Register;
2924 if (type->isFloatTy())
2925 weight = CW_Register;
2931 /// Given a register class constraint, like 'r', if this corresponds directly
2932 /// to an LLVM register class, return a register of 0 and the register class
2934 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2935 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2937 if (Constraint.size() == 1) {
2938 switch (Constraint[0]) {
2939 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2940 case 'y': // Same as 'r'. Exists for compatibility.
2943 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2944 assert(VT == MVT::i64 && "Unexpected type.");
2945 return std::make_pair(0U, Mips::CPU64RegsRegisterClass);
2948 return std::make_pair(0U, Mips::FGR32RegisterClass);
2949 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2950 if (Subtarget->isFP64bit())
2951 return std::make_pair(0U, Mips::FGR64RegisterClass);
2953 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2957 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2961 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2962 // The Mips target isn't yet aware of offsets.
2966 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2967 if (VT != MVT::f32 && VT != MVT::f64)
2969 if (Imm.isNegZero())
2971 return Imm.isZero();
2974 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2976 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2978 return TargetLowering::getJumpTableEncoding();