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 "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "InstPrinter/MipsInstPrinter.h"
27 #include "MCTargetDesc/MipsBaseInfo.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 (!isUInt<32>(I) || !isShiftedMask_32(I))
46 Size = CountPopulation_32(I);
47 Pos = CountTrailingZeros_32(I);
51 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
53 case MipsISD::JmpLink: return "MipsISD::JmpLink";
54 case MipsISD::Hi: return "MipsISD::Hi";
55 case MipsISD::Lo: return "MipsISD::Lo";
56 case MipsISD::GPRel: return "MipsISD::GPRel";
57 case MipsISD::TlsGd: return "MipsISD::TlsGd";
58 case MipsISD::TprelHi: return "MipsISD::TprelHi";
59 case MipsISD::TprelLo: return "MipsISD::TprelLo";
60 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
61 case MipsISD::Ret: return "MipsISD::Ret";
62 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
63 case MipsISD::FPCmp: return "MipsISD::FPCmp";
64 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
65 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
66 case MipsISD::FPRound: return "MipsISD::FPRound";
67 case MipsISD::MAdd: return "MipsISD::MAdd";
68 case MipsISD::MAddu: return "MipsISD::MAddu";
69 case MipsISD::MSub: return "MipsISD::MSub";
70 case MipsISD::MSubu: return "MipsISD::MSubu";
71 case MipsISD::DivRem: return "MipsISD::DivRem";
72 case MipsISD::DivRemU: return "MipsISD::DivRemU";
73 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
74 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
75 case MipsISD::WrapperPIC: return "MipsISD::WrapperPIC";
76 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
77 case MipsISD::Sync: return "MipsISD::Sync";
78 case MipsISD::Ext: return "MipsISD::Ext";
79 case MipsISD::Ins: return "MipsISD::Ins";
85 MipsTargetLowering(MipsTargetMachine &TM)
86 : TargetLowering(TM, new MipsTargetObjectFile()),
87 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
88 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
89 IsO32(Subtarget->isABI_O32()) {
91 // Mips does not have i1 type, so use i32 for
92 // setcc operations results (slt, sgt, ...).
93 setBooleanContents(ZeroOrOneBooleanContent);
94 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
96 // Set up the register classes
97 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
98 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
101 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
103 // When dealing with single precision only, use libcalls
104 if (!Subtarget->isSingleFloat()) {
106 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
108 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
111 // Load extented operations for i1 types must be promoted
112 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
113 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
114 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
116 // MIPS doesn't have extending float->double load/store
117 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
118 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
120 // Used by legalize types to correctly generate the setcc result.
121 // Without this, every float setcc comes with a AND/OR with the result,
122 // we don't want this, since the fpcmp result goes to a flag register,
123 // which is used implicitly by brcond and select operations.
124 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
126 // Mips Custom Operations
127 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
128 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
129 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
130 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
131 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
132 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
133 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
134 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
135 setOperationAction(ISD::SELECT, MVT::f32, Custom);
136 setOperationAction(ISD::SELECT, MVT::f64, Custom);
137 setOperationAction(ISD::SELECT, MVT::i32, Custom);
138 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
139 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
140 setOperationAction(ISD::VASTART, MVT::Other, Custom);
142 setOperationAction(ISD::SDIV, MVT::i32, Expand);
143 setOperationAction(ISD::SREM, MVT::i32, Expand);
144 setOperationAction(ISD::UDIV, MVT::i32, Expand);
145 setOperationAction(ISD::UREM, MVT::i32, Expand);
146 setOperationAction(ISD::SDIV, MVT::i64, Expand);
147 setOperationAction(ISD::SREM, MVT::i64, Expand);
148 setOperationAction(ISD::UDIV, MVT::i64, Expand);
149 setOperationAction(ISD::UREM, MVT::i64, Expand);
151 // Operations not directly supported by Mips.
152 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
153 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
154 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
155 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
156 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
157 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
158 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
159 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
160 setOperationAction(ISD::ROTL, MVT::i32, Expand);
161 setOperationAction(ISD::ROTL, MVT::i64, Expand);
163 if (!Subtarget->hasMips32r2())
164 setOperationAction(ISD::ROTR, MVT::i32, Expand);
166 if (!Subtarget->hasMips64r2())
167 setOperationAction(ISD::ROTR, MVT::i64, Expand);
169 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
170 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
171 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
172 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
173 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
174 setOperationAction(ISD::FSIN, MVT::f32, Expand);
175 setOperationAction(ISD::FSIN, MVT::f64, Expand);
176 setOperationAction(ISD::FCOS, MVT::f32, Expand);
177 setOperationAction(ISD::FCOS, MVT::f64, Expand);
178 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
179 setOperationAction(ISD::FPOW, MVT::f32, Expand);
180 setOperationAction(ISD::FPOW, MVT::f64, Expand);
181 setOperationAction(ISD::FLOG, MVT::f32, Expand);
182 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
183 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
184 setOperationAction(ISD::FEXP, MVT::f32, Expand);
185 setOperationAction(ISD::FMA, MVT::f32, Expand);
186 setOperationAction(ISD::FMA, MVT::f64, Expand);
188 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
189 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
191 setOperationAction(ISD::VAARG, MVT::Other, Expand);
192 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
193 setOperationAction(ISD::VAEND, MVT::Other, Expand);
195 // Use the default for now
196 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
197 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
199 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
200 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
202 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
203 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
205 setInsertFencesForAtomic(true);
207 if (Subtarget->isSingleFloat())
208 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
210 if (!Subtarget->hasSEInReg()) {
211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
215 if (!Subtarget->hasBitCount())
216 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
218 if (!Subtarget->hasSwap())
219 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
221 setTargetDAGCombine(ISD::ADDE);
222 setTargetDAGCombine(ISD::SUBE);
223 setTargetDAGCombine(ISD::SDIVREM);
224 setTargetDAGCombine(ISD::UDIVREM);
225 setTargetDAGCombine(ISD::SETCC);
226 setTargetDAGCombine(ISD::AND);
227 setTargetDAGCombine(ISD::OR);
229 setMinFunctionAlignment(2);
231 setStackPointerRegisterToSaveRestore(Mips::SP);
232 computeRegisterProperties();
234 setExceptionPointerRegister(Mips::A0);
235 setExceptionSelectorRegister(Mips::A1);
238 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
239 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
240 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
243 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
248 // Transforms a subgraph in CurDAG if the following pattern is found:
249 // (addc multLo, Lo0), (adde multHi, Hi0),
251 // multHi/Lo: product of multiplication
252 // Lo0: initial value of Lo register
253 // Hi0: initial value of Hi register
254 // Return true if pattern matching was successful.
255 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
256 // ADDENode's second operand must be a flag output of an ADDC node in order
257 // for the matching to be successful.
258 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
260 if (ADDCNode->getOpcode() != ISD::ADDC)
263 SDValue MultHi = ADDENode->getOperand(0);
264 SDValue MultLo = ADDCNode->getOperand(0);
265 SDNode* MultNode = MultHi.getNode();
266 unsigned MultOpc = MultHi.getOpcode();
268 // MultHi and MultLo must be generated by the same node,
269 if (MultLo.getNode() != MultNode)
272 // and it must be a multiplication.
273 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
276 // MultLo amd MultHi must be the first and second output of MultNode
278 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
281 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
282 // of the values of MultNode, in which case MultNode will be removed in later
284 // If there exist users other than ADDENode or ADDCNode, this function returns
285 // here, which will result in MultNode being mapped to a single MULT
286 // instruction node rather than a pair of MULT and MADD instructions being
288 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
291 SDValue Chain = CurDAG->getEntryNode();
292 DebugLoc dl = ADDENode->getDebugLoc();
294 // create MipsMAdd(u) node
295 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
297 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
299 MultNode->getOperand(0),// Factor 0
300 MultNode->getOperand(1),// Factor 1
301 ADDCNode->getOperand(1),// Lo0
302 ADDENode->getOperand(1));// Hi0
304 // create CopyFromReg nodes
305 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
307 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
309 CopyFromLo.getValue(2));
311 // replace uses of adde and addc here
312 if (!SDValue(ADDCNode, 0).use_empty())
313 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
315 if (!SDValue(ADDENode, 0).use_empty())
316 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
322 // Transforms a subgraph in CurDAG if the following pattern is found:
323 // (addc Lo0, multLo), (sube Hi0, multHi),
325 // multHi/Lo: product of multiplication
326 // Lo0: initial value of Lo register
327 // Hi0: initial value of Hi register
328 // Return true if pattern matching was successful.
329 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
330 // SUBENode's second operand must be a flag output of an SUBC node in order
331 // for the matching to be successful.
332 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
334 if (SUBCNode->getOpcode() != ISD::SUBC)
337 SDValue MultHi = SUBENode->getOperand(1);
338 SDValue MultLo = SUBCNode->getOperand(1);
339 SDNode* MultNode = MultHi.getNode();
340 unsigned MultOpc = MultHi.getOpcode();
342 // MultHi and MultLo must be generated by the same node,
343 if (MultLo.getNode() != MultNode)
346 // and it must be a multiplication.
347 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
350 // MultLo amd MultHi must be the first and second output of MultNode
352 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
355 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
356 // of the values of MultNode, in which case MultNode will be removed in later
358 // If there exist users other than SUBENode or SUBCNode, this function returns
359 // here, which will result in MultNode being mapped to a single MULT
360 // instruction node rather than a pair of MULT and MSUB instructions being
362 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
365 SDValue Chain = CurDAG->getEntryNode();
366 DebugLoc dl = SUBENode->getDebugLoc();
368 // create MipsSub(u) node
369 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
371 SDValue MSub = CurDAG->getNode(MultOpc, dl,
373 MultNode->getOperand(0),// Factor 0
374 MultNode->getOperand(1),// Factor 1
375 SUBCNode->getOperand(0),// Lo0
376 SUBENode->getOperand(0));// Hi0
378 // create CopyFromReg nodes
379 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
381 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
383 CopyFromLo.getValue(2));
385 // replace uses of sube and subc here
386 if (!SDValue(SUBCNode, 0).use_empty())
387 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
389 if (!SDValue(SUBENode, 0).use_empty())
390 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
395 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
396 TargetLowering::DAGCombinerInfo &DCI,
397 const MipsSubtarget* Subtarget) {
398 if (DCI.isBeforeLegalize())
401 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
403 return SDValue(N, 0);
408 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
409 TargetLowering::DAGCombinerInfo &DCI,
410 const MipsSubtarget* Subtarget) {
411 if (DCI.isBeforeLegalize())
414 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
416 return SDValue(N, 0);
421 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
422 TargetLowering::DAGCombinerInfo &DCI,
423 const MipsSubtarget* Subtarget) {
424 if (DCI.isBeforeLegalizeOps())
427 EVT Ty = N->getValueType(0);
428 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
429 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
430 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
432 DebugLoc dl = N->getDebugLoc();
434 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
435 N->getOperand(0), N->getOperand(1));
436 SDValue InChain = DAG.getEntryNode();
437 SDValue InGlue = DivRem;
440 if (N->hasAnyUseOfValue(0)) {
441 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
444 InChain = CopyFromLo.getValue(1);
445 InGlue = CopyFromLo.getValue(2);
449 if (N->hasAnyUseOfValue(1)) {
450 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
458 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
460 default: llvm_unreachable("Unknown fp condition code!");
462 case ISD::SETOEQ: return Mips::FCOND_OEQ;
463 case ISD::SETUNE: return Mips::FCOND_UNE;
465 case ISD::SETOLT: return Mips::FCOND_OLT;
467 case ISD::SETOGT: return Mips::FCOND_OGT;
469 case ISD::SETOLE: return Mips::FCOND_OLE;
471 case ISD::SETOGE: return Mips::FCOND_OGE;
472 case ISD::SETULT: return Mips::FCOND_ULT;
473 case ISD::SETULE: return Mips::FCOND_ULE;
474 case ISD::SETUGT: return Mips::FCOND_UGT;
475 case ISD::SETUGE: return Mips::FCOND_UGE;
476 case ISD::SETUO: return Mips::FCOND_UN;
477 case ISD::SETO: return Mips::FCOND_OR;
479 case ISD::SETONE: return Mips::FCOND_ONE;
480 case ISD::SETUEQ: return Mips::FCOND_UEQ;
485 // Returns true if condition code has to be inverted.
486 static bool InvertFPCondCode(Mips::CondCode CC) {
487 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
490 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
493 assert(false && "Illegal Condition Code");
497 // Creates and returns an FPCmp node from a setcc node.
498 // Returns Op if setcc is not a floating point comparison.
499 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
500 // must be a SETCC node
501 if (Op.getOpcode() != ISD::SETCC)
504 SDValue LHS = Op.getOperand(0);
506 if (!LHS.getValueType().isFloatingPoint())
509 SDValue RHS = Op.getOperand(1);
510 DebugLoc dl = Op.getDebugLoc();
512 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
513 // node if necessary.
514 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
516 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
517 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
520 // Creates and returns a CMovFPT/F node.
521 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
522 SDValue False, DebugLoc DL) {
523 bool invert = InvertFPCondCode((Mips::CondCode)
524 cast<ConstantSDNode>(Cond.getOperand(2))
527 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
528 True.getValueType(), True, False, Cond);
531 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
532 TargetLowering::DAGCombinerInfo &DCI,
533 const MipsSubtarget* Subtarget) {
534 if (DCI.isBeforeLegalizeOps())
537 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
539 if (Cond.getOpcode() != MipsISD::FPCmp)
542 SDValue True = DAG.getConstant(1, MVT::i32);
543 SDValue False = DAG.getConstant(0, MVT::i32);
545 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
548 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
549 TargetLowering::DAGCombinerInfo &DCI,
550 const MipsSubtarget* Subtarget) {
551 // Pattern match EXT.
552 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
553 // => ext $dst, $src, size, pos
554 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
557 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
559 // Op's first operand must be a shift right.
560 if (ShiftRight.getOpcode() != ISD::SRA && ShiftRight.getOpcode() != ISD::SRL)
563 // The second operand of the shift must be an immediate.
566 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
569 Pos = CN->getZExtValue();
571 uint64_t SMPos, SMSize;
572 // Op's second operand must be a shifted mask.
573 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
574 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
577 // Return if the shifted mask does not start at bit 0 or the sum of its size
578 // and Pos exceeds the word's size.
579 if (SMPos != 0 || Pos + SMSize > 32)
582 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
583 ShiftRight.getOperand(0),
584 DAG.getConstant(Pos, MVT::i32),
585 DAG.getConstant(SMSize, MVT::i32));
588 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
589 TargetLowering::DAGCombinerInfo &DCI,
590 const MipsSubtarget* Subtarget) {
591 // Pattern match INS.
592 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
593 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
594 // => ins $dst, $src, size, pos, $src1
595 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
598 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
599 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
602 // See if Op's first operand matches (and $src1 , mask0).
603 if (And0.getOpcode() != ISD::AND)
606 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
607 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
610 // See if Op's second operand matches (and (shl $src, pos), mask1).
611 if (And1.getOpcode() != ISD::AND)
614 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
615 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
618 // The shift masks must have the same position and size.
619 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
622 SDValue Shl = And1.getOperand(0);
623 if (Shl.getOpcode() != ISD::SHL)
626 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
629 unsigned Shamt = CN->getZExtValue();
631 // Return if the shift amount and the first bit position of mask are not the
636 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
638 DAG.getConstant(SMPos0, MVT::i32),
639 DAG.getConstant(SMSize0, MVT::i32),
643 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
645 SelectionDAG &DAG = DCI.DAG;
646 unsigned opc = N->getOpcode();
651 return PerformADDECombine(N, DAG, DCI, Subtarget);
653 return PerformSUBECombine(N, DAG, DCI, Subtarget);
656 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
658 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
660 return PerformANDCombine(N, DAG, DCI, Subtarget);
662 return PerformORCombine(N, DAG, DCI, Subtarget);
668 SDValue MipsTargetLowering::
669 LowerOperation(SDValue Op, SelectionDAG &DAG) const
671 switch (Op.getOpcode())
673 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
674 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
675 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
676 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
677 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
678 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
679 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
680 case ISD::SELECT: return LowerSELECT(Op, DAG);
681 case ISD::VASTART: return LowerVASTART(Op, DAG);
682 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
683 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
684 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
685 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
690 //===----------------------------------------------------------------------===//
691 // Lower helper functions
692 //===----------------------------------------------------------------------===//
694 // AddLiveIn - This helper function adds the specified physical register to the
695 // MachineFunction as a live in value. It also creates a corresponding
696 // virtual register for it.
698 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
700 assert(RC->contains(PReg) && "Not the correct regclass!");
701 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
702 MF.getRegInfo().addLiveIn(PReg, VReg);
706 // Get fp branch code (not opcode) from condition code.
707 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
708 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
709 return Mips::BRANCH_T;
711 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
712 return Mips::BRANCH_F;
714 return Mips::BRANCH_INVALID;
718 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
720 const MipsSubtarget* Subtarget,
721 const TargetInstrInfo *TII,
722 bool isFPCmp, unsigned Opc) {
723 // There is no need to expand CMov instructions if target has
724 // conditional moves.
725 if (Subtarget->hasCondMov())
728 // To "insert" a SELECT_CC instruction, we actually have to insert the
729 // diamond control-flow pattern. The incoming instruction knows the
730 // destination vreg to set, the condition code register to branch on, the
731 // true/false values to select between, and a branch opcode to use.
732 const BasicBlock *LLVM_BB = BB->getBasicBlock();
733 MachineFunction::iterator It = BB;
740 // bNE r1, r0, copy1MBB
741 // fallthrough --> copy0MBB
742 MachineBasicBlock *thisMBB = BB;
743 MachineFunction *F = BB->getParent();
744 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
745 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
746 F->insert(It, copy0MBB);
747 F->insert(It, sinkMBB);
749 // Transfer the remainder of BB and its successor edges to sinkMBB.
750 sinkMBB->splice(sinkMBB->begin(), BB,
751 llvm::next(MachineBasicBlock::iterator(MI)),
753 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
755 // Next, add the true and fallthrough blocks as its successors.
756 BB->addSuccessor(copy0MBB);
757 BB->addSuccessor(sinkMBB);
759 // Emit the right instruction according to the type of the operands compared
761 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
763 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
764 .addReg(Mips::ZERO).addMBB(sinkMBB);
768 // # fallthrough to sinkMBB
771 // Update machine-CFG edges
772 BB->addSuccessor(sinkMBB);
775 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
780 BuildMI(*BB, BB->begin(), dl,
781 TII->get(Mips::PHI), MI->getOperand(0).getReg())
782 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
783 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
785 BuildMI(*BB, BB->begin(), dl,
786 TII->get(Mips::PHI), MI->getOperand(0).getReg())
787 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
788 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
790 MI->eraseFromParent(); // The pseudo instruction is gone now.
795 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
796 MachineBasicBlock *BB) const {
797 switch (MI->getOpcode()) {
799 assert(false && "Unexpected instr type to insert");
801 case Mips::ATOMIC_LOAD_ADD_I8:
802 case Mips::ATOMIC_LOAD_ADD_I8_P8:
803 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
804 case Mips::ATOMIC_LOAD_ADD_I16:
805 case Mips::ATOMIC_LOAD_ADD_I16_P8:
806 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
807 case Mips::ATOMIC_LOAD_ADD_I32:
808 case Mips::ATOMIC_LOAD_ADD_I32_P8:
809 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
810 case Mips::ATOMIC_LOAD_ADD_I64:
811 case Mips::ATOMIC_LOAD_ADD_I64_P8:
812 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
814 case Mips::ATOMIC_LOAD_AND_I8:
815 case Mips::ATOMIC_LOAD_AND_I8_P8:
816 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
817 case Mips::ATOMIC_LOAD_AND_I16:
818 case Mips::ATOMIC_LOAD_AND_I16_P8:
819 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
820 case Mips::ATOMIC_LOAD_AND_I32:
821 case Mips::ATOMIC_LOAD_AND_I32_P8:
822 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
823 case Mips::ATOMIC_LOAD_AND_I64:
824 case Mips::ATOMIC_LOAD_AND_I64_P8:
825 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
827 case Mips::ATOMIC_LOAD_OR_I8:
828 case Mips::ATOMIC_LOAD_OR_I8_P8:
829 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
830 case Mips::ATOMIC_LOAD_OR_I16:
831 case Mips::ATOMIC_LOAD_OR_I16_P8:
832 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
833 case Mips::ATOMIC_LOAD_OR_I32:
834 case Mips::ATOMIC_LOAD_OR_I32_P8:
835 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
836 case Mips::ATOMIC_LOAD_OR_I64:
837 case Mips::ATOMIC_LOAD_OR_I64_P8:
838 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
840 case Mips::ATOMIC_LOAD_XOR_I8:
841 case Mips::ATOMIC_LOAD_XOR_I8_P8:
842 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
843 case Mips::ATOMIC_LOAD_XOR_I16:
844 case Mips::ATOMIC_LOAD_XOR_I16_P8:
845 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
846 case Mips::ATOMIC_LOAD_XOR_I32:
847 case Mips::ATOMIC_LOAD_XOR_I32_P8:
848 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
849 case Mips::ATOMIC_LOAD_XOR_I64:
850 case Mips::ATOMIC_LOAD_XOR_I64_P8:
851 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
853 case Mips::ATOMIC_LOAD_NAND_I8:
854 case Mips::ATOMIC_LOAD_NAND_I8_P8:
855 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
856 case Mips::ATOMIC_LOAD_NAND_I16:
857 case Mips::ATOMIC_LOAD_NAND_I16_P8:
858 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
859 case Mips::ATOMIC_LOAD_NAND_I32:
860 case Mips::ATOMIC_LOAD_NAND_I32_P8:
861 return EmitAtomicBinary(MI, BB, 4, 0, true);
862 case Mips::ATOMIC_LOAD_NAND_I64:
863 case Mips::ATOMIC_LOAD_NAND_I64_P8:
864 return EmitAtomicBinary(MI, BB, 8, 0, true);
866 case Mips::ATOMIC_LOAD_SUB_I8:
867 case Mips::ATOMIC_LOAD_SUB_I8_P8:
868 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
869 case Mips::ATOMIC_LOAD_SUB_I16:
870 case Mips::ATOMIC_LOAD_SUB_I16_P8:
871 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
872 case Mips::ATOMIC_LOAD_SUB_I32:
873 case Mips::ATOMIC_LOAD_SUB_I32_P8:
874 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
875 case Mips::ATOMIC_LOAD_SUB_I64:
876 case Mips::ATOMIC_LOAD_SUB_I64_P8:
877 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
879 case Mips::ATOMIC_SWAP_I8:
880 case Mips::ATOMIC_SWAP_I8_P8:
881 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
882 case Mips::ATOMIC_SWAP_I16:
883 case Mips::ATOMIC_SWAP_I16_P8:
884 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
885 case Mips::ATOMIC_SWAP_I32:
886 case Mips::ATOMIC_SWAP_I32_P8:
887 return EmitAtomicBinary(MI, BB, 4, 0);
888 case Mips::ATOMIC_SWAP_I64:
889 case Mips::ATOMIC_SWAP_I64_P8:
890 return EmitAtomicBinary(MI, BB, 8, 0);
892 case Mips::ATOMIC_CMP_SWAP_I8:
893 case Mips::ATOMIC_CMP_SWAP_I8_P8:
894 return EmitAtomicCmpSwapPartword(MI, BB, 1);
895 case Mips::ATOMIC_CMP_SWAP_I16:
896 case Mips::ATOMIC_CMP_SWAP_I16_P8:
897 return EmitAtomicCmpSwapPartword(MI, BB, 2);
898 case Mips::ATOMIC_CMP_SWAP_I32:
899 case Mips::ATOMIC_CMP_SWAP_I32_P8:
900 return EmitAtomicCmpSwap(MI, BB, 4);
901 case Mips::ATOMIC_CMP_SWAP_I64:
902 case Mips::ATOMIC_CMP_SWAP_I64_P8:
903 return EmitAtomicCmpSwap(MI, BB, 8);
907 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
908 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
910 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
911 unsigned Size, unsigned BinOpcode,
913 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
915 MachineFunction *MF = BB->getParent();
916 MachineRegisterInfo &RegInfo = MF->getRegInfo();
917 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
918 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
919 DebugLoc dl = MI->getDebugLoc();
920 unsigned LL, SC, AND, NOR, ZERO, BEQ;
923 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
924 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
931 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
932 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
935 ZERO = Mips::ZERO_64;
939 unsigned OldVal = MI->getOperand(0).getReg();
940 unsigned Ptr = MI->getOperand(1).getReg();
941 unsigned Incr = MI->getOperand(2).getReg();
943 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
944 unsigned AndRes = RegInfo.createVirtualRegister(RC);
945 unsigned Success = RegInfo.createVirtualRegister(RC);
947 // insert new blocks after the current block
948 const BasicBlock *LLVM_BB = BB->getBasicBlock();
949 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
950 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
951 MachineFunction::iterator It = BB;
953 MF->insert(It, loopMBB);
954 MF->insert(It, exitMBB);
956 // Transfer the remainder of BB and its successor edges to exitMBB.
957 exitMBB->splice(exitMBB->begin(), BB,
958 llvm::next(MachineBasicBlock::iterator(MI)),
960 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
964 // fallthrough --> loopMBB
965 BB->addSuccessor(loopMBB);
966 loopMBB->addSuccessor(loopMBB);
967 loopMBB->addSuccessor(exitMBB);
971 // <binop> storeval, oldval, incr
972 // sc success, storeval, 0(ptr)
973 // beq success, $0, loopMBB
975 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
977 // and andres, oldval, incr
978 // nor storeval, $0, andres
979 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
980 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
981 } else if (BinOpcode) {
982 // <binop> storeval, oldval, incr
983 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
987 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
988 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
990 MI->eraseFromParent(); // The instruction is gone now.
996 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
997 MachineBasicBlock *BB,
998 unsigned Size, unsigned BinOpcode,
1000 assert((Size == 1 || Size == 2) &&
1001 "Unsupported size for EmitAtomicBinaryPartial.");
1003 MachineFunction *MF = BB->getParent();
1004 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1005 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1006 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1007 DebugLoc dl = MI->getDebugLoc();
1008 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1009 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1011 unsigned Dest = MI->getOperand(0).getReg();
1012 unsigned Ptr = MI->getOperand(1).getReg();
1013 unsigned Incr = MI->getOperand(2).getReg();
1015 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1016 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1017 unsigned Mask = RegInfo.createVirtualRegister(RC);
1018 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1019 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1020 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1021 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1022 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1023 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1024 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1025 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1026 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1027 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1028 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1029 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1030 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1031 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1032 unsigned Success = RegInfo.createVirtualRegister(RC);
1034 // insert new blocks after the current block
1035 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1036 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1037 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1038 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1039 MachineFunction::iterator It = BB;
1041 MF->insert(It, loopMBB);
1042 MF->insert(It, sinkMBB);
1043 MF->insert(It, exitMBB);
1045 // Transfer the remainder of BB and its successor edges to exitMBB.
1046 exitMBB->splice(exitMBB->begin(), BB,
1047 llvm::next(MachineBasicBlock::iterator(MI)),
1049 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1051 BB->addSuccessor(loopMBB);
1052 loopMBB->addSuccessor(loopMBB);
1053 loopMBB->addSuccessor(sinkMBB);
1054 sinkMBB->addSuccessor(exitMBB);
1057 // addiu masklsb2,$0,-4 # 0xfffffffc
1058 // and alignedaddr,ptr,masklsb2
1059 // andi ptrlsb2,ptr,3
1060 // sll shiftamt,ptrlsb2,3
1061 // ori maskupper,$0,255 # 0xff
1062 // sll mask,maskupper,shiftamt
1063 // nor mask2,$0,mask
1064 // sll incr2,incr,shiftamt
1066 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1067 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1068 .addReg(Mips::ZERO).addImm(-4);
1069 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1070 .addReg(Ptr).addReg(MaskLSB2);
1071 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1072 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1073 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1074 .addReg(Mips::ZERO).addImm(MaskImm);
1075 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1076 .addReg(ShiftAmt).addReg(MaskUpper);
1077 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1078 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1081 // atomic.load.binop
1083 // ll oldval,0(alignedaddr)
1084 // binop binopres,oldval,incr2
1085 // and newval,binopres,mask
1086 // and maskedoldval0,oldval,mask2
1087 // or storeval,maskedoldval0,newval
1088 // sc success,storeval,0(alignedaddr)
1089 // beq success,$0,loopMBB
1093 // ll oldval,0(alignedaddr)
1094 // and newval,incr2,mask
1095 // and maskedoldval0,oldval,mask2
1096 // or storeval,maskedoldval0,newval
1097 // sc success,storeval,0(alignedaddr)
1098 // beq success,$0,loopMBB
1101 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1103 // and andres, oldval, incr2
1104 // nor binopres, $0, andres
1105 // and newval, binopres, mask
1106 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1107 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1108 .addReg(Mips::ZERO).addReg(AndRes);
1109 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1110 } else if (BinOpcode) {
1111 // <binop> binopres, oldval, incr2
1112 // and newval, binopres, mask
1113 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1114 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1115 } else {// atomic.swap
1116 // and newval, incr2, mask
1117 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1120 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1121 .addReg(OldVal).addReg(Mask2);
1122 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1123 .addReg(MaskedOldVal0).addReg(NewVal);
1124 BuildMI(BB, dl, TII->get(SC), Success)
1125 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1126 BuildMI(BB, dl, TII->get(Mips::BEQ))
1127 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1130 // and maskedoldval1,oldval,mask
1131 // srl srlres,maskedoldval1,shiftamt
1132 // sll sllres,srlres,24
1133 // sra dest,sllres,24
1135 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1137 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1138 .addReg(OldVal).addReg(Mask);
1139 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1140 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1141 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1142 .addReg(SrlRes).addImm(ShiftImm);
1143 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1144 .addReg(SllRes).addImm(ShiftImm);
1146 MI->eraseFromParent(); // The instruction is gone now.
1152 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1153 MachineBasicBlock *BB,
1154 unsigned Size) const {
1155 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1157 MachineFunction *MF = BB->getParent();
1158 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1159 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1160 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1161 DebugLoc dl = MI->getDebugLoc();
1162 unsigned LL, SC, ZERO, BNE, BEQ;
1165 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1166 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1172 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1173 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1174 ZERO = Mips::ZERO_64;
1179 unsigned Dest = MI->getOperand(0).getReg();
1180 unsigned Ptr = MI->getOperand(1).getReg();
1181 unsigned OldVal = MI->getOperand(2).getReg();
1182 unsigned NewVal = MI->getOperand(3).getReg();
1184 unsigned Success = RegInfo.createVirtualRegister(RC);
1186 // insert new blocks after the current block
1187 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1188 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1189 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1190 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1191 MachineFunction::iterator It = BB;
1193 MF->insert(It, loop1MBB);
1194 MF->insert(It, loop2MBB);
1195 MF->insert(It, exitMBB);
1197 // Transfer the remainder of BB and its successor edges to exitMBB.
1198 exitMBB->splice(exitMBB->begin(), BB,
1199 llvm::next(MachineBasicBlock::iterator(MI)),
1201 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1205 // fallthrough --> loop1MBB
1206 BB->addSuccessor(loop1MBB);
1207 loop1MBB->addSuccessor(exitMBB);
1208 loop1MBB->addSuccessor(loop2MBB);
1209 loop2MBB->addSuccessor(loop1MBB);
1210 loop2MBB->addSuccessor(exitMBB);
1214 // bne dest, oldval, exitMBB
1216 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1217 BuildMI(BB, dl, TII->get(BNE))
1218 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1221 // sc success, newval, 0(ptr)
1222 // beq success, $0, loop1MBB
1224 BuildMI(BB, dl, TII->get(SC), Success)
1225 .addReg(NewVal).addReg(Ptr).addImm(0);
1226 BuildMI(BB, dl, TII->get(BEQ))
1227 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1229 MI->eraseFromParent(); // The instruction is gone now.
1235 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1236 MachineBasicBlock *BB,
1237 unsigned Size) const {
1238 assert((Size == 1 || Size == 2) &&
1239 "Unsupported size for EmitAtomicCmpSwapPartial.");
1241 MachineFunction *MF = BB->getParent();
1242 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1243 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1244 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1245 DebugLoc dl = MI->getDebugLoc();
1246 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1247 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1249 unsigned Dest = MI->getOperand(0).getReg();
1250 unsigned Ptr = MI->getOperand(1).getReg();
1251 unsigned CmpVal = MI->getOperand(2).getReg();
1252 unsigned NewVal = MI->getOperand(3).getReg();
1254 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1255 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1256 unsigned Mask = RegInfo.createVirtualRegister(RC);
1257 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1258 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1259 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1260 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1261 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1262 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1263 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1264 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1265 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1266 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1267 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1268 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1269 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1270 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1271 unsigned Success = RegInfo.createVirtualRegister(RC);
1273 // insert new blocks after the current block
1274 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1275 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1276 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1277 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1278 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1279 MachineFunction::iterator It = BB;
1281 MF->insert(It, loop1MBB);
1282 MF->insert(It, loop2MBB);
1283 MF->insert(It, sinkMBB);
1284 MF->insert(It, exitMBB);
1286 // Transfer the remainder of BB and its successor edges to exitMBB.
1287 exitMBB->splice(exitMBB->begin(), BB,
1288 llvm::next(MachineBasicBlock::iterator(MI)),
1290 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1292 BB->addSuccessor(loop1MBB);
1293 loop1MBB->addSuccessor(sinkMBB);
1294 loop1MBB->addSuccessor(loop2MBB);
1295 loop2MBB->addSuccessor(loop1MBB);
1296 loop2MBB->addSuccessor(sinkMBB);
1297 sinkMBB->addSuccessor(exitMBB);
1299 // FIXME: computation of newval2 can be moved to loop2MBB.
1301 // addiu masklsb2,$0,-4 # 0xfffffffc
1302 // and alignedaddr,ptr,masklsb2
1303 // andi ptrlsb2,ptr,3
1304 // sll shiftamt,ptrlsb2,3
1305 // ori maskupper,$0,255 # 0xff
1306 // sll mask,maskupper,shiftamt
1307 // nor mask2,$0,mask
1308 // andi maskedcmpval,cmpval,255
1309 // sll shiftedcmpval,maskedcmpval,shiftamt
1310 // andi maskednewval,newval,255
1311 // sll shiftednewval,maskednewval,shiftamt
1312 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1313 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1314 .addReg(Mips::ZERO).addImm(-4);
1315 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1316 .addReg(Ptr).addReg(MaskLSB2);
1317 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1318 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1319 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1320 .addReg(Mips::ZERO).addImm(MaskImm);
1321 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1322 .addReg(ShiftAmt).addReg(MaskUpper);
1323 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1324 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1325 .addReg(CmpVal).addImm(MaskImm);
1326 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1327 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1328 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1329 .addReg(NewVal).addImm(MaskImm);
1330 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1331 .addReg(ShiftAmt).addReg(MaskedNewVal);
1334 // ll oldval,0(alginedaddr)
1335 // and maskedoldval0,oldval,mask
1336 // bne maskedoldval0,shiftedcmpval,sinkMBB
1338 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1339 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1340 .addReg(OldVal).addReg(Mask);
1341 BuildMI(BB, dl, TII->get(Mips::BNE))
1342 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1345 // and maskedoldval1,oldval,mask2
1346 // or storeval,maskedoldval1,shiftednewval
1347 // sc success,storeval,0(alignedaddr)
1348 // beq success,$0,loop1MBB
1350 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1351 .addReg(OldVal).addReg(Mask2);
1352 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1353 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1354 BuildMI(BB, dl, TII->get(SC), Success)
1355 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1356 BuildMI(BB, dl, TII->get(Mips::BEQ))
1357 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1360 // srl srlres,maskedoldval0,shiftamt
1361 // sll sllres,srlres,24
1362 // sra dest,sllres,24
1364 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1366 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1367 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1368 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1369 .addReg(SrlRes).addImm(ShiftImm);
1370 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1371 .addReg(SllRes).addImm(ShiftImm);
1373 MI->eraseFromParent(); // The instruction is gone now.
1378 //===----------------------------------------------------------------------===//
1379 // Misc Lower Operation implementation
1380 //===----------------------------------------------------------------------===//
1381 SDValue MipsTargetLowering::
1382 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1384 MachineFunction &MF = DAG.getMachineFunction();
1385 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1386 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1388 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1389 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1390 "Cannot lower if the alignment of the allocated space is larger than \
1391 that of the stack.");
1393 SDValue Chain = Op.getOperand(0);
1394 SDValue Size = Op.getOperand(1);
1395 DebugLoc dl = Op.getDebugLoc();
1397 // Get a reference from Mips stack pointer
1398 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1400 // Subtract the dynamic size from the actual stack size to
1401 // obtain the new stack size.
1402 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1404 // The Sub result contains the new stack start address, so it
1405 // must be placed in the stack pointer register.
1406 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1408 // This node always has two return values: a new stack pointer
1409 // value and a chain
1410 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1411 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1412 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1414 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1417 SDValue MipsTargetLowering::
1418 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1420 // The first operand is the chain, the second is the condition, the third is
1421 // the block to branch to if the condition is true.
1422 SDValue Chain = Op.getOperand(0);
1423 SDValue Dest = Op.getOperand(2);
1424 DebugLoc dl = Op.getDebugLoc();
1426 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1428 // Return if flag is not set by a floating point comparison.
1429 if (CondRes.getOpcode() != MipsISD::FPCmp)
1432 SDValue CCNode = CondRes.getOperand(2);
1434 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1435 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1437 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1441 SDValue MipsTargetLowering::
1442 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1444 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1446 // Return if flag is not set by a floating point comparison.
1447 if (Cond.getOpcode() != MipsISD::FPCmp)
1450 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1454 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1455 SelectionDAG &DAG) const {
1456 // FIXME there isn't actually debug info here
1457 DebugLoc dl = Op.getDebugLoc();
1458 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1460 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1461 SDVTList VTs = DAG.getVTList(MVT::i32);
1463 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1465 // %gp_rel relocation
1466 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1467 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1469 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1470 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1471 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1473 // %hi/%lo relocation
1474 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1476 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1478 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1479 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1480 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1483 EVT ValTy = Op.getValueType();
1484 bool HasGotOfst = (GV->hasInternalLinkage() ||
1485 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1486 unsigned GotFlag = IsN64 ?
1487 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1489 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1490 GA = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
1491 SDValue ResNode = DAG.getLoad(ValTy, dl,
1492 DAG.getEntryNode(), GA, MachinePointerInfo(),
1493 false, false, false, 0);
1494 // On functions and global targets not internal linked only
1495 // a load from got/GP is necessary for PIC to work.
1498 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1499 IsN64 ? MipsII::MO_GOT_OFST :
1501 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1502 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1505 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1506 SelectionDAG &DAG) const {
1507 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1508 // FIXME there isn't actually debug info here
1509 DebugLoc dl = Op.getDebugLoc();
1511 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1512 // %hi/%lo relocation
1513 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1515 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1517 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1518 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1519 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1522 EVT ValTy = Op.getValueType();
1523 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1524 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1525 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1526 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, BAGOTOffset);
1527 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1528 SDValue Load = DAG.getLoad(ValTy, dl,
1529 DAG.getEntryNode(), BAGOTOffset,
1530 MachinePointerInfo(), false, false, false, 0);
1531 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1532 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1535 SDValue MipsTargetLowering::
1536 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1538 // If the relocation model is PIC, use the General Dynamic TLS Model,
1539 // otherwise use the Initial Exec or Local Exec TLS Model.
1540 // TODO: implement Local Dynamic TLS model
1542 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1543 DebugLoc dl = GA->getDebugLoc();
1544 const GlobalValue *GV = GA->getGlobal();
1545 EVT PtrVT = getPointerTy();
1547 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1548 // General Dynamic TLS Model
1549 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1550 0, MipsII::MO_TLSGD);
1551 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1552 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1553 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1557 Entry.Node = Argument;
1558 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1559 Args.push_back(Entry);
1560 std::pair<SDValue, SDValue> CallResult =
1561 LowerCallTo(DAG.getEntryNode(),
1562 (Type *) Type::getInt32Ty(*DAG.getContext()),
1563 false, false, false, false, 0, CallingConv::C, false, true,
1564 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1567 return CallResult.first;
1571 if (GV->isDeclaration()) {
1572 // Initial Exec TLS Model
1573 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1574 MipsII::MO_GOTTPREL);
1575 Offset = DAG.getLoad(MVT::i32, dl,
1576 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1577 false, false, false, 0);
1579 // Local Exec TLS Model
1580 SDVTList VTs = DAG.getVTList(MVT::i32);
1581 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1582 MipsII::MO_TPREL_HI);
1583 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1584 MipsII::MO_TPREL_LO);
1585 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1586 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1587 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1590 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1591 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1594 SDValue MipsTargetLowering::
1595 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1599 // FIXME there isn't actually debug info here
1600 DebugLoc dl = Op.getDebugLoc();
1601 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1602 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1604 EVT PtrVT = Op.getValueType();
1605 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1607 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1610 SDValue Ops[] = { JTI };
1611 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1612 } else {// Emit Load from Global Pointer
1613 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1614 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1615 MachinePointerInfo(),
1616 false, false, false, 0);
1619 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1621 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1622 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1627 SDValue MipsTargetLowering::
1628 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1631 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1632 const Constant *C = N->getConstVal();
1633 // FIXME there isn't actually debug info here
1634 DebugLoc dl = Op.getDebugLoc();
1636 // gp_rel relocation
1637 // FIXME: we should reference the constant pool using small data sections,
1638 // but the asm printer currently doesn't support this feature without
1639 // hacking it. This feature should come soon so we can uncomment the
1641 //if (IsInSmallSection(C->getType())) {
1642 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1643 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1644 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1646 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1647 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1648 N->getOffset(), MipsII::MO_ABS_HI);
1649 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1650 N->getOffset(), MipsII::MO_ABS_LO);
1651 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1652 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1653 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1655 EVT ValTy = Op.getValueType();
1656 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1657 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1658 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1659 N->getOffset(), GOTFlag);
1660 CP = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, CP);
1661 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(),
1662 CP, MachinePointerInfo::getConstantPool(),
1663 false, false, false, 0);
1664 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1665 N->getOffset(), OFSTFlag);
1666 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1667 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1673 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1674 MachineFunction &MF = DAG.getMachineFunction();
1675 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1677 DebugLoc dl = Op.getDebugLoc();
1678 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1681 // vastart just stores the address of the VarArgsFrameIndex slot into the
1682 // memory location argument.
1683 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1684 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1685 MachinePointerInfo(SV),
1689 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1690 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1691 DebugLoc dl = Op.getDebugLoc();
1692 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1693 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1694 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1695 DAG.getConstant(0x7fffffff, MVT::i32));
1696 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1697 DAG.getConstant(0x80000000, MVT::i32));
1698 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1699 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1702 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1704 // Use ext/ins instructions if target architecture is Mips32r2.
1705 // Eliminate redundant mfc1 and mtc1 instructions.
1706 unsigned LoIdx = 0, HiIdx = 1;
1709 std::swap(LoIdx, HiIdx);
1711 DebugLoc dl = Op.getDebugLoc();
1712 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1714 DAG.getConstant(LoIdx, MVT::i32));
1715 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1716 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1717 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1718 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1719 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1720 DAG.getConstant(0x7fffffff, MVT::i32));
1721 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1722 DAG.getConstant(0x80000000, MVT::i32));
1723 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1726 std::swap(Word0, Word1);
1728 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1731 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1733 EVT Ty = Op.getValueType();
1735 assert(Ty == MVT::f32 || Ty == MVT::f64);
1738 return LowerFCOPYSIGN32(Op, DAG);
1740 return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1743 SDValue MipsTargetLowering::
1744 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1746 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1747 "Frame address can only be determined for current frame.");
1749 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1750 MFI->setFrameAddressIsTaken(true);
1751 EVT VT = Op.getValueType();
1752 DebugLoc dl = Op.getDebugLoc();
1753 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1754 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1758 // TODO: set SType according to the desired memory barrier behavior.
1759 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1760 SelectionDAG& DAG) const {
1762 DebugLoc dl = Op.getDebugLoc();
1763 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1764 DAG.getConstant(SType, MVT::i32));
1767 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1768 SelectionDAG& DAG) const {
1769 // FIXME: Need pseudo-fence for 'singlethread' fences
1770 // FIXME: Set SType for weaker fences where supported/appropriate.
1772 DebugLoc dl = Op.getDebugLoc();
1773 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1774 DAG.getConstant(SType, MVT::i32));
1777 //===----------------------------------------------------------------------===//
1778 // Calling Convention Implementation
1779 //===----------------------------------------------------------------------===//
1781 //===----------------------------------------------------------------------===//
1782 // TODO: Implement a generic logic using tblgen that can support this.
1783 // Mips O32 ABI rules:
1785 // i32 - Passed in A0, A1, A2, A3 and stack
1786 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1787 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1788 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1789 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1790 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1793 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1794 //===----------------------------------------------------------------------===//
1796 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1797 MVT LocVT, CCValAssign::LocInfo LocInfo,
1798 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1800 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1802 static const unsigned IntRegs[] = {
1803 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1805 static const unsigned F32Regs[] = {
1806 Mips::F12, Mips::F14
1808 static const unsigned F64Regs[] = {
1813 if (ArgFlags.isByVal()) {
1814 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1815 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1816 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1817 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1818 r < std::min(IntRegsSize, NextReg); ++r)
1819 State.AllocateReg(IntRegs[r]);
1823 // Promote i8 and i16
1824 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1826 if (ArgFlags.isSExt())
1827 LocInfo = CCValAssign::SExt;
1828 else if (ArgFlags.isZExt())
1829 LocInfo = CCValAssign::ZExt;
1831 LocInfo = CCValAssign::AExt;
1836 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1837 // is true: function is vararg, argument is 3rd or higher, there is previous
1838 // argument which is not f32 or f64.
1839 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1840 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1841 unsigned OrigAlign = ArgFlags.getOrigAlign();
1842 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1844 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1845 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1846 // If this is the first part of an i64 arg,
1847 // the allocated register must be either A0 or A2.
1848 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1849 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1851 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1852 // Allocate int register and shadow next int register. If first
1853 // available register is Mips::A1 or Mips::A3, shadow it too.
1854 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1855 if (Reg == Mips::A1 || Reg == Mips::A3)
1856 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1857 State.AllocateReg(IntRegs, IntRegsSize);
1859 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1860 // we are guaranteed to find an available float register
1861 if (ValVT == MVT::f32) {
1862 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1863 // Shadow int register
1864 State.AllocateReg(IntRegs, IntRegsSize);
1866 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1867 // Shadow int registers
1868 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1869 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1870 State.AllocateReg(IntRegs, IntRegsSize);
1871 State.AllocateReg(IntRegs, IntRegsSize);
1874 llvm_unreachable("Cannot handle this ValVT.");
1876 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1877 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1880 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1882 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1884 return false; // CC must always match
1887 static const unsigned Mips64IntRegs[8] =
1888 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1889 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1890 static const unsigned Mips64DPRegs[8] =
1891 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1892 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1894 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1895 CCValAssign::LocInfo LocInfo,
1896 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1897 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1898 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1899 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1901 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1903 // If byval is 16-byte aligned, the first arg register must be even.
1904 if ((Align == 16) && (FirstIdx % 2)) {
1905 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1909 // Mark the registers allocated.
1910 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1911 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1913 // Allocate space on caller's stack.
1914 unsigned Offset = State.AllocateStack(Size, Align);
1917 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1920 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1925 #include "MipsGenCallingConv.inc"
1928 AnalyzeMips64CallOperands(CCState CCInfo,
1929 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1930 unsigned NumOps = Outs.size();
1931 for (unsigned i = 0; i != NumOps; ++i) {
1932 MVT ArgVT = Outs[i].VT;
1933 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1936 if (Outs[i].IsFixed)
1937 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1939 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1943 dbgs() << "Call operand #" << i << " has unhandled type "
1944 << EVT(ArgVT).getEVTString();
1946 llvm_unreachable(0);
1951 //===----------------------------------------------------------------------===//
1952 // Call Calling Convention Implementation
1953 //===----------------------------------------------------------------------===//
1955 static const unsigned O32IntRegsSize = 4;
1957 static const unsigned O32IntRegs[] = {
1958 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1961 // Return next O32 integer argument register.
1962 static unsigned getNextIntArgReg(unsigned Reg) {
1963 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1964 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1967 // Write ByVal Arg to arg registers and stack.
1969 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1970 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1971 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1972 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1973 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1974 MVT PtrType, bool isLittle) {
1975 unsigned LocMemOffset = VA.getLocMemOffset();
1976 unsigned Offset = 0;
1977 uint32_t RemainingSize = Flags.getByValSize();
1978 unsigned ByValAlign = Flags.getByValAlign();
1980 // Copy the first 4 words of byval arg to registers A0 - A3.
1981 // FIXME: Use a stricter alignment if it enables better optimization in passes
1983 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1984 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1985 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1986 DAG.getConstant(Offset, MVT::i32));
1987 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1988 MachinePointerInfo(),
1989 false, false, false, std::min(ByValAlign,
1991 MemOpChains.push_back(LoadVal.getValue(1));
1992 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1993 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1996 if (RemainingSize == 0)
1999 // If there still is a register available for argument passing, write the
2000 // remaining part of the structure to it using subword loads and shifts.
2001 if (LocMemOffset < 4 * 4) {
2002 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2003 "There must be one to three bytes remaining.");
2004 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2005 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2006 DAG.getConstant(Offset, MVT::i32));
2007 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2008 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2009 LoadPtr, MachinePointerInfo(),
2010 MVT::getIntegerVT(LoadSize * 8), false,
2012 MemOpChains.push_back(LoadVal.getValue(1));
2014 // If target is big endian, shift it to the most significant half-word or
2017 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2018 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2021 RemainingSize -= LoadSize;
2023 // Read second subword if necessary.
2024 if (RemainingSize != 0) {
2025 assert(RemainingSize == 1 && "There must be one byte remaining.");
2026 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2027 DAG.getConstant(Offset, MVT::i32));
2028 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2029 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2030 LoadPtr, MachinePointerInfo(),
2031 MVT::i8, false, false, Alignment);
2032 MemOpChains.push_back(Subword.getValue(1));
2033 // Insert the loaded byte to LoadVal.
2034 // FIXME: Use INS if supported by target.
2035 unsigned ShiftAmt = isLittle ? 16 : 8;
2036 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2037 DAG.getConstant(ShiftAmt, MVT::i32));
2038 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2041 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2042 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2046 // Create a fixed object on stack at offset LocMemOffset and copy
2047 // remaining part of byval arg to it using memcpy.
2048 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2049 DAG.getConstant(Offset, MVT::i32));
2050 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2051 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2052 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2053 DAG.getConstant(RemainingSize, MVT::i32),
2054 std::min(ByValAlign, (unsigned)4),
2055 /*isVolatile=*/false, /*AlwaysInline=*/false,
2056 MachinePointerInfo(0), MachinePointerInfo(0));
2059 // Copy Mips64 byVal arg to registers and stack.
2061 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2062 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2063 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2064 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2065 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2066 EVT PtrTy, bool isLittle) {
2067 unsigned ByValSize = Flags.getByValSize();
2068 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2069 bool IsRegLoc = VA.isRegLoc();
2070 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2071 unsigned LocMemOffset = 0;
2072 unsigned MemCpySize = ByValSize;
2075 LocMemOffset = VA.getLocMemOffset();
2077 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2079 const unsigned *RegEnd = Mips64IntRegs + 8;
2081 // Copy double words to registers.
2082 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2083 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2084 DAG.getConstant(Offset, PtrTy));
2085 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2086 MachinePointerInfo(), false, false, false,
2088 MemOpChains.push_back(LoadVal.getValue(1));
2089 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2092 // Return if the struct has been fully copied.
2093 if (!(MemCpySize = ByValSize - Offset))
2096 // If there is an argument register available, copy the remainder of the
2097 // byval argument with sub-doubleword loads and shifts.
2098 if (Reg != RegEnd) {
2099 assert((ByValSize < Offset + 8) &&
2100 "Size of the remainder should be smaller than 8-byte.");
2102 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2103 unsigned RemSize = ByValSize - Offset;
2105 if (RemSize < LoadSize)
2108 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2109 DAG.getConstant(Offset, PtrTy));
2111 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2112 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2113 false, false, Alignment);
2114 MemOpChains.push_back(LoadVal.getValue(1));
2116 // Offset in number of bits from double word boundary.
2117 unsigned OffsetDW = (Offset % 8) * 8;
2118 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2119 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2120 DAG.getConstant(Shamt, MVT::i32));
2122 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2125 Alignment = std::min(Alignment, LoadSize);
2128 RegsToPass.push_back(std::make_pair(*Reg, Val));
2133 assert(MemCpySize && "MemCpySize must not be zero.");
2135 // Create a fixed object on stack at offset LocMemOffset and copy
2136 // remainder of byval arg to it with memcpy.
2137 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2138 DAG.getConstant(Offset, PtrTy));
2139 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2140 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2141 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2142 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2143 /*isVolatile=*/false, /*AlwaysInline=*/false,
2144 MachinePointerInfo(0), MachinePointerInfo(0));
2147 /// LowerCall - functions arguments are copied from virtual regs to
2148 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2149 /// TODO: isTailCall.
2151 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2152 CallingConv::ID CallConv, bool isVarArg,
2154 const SmallVectorImpl<ISD::OutputArg> &Outs,
2155 const SmallVectorImpl<SDValue> &OutVals,
2156 const SmallVectorImpl<ISD::InputArg> &Ins,
2157 DebugLoc dl, SelectionDAG &DAG,
2158 SmallVectorImpl<SDValue> &InVals) const {
2159 // MIPs target does not yet support tail call optimization.
2162 MachineFunction &MF = DAG.getMachineFunction();
2163 MachineFrameInfo *MFI = MF.getFrameInfo();
2164 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2165 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2166 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2168 // Analyze operands of the call, assigning locations to each operand.
2169 SmallVector<CCValAssign, 16> ArgLocs;
2170 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2171 getTargetMachine(), ArgLocs, *DAG.getContext());
2174 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2176 AnalyzeMips64CallOperands(CCInfo, Outs);
2178 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2180 // Get a count of how many bytes are to be pushed on the stack.
2181 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2183 // Chain is the output chain of the last Load/Store or CopyToReg node.
2184 // ByValChain is the output chain of the last Memcpy node created for copying
2185 // byval arguments to the stack.
2186 SDValue Chain, CallSeqStart, ByValChain;
2187 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2188 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2189 ByValChain = InChain;
2191 // If this is the first call, create a stack frame object that points to
2192 // a location to which .cprestore saves $gp.
2193 if (IsO32 && IsPIC && !MipsFI->getGPFI())
2194 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2196 // Get the frame index of the stack frame object that points to the location
2197 // of dynamically allocated area on the stack.
2198 int DynAllocFI = MipsFI->getDynAllocFI();
2200 // Update size of the maximum argument space.
2201 // For O32, a minimum of four words (16 bytes) of argument space is
2204 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2206 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2208 if (MaxCallFrameSize < NextStackOffset) {
2209 MipsFI->setMaxCallFrameSize(NextStackOffset);
2211 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2212 // allocated stack space. These offsets must be aligned to a boundary
2213 // determined by the stack alignment of the ABI.
2214 unsigned StackAlignment = TFL->getStackAlignment();
2215 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2216 StackAlignment * StackAlignment;
2218 if (MipsFI->needGPSaveRestore())
2219 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2221 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2224 // With EABI is it possible to have 16 args on registers.
2225 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2226 SmallVector<SDValue, 8> MemOpChains;
2228 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2230 // Walk the register/memloc assignments, inserting copies/loads.
2231 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2232 SDValue Arg = OutVals[i];
2233 CCValAssign &VA = ArgLocs[i];
2234 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2235 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2238 if (Flags.isByVal()) {
2239 assert(Flags.getByValSize() &&
2240 "ByVal args of size 0 should have been ignored by front-end.");
2242 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2243 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2244 Subtarget->isLittle());
2246 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2247 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2248 Subtarget->isLittle());
2252 // Promote the value if needed.
2253 switch (VA.getLocInfo()) {
2254 default: llvm_unreachable("Unknown loc info!");
2255 case CCValAssign::Full:
2256 if (VA.isRegLoc()) {
2257 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2258 (ValVT == MVT::f64 && LocVT == MVT::i64))
2259 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2260 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2261 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2262 Arg, DAG.getConstant(0, MVT::i32));
2263 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2264 Arg, DAG.getConstant(1, MVT::i32));
2265 if (!Subtarget->isLittle())
2267 unsigned LocRegLo = VA.getLocReg();
2268 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2269 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2270 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2275 case CCValAssign::SExt:
2276 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2278 case CCValAssign::ZExt:
2279 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2281 case CCValAssign::AExt:
2282 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2286 // Arguments that can be passed on register must be kept at
2287 // RegsToPass vector
2288 if (VA.isRegLoc()) {
2289 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2293 // Register can't get to this point...
2294 assert(VA.isMemLoc());
2296 // Create the frame index object for this incoming parameter
2297 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2298 VA.getLocMemOffset(), true);
2299 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2301 // emit ISD::STORE whichs stores the
2302 // parameter value to a stack Location
2303 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2304 MachinePointerInfo(),
2308 // Extend range of indices of frame objects for outgoing arguments that were
2309 // created during this function call. Skip this step if no such objects were
2312 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2314 // If a memcpy has been created to copy a byval arg to a stack, replace the
2315 // chain input of CallSeqStart with ByValChain.
2316 if (InChain != ByValChain)
2317 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2318 NextStackOffsetVal);
2320 // Transform all store nodes into one single node because all store
2321 // nodes are independent of each other.
2322 if (!MemOpChains.empty())
2323 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2324 &MemOpChains[0], MemOpChains.size());
2326 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2327 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2328 // node so that legalize doesn't hack it.
2329 unsigned char OpFlag;
2330 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2331 bool LoadSymAddr = false;
2334 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2335 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2336 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2337 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2338 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2340 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2343 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2344 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2345 getPointerTy(), 0, OpFlag);
2350 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2351 if (IsN64 || (!IsO32 && IsPIC))
2352 OpFlag = MipsII::MO_GOT_DISP;
2353 else if (!IsPIC) // !N64 && static
2354 OpFlag = MipsII::MO_NO_FLAG;
2356 OpFlag = MipsII::MO_GOT_CALL;
2357 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2358 getPointerTy(), OpFlag);
2364 // Create nodes that load address of callee and copy it to T9
2367 // Load callee address
2368 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, getPointerTy(), Callee);
2369 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2370 Callee, MachinePointerInfo::getGOT(),
2371 false, false, false, 0);
2373 // Use GOT+LO if callee has internal linkage.
2374 if (CalleeLo.getNode()) {
2375 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2376 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2382 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2383 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2384 InFlag = Chain.getValue(1);
2385 Callee = DAG.getRegister(T9Reg, getPointerTy());
2388 // Build a sequence of copy-to-reg nodes chained together with token
2389 // chain and flag operands which copy the outgoing args into registers.
2390 // The InFlag in necessary since all emitted instructions must be
2392 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2393 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2394 RegsToPass[i].second, InFlag);
2395 InFlag = Chain.getValue(1);
2398 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2399 // = Chain, Callee, Reg#1, Reg#2, ...
2401 // Returns a chain & a flag for retval copy to use.
2402 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2403 SmallVector<SDValue, 8> Ops;
2404 Ops.push_back(Chain);
2405 Ops.push_back(Callee);
2407 // Add argument registers to the end of the list so that they are
2408 // known live into the call.
2409 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2410 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2411 RegsToPass[i].second.getValueType()));
2413 if (InFlag.getNode())
2414 Ops.push_back(InFlag);
2416 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2417 InFlag = Chain.getValue(1);
2419 // Create the CALLSEQ_END node.
2420 Chain = DAG.getCALLSEQ_END(Chain,
2421 DAG.getIntPtrConstant(NextStackOffset, true),
2422 DAG.getIntPtrConstant(0, true), InFlag);
2423 InFlag = Chain.getValue(1);
2425 // Handle result values, copying them out of physregs into vregs that we
2427 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2428 Ins, dl, DAG, InVals);
2431 /// LowerCallResult - Lower the result values of a call into the
2432 /// appropriate copies out of appropriate physical registers.
2434 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2435 CallingConv::ID CallConv, bool isVarArg,
2436 const SmallVectorImpl<ISD::InputArg> &Ins,
2437 DebugLoc dl, SelectionDAG &DAG,
2438 SmallVectorImpl<SDValue> &InVals) const {
2439 // Assign locations to each value returned by this call.
2440 SmallVector<CCValAssign, 16> RVLocs;
2441 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2442 getTargetMachine(), RVLocs, *DAG.getContext());
2444 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2446 // Copy all of the result registers out of their specified physreg.
2447 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2448 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2449 RVLocs[i].getValVT(), InFlag).getValue(1);
2450 InFlag = Chain.getValue(2);
2451 InVals.push_back(Chain.getValue(0));
2457 //===----------------------------------------------------------------------===//
2458 // Formal Arguments Calling Convention Implementation
2459 //===----------------------------------------------------------------------===//
2460 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2461 std::vector<SDValue>& OutChains,
2462 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2463 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2464 unsigned LocMem = VA.getLocMemOffset();
2465 unsigned FirstWord = LocMem / 4;
2467 // copy register A0 - A3 to frame object
2468 for (unsigned i = 0; i < NumWords; ++i) {
2469 unsigned CurWord = FirstWord + i;
2470 if (CurWord >= O32IntRegsSize)
2473 unsigned SrcReg = O32IntRegs[CurWord];
2474 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2475 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2476 DAG.getConstant(i * 4, MVT::i32));
2477 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2478 StorePtr, MachinePointerInfo(), false,
2480 OutChains.push_back(Store);
2484 // Create frame object on stack and copy registers used for byval passing to it.
2486 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2487 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2488 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2489 MachineFrameInfo *MFI, bool IsRegLoc,
2490 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2492 const unsigned *Reg = Mips64IntRegs + 8;
2493 int FOOffset; // Frame object offset from virtual frame pointer.
2496 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2497 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2500 FOOffset = VA.getLocMemOffset();
2502 // Create frame object.
2503 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2504 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2505 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2506 InVals.push_back(FIN);
2508 // Copy arg registers.
2509 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2511 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2512 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2513 DAG.getConstant(I * 8, PtrTy));
2514 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2515 StorePtr, MachinePointerInfo(), false,
2517 OutChains.push_back(Store);
2523 /// LowerFormalArguments - transform physical registers into virtual registers
2524 /// and generate load operations for arguments places on the stack.
2526 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2527 CallingConv::ID CallConv,
2529 const SmallVectorImpl<ISD::InputArg>
2531 DebugLoc dl, SelectionDAG &DAG,
2532 SmallVectorImpl<SDValue> &InVals)
2534 MachineFunction &MF = DAG.getMachineFunction();
2535 MachineFrameInfo *MFI = MF.getFrameInfo();
2536 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2538 MipsFI->setVarArgsFrameIndex(0);
2540 // Used with vargs to acumulate store chains.
2541 std::vector<SDValue> OutChains;
2543 // Assign locations to all of the incoming arguments.
2544 SmallVector<CCValAssign, 16> ArgLocs;
2545 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2546 getTargetMachine(), ArgLocs, *DAG.getContext());
2549 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2551 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2553 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2555 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2556 CCValAssign &VA = ArgLocs[i];
2557 EVT ValVT = VA.getValVT();
2558 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2559 bool IsRegLoc = VA.isRegLoc();
2561 if (Flags.isByVal()) {
2562 assert(Flags.getByValSize() &&
2563 "ByVal args of size 0 should have been ignored by front-end.");
2565 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2566 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2568 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2569 InVals.push_back(FIN);
2570 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2572 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2573 MFI, IsRegLoc, InVals, MipsFI,
2578 // Arguments stored on registers
2580 EVT RegVT = VA.getLocVT();
2581 unsigned ArgReg = VA.getLocReg();
2582 TargetRegisterClass *RC = 0;
2584 if (RegVT == MVT::i32)
2585 RC = Mips::CPURegsRegisterClass;
2586 else if (RegVT == MVT::i64)
2587 RC = Mips::CPU64RegsRegisterClass;
2588 else if (RegVT == MVT::f32)
2589 RC = Mips::FGR32RegisterClass;
2590 else if (RegVT == MVT::f64)
2591 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2593 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2595 // Transform the arguments stored on
2596 // physical registers into virtual ones
2597 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2598 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2600 // If this is an 8 or 16-bit value, it has been passed promoted
2601 // to 32 bits. Insert an assert[sz]ext to capture this, then
2602 // truncate to the right size.
2603 if (VA.getLocInfo() != CCValAssign::Full) {
2604 unsigned Opcode = 0;
2605 if (VA.getLocInfo() == CCValAssign::SExt)
2606 Opcode = ISD::AssertSext;
2607 else if (VA.getLocInfo() == CCValAssign::ZExt)
2608 Opcode = ISD::AssertZext;
2610 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2611 DAG.getValueType(ValVT));
2612 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2615 // Handle floating point arguments passed in integer registers.
2616 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2617 (RegVT == MVT::i64 && ValVT == MVT::f64))
2618 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2619 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2620 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2621 getNextIntArgReg(ArgReg), RC);
2622 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2623 if (!Subtarget->isLittle())
2624 std::swap(ArgValue, ArgValue2);
2625 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2626 ArgValue, ArgValue2);
2629 InVals.push_back(ArgValue);
2630 } else { // VA.isRegLoc()
2633 assert(VA.isMemLoc());
2635 // The stack pointer offset is relative to the caller stack frame.
2636 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2637 VA.getLocMemOffset(), true);
2639 // Create load nodes to retrieve arguments from the stack
2640 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2641 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2642 MachinePointerInfo::getFixedStack(LastFI),
2643 false, false, false, 0));
2647 // The mips ABIs for returning structs by value requires that we copy
2648 // the sret argument into $v0 for the return. Save the argument into
2649 // a virtual register so that we can access it from the return points.
2650 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2651 unsigned Reg = MipsFI->getSRetReturnReg();
2653 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2654 MipsFI->setSRetReturnReg(Reg);
2656 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2657 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2661 unsigned NumOfRegs = IsO32 ? 4 : 8;
2662 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2663 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2664 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2665 TargetRegisterClass *RC
2666 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2667 unsigned RegSize = RC->getSize();
2668 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2670 // Offset of the first variable argument from stack pointer.
2671 int FirstVaArgOffset;
2673 if (IsO32 || (Idx == NumOfRegs)) {
2675 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2677 FirstVaArgOffset = RegSlotOffset;
2679 // Record the frame index of the first variable argument
2680 // which is a value necessary to VASTART.
2681 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2682 MipsFI->setVarArgsFrameIndex(LastFI);
2684 // Copy the integer registers that have not been used for argument passing
2685 // to the argument register save area. For O32, the save area is allocated
2686 // in the caller's stack frame, while for N32/64, it is allocated in the
2687 // callee's stack frame.
2688 for (int StackOffset = RegSlotOffset;
2689 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2690 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2691 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2692 MVT::getIntegerVT(RegSize * 8));
2693 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2694 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2695 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2696 MachinePointerInfo(),
2701 MipsFI->setLastInArgFI(LastFI);
2703 // All stores are grouped in one node to allow the matching between
2704 // the size of Ins and InVals. This only happens when on varg functions
2705 if (!OutChains.empty()) {
2706 OutChains.push_back(Chain);
2707 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2708 &OutChains[0], OutChains.size());
2714 //===----------------------------------------------------------------------===//
2715 // Return Value Calling Convention Implementation
2716 //===----------------------------------------------------------------------===//
2719 MipsTargetLowering::LowerReturn(SDValue Chain,
2720 CallingConv::ID CallConv, bool isVarArg,
2721 const SmallVectorImpl<ISD::OutputArg> &Outs,
2722 const SmallVectorImpl<SDValue> &OutVals,
2723 DebugLoc dl, SelectionDAG &DAG) const {
2725 // CCValAssign - represent the assignment of
2726 // the return value to a location
2727 SmallVector<CCValAssign, 16> RVLocs;
2729 // CCState - Info about the registers and stack slot.
2730 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2731 getTargetMachine(), RVLocs, *DAG.getContext());
2733 // Analize return values.
2734 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2736 // If this is the first return lowered for this function, add
2737 // the regs to the liveout set for the function.
2738 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2739 for (unsigned i = 0; i != RVLocs.size(); ++i)
2740 if (RVLocs[i].isRegLoc())
2741 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2746 // Copy the result values into the output registers.
2747 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2748 CCValAssign &VA = RVLocs[i];
2749 assert(VA.isRegLoc() && "Can only return in registers!");
2751 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2754 // guarantee that all emitted copies are
2755 // stuck together, avoiding something bad
2756 Flag = Chain.getValue(1);
2759 // The mips ABIs for returning structs by value requires that we copy
2760 // the sret argument into $v0 for the return. We saved the argument into
2761 // a virtual register in the entry block, so now we copy the value out
2763 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2764 MachineFunction &MF = DAG.getMachineFunction();
2765 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2766 unsigned Reg = MipsFI->getSRetReturnReg();
2769 llvm_unreachable("sret virtual register not created in the entry block");
2770 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2772 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2773 Flag = Chain.getValue(1);
2776 // Return on Mips is always a "jr $ra"
2778 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2779 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2781 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2782 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2785 //===----------------------------------------------------------------------===//
2786 // Mips Inline Assembly Support
2787 //===----------------------------------------------------------------------===//
2789 /// getConstraintType - Given a constraint letter, return the type of
2790 /// constraint it is for this target.
2791 MipsTargetLowering::ConstraintType MipsTargetLowering::
2792 getConstraintType(const std::string &Constraint) const
2794 // Mips specific constrainy
2795 // GCC config/mips/constraints.md
2797 // 'd' : An address register. Equivalent to r
2798 // unless generating MIPS16 code.
2799 // 'y' : Equivalent to r; retained for
2800 // backwards compatibility.
2801 // 'f' : Floating Point registers.
2802 if (Constraint.size() == 1) {
2803 switch (Constraint[0]) {
2808 return C_RegisterClass;
2812 return TargetLowering::getConstraintType(Constraint);
2815 /// Examine constraint type and operand type and determine a weight value.
2816 /// This object must already have been set up with the operand type
2817 /// and the current alternative constraint selected.
2818 TargetLowering::ConstraintWeight
2819 MipsTargetLowering::getSingleConstraintMatchWeight(
2820 AsmOperandInfo &info, const char *constraint) const {
2821 ConstraintWeight weight = CW_Invalid;
2822 Value *CallOperandVal = info.CallOperandVal;
2823 // If we don't have a value, we can't do a match,
2824 // but allow it at the lowest weight.
2825 if (CallOperandVal == NULL)
2827 Type *type = CallOperandVal->getType();
2828 // Look at the constraint type.
2829 switch (*constraint) {
2831 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2835 if (type->isIntegerTy())
2836 weight = CW_Register;
2839 if (type->isFloatTy())
2840 weight = CW_Register;
2846 /// Given a register class constraint, like 'r', if this corresponds directly
2847 /// to an LLVM register class, return a register of 0 and the register class
2849 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2850 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2852 if (Constraint.size() == 1) {
2853 switch (Constraint[0]) {
2854 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2855 case 'y': // Same as 'r'. Exists for compatibility.
2857 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2860 return std::make_pair(0U, Mips::FGR32RegisterClass);
2862 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2863 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2867 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2871 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2872 // The Mips target isn't yet aware of offsets.
2876 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2877 if (VT != MVT::f32 && VT != MVT::f64)
2879 if (Imm.isNegZero())
2881 return Imm.isZero();