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::GlobalTLSAddress, MVT::i32, Custom);
131 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
132 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
133 setOperationAction(ISD::SELECT, MVT::f32, Custom);
134 setOperationAction(ISD::SELECT, MVT::f64, Custom);
135 setOperationAction(ISD::SELECT, MVT::i32, Custom);
136 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
137 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
138 setOperationAction(ISD::VASTART, MVT::Other, Custom);
140 setOperationAction(ISD::SDIV, MVT::i32, Expand);
141 setOperationAction(ISD::SREM, MVT::i32, Expand);
142 setOperationAction(ISD::UDIV, MVT::i32, Expand);
143 setOperationAction(ISD::UREM, MVT::i32, Expand);
144 setOperationAction(ISD::SDIV, MVT::i64, Expand);
145 setOperationAction(ISD::SREM, MVT::i64, Expand);
146 setOperationAction(ISD::UDIV, MVT::i64, Expand);
147 setOperationAction(ISD::UREM, MVT::i64, Expand);
149 // Operations not directly supported by Mips.
150 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
151 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
152 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
153 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
154 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
155 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
156 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
157 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
158 setOperationAction(ISD::ROTL, MVT::i32, Expand);
159 setOperationAction(ISD::ROTL, MVT::i64, Expand);
161 if (!Subtarget->hasMips32r2())
162 setOperationAction(ISD::ROTR, MVT::i32, Expand);
164 if (!Subtarget->hasMips64r2())
165 setOperationAction(ISD::ROTR, MVT::i64, Expand);
167 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
168 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
169 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
170 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
171 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
172 setOperationAction(ISD::FSIN, MVT::f32, Expand);
173 setOperationAction(ISD::FSIN, MVT::f64, Expand);
174 setOperationAction(ISD::FCOS, MVT::f32, Expand);
175 setOperationAction(ISD::FCOS, MVT::f64, Expand);
176 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
177 setOperationAction(ISD::FPOW, MVT::f32, Expand);
178 setOperationAction(ISD::FPOW, MVT::f64, Expand);
179 setOperationAction(ISD::FLOG, MVT::f32, Expand);
180 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
181 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
182 setOperationAction(ISD::FEXP, MVT::f32, Expand);
183 setOperationAction(ISD::FMA, MVT::f32, Expand);
184 setOperationAction(ISD::FMA, MVT::f64, Expand);
186 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
187 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
189 setOperationAction(ISD::VAARG, MVT::Other, Expand);
190 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
191 setOperationAction(ISD::VAEND, MVT::Other, Expand);
193 // Use the default for now
194 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
195 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
197 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
198 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
200 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
201 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
203 setInsertFencesForAtomic(true);
205 if (Subtarget->isSingleFloat())
206 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
208 if (!Subtarget->hasSEInReg()) {
209 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
213 if (!Subtarget->hasBitCount())
214 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
216 if (!Subtarget->hasSwap())
217 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
219 setTargetDAGCombine(ISD::ADDE);
220 setTargetDAGCombine(ISD::SUBE);
221 setTargetDAGCombine(ISD::SDIVREM);
222 setTargetDAGCombine(ISD::UDIVREM);
223 setTargetDAGCombine(ISD::SETCC);
224 setTargetDAGCombine(ISD::AND);
225 setTargetDAGCombine(ISD::OR);
227 setMinFunctionAlignment(2);
229 setStackPointerRegisterToSaveRestore(Mips::SP);
230 computeRegisterProperties();
232 setExceptionPointerRegister(Mips::A0);
233 setExceptionSelectorRegister(Mips::A1);
236 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
237 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
238 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
241 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
246 // Transforms a subgraph in CurDAG if the following pattern is found:
247 // (addc multLo, Lo0), (adde multHi, Hi0),
249 // multHi/Lo: product of multiplication
250 // Lo0: initial value of Lo register
251 // Hi0: initial value of Hi register
252 // Return true if pattern matching was successful.
253 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
254 // ADDENode's second operand must be a flag output of an ADDC node in order
255 // for the matching to be successful.
256 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
258 if (ADDCNode->getOpcode() != ISD::ADDC)
261 SDValue MultHi = ADDENode->getOperand(0);
262 SDValue MultLo = ADDCNode->getOperand(0);
263 SDNode* MultNode = MultHi.getNode();
264 unsigned MultOpc = MultHi.getOpcode();
266 // MultHi and MultLo must be generated by the same node,
267 if (MultLo.getNode() != MultNode)
270 // and it must be a multiplication.
271 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
274 // MultLo amd MultHi must be the first and second output of MultNode
276 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
279 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
280 // of the values of MultNode, in which case MultNode will be removed in later
282 // If there exist users other than ADDENode or ADDCNode, this function returns
283 // here, which will result in MultNode being mapped to a single MULT
284 // instruction node rather than a pair of MULT and MADD instructions being
286 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
289 SDValue Chain = CurDAG->getEntryNode();
290 DebugLoc dl = ADDENode->getDebugLoc();
292 // create MipsMAdd(u) node
293 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
295 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
297 MultNode->getOperand(0),// Factor 0
298 MultNode->getOperand(1),// Factor 1
299 ADDCNode->getOperand(1),// Lo0
300 ADDENode->getOperand(1));// Hi0
302 // create CopyFromReg nodes
303 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
305 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
307 CopyFromLo.getValue(2));
309 // replace uses of adde and addc here
310 if (!SDValue(ADDCNode, 0).use_empty())
311 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
313 if (!SDValue(ADDENode, 0).use_empty())
314 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
320 // Transforms a subgraph in CurDAG if the following pattern is found:
321 // (addc Lo0, multLo), (sube Hi0, multHi),
323 // multHi/Lo: product of multiplication
324 // Lo0: initial value of Lo register
325 // Hi0: initial value of Hi register
326 // Return true if pattern matching was successful.
327 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
328 // SUBENode's second operand must be a flag output of an SUBC node in order
329 // for the matching to be successful.
330 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
332 if (SUBCNode->getOpcode() != ISD::SUBC)
335 SDValue MultHi = SUBENode->getOperand(1);
336 SDValue MultLo = SUBCNode->getOperand(1);
337 SDNode* MultNode = MultHi.getNode();
338 unsigned MultOpc = MultHi.getOpcode();
340 // MultHi and MultLo must be generated by the same node,
341 if (MultLo.getNode() != MultNode)
344 // and it must be a multiplication.
345 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
348 // MultLo amd MultHi must be the first and second output of MultNode
350 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
353 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
354 // of the values of MultNode, in which case MultNode will be removed in later
356 // If there exist users other than SUBENode or SUBCNode, this function returns
357 // here, which will result in MultNode being mapped to a single MULT
358 // instruction node rather than a pair of MULT and MSUB instructions being
360 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
363 SDValue Chain = CurDAG->getEntryNode();
364 DebugLoc dl = SUBENode->getDebugLoc();
366 // create MipsSub(u) node
367 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
369 SDValue MSub = CurDAG->getNode(MultOpc, dl,
371 MultNode->getOperand(0),// Factor 0
372 MultNode->getOperand(1),// Factor 1
373 SUBCNode->getOperand(0),// Lo0
374 SUBENode->getOperand(0));// Hi0
376 // create CopyFromReg nodes
377 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
379 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
381 CopyFromLo.getValue(2));
383 // replace uses of sube and subc here
384 if (!SDValue(SUBCNode, 0).use_empty())
385 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
387 if (!SDValue(SUBENode, 0).use_empty())
388 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
393 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
394 TargetLowering::DAGCombinerInfo &DCI,
395 const MipsSubtarget* Subtarget) {
396 if (DCI.isBeforeLegalize())
399 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
401 return SDValue(N, 0);
406 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
407 TargetLowering::DAGCombinerInfo &DCI,
408 const MipsSubtarget* Subtarget) {
409 if (DCI.isBeforeLegalize())
412 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
414 return SDValue(N, 0);
419 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
420 TargetLowering::DAGCombinerInfo &DCI,
421 const MipsSubtarget* Subtarget) {
422 if (DCI.isBeforeLegalizeOps())
425 EVT Ty = N->getValueType(0);
426 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
427 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
428 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
430 DebugLoc dl = N->getDebugLoc();
432 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
433 N->getOperand(0), N->getOperand(1));
434 SDValue InChain = DAG.getEntryNode();
435 SDValue InGlue = DivRem;
438 if (N->hasAnyUseOfValue(0)) {
439 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
442 InChain = CopyFromLo.getValue(1);
443 InGlue = CopyFromLo.getValue(2);
447 if (N->hasAnyUseOfValue(1)) {
448 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
450 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
456 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
458 default: llvm_unreachable("Unknown fp condition code!");
460 case ISD::SETOEQ: return Mips::FCOND_OEQ;
461 case ISD::SETUNE: return Mips::FCOND_UNE;
463 case ISD::SETOLT: return Mips::FCOND_OLT;
465 case ISD::SETOGT: return Mips::FCOND_OGT;
467 case ISD::SETOLE: return Mips::FCOND_OLE;
469 case ISD::SETOGE: return Mips::FCOND_OGE;
470 case ISD::SETULT: return Mips::FCOND_ULT;
471 case ISD::SETULE: return Mips::FCOND_ULE;
472 case ISD::SETUGT: return Mips::FCOND_UGT;
473 case ISD::SETUGE: return Mips::FCOND_UGE;
474 case ISD::SETUO: return Mips::FCOND_UN;
475 case ISD::SETO: return Mips::FCOND_OR;
477 case ISD::SETONE: return Mips::FCOND_ONE;
478 case ISD::SETUEQ: return Mips::FCOND_UEQ;
483 // Returns true if condition code has to be inverted.
484 static bool InvertFPCondCode(Mips::CondCode CC) {
485 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
488 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
491 assert(false && "Illegal Condition Code");
495 // Creates and returns an FPCmp node from a setcc node.
496 // Returns Op if setcc is not a floating point comparison.
497 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
498 // must be a SETCC node
499 if (Op.getOpcode() != ISD::SETCC)
502 SDValue LHS = Op.getOperand(0);
504 if (!LHS.getValueType().isFloatingPoint())
507 SDValue RHS = Op.getOperand(1);
508 DebugLoc dl = Op.getDebugLoc();
510 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
511 // node if necessary.
512 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
514 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
515 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
518 // Creates and returns a CMovFPT/F node.
519 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
520 SDValue False, DebugLoc DL) {
521 bool invert = InvertFPCondCode((Mips::CondCode)
522 cast<ConstantSDNode>(Cond.getOperand(2))
525 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
526 True.getValueType(), True, False, Cond);
529 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
530 TargetLowering::DAGCombinerInfo &DCI,
531 const MipsSubtarget* Subtarget) {
532 if (DCI.isBeforeLegalizeOps())
535 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
537 if (Cond.getOpcode() != MipsISD::FPCmp)
540 SDValue True = DAG.getConstant(1, MVT::i32);
541 SDValue False = DAG.getConstant(0, MVT::i32);
543 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
546 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
547 TargetLowering::DAGCombinerInfo &DCI,
548 const MipsSubtarget* Subtarget) {
549 // Pattern match EXT.
550 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
551 // => ext $dst, $src, size, pos
552 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
555 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
557 // Op's first operand must be a shift right.
558 if (ShiftRight.getOpcode() != ISD::SRA && ShiftRight.getOpcode() != ISD::SRL)
561 // The second operand of the shift must be an immediate.
564 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
567 Pos = CN->getZExtValue();
569 uint64_t SMPos, SMSize;
570 // Op's second operand must be a shifted mask.
571 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
572 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
575 // Return if the shifted mask does not start at bit 0 or the sum of its size
576 // and Pos exceeds the word's size.
577 if (SMPos != 0 || Pos + SMSize > 32)
580 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
581 ShiftRight.getOperand(0),
582 DAG.getConstant(Pos, MVT::i32),
583 DAG.getConstant(SMSize, MVT::i32));
586 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
587 TargetLowering::DAGCombinerInfo &DCI,
588 const MipsSubtarget* Subtarget) {
589 // Pattern match INS.
590 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
591 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
592 // => ins $dst, $src, size, pos, $src1
593 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
596 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
597 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
600 // See if Op's first operand matches (and $src1 , mask0).
601 if (And0.getOpcode() != ISD::AND)
604 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
605 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
608 // See if Op's second operand matches (and (shl $src, pos), mask1).
609 if (And1.getOpcode() != ISD::AND)
612 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
613 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
616 // The shift masks must have the same position and size.
617 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
620 SDValue Shl = And1.getOperand(0);
621 if (Shl.getOpcode() != ISD::SHL)
624 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
627 unsigned Shamt = CN->getZExtValue();
629 // Return if the shift amount and the first bit position of mask are not the
634 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
636 DAG.getConstant(SMPos0, MVT::i32),
637 DAG.getConstant(SMSize0, MVT::i32),
641 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
643 SelectionDAG &DAG = DCI.DAG;
644 unsigned opc = N->getOpcode();
649 return PerformADDECombine(N, DAG, DCI, Subtarget);
651 return PerformSUBECombine(N, DAG, DCI, Subtarget);
654 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
656 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
658 return PerformANDCombine(N, DAG, DCI, Subtarget);
660 return PerformORCombine(N, DAG, DCI, Subtarget);
666 SDValue MipsTargetLowering::
667 LowerOperation(SDValue Op, SelectionDAG &DAG) const
669 switch (Op.getOpcode())
671 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
672 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
673 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
674 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
675 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
676 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
677 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
678 case ISD::SELECT: return LowerSELECT(Op, DAG);
679 case ISD::VASTART: return LowerVASTART(Op, DAG);
680 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
681 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
682 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
683 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
688 //===----------------------------------------------------------------------===//
689 // Lower helper functions
690 //===----------------------------------------------------------------------===//
692 // AddLiveIn - This helper function adds the specified physical register to the
693 // MachineFunction as a live in value. It also creates a corresponding
694 // virtual register for it.
696 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
698 assert(RC->contains(PReg) && "Not the correct regclass!");
699 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
700 MF.getRegInfo().addLiveIn(PReg, VReg);
704 // Get fp branch code (not opcode) from condition code.
705 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
706 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
707 return Mips::BRANCH_T;
709 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
710 return Mips::BRANCH_F;
712 return Mips::BRANCH_INVALID;
716 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
718 const MipsSubtarget* Subtarget,
719 const TargetInstrInfo *TII,
720 bool isFPCmp, unsigned Opc) {
721 // There is no need to expand CMov instructions if target has
722 // conditional moves.
723 if (Subtarget->hasCondMov())
726 // To "insert" a SELECT_CC instruction, we actually have to insert the
727 // diamond control-flow pattern. The incoming instruction knows the
728 // destination vreg to set, the condition code register to branch on, the
729 // true/false values to select between, and a branch opcode to use.
730 const BasicBlock *LLVM_BB = BB->getBasicBlock();
731 MachineFunction::iterator It = BB;
738 // bNE r1, r0, copy1MBB
739 // fallthrough --> copy0MBB
740 MachineBasicBlock *thisMBB = BB;
741 MachineFunction *F = BB->getParent();
742 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
743 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
744 F->insert(It, copy0MBB);
745 F->insert(It, sinkMBB);
747 // Transfer the remainder of BB and its successor edges to sinkMBB.
748 sinkMBB->splice(sinkMBB->begin(), BB,
749 llvm::next(MachineBasicBlock::iterator(MI)),
751 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
753 // Next, add the true and fallthrough blocks as its successors.
754 BB->addSuccessor(copy0MBB);
755 BB->addSuccessor(sinkMBB);
757 // Emit the right instruction according to the type of the operands compared
759 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
761 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
762 .addReg(Mips::ZERO).addMBB(sinkMBB);
766 // # fallthrough to sinkMBB
769 // Update machine-CFG edges
770 BB->addSuccessor(sinkMBB);
773 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
778 BuildMI(*BB, BB->begin(), dl,
779 TII->get(Mips::PHI), MI->getOperand(0).getReg())
780 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
781 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
783 BuildMI(*BB, BB->begin(), dl,
784 TII->get(Mips::PHI), MI->getOperand(0).getReg())
785 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
786 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
788 MI->eraseFromParent(); // The pseudo instruction is gone now.
793 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
794 MachineBasicBlock *BB) const {
795 switch (MI->getOpcode()) {
797 assert(false && "Unexpected instr type to insert");
799 case Mips::ATOMIC_LOAD_ADD_I8:
800 case Mips::ATOMIC_LOAD_ADD_I8_P8:
801 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
802 case Mips::ATOMIC_LOAD_ADD_I16:
803 case Mips::ATOMIC_LOAD_ADD_I16_P8:
804 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
805 case Mips::ATOMIC_LOAD_ADD_I32:
806 case Mips::ATOMIC_LOAD_ADD_I32_P8:
807 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
808 case Mips::ATOMIC_LOAD_ADD_I64:
809 case Mips::ATOMIC_LOAD_ADD_I64_P8:
810 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
812 case Mips::ATOMIC_LOAD_AND_I8:
813 case Mips::ATOMIC_LOAD_AND_I8_P8:
814 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
815 case Mips::ATOMIC_LOAD_AND_I16:
816 case Mips::ATOMIC_LOAD_AND_I16_P8:
817 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
818 case Mips::ATOMIC_LOAD_AND_I32:
819 case Mips::ATOMIC_LOAD_AND_I32_P8:
820 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
821 case Mips::ATOMIC_LOAD_AND_I64:
822 case Mips::ATOMIC_LOAD_AND_I64_P8:
823 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
825 case Mips::ATOMIC_LOAD_OR_I8:
826 case Mips::ATOMIC_LOAD_OR_I8_P8:
827 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
828 case Mips::ATOMIC_LOAD_OR_I16:
829 case Mips::ATOMIC_LOAD_OR_I16_P8:
830 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
831 case Mips::ATOMIC_LOAD_OR_I32:
832 case Mips::ATOMIC_LOAD_OR_I32_P8:
833 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
834 case Mips::ATOMIC_LOAD_OR_I64:
835 case Mips::ATOMIC_LOAD_OR_I64_P8:
836 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
838 case Mips::ATOMIC_LOAD_XOR_I8:
839 case Mips::ATOMIC_LOAD_XOR_I8_P8:
840 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
841 case Mips::ATOMIC_LOAD_XOR_I16:
842 case Mips::ATOMIC_LOAD_XOR_I16_P8:
843 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
844 case Mips::ATOMIC_LOAD_XOR_I32:
845 case Mips::ATOMIC_LOAD_XOR_I32_P8:
846 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
847 case Mips::ATOMIC_LOAD_XOR_I64:
848 case Mips::ATOMIC_LOAD_XOR_I64_P8:
849 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
851 case Mips::ATOMIC_LOAD_NAND_I8:
852 case Mips::ATOMIC_LOAD_NAND_I8_P8:
853 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
854 case Mips::ATOMIC_LOAD_NAND_I16:
855 case Mips::ATOMIC_LOAD_NAND_I16_P8:
856 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
857 case Mips::ATOMIC_LOAD_NAND_I32:
858 case Mips::ATOMIC_LOAD_NAND_I32_P8:
859 return EmitAtomicBinary(MI, BB, 4, 0, true);
860 case Mips::ATOMIC_LOAD_NAND_I64:
861 case Mips::ATOMIC_LOAD_NAND_I64_P8:
862 return EmitAtomicBinary(MI, BB, 8, 0, true);
864 case Mips::ATOMIC_LOAD_SUB_I8:
865 case Mips::ATOMIC_LOAD_SUB_I8_P8:
866 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
867 case Mips::ATOMIC_LOAD_SUB_I16:
868 case Mips::ATOMIC_LOAD_SUB_I16_P8:
869 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
870 case Mips::ATOMIC_LOAD_SUB_I32:
871 case Mips::ATOMIC_LOAD_SUB_I32_P8:
872 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
873 case Mips::ATOMIC_LOAD_SUB_I64:
874 case Mips::ATOMIC_LOAD_SUB_I64_P8:
875 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
877 case Mips::ATOMIC_SWAP_I8:
878 case Mips::ATOMIC_SWAP_I8_P8:
879 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
880 case Mips::ATOMIC_SWAP_I16:
881 case Mips::ATOMIC_SWAP_I16_P8:
882 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
883 case Mips::ATOMIC_SWAP_I32:
884 case Mips::ATOMIC_SWAP_I32_P8:
885 return EmitAtomicBinary(MI, BB, 4, 0);
886 case Mips::ATOMIC_SWAP_I64:
887 case Mips::ATOMIC_SWAP_I64_P8:
888 return EmitAtomicBinary(MI, BB, 8, 0);
890 case Mips::ATOMIC_CMP_SWAP_I8:
891 case Mips::ATOMIC_CMP_SWAP_I8_P8:
892 return EmitAtomicCmpSwapPartword(MI, BB, 1);
893 case Mips::ATOMIC_CMP_SWAP_I16:
894 case Mips::ATOMIC_CMP_SWAP_I16_P8:
895 return EmitAtomicCmpSwapPartword(MI, BB, 2);
896 case Mips::ATOMIC_CMP_SWAP_I32:
897 case Mips::ATOMIC_CMP_SWAP_I32_P8:
898 return EmitAtomicCmpSwap(MI, BB, 4);
899 case Mips::ATOMIC_CMP_SWAP_I64:
900 case Mips::ATOMIC_CMP_SWAP_I64_P8:
901 return EmitAtomicCmpSwap(MI, BB, 8);
905 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
906 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
908 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
909 unsigned Size, unsigned BinOpcode,
911 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
913 MachineFunction *MF = BB->getParent();
914 MachineRegisterInfo &RegInfo = MF->getRegInfo();
915 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
916 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
917 DebugLoc dl = MI->getDebugLoc();
918 unsigned LL, SC, AND, NOR, ZERO, BEQ;
921 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
922 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
929 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
930 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
933 ZERO = Mips::ZERO_64;
937 unsigned OldVal = MI->getOperand(0).getReg();
938 unsigned Ptr = MI->getOperand(1).getReg();
939 unsigned Incr = MI->getOperand(2).getReg();
941 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
942 unsigned AndRes = RegInfo.createVirtualRegister(RC);
943 unsigned Success = RegInfo.createVirtualRegister(RC);
945 // insert new blocks after the current block
946 const BasicBlock *LLVM_BB = BB->getBasicBlock();
947 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
948 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
949 MachineFunction::iterator It = BB;
951 MF->insert(It, loopMBB);
952 MF->insert(It, exitMBB);
954 // Transfer the remainder of BB and its successor edges to exitMBB.
955 exitMBB->splice(exitMBB->begin(), BB,
956 llvm::next(MachineBasicBlock::iterator(MI)),
958 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
962 // fallthrough --> loopMBB
963 BB->addSuccessor(loopMBB);
964 loopMBB->addSuccessor(loopMBB);
965 loopMBB->addSuccessor(exitMBB);
969 // <binop> storeval, oldval, incr
970 // sc success, storeval, 0(ptr)
971 // beq success, $0, loopMBB
973 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
975 // and andres, oldval, incr
976 // nor storeval, $0, andres
977 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
978 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
979 } else if (BinOpcode) {
980 // <binop> storeval, oldval, incr
981 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
985 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
986 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
988 MI->eraseFromParent(); // The instruction is gone now.
994 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
995 MachineBasicBlock *BB,
996 unsigned Size, unsigned BinOpcode,
998 assert((Size == 1 || Size == 2) &&
999 "Unsupported size for EmitAtomicBinaryPartial.");
1001 MachineFunction *MF = BB->getParent();
1002 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1003 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1004 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1005 DebugLoc dl = MI->getDebugLoc();
1006 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1007 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1009 unsigned Dest = MI->getOperand(0).getReg();
1010 unsigned Ptr = MI->getOperand(1).getReg();
1011 unsigned Incr = MI->getOperand(2).getReg();
1013 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1014 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1015 unsigned Mask = RegInfo.createVirtualRegister(RC);
1016 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1017 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1018 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1019 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1020 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1021 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1022 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1023 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1024 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1025 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1026 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1027 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1028 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1029 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1030 unsigned Success = RegInfo.createVirtualRegister(RC);
1032 // insert new blocks after the current block
1033 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1034 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1035 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1036 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1037 MachineFunction::iterator It = BB;
1039 MF->insert(It, loopMBB);
1040 MF->insert(It, sinkMBB);
1041 MF->insert(It, exitMBB);
1043 // Transfer the remainder of BB and its successor edges to exitMBB.
1044 exitMBB->splice(exitMBB->begin(), BB,
1045 llvm::next(MachineBasicBlock::iterator(MI)),
1047 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1049 BB->addSuccessor(loopMBB);
1050 loopMBB->addSuccessor(loopMBB);
1051 loopMBB->addSuccessor(sinkMBB);
1052 sinkMBB->addSuccessor(exitMBB);
1055 // addiu masklsb2,$0,-4 # 0xfffffffc
1056 // and alignedaddr,ptr,masklsb2
1057 // andi ptrlsb2,ptr,3
1058 // sll shiftamt,ptrlsb2,3
1059 // ori maskupper,$0,255 # 0xff
1060 // sll mask,maskupper,shiftamt
1061 // nor mask2,$0,mask
1062 // sll incr2,incr,shiftamt
1064 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1065 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1066 .addReg(Mips::ZERO).addImm(-4);
1067 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1068 .addReg(Ptr).addReg(MaskLSB2);
1069 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1070 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1071 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1072 .addReg(Mips::ZERO).addImm(MaskImm);
1073 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1074 .addReg(ShiftAmt).addReg(MaskUpper);
1075 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1076 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1079 // atomic.load.binop
1081 // ll oldval,0(alignedaddr)
1082 // binop binopres,oldval,incr2
1083 // and newval,binopres,mask
1084 // and maskedoldval0,oldval,mask2
1085 // or storeval,maskedoldval0,newval
1086 // sc success,storeval,0(alignedaddr)
1087 // beq success,$0,loopMBB
1091 // ll oldval,0(alignedaddr)
1092 // and newval,incr2,mask
1093 // and maskedoldval0,oldval,mask2
1094 // or storeval,maskedoldval0,newval
1095 // sc success,storeval,0(alignedaddr)
1096 // beq success,$0,loopMBB
1099 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1101 // and andres, oldval, incr2
1102 // nor binopres, $0, andres
1103 // and newval, binopres, mask
1104 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1105 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1106 .addReg(Mips::ZERO).addReg(AndRes);
1107 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1108 } else if (BinOpcode) {
1109 // <binop> binopres, oldval, incr2
1110 // and newval, binopres, mask
1111 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1112 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1113 } else {// atomic.swap
1114 // and newval, incr2, mask
1115 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1118 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1119 .addReg(OldVal).addReg(Mask2);
1120 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1121 .addReg(MaskedOldVal0).addReg(NewVal);
1122 BuildMI(BB, dl, TII->get(SC), Success)
1123 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1124 BuildMI(BB, dl, TII->get(Mips::BEQ))
1125 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1128 // and maskedoldval1,oldval,mask
1129 // srl srlres,maskedoldval1,shiftamt
1130 // sll sllres,srlres,24
1131 // sra dest,sllres,24
1133 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1135 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1136 .addReg(OldVal).addReg(Mask);
1137 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1138 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1139 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1140 .addReg(SrlRes).addImm(ShiftImm);
1141 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1142 .addReg(SllRes).addImm(ShiftImm);
1144 MI->eraseFromParent(); // The instruction is gone now.
1150 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1151 MachineBasicBlock *BB,
1152 unsigned Size) const {
1153 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1155 MachineFunction *MF = BB->getParent();
1156 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1157 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1158 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1159 DebugLoc dl = MI->getDebugLoc();
1160 unsigned LL, SC, ZERO, BNE, BEQ;
1163 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1164 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1170 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1171 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1172 ZERO = Mips::ZERO_64;
1177 unsigned Dest = MI->getOperand(0).getReg();
1178 unsigned Ptr = MI->getOperand(1).getReg();
1179 unsigned OldVal = MI->getOperand(2).getReg();
1180 unsigned NewVal = MI->getOperand(3).getReg();
1182 unsigned Success = RegInfo.createVirtualRegister(RC);
1184 // insert new blocks after the current block
1185 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1186 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1187 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1188 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1189 MachineFunction::iterator It = BB;
1191 MF->insert(It, loop1MBB);
1192 MF->insert(It, loop2MBB);
1193 MF->insert(It, exitMBB);
1195 // Transfer the remainder of BB and its successor edges to exitMBB.
1196 exitMBB->splice(exitMBB->begin(), BB,
1197 llvm::next(MachineBasicBlock::iterator(MI)),
1199 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1203 // fallthrough --> loop1MBB
1204 BB->addSuccessor(loop1MBB);
1205 loop1MBB->addSuccessor(exitMBB);
1206 loop1MBB->addSuccessor(loop2MBB);
1207 loop2MBB->addSuccessor(loop1MBB);
1208 loop2MBB->addSuccessor(exitMBB);
1212 // bne dest, oldval, exitMBB
1214 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1215 BuildMI(BB, dl, TII->get(BNE))
1216 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1219 // sc success, newval, 0(ptr)
1220 // beq success, $0, loop1MBB
1222 BuildMI(BB, dl, TII->get(SC), Success)
1223 .addReg(NewVal).addReg(Ptr).addImm(0);
1224 BuildMI(BB, dl, TII->get(BEQ))
1225 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1227 MI->eraseFromParent(); // The instruction is gone now.
1233 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1234 MachineBasicBlock *BB,
1235 unsigned Size) const {
1236 assert((Size == 1 || Size == 2) &&
1237 "Unsupported size for EmitAtomicCmpSwapPartial.");
1239 MachineFunction *MF = BB->getParent();
1240 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1241 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1242 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1243 DebugLoc dl = MI->getDebugLoc();
1244 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1245 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1247 unsigned Dest = MI->getOperand(0).getReg();
1248 unsigned Ptr = MI->getOperand(1).getReg();
1249 unsigned CmpVal = MI->getOperand(2).getReg();
1250 unsigned NewVal = MI->getOperand(3).getReg();
1252 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1253 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1254 unsigned Mask = RegInfo.createVirtualRegister(RC);
1255 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1256 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1257 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1258 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1259 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1260 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1261 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1262 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1263 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1264 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1265 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1266 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1267 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1268 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1269 unsigned Success = RegInfo.createVirtualRegister(RC);
1271 // insert new blocks after the current block
1272 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1273 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1274 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1275 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1276 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1277 MachineFunction::iterator It = BB;
1279 MF->insert(It, loop1MBB);
1280 MF->insert(It, loop2MBB);
1281 MF->insert(It, sinkMBB);
1282 MF->insert(It, exitMBB);
1284 // Transfer the remainder of BB and its successor edges to exitMBB.
1285 exitMBB->splice(exitMBB->begin(), BB,
1286 llvm::next(MachineBasicBlock::iterator(MI)),
1288 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1290 BB->addSuccessor(loop1MBB);
1291 loop1MBB->addSuccessor(sinkMBB);
1292 loop1MBB->addSuccessor(loop2MBB);
1293 loop2MBB->addSuccessor(loop1MBB);
1294 loop2MBB->addSuccessor(sinkMBB);
1295 sinkMBB->addSuccessor(exitMBB);
1297 // FIXME: computation of newval2 can be moved to loop2MBB.
1299 // addiu masklsb2,$0,-4 # 0xfffffffc
1300 // and alignedaddr,ptr,masklsb2
1301 // andi ptrlsb2,ptr,3
1302 // sll shiftamt,ptrlsb2,3
1303 // ori maskupper,$0,255 # 0xff
1304 // sll mask,maskupper,shiftamt
1305 // nor mask2,$0,mask
1306 // andi maskedcmpval,cmpval,255
1307 // sll shiftedcmpval,maskedcmpval,shiftamt
1308 // andi maskednewval,newval,255
1309 // sll shiftednewval,maskednewval,shiftamt
1310 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1311 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1312 .addReg(Mips::ZERO).addImm(-4);
1313 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1314 .addReg(Ptr).addReg(MaskLSB2);
1315 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1316 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1317 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1318 .addReg(Mips::ZERO).addImm(MaskImm);
1319 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1320 .addReg(ShiftAmt).addReg(MaskUpper);
1321 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1322 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1323 .addReg(CmpVal).addImm(MaskImm);
1324 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1325 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1326 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1327 .addReg(NewVal).addImm(MaskImm);
1328 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1329 .addReg(ShiftAmt).addReg(MaskedNewVal);
1332 // ll oldval,0(alginedaddr)
1333 // and maskedoldval0,oldval,mask
1334 // bne maskedoldval0,shiftedcmpval,sinkMBB
1336 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1337 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1338 .addReg(OldVal).addReg(Mask);
1339 BuildMI(BB, dl, TII->get(Mips::BNE))
1340 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1343 // and maskedoldval1,oldval,mask2
1344 // or storeval,maskedoldval1,shiftednewval
1345 // sc success,storeval,0(alignedaddr)
1346 // beq success,$0,loop1MBB
1348 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1349 .addReg(OldVal).addReg(Mask2);
1350 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1351 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1352 BuildMI(BB, dl, TII->get(SC), Success)
1353 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1354 BuildMI(BB, dl, TII->get(Mips::BEQ))
1355 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1358 // srl srlres,maskedoldval0,shiftamt
1359 // sll sllres,srlres,24
1360 // sra dest,sllres,24
1362 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1364 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1365 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1366 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1367 .addReg(SrlRes).addImm(ShiftImm);
1368 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1369 .addReg(SllRes).addImm(ShiftImm);
1371 MI->eraseFromParent(); // The instruction is gone now.
1376 //===----------------------------------------------------------------------===//
1377 // Misc Lower Operation implementation
1378 //===----------------------------------------------------------------------===//
1379 SDValue MipsTargetLowering::
1380 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1382 MachineFunction &MF = DAG.getMachineFunction();
1383 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1384 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1386 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1387 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1388 "Cannot lower if the alignment of the allocated space is larger than \
1389 that of the stack.");
1391 SDValue Chain = Op.getOperand(0);
1392 SDValue Size = Op.getOperand(1);
1393 DebugLoc dl = Op.getDebugLoc();
1395 // Get a reference from Mips stack pointer
1396 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1398 // Subtract the dynamic size from the actual stack size to
1399 // obtain the new stack size.
1400 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1402 // The Sub result contains the new stack start address, so it
1403 // must be placed in the stack pointer register.
1404 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1406 // This node always has two return values: a new stack pointer
1407 // value and a chain
1408 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1409 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1410 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1412 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1415 SDValue MipsTargetLowering::
1416 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1418 // The first operand is the chain, the second is the condition, the third is
1419 // the block to branch to if the condition is true.
1420 SDValue Chain = Op.getOperand(0);
1421 SDValue Dest = Op.getOperand(2);
1422 DebugLoc dl = Op.getDebugLoc();
1424 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1426 // Return if flag is not set by a floating point comparison.
1427 if (CondRes.getOpcode() != MipsISD::FPCmp)
1430 SDValue CCNode = CondRes.getOperand(2);
1432 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1433 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1435 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1439 SDValue MipsTargetLowering::
1440 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1442 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1444 // Return if flag is not set by a floating point comparison.
1445 if (Cond.getOpcode() != MipsISD::FPCmp)
1448 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1452 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1453 SelectionDAG &DAG) const {
1454 // FIXME there isn't actually debug info here
1455 DebugLoc dl = Op.getDebugLoc();
1456 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1458 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1459 SDVTList VTs = DAG.getVTList(MVT::i32);
1461 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1463 // %gp_rel relocation
1464 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1465 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1467 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1468 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1469 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1471 // %hi/%lo relocation
1472 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1474 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1476 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1477 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1478 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1481 EVT ValTy = Op.getValueType();
1482 bool HasGotOfst = (GV->hasInternalLinkage() ||
1483 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1484 unsigned GotFlag = IsN64 ?
1485 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1487 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1488 GA = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
1489 SDValue ResNode = DAG.getLoad(ValTy, dl,
1490 DAG.getEntryNode(), GA, MachinePointerInfo(),
1491 false, false, false, 0);
1492 // On functions and global targets not internal linked only
1493 // a load from got/GP is necessary for PIC to work.
1496 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1497 IsN64 ? MipsII::MO_GOT_OFST :
1499 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1500 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1503 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1504 SelectionDAG &DAG) const {
1505 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1506 // FIXME there isn't actually debug info here
1507 DebugLoc dl = Op.getDebugLoc();
1509 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1510 // %hi/%lo relocation
1511 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1513 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1515 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1516 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1517 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1520 SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1522 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1523 SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1525 SDValue Load = DAG.getLoad(MVT::i32, dl,
1526 DAG.getEntryNode(), BAGOTOffset,
1527 MachinePointerInfo(), false, false, false, 0);
1528 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1529 return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1532 SDValue MipsTargetLowering::
1533 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1535 // If the relocation model is PIC, use the General Dynamic TLS Model,
1536 // otherwise use the Initial Exec or Local Exec TLS Model.
1537 // TODO: implement Local Dynamic TLS model
1539 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1540 DebugLoc dl = GA->getDebugLoc();
1541 const GlobalValue *GV = GA->getGlobal();
1542 EVT PtrVT = getPointerTy();
1544 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1545 // General Dynamic TLS Model
1546 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1547 0, MipsII::MO_TLSGD);
1548 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1549 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1550 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1554 Entry.Node = Argument;
1555 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1556 Args.push_back(Entry);
1557 std::pair<SDValue, SDValue> CallResult =
1558 LowerCallTo(DAG.getEntryNode(),
1559 (Type *) Type::getInt32Ty(*DAG.getContext()),
1560 false, false, false, false, 0, CallingConv::C, false, true,
1561 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1564 return CallResult.first;
1568 if (GV->isDeclaration()) {
1569 // Initial Exec TLS Model
1570 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1571 MipsII::MO_GOTTPREL);
1572 Offset = DAG.getLoad(MVT::i32, dl,
1573 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1574 false, false, false, 0);
1576 // Local Exec TLS Model
1577 SDVTList VTs = DAG.getVTList(MVT::i32);
1578 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1579 MipsII::MO_TPREL_HI);
1580 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1581 MipsII::MO_TPREL_LO);
1582 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1583 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1584 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1587 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1588 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1591 SDValue MipsTargetLowering::
1592 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1596 // FIXME there isn't actually debug info here
1597 DebugLoc dl = Op.getDebugLoc();
1598 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1599 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1601 EVT PtrVT = Op.getValueType();
1602 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1604 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1607 SDValue Ops[] = { JTI };
1608 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1609 } else {// Emit Load from Global Pointer
1610 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1611 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1612 MachinePointerInfo(),
1613 false, false, false, 0);
1616 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1618 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1619 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1624 SDValue MipsTargetLowering::
1625 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1628 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1629 const Constant *C = N->getConstVal();
1630 // FIXME there isn't actually debug info here
1631 DebugLoc dl = Op.getDebugLoc();
1633 // gp_rel relocation
1634 // FIXME: we should reference the constant pool using small data sections,
1635 // but the asm printer currently doesn't support this feature without
1636 // hacking it. This feature should come soon so we can uncomment the
1638 //if (IsInSmallSection(C->getType())) {
1639 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1640 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1641 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1643 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1644 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1645 N->getOffset(), MipsII::MO_ABS_HI);
1646 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1647 N->getOffset(), MipsII::MO_ABS_LO);
1648 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1649 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1650 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1652 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1653 N->getOffset(), MipsII::MO_GOT);
1654 CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1655 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1656 CP, MachinePointerInfo::getConstantPool(),
1657 false, false, false, 0);
1658 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1659 N->getOffset(), MipsII::MO_ABS_LO);
1660 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1661 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1667 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1668 MachineFunction &MF = DAG.getMachineFunction();
1669 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1671 DebugLoc dl = Op.getDebugLoc();
1672 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1675 // vastart just stores the address of the VarArgsFrameIndex slot into the
1676 // memory location argument.
1677 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1678 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1679 MachinePointerInfo(SV),
1683 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1684 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1685 DebugLoc dl = Op.getDebugLoc();
1686 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1687 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1688 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1689 DAG.getConstant(0x7fffffff, MVT::i32));
1690 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1691 DAG.getConstant(0x80000000, MVT::i32));
1692 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1693 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1696 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1698 // Use ext/ins instructions if target architecture is Mips32r2.
1699 // Eliminate redundant mfc1 and mtc1 instructions.
1700 unsigned LoIdx = 0, HiIdx = 1;
1703 std::swap(LoIdx, HiIdx);
1705 DebugLoc dl = Op.getDebugLoc();
1706 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1708 DAG.getConstant(LoIdx, MVT::i32));
1709 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1710 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1711 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1712 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1713 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1714 DAG.getConstant(0x7fffffff, MVT::i32));
1715 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1716 DAG.getConstant(0x80000000, MVT::i32));
1717 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1720 std::swap(Word0, Word1);
1722 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1725 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1727 EVT Ty = Op.getValueType();
1729 assert(Ty == MVT::f32 || Ty == MVT::f64);
1732 return LowerFCOPYSIGN32(Op, DAG);
1734 return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1737 SDValue MipsTargetLowering::
1738 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1740 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1741 "Frame address can only be determined for current frame.");
1743 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1744 MFI->setFrameAddressIsTaken(true);
1745 EVT VT = Op.getValueType();
1746 DebugLoc dl = Op.getDebugLoc();
1747 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1748 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1752 // TODO: set SType according to the desired memory barrier behavior.
1753 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1754 SelectionDAG& DAG) const {
1756 DebugLoc dl = Op.getDebugLoc();
1757 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1758 DAG.getConstant(SType, MVT::i32));
1761 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1762 SelectionDAG& DAG) const {
1763 // FIXME: Need pseudo-fence for 'singlethread' fences
1764 // FIXME: Set SType for weaker fences where supported/appropriate.
1766 DebugLoc dl = Op.getDebugLoc();
1767 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1768 DAG.getConstant(SType, MVT::i32));
1771 //===----------------------------------------------------------------------===//
1772 // Calling Convention Implementation
1773 //===----------------------------------------------------------------------===//
1775 //===----------------------------------------------------------------------===//
1776 // TODO: Implement a generic logic using tblgen that can support this.
1777 // Mips O32 ABI rules:
1779 // i32 - Passed in A0, A1, A2, A3 and stack
1780 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1781 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1782 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1783 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1784 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1787 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1788 //===----------------------------------------------------------------------===//
1790 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1791 MVT LocVT, CCValAssign::LocInfo LocInfo,
1792 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1794 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1796 static const unsigned IntRegs[] = {
1797 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1799 static const unsigned F32Regs[] = {
1800 Mips::F12, Mips::F14
1802 static const unsigned F64Regs[] = {
1807 if (ArgFlags.isByVal()) {
1808 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1809 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1810 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1811 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1812 r < std::min(IntRegsSize, NextReg); ++r)
1813 State.AllocateReg(IntRegs[r]);
1817 // Promote i8 and i16
1818 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1820 if (ArgFlags.isSExt())
1821 LocInfo = CCValAssign::SExt;
1822 else if (ArgFlags.isZExt())
1823 LocInfo = CCValAssign::ZExt;
1825 LocInfo = CCValAssign::AExt;
1830 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1831 // is true: function is vararg, argument is 3rd or higher, there is previous
1832 // argument which is not f32 or f64.
1833 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1834 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1835 unsigned OrigAlign = ArgFlags.getOrigAlign();
1836 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1838 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1839 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1840 // If this is the first part of an i64 arg,
1841 // the allocated register must be either A0 or A2.
1842 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1843 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1845 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1846 // Allocate int register and shadow next int register. If first
1847 // available register is Mips::A1 or Mips::A3, shadow it too.
1848 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1849 if (Reg == Mips::A1 || Reg == Mips::A3)
1850 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1851 State.AllocateReg(IntRegs, IntRegsSize);
1853 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1854 // we are guaranteed to find an available float register
1855 if (ValVT == MVT::f32) {
1856 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1857 // Shadow int register
1858 State.AllocateReg(IntRegs, IntRegsSize);
1860 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1861 // Shadow int registers
1862 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1863 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1864 State.AllocateReg(IntRegs, IntRegsSize);
1865 State.AllocateReg(IntRegs, IntRegsSize);
1868 llvm_unreachable("Cannot handle this ValVT.");
1870 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1871 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1874 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1876 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1878 return false; // CC must always match
1881 static const unsigned Mips64IntRegs[8] =
1882 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1883 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1884 static const unsigned Mips64DPRegs[8] =
1885 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1886 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1888 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1889 CCValAssign::LocInfo LocInfo,
1890 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1891 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1892 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1893 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1895 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1897 // If byval is 16-byte aligned, the first arg register must be even.
1898 if ((Align == 16) && (FirstIdx % 2)) {
1899 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1903 // Mark the registers allocated.
1904 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1905 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1907 // Allocate space on caller's stack.
1908 unsigned Offset = State.AllocateStack(Size, Align);
1911 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1914 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1919 #include "MipsGenCallingConv.inc"
1922 AnalyzeMips64CallOperands(CCState CCInfo,
1923 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1924 unsigned NumOps = Outs.size();
1925 for (unsigned i = 0; i != NumOps; ++i) {
1926 MVT ArgVT = Outs[i].VT;
1927 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1930 if (Outs[i].IsFixed)
1931 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1933 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1937 dbgs() << "Call operand #" << i << " has unhandled type "
1938 << EVT(ArgVT).getEVTString();
1940 llvm_unreachable(0);
1945 //===----------------------------------------------------------------------===//
1946 // Call Calling Convention Implementation
1947 //===----------------------------------------------------------------------===//
1949 static const unsigned O32IntRegsSize = 4;
1951 static const unsigned O32IntRegs[] = {
1952 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1955 // Return next O32 integer argument register.
1956 static unsigned getNextIntArgReg(unsigned Reg) {
1957 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1958 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1961 // Write ByVal Arg to arg registers and stack.
1963 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1964 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1965 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1966 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1967 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1968 MVT PtrType, bool isLittle) {
1969 unsigned LocMemOffset = VA.getLocMemOffset();
1970 unsigned Offset = 0;
1971 uint32_t RemainingSize = Flags.getByValSize();
1972 unsigned ByValAlign = Flags.getByValAlign();
1974 // Copy the first 4 words of byval arg to registers A0 - A3.
1975 // FIXME: Use a stricter alignment if it enables better optimization in passes
1977 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1978 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1979 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1980 DAG.getConstant(Offset, MVT::i32));
1981 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1982 MachinePointerInfo(),
1983 false, false, false, std::min(ByValAlign,
1985 MemOpChains.push_back(LoadVal.getValue(1));
1986 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1987 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1990 if (RemainingSize == 0)
1993 // If there still is a register available for argument passing, write the
1994 // remaining part of the structure to it using subword loads and shifts.
1995 if (LocMemOffset < 4 * 4) {
1996 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
1997 "There must be one to three bytes remaining.");
1998 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
1999 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2000 DAG.getConstant(Offset, MVT::i32));
2001 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2002 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2003 LoadPtr, MachinePointerInfo(),
2004 MVT::getIntegerVT(LoadSize * 8), false,
2006 MemOpChains.push_back(LoadVal.getValue(1));
2008 // If target is big endian, shift it to the most significant half-word or
2011 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2012 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2015 RemainingSize -= LoadSize;
2017 // Read second subword if necessary.
2018 if (RemainingSize != 0) {
2019 assert(RemainingSize == 1 && "There must be one byte remaining.");
2020 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2021 DAG.getConstant(Offset, MVT::i32));
2022 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2023 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2024 LoadPtr, MachinePointerInfo(),
2025 MVT::i8, false, false, Alignment);
2026 MemOpChains.push_back(Subword.getValue(1));
2027 // Insert the loaded byte to LoadVal.
2028 // FIXME: Use INS if supported by target.
2029 unsigned ShiftAmt = isLittle ? 16 : 8;
2030 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2031 DAG.getConstant(ShiftAmt, MVT::i32));
2032 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2035 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2036 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2040 // Create a fixed object on stack at offset LocMemOffset and copy
2041 // remaining part of byval arg to it using memcpy.
2042 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2043 DAG.getConstant(Offset, MVT::i32));
2044 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2045 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2046 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2047 DAG.getConstant(RemainingSize, MVT::i32),
2048 std::min(ByValAlign, (unsigned)4),
2049 /*isVolatile=*/false, /*AlwaysInline=*/false,
2050 MachinePointerInfo(0), MachinePointerInfo(0));
2053 // Copy Mips64 byVal arg to registers and stack.
2055 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2056 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2057 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2058 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2059 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2060 EVT PtrTy, bool isLittle) {
2061 unsigned ByValSize = Flags.getByValSize();
2062 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2063 bool IsRegLoc = VA.isRegLoc();
2064 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2065 unsigned LocMemOffset = 0;
2068 LocMemOffset = VA.getLocMemOffset();
2070 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2072 const unsigned *RegEnd = Mips64IntRegs + 8;
2074 // Copy double words to registers.
2075 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2076 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2077 DAG.getConstant(Offset, PtrTy));
2078 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2079 MachinePointerInfo(), false, false, false,
2081 MemOpChains.push_back(LoadVal.getValue(1));
2082 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2085 // If there is an argument register available, copy the remainder of the
2086 // byval argument with sub-doubleword loads and shifts.
2087 if ((Reg != RegEnd) && (ByValSize != Offset)) {
2088 assert((ByValSize < Offset + 8) &&
2089 "Size of the remainder should be smaller than 8-byte.");
2091 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2092 unsigned RemSize = ByValSize - Offset;
2094 if (RemSize < LoadSize)
2097 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2098 DAG.getConstant(Offset, PtrTy));
2100 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2101 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2102 false, false, Alignment);
2103 MemOpChains.push_back(LoadVal.getValue(1));
2105 // Offset in number of bits from double word boundary.
2106 unsigned OffsetDW = (Offset % 8) * 8;
2107 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2108 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2109 DAG.getConstant(Shamt, MVT::i32));
2111 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2114 Alignment = std::min(Alignment, LoadSize);
2117 RegsToPass.push_back(std::make_pair(*Reg, Val));
2122 unsigned MemCpySize = ByValSize - Offset;
2124 // Create a fixed object on stack at offset LocMemOffset and copy
2125 // remainder of byval arg to it with memcpy.
2126 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2127 DAG.getConstant(Offset, PtrTy));
2128 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2129 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2130 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2131 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2132 /*isVolatile=*/false, /*AlwaysInline=*/false,
2133 MachinePointerInfo(0), MachinePointerInfo(0));
2137 /// LowerCall - functions arguments are copied from virtual regs to
2138 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2139 /// TODO: isTailCall.
2141 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2142 CallingConv::ID CallConv, bool isVarArg,
2144 const SmallVectorImpl<ISD::OutputArg> &Outs,
2145 const SmallVectorImpl<SDValue> &OutVals,
2146 const SmallVectorImpl<ISD::InputArg> &Ins,
2147 DebugLoc dl, SelectionDAG &DAG,
2148 SmallVectorImpl<SDValue> &InVals) const {
2149 // MIPs target does not yet support tail call optimization.
2152 MachineFunction &MF = DAG.getMachineFunction();
2153 MachineFrameInfo *MFI = MF.getFrameInfo();
2154 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2155 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2156 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2158 // Analyze operands of the call, assigning locations to each operand.
2159 SmallVector<CCValAssign, 16> ArgLocs;
2160 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2161 getTargetMachine(), ArgLocs, *DAG.getContext());
2164 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2166 AnalyzeMips64CallOperands(CCInfo, Outs);
2168 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2170 // Get a count of how many bytes are to be pushed on the stack.
2171 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2173 // Chain is the output chain of the last Load/Store or CopyToReg node.
2174 // ByValChain is the output chain of the last Memcpy node created for copying
2175 // byval arguments to the stack.
2176 SDValue Chain, CallSeqStart, ByValChain;
2177 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2178 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2179 ByValChain = InChain;
2181 // If this is the first call, create a stack frame object that points to
2182 // a location to which .cprestore saves $gp.
2183 if (IsO32 && IsPIC && !MipsFI->getGPFI())
2184 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2186 // Get the frame index of the stack frame object that points to the location
2187 // of dynamically allocated area on the stack.
2188 int DynAllocFI = MipsFI->getDynAllocFI();
2190 // Update size of the maximum argument space.
2191 // For O32, a minimum of four words (16 bytes) of argument space is
2194 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2196 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2198 if (MaxCallFrameSize < NextStackOffset) {
2199 MipsFI->setMaxCallFrameSize(NextStackOffset);
2201 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2202 // allocated stack space. These offsets must be aligned to a boundary
2203 // determined by the stack alignment of the ABI.
2204 unsigned StackAlignment = TFL->getStackAlignment();
2205 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2206 StackAlignment * StackAlignment;
2208 if (MipsFI->needGPSaveRestore())
2209 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2211 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2214 // With EABI is it possible to have 16 args on registers.
2215 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2216 SmallVector<SDValue, 8> MemOpChains;
2218 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2220 // Walk the register/memloc assignments, inserting copies/loads.
2221 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2222 SDValue Arg = OutVals[i];
2223 CCValAssign &VA = ArgLocs[i];
2224 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2225 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2228 if (Flags.isByVal()) {
2229 assert(Flags.getByValSize() &&
2230 "ByVal args of size 0 should have been ignored by front-end.");
2232 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2233 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2234 Subtarget->isLittle());
2236 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2237 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2238 Subtarget->isLittle());
2242 // Promote the value if needed.
2243 switch (VA.getLocInfo()) {
2244 default: llvm_unreachable("Unknown loc info!");
2245 case CCValAssign::Full:
2246 if (VA.isRegLoc()) {
2247 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2248 (ValVT == MVT::f64 && LocVT == MVT::i64))
2249 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2250 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2251 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2252 Arg, DAG.getConstant(0, MVT::i32));
2253 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2254 Arg, DAG.getConstant(1, MVT::i32));
2255 if (!Subtarget->isLittle())
2257 unsigned LocRegLo = VA.getLocReg();
2258 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2259 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2260 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2265 case CCValAssign::SExt:
2266 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2268 case CCValAssign::ZExt:
2269 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2271 case CCValAssign::AExt:
2272 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2276 // Arguments that can be passed on register must be kept at
2277 // RegsToPass vector
2278 if (VA.isRegLoc()) {
2279 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2283 // Register can't get to this point...
2284 assert(VA.isMemLoc());
2286 // Create the frame index object for this incoming parameter
2287 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2288 VA.getLocMemOffset(), true);
2289 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2291 // emit ISD::STORE whichs stores the
2292 // parameter value to a stack Location
2293 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2294 MachinePointerInfo(),
2298 // Extend range of indices of frame objects for outgoing arguments that were
2299 // created during this function call. Skip this step if no such objects were
2302 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2304 // If a memcpy has been created to copy a byval arg to a stack, replace the
2305 // chain input of CallSeqStart with ByValChain.
2306 if (InChain != ByValChain)
2307 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2308 NextStackOffsetVal);
2310 // Transform all store nodes into one single node because all store
2311 // nodes are independent of each other.
2312 if (!MemOpChains.empty())
2313 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2314 &MemOpChains[0], MemOpChains.size());
2316 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2317 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2318 // node so that legalize doesn't hack it.
2319 unsigned char OpFlag;
2320 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2321 bool LoadSymAddr = false;
2324 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2325 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2326 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2327 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2328 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2330 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2333 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2334 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2335 getPointerTy(), 0, OpFlag);
2340 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2341 if (IsN64 || (!IsO32 && IsPIC))
2342 OpFlag = MipsII::MO_GOT_DISP;
2343 else if (!IsPIC) // !N64 && static
2344 OpFlag = MipsII::MO_NO_FLAG;
2346 OpFlag = MipsII::MO_GOT_CALL;
2347 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2348 getPointerTy(), OpFlag);
2354 // Create nodes that load address of callee and copy it to T9
2357 // Load callee address
2358 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, getPointerTy(), Callee);
2359 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2360 Callee, MachinePointerInfo::getGOT(),
2361 false, false, false, 0);
2363 // Use GOT+LO if callee has internal linkage.
2364 if (CalleeLo.getNode()) {
2365 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2366 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2372 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2373 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2374 InFlag = Chain.getValue(1);
2375 Callee = DAG.getRegister(T9Reg, getPointerTy());
2378 // Build a sequence of copy-to-reg nodes chained together with token
2379 // chain and flag operands which copy the outgoing args into registers.
2380 // The InFlag in necessary since all emitted instructions must be
2382 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2383 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2384 RegsToPass[i].second, InFlag);
2385 InFlag = Chain.getValue(1);
2388 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2389 // = Chain, Callee, Reg#1, Reg#2, ...
2391 // Returns a chain & a flag for retval copy to use.
2392 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2393 SmallVector<SDValue, 8> Ops;
2394 Ops.push_back(Chain);
2395 Ops.push_back(Callee);
2397 // Add argument registers to the end of the list so that they are
2398 // known live into the call.
2399 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2400 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2401 RegsToPass[i].second.getValueType()));
2403 if (InFlag.getNode())
2404 Ops.push_back(InFlag);
2406 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2407 InFlag = Chain.getValue(1);
2409 // Create the CALLSEQ_END node.
2410 Chain = DAG.getCALLSEQ_END(Chain,
2411 DAG.getIntPtrConstant(NextStackOffset, true),
2412 DAG.getIntPtrConstant(0, true), InFlag);
2413 InFlag = Chain.getValue(1);
2415 // Handle result values, copying them out of physregs into vregs that we
2417 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2418 Ins, dl, DAG, InVals);
2421 /// LowerCallResult - Lower the result values of a call into the
2422 /// appropriate copies out of appropriate physical registers.
2424 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2425 CallingConv::ID CallConv, bool isVarArg,
2426 const SmallVectorImpl<ISD::InputArg> &Ins,
2427 DebugLoc dl, SelectionDAG &DAG,
2428 SmallVectorImpl<SDValue> &InVals) const {
2429 // Assign locations to each value returned by this call.
2430 SmallVector<CCValAssign, 16> RVLocs;
2431 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2432 getTargetMachine(), RVLocs, *DAG.getContext());
2434 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2436 // Copy all of the result registers out of their specified physreg.
2437 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2438 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2439 RVLocs[i].getValVT(), InFlag).getValue(1);
2440 InFlag = Chain.getValue(2);
2441 InVals.push_back(Chain.getValue(0));
2447 //===----------------------------------------------------------------------===//
2448 // Formal Arguments Calling Convention Implementation
2449 //===----------------------------------------------------------------------===//
2450 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2451 std::vector<SDValue>& OutChains,
2452 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2453 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2454 unsigned LocMem = VA.getLocMemOffset();
2455 unsigned FirstWord = LocMem / 4;
2457 // copy register A0 - A3 to frame object
2458 for (unsigned i = 0; i < NumWords; ++i) {
2459 unsigned CurWord = FirstWord + i;
2460 if (CurWord >= O32IntRegsSize)
2463 unsigned SrcReg = O32IntRegs[CurWord];
2464 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2465 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2466 DAG.getConstant(i * 4, MVT::i32));
2467 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2468 StorePtr, MachinePointerInfo(), false,
2470 OutChains.push_back(Store);
2474 // Create frame object on stack and copy registers used for byval passing to it.
2476 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2477 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2478 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2479 MachineFrameInfo *MFI, bool IsRegLoc,
2480 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2482 const unsigned *Reg = Mips64IntRegs + 8;
2483 int FOOffset; // Frame object offset from virtual frame pointer.
2486 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2487 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2490 FOOffset = VA.getLocMemOffset();
2492 // Create frame object.
2493 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2494 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2495 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2496 InVals.push_back(FIN);
2498 // Copy arg registers.
2499 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2501 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2502 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2503 DAG.getConstant(I * 8, PtrTy));
2504 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2505 StorePtr, MachinePointerInfo(), false,
2507 OutChains.push_back(Store);
2513 /// LowerFormalArguments - transform physical registers into virtual registers
2514 /// and generate load operations for arguments places on the stack.
2516 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2517 CallingConv::ID CallConv,
2519 const SmallVectorImpl<ISD::InputArg>
2521 DebugLoc dl, SelectionDAG &DAG,
2522 SmallVectorImpl<SDValue> &InVals)
2524 MachineFunction &MF = DAG.getMachineFunction();
2525 MachineFrameInfo *MFI = MF.getFrameInfo();
2526 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2528 MipsFI->setVarArgsFrameIndex(0);
2530 // Used with vargs to acumulate store chains.
2531 std::vector<SDValue> OutChains;
2533 // Assign locations to all of the incoming arguments.
2534 SmallVector<CCValAssign, 16> ArgLocs;
2535 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2536 getTargetMachine(), ArgLocs, *DAG.getContext());
2539 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2541 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2543 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2545 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2546 CCValAssign &VA = ArgLocs[i];
2547 EVT ValVT = VA.getValVT();
2548 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2549 bool IsRegLoc = VA.isRegLoc();
2551 if (Flags.isByVal()) {
2552 assert(Flags.getByValSize() &&
2553 "ByVal args of size 0 should have been ignored by front-end.");
2555 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2556 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2558 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2559 InVals.push_back(FIN);
2560 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2562 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2563 MFI, IsRegLoc, InVals, MipsFI,
2568 // Arguments stored on registers
2570 EVT RegVT = VA.getLocVT();
2571 unsigned ArgReg = VA.getLocReg();
2572 TargetRegisterClass *RC = 0;
2574 if (RegVT == MVT::i32)
2575 RC = Mips::CPURegsRegisterClass;
2576 else if (RegVT == MVT::i64)
2577 RC = Mips::CPU64RegsRegisterClass;
2578 else if (RegVT == MVT::f32)
2579 RC = Mips::FGR32RegisterClass;
2580 else if (RegVT == MVT::f64)
2581 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2583 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2585 // Transform the arguments stored on
2586 // physical registers into virtual ones
2587 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2588 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2590 // If this is an 8 or 16-bit value, it has been passed promoted
2591 // to 32 bits. Insert an assert[sz]ext to capture this, then
2592 // truncate to the right size.
2593 if (VA.getLocInfo() != CCValAssign::Full) {
2594 unsigned Opcode = 0;
2595 if (VA.getLocInfo() == CCValAssign::SExt)
2596 Opcode = ISD::AssertSext;
2597 else if (VA.getLocInfo() == CCValAssign::ZExt)
2598 Opcode = ISD::AssertZext;
2600 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2601 DAG.getValueType(ValVT));
2602 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2605 // Handle floating point arguments passed in integer registers.
2606 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2607 (RegVT == MVT::i64 && ValVT == MVT::f64))
2608 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2609 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2610 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2611 getNextIntArgReg(ArgReg), RC);
2612 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2613 if (!Subtarget->isLittle())
2614 std::swap(ArgValue, ArgValue2);
2615 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2616 ArgValue, ArgValue2);
2619 InVals.push_back(ArgValue);
2620 } else { // VA.isRegLoc()
2623 assert(VA.isMemLoc());
2625 // The stack pointer offset is relative to the caller stack frame.
2626 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2627 VA.getLocMemOffset(), true);
2629 // Create load nodes to retrieve arguments from the stack
2630 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2631 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2632 MachinePointerInfo::getFixedStack(LastFI),
2633 false, false, false, 0));
2637 // The mips ABIs for returning structs by value requires that we copy
2638 // the sret argument into $v0 for the return. Save the argument into
2639 // a virtual register so that we can access it from the return points.
2640 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2641 unsigned Reg = MipsFI->getSRetReturnReg();
2643 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2644 MipsFI->setSRetReturnReg(Reg);
2646 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2647 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2651 unsigned NumOfRegs = IsO32 ? 4 : 8;
2652 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2653 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2654 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2655 TargetRegisterClass *RC
2656 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2657 unsigned RegSize = RC->getSize();
2658 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2660 // Offset of the first variable argument from stack pointer.
2661 int FirstVaArgOffset;
2663 if (IsO32 || (Idx == NumOfRegs)) {
2665 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2667 FirstVaArgOffset = RegSlotOffset;
2669 // Record the frame index of the first variable argument
2670 // which is a value necessary to VASTART.
2671 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2672 MipsFI->setVarArgsFrameIndex(LastFI);
2674 // Copy the integer registers that have not been used for argument passing
2675 // to the argument register save area. For O32, the save area is allocated
2676 // in the caller's stack frame, while for N32/64, it is allocated in the
2677 // callee's stack frame.
2678 for (int StackOffset = RegSlotOffset;
2679 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2680 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2681 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2682 MVT::getIntegerVT(RegSize * 8));
2683 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2684 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2685 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2686 MachinePointerInfo(),
2691 MipsFI->setLastInArgFI(LastFI);
2693 // All stores are grouped in one node to allow the matching between
2694 // the size of Ins and InVals. This only happens when on varg functions
2695 if (!OutChains.empty()) {
2696 OutChains.push_back(Chain);
2697 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2698 &OutChains[0], OutChains.size());
2704 //===----------------------------------------------------------------------===//
2705 // Return Value Calling Convention Implementation
2706 //===----------------------------------------------------------------------===//
2709 MipsTargetLowering::LowerReturn(SDValue Chain,
2710 CallingConv::ID CallConv, bool isVarArg,
2711 const SmallVectorImpl<ISD::OutputArg> &Outs,
2712 const SmallVectorImpl<SDValue> &OutVals,
2713 DebugLoc dl, SelectionDAG &DAG) const {
2715 // CCValAssign - represent the assignment of
2716 // the return value to a location
2717 SmallVector<CCValAssign, 16> RVLocs;
2719 // CCState - Info about the registers and stack slot.
2720 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2721 getTargetMachine(), RVLocs, *DAG.getContext());
2723 // Analize return values.
2724 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2726 // If this is the first return lowered for this function, add
2727 // the regs to the liveout set for the function.
2728 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2729 for (unsigned i = 0; i != RVLocs.size(); ++i)
2730 if (RVLocs[i].isRegLoc())
2731 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2736 // Copy the result values into the output registers.
2737 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2738 CCValAssign &VA = RVLocs[i];
2739 assert(VA.isRegLoc() && "Can only return in registers!");
2741 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2744 // guarantee that all emitted copies are
2745 // stuck together, avoiding something bad
2746 Flag = Chain.getValue(1);
2749 // The mips ABIs for returning structs by value requires that we copy
2750 // the sret argument into $v0 for the return. We saved the argument into
2751 // a virtual register in the entry block, so now we copy the value out
2753 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2754 MachineFunction &MF = DAG.getMachineFunction();
2755 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2756 unsigned Reg = MipsFI->getSRetReturnReg();
2759 llvm_unreachable("sret virtual register not created in the entry block");
2760 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2762 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2763 Flag = Chain.getValue(1);
2766 // Return on Mips is always a "jr $ra"
2768 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2769 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2771 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2772 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2775 //===----------------------------------------------------------------------===//
2776 // Mips Inline Assembly Support
2777 //===----------------------------------------------------------------------===//
2779 /// getConstraintType - Given a constraint letter, return the type of
2780 /// constraint it is for this target.
2781 MipsTargetLowering::ConstraintType MipsTargetLowering::
2782 getConstraintType(const std::string &Constraint) const
2784 // Mips specific constrainy
2785 // GCC config/mips/constraints.md
2787 // 'd' : An address register. Equivalent to r
2788 // unless generating MIPS16 code.
2789 // 'y' : Equivalent to r; retained for
2790 // backwards compatibility.
2791 // 'f' : Floating Point registers.
2792 if (Constraint.size() == 1) {
2793 switch (Constraint[0]) {
2798 return C_RegisterClass;
2802 return TargetLowering::getConstraintType(Constraint);
2805 /// Examine constraint type and operand type and determine a weight value.
2806 /// This object must already have been set up with the operand type
2807 /// and the current alternative constraint selected.
2808 TargetLowering::ConstraintWeight
2809 MipsTargetLowering::getSingleConstraintMatchWeight(
2810 AsmOperandInfo &info, const char *constraint) const {
2811 ConstraintWeight weight = CW_Invalid;
2812 Value *CallOperandVal = info.CallOperandVal;
2813 // If we don't have a value, we can't do a match,
2814 // but allow it at the lowest weight.
2815 if (CallOperandVal == NULL)
2817 Type *type = CallOperandVal->getType();
2818 // Look at the constraint type.
2819 switch (*constraint) {
2821 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2825 if (type->isIntegerTy())
2826 weight = CW_Register;
2829 if (type->isFloatTy())
2830 weight = CW_Register;
2836 /// Given a register class constraint, like 'r', if this corresponds directly
2837 /// to an LLVM register class, return a register of 0 and the register class
2839 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2840 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2842 if (Constraint.size() == 1) {
2843 switch (Constraint[0]) {
2844 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2845 case 'y': // Same as 'r'. Exists for compatibility.
2847 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2850 return std::make_pair(0U, Mips::FGR32RegisterClass);
2852 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2853 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2857 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2861 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2862 // The Mips target isn't yet aware of offsets.
2866 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2867 if (VT != MVT::f32 && VT != MVT::f64)
2869 if (Imm.isNegZero())
2871 return Imm.isZero();