1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Function.h"
23 #include "llvm/GlobalVariable.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/CallingConv.h"
26 #include "InstPrinter/MipsInstPrinter.h"
27 #include "MCTargetDesc/MipsBaseInfo.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
39 // If I is a shifted mask, set the size (Size) and the first bit of the
40 // mask (Pos), and return true.
41 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
42 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
43 if (!isUInt<32>(I) || !isShiftedMask_32(I))
46 Size = CountPopulation_32(I);
47 Pos = CountTrailingZeros_32(I);
51 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
53 case MipsISD::JmpLink: return "MipsISD::JmpLink";
54 case MipsISD::Hi: return "MipsISD::Hi";
55 case MipsISD::Lo: return "MipsISD::Lo";
56 case MipsISD::GPRel: return "MipsISD::GPRel";
57 case MipsISD::TlsGd: return "MipsISD::TlsGd";
58 case MipsISD::TprelHi: return "MipsISD::TprelHi";
59 case MipsISD::TprelLo: return "MipsISD::TprelLo";
60 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
61 case MipsISD::Ret: return "MipsISD::Ret";
62 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
63 case MipsISD::FPCmp: return "MipsISD::FPCmp";
64 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
65 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
66 case MipsISD::FPRound: return "MipsISD::FPRound";
67 case MipsISD::MAdd: return "MipsISD::MAdd";
68 case MipsISD::MAddu: return "MipsISD::MAddu";
69 case MipsISD::MSub: return "MipsISD::MSub";
70 case MipsISD::MSubu: return "MipsISD::MSubu";
71 case MipsISD::DivRem: return "MipsISD::DivRem";
72 case MipsISD::DivRemU: return "MipsISD::DivRemU";
73 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
74 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
75 case MipsISD::WrapperPIC: return "MipsISD::WrapperPIC";
76 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
77 case MipsISD::Sync: return "MipsISD::Sync";
78 case MipsISD::Ext: return "MipsISD::Ext";
79 case MipsISD::Ins: return "MipsISD::Ins";
85 MipsTargetLowering(MipsTargetMachine &TM)
86 : TargetLowering(TM, new MipsTargetObjectFile()),
87 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
88 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
89 IsO32(Subtarget->isABI_O32()) {
91 // Mips does not have i1 type, so use i32 for
92 // setcc operations results (slt, sgt, ...).
93 setBooleanContents(ZeroOrOneBooleanContent);
94 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
96 // Set up the register classes
97 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
98 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
101 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
103 // When dealing with single precision only, use libcalls
104 if (!Subtarget->isSingleFloat()) {
106 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
108 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
111 // Load extented operations for i1 types must be promoted
112 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
113 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
114 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
116 // MIPS doesn't have extending float->double load/store
117 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
118 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
120 // Used by legalize types to correctly generate the setcc result.
121 // Without this, every float setcc comes with a AND/OR with the result,
122 // we don't want this, since the fpcmp result goes to a flag register,
123 // which is used implicitly by brcond and select operations.
124 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
126 // Mips Custom Operations
127 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
128 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
129 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
130 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
131 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
132 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
133 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
134 setOperationAction(ISD::SELECT, MVT::f32, Custom);
135 setOperationAction(ISD::SELECT, MVT::f64, Custom);
136 setOperationAction(ISD::SELECT, MVT::i32, Custom);
137 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
138 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
139 setOperationAction(ISD::VASTART, MVT::Other, Custom);
141 setOperationAction(ISD::SDIV, MVT::i32, Expand);
142 setOperationAction(ISD::SREM, MVT::i32, Expand);
143 setOperationAction(ISD::UDIV, MVT::i32, Expand);
144 setOperationAction(ISD::UREM, MVT::i32, Expand);
145 setOperationAction(ISD::SDIV, MVT::i64, Expand);
146 setOperationAction(ISD::SREM, MVT::i64, Expand);
147 setOperationAction(ISD::UDIV, MVT::i64, Expand);
148 setOperationAction(ISD::UREM, MVT::i64, Expand);
150 // Operations not directly supported by Mips.
151 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
152 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
153 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
154 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
155 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
156 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
157 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
158 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
159 setOperationAction(ISD::ROTL, MVT::i32, Expand);
160 setOperationAction(ISD::ROTL, MVT::i64, Expand);
162 if (!Subtarget->hasMips32r2())
163 setOperationAction(ISD::ROTR, MVT::i32, Expand);
165 if (!Subtarget->hasMips64r2())
166 setOperationAction(ISD::ROTR, MVT::i64, Expand);
168 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
169 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
170 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
171 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
172 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
173 setOperationAction(ISD::FSIN, MVT::f32, Expand);
174 setOperationAction(ISD::FSIN, MVT::f64, Expand);
175 setOperationAction(ISD::FCOS, MVT::f32, Expand);
176 setOperationAction(ISD::FCOS, MVT::f64, Expand);
177 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
178 setOperationAction(ISD::FPOW, MVT::f32, Expand);
179 setOperationAction(ISD::FPOW, MVT::f64, Expand);
180 setOperationAction(ISD::FLOG, MVT::f32, Expand);
181 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
182 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
183 setOperationAction(ISD::FEXP, MVT::f32, Expand);
184 setOperationAction(ISD::FMA, MVT::f32, Expand);
185 setOperationAction(ISD::FMA, MVT::f64, Expand);
187 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
188 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
190 setOperationAction(ISD::VAARG, MVT::Other, Expand);
191 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
192 setOperationAction(ISD::VAEND, MVT::Other, Expand);
194 // Use the default for now
195 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
196 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
198 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
199 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
201 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
202 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
204 setInsertFencesForAtomic(true);
206 if (Subtarget->isSingleFloat())
207 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
209 if (!Subtarget->hasSEInReg()) {
210 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
211 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
214 if (!Subtarget->hasBitCount())
215 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
217 if (!Subtarget->hasSwap())
218 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
220 setTargetDAGCombine(ISD::ADDE);
221 setTargetDAGCombine(ISD::SUBE);
222 setTargetDAGCombine(ISD::SDIVREM);
223 setTargetDAGCombine(ISD::UDIVREM);
224 setTargetDAGCombine(ISD::SETCC);
225 setTargetDAGCombine(ISD::AND);
226 setTargetDAGCombine(ISD::OR);
228 setMinFunctionAlignment(2);
230 setStackPointerRegisterToSaveRestore(Mips::SP);
231 computeRegisterProperties();
233 setExceptionPointerRegister(Mips::A0);
234 setExceptionSelectorRegister(Mips::A1);
237 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
238 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
239 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
242 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
247 // Transforms a subgraph in CurDAG if the following pattern is found:
248 // (addc multLo, Lo0), (adde multHi, Hi0),
250 // multHi/Lo: product of multiplication
251 // Lo0: initial value of Lo register
252 // Hi0: initial value of Hi register
253 // Return true if pattern matching was successful.
254 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
255 // ADDENode's second operand must be a flag output of an ADDC node in order
256 // for the matching to be successful.
257 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
259 if (ADDCNode->getOpcode() != ISD::ADDC)
262 SDValue MultHi = ADDENode->getOperand(0);
263 SDValue MultLo = ADDCNode->getOperand(0);
264 SDNode* MultNode = MultHi.getNode();
265 unsigned MultOpc = MultHi.getOpcode();
267 // MultHi and MultLo must be generated by the same node,
268 if (MultLo.getNode() != MultNode)
271 // and it must be a multiplication.
272 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
275 // MultLo amd MultHi must be the first and second output of MultNode
277 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
280 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
281 // of the values of MultNode, in which case MultNode will be removed in later
283 // If there exist users other than ADDENode or ADDCNode, this function returns
284 // here, which will result in MultNode being mapped to a single MULT
285 // instruction node rather than a pair of MULT and MADD instructions being
287 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
290 SDValue Chain = CurDAG->getEntryNode();
291 DebugLoc dl = ADDENode->getDebugLoc();
293 // create MipsMAdd(u) node
294 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
296 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
298 MultNode->getOperand(0),// Factor 0
299 MultNode->getOperand(1),// Factor 1
300 ADDCNode->getOperand(1),// Lo0
301 ADDENode->getOperand(1));// Hi0
303 // create CopyFromReg nodes
304 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
306 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
308 CopyFromLo.getValue(2));
310 // replace uses of adde and addc here
311 if (!SDValue(ADDCNode, 0).use_empty())
312 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
314 if (!SDValue(ADDENode, 0).use_empty())
315 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
321 // Transforms a subgraph in CurDAG if the following pattern is found:
322 // (addc Lo0, multLo), (sube Hi0, multHi),
324 // multHi/Lo: product of multiplication
325 // Lo0: initial value of Lo register
326 // Hi0: initial value of Hi register
327 // Return true if pattern matching was successful.
328 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
329 // SUBENode's second operand must be a flag output of an SUBC node in order
330 // for the matching to be successful.
331 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
333 if (SUBCNode->getOpcode() != ISD::SUBC)
336 SDValue MultHi = SUBENode->getOperand(1);
337 SDValue MultLo = SUBCNode->getOperand(1);
338 SDNode* MultNode = MultHi.getNode();
339 unsigned MultOpc = MultHi.getOpcode();
341 // MultHi and MultLo must be generated by the same node,
342 if (MultLo.getNode() != MultNode)
345 // and it must be a multiplication.
346 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
349 // MultLo amd MultHi must be the first and second output of MultNode
351 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
354 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
355 // of the values of MultNode, in which case MultNode will be removed in later
357 // If there exist users other than SUBENode or SUBCNode, this function returns
358 // here, which will result in MultNode being mapped to a single MULT
359 // instruction node rather than a pair of MULT and MSUB instructions being
361 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
364 SDValue Chain = CurDAG->getEntryNode();
365 DebugLoc dl = SUBENode->getDebugLoc();
367 // create MipsSub(u) node
368 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
370 SDValue MSub = CurDAG->getNode(MultOpc, dl,
372 MultNode->getOperand(0),// Factor 0
373 MultNode->getOperand(1),// Factor 1
374 SUBCNode->getOperand(0),// Lo0
375 SUBENode->getOperand(0));// Hi0
377 // create CopyFromReg nodes
378 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
380 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
382 CopyFromLo.getValue(2));
384 // replace uses of sube and subc here
385 if (!SDValue(SUBCNode, 0).use_empty())
386 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
388 if (!SDValue(SUBENode, 0).use_empty())
389 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
394 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
395 TargetLowering::DAGCombinerInfo &DCI,
396 const MipsSubtarget* Subtarget) {
397 if (DCI.isBeforeLegalize())
400 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
402 return SDValue(N, 0);
407 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
408 TargetLowering::DAGCombinerInfo &DCI,
409 const MipsSubtarget* Subtarget) {
410 if (DCI.isBeforeLegalize())
413 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
415 return SDValue(N, 0);
420 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
421 TargetLowering::DAGCombinerInfo &DCI,
422 const MipsSubtarget* Subtarget) {
423 if (DCI.isBeforeLegalizeOps())
426 EVT Ty = N->getValueType(0);
427 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
428 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
429 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
431 DebugLoc dl = N->getDebugLoc();
433 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
434 N->getOperand(0), N->getOperand(1));
435 SDValue InChain = DAG.getEntryNode();
436 SDValue InGlue = DivRem;
439 if (N->hasAnyUseOfValue(0)) {
440 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
442 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
443 InChain = CopyFromLo.getValue(1);
444 InGlue = CopyFromLo.getValue(2);
448 if (N->hasAnyUseOfValue(1)) {
449 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
451 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
457 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
459 default: llvm_unreachable("Unknown fp condition code!");
461 case ISD::SETOEQ: return Mips::FCOND_OEQ;
462 case ISD::SETUNE: return Mips::FCOND_UNE;
464 case ISD::SETOLT: return Mips::FCOND_OLT;
466 case ISD::SETOGT: return Mips::FCOND_OGT;
468 case ISD::SETOLE: return Mips::FCOND_OLE;
470 case ISD::SETOGE: return Mips::FCOND_OGE;
471 case ISD::SETULT: return Mips::FCOND_ULT;
472 case ISD::SETULE: return Mips::FCOND_ULE;
473 case ISD::SETUGT: return Mips::FCOND_UGT;
474 case ISD::SETUGE: return Mips::FCOND_UGE;
475 case ISD::SETUO: return Mips::FCOND_UN;
476 case ISD::SETO: return Mips::FCOND_OR;
478 case ISD::SETONE: return Mips::FCOND_ONE;
479 case ISD::SETUEQ: return Mips::FCOND_UEQ;
484 // Returns true if condition code has to be inverted.
485 static bool InvertFPCondCode(Mips::CondCode CC) {
486 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
489 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
492 assert(false && "Illegal Condition Code");
496 // Creates and returns an FPCmp node from a setcc node.
497 // Returns Op if setcc is not a floating point comparison.
498 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
499 // must be a SETCC node
500 if (Op.getOpcode() != ISD::SETCC)
503 SDValue LHS = Op.getOperand(0);
505 if (!LHS.getValueType().isFloatingPoint())
508 SDValue RHS = Op.getOperand(1);
509 DebugLoc dl = Op.getDebugLoc();
511 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
512 // node if necessary.
513 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
515 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
516 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
519 // Creates and returns a CMovFPT/F node.
520 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
521 SDValue False, DebugLoc DL) {
522 bool invert = InvertFPCondCode((Mips::CondCode)
523 cast<ConstantSDNode>(Cond.getOperand(2))
526 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
527 True.getValueType(), True, False, Cond);
530 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
531 TargetLowering::DAGCombinerInfo &DCI,
532 const MipsSubtarget* Subtarget) {
533 if (DCI.isBeforeLegalizeOps())
536 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
538 if (Cond.getOpcode() != MipsISD::FPCmp)
541 SDValue True = DAG.getConstant(1, MVT::i32);
542 SDValue False = DAG.getConstant(0, MVT::i32);
544 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
547 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
548 TargetLowering::DAGCombinerInfo &DCI,
549 const MipsSubtarget* Subtarget) {
550 // Pattern match EXT.
551 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
552 // => ext $dst, $src, size, pos
553 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
556 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
558 // Op's first operand must be a shift right.
559 if (ShiftRight.getOpcode() != ISD::SRA && ShiftRight.getOpcode() != ISD::SRL)
562 // The second operand of the shift must be an immediate.
565 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
568 Pos = CN->getZExtValue();
570 uint64_t SMPos, SMSize;
571 // Op's second operand must be a shifted mask.
572 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
573 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
576 // Return if the shifted mask does not start at bit 0 or the sum of its size
577 // and Pos exceeds the word's size.
578 if (SMPos != 0 || Pos + SMSize > 32)
581 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
582 ShiftRight.getOperand(0),
583 DAG.getConstant(Pos, MVT::i32),
584 DAG.getConstant(SMSize, MVT::i32));
587 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
588 TargetLowering::DAGCombinerInfo &DCI,
589 const MipsSubtarget* Subtarget) {
590 // Pattern match INS.
591 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
592 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
593 // => ins $dst, $src, size, pos, $src1
594 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
597 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
598 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
601 // See if Op's first operand matches (and $src1 , mask0).
602 if (And0.getOpcode() != ISD::AND)
605 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
606 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
609 // See if Op's second operand matches (and (shl $src, pos), mask1).
610 if (And1.getOpcode() != ISD::AND)
613 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
614 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
617 // The shift masks must have the same position and size.
618 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
621 SDValue Shl = And1.getOperand(0);
622 if (Shl.getOpcode() != ISD::SHL)
625 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
628 unsigned Shamt = CN->getZExtValue();
630 // Return if the shift amount and the first bit position of mask are not the
635 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
637 DAG.getConstant(SMPos0, MVT::i32),
638 DAG.getConstant(SMSize0, MVT::i32),
642 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
644 SelectionDAG &DAG = DCI.DAG;
645 unsigned opc = N->getOpcode();
650 return PerformADDECombine(N, DAG, DCI, Subtarget);
652 return PerformSUBECombine(N, DAG, DCI, Subtarget);
655 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
657 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
659 return PerformANDCombine(N, DAG, DCI, Subtarget);
661 return PerformORCombine(N, DAG, DCI, Subtarget);
667 SDValue MipsTargetLowering::
668 LowerOperation(SDValue Op, SelectionDAG &DAG) const
670 switch (Op.getOpcode())
672 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
673 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
674 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
675 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
676 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
677 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
678 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
679 case ISD::SELECT: return LowerSELECT(Op, DAG);
680 case ISD::VASTART: return LowerVASTART(Op, DAG);
681 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
682 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
683 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
684 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
689 //===----------------------------------------------------------------------===//
690 // Lower helper functions
691 //===----------------------------------------------------------------------===//
693 // AddLiveIn - This helper function adds the specified physical register to the
694 // MachineFunction as a live in value. It also creates a corresponding
695 // virtual register for it.
697 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
699 assert(RC->contains(PReg) && "Not the correct regclass!");
700 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
701 MF.getRegInfo().addLiveIn(PReg, VReg);
705 // Get fp branch code (not opcode) from condition code.
706 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
707 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
708 return Mips::BRANCH_T;
710 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
711 return Mips::BRANCH_F;
713 return Mips::BRANCH_INVALID;
717 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
719 const MipsSubtarget* Subtarget,
720 const TargetInstrInfo *TII,
721 bool isFPCmp, unsigned Opc) {
722 // There is no need to expand CMov instructions if target has
723 // conditional moves.
724 if (Subtarget->hasCondMov())
727 // To "insert" a SELECT_CC instruction, we actually have to insert the
728 // diamond control-flow pattern. The incoming instruction knows the
729 // destination vreg to set, the condition code register to branch on, the
730 // true/false values to select between, and a branch opcode to use.
731 const BasicBlock *LLVM_BB = BB->getBasicBlock();
732 MachineFunction::iterator It = BB;
739 // bNE r1, r0, copy1MBB
740 // fallthrough --> copy0MBB
741 MachineBasicBlock *thisMBB = BB;
742 MachineFunction *F = BB->getParent();
743 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
744 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
745 F->insert(It, copy0MBB);
746 F->insert(It, sinkMBB);
748 // Transfer the remainder of BB and its successor edges to sinkMBB.
749 sinkMBB->splice(sinkMBB->begin(), BB,
750 llvm::next(MachineBasicBlock::iterator(MI)),
752 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
754 // Next, add the true and fallthrough blocks as its successors.
755 BB->addSuccessor(copy0MBB);
756 BB->addSuccessor(sinkMBB);
758 // Emit the right instruction according to the type of the operands compared
760 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
762 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
763 .addReg(Mips::ZERO).addMBB(sinkMBB);
767 // # fallthrough to sinkMBB
770 // Update machine-CFG edges
771 BB->addSuccessor(sinkMBB);
774 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
779 BuildMI(*BB, BB->begin(), dl,
780 TII->get(Mips::PHI), MI->getOperand(0).getReg())
781 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
782 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
784 BuildMI(*BB, BB->begin(), dl,
785 TII->get(Mips::PHI), MI->getOperand(0).getReg())
786 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
787 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
789 MI->eraseFromParent(); // The pseudo instruction is gone now.
794 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
795 MachineBasicBlock *BB) const {
796 switch (MI->getOpcode()) {
798 assert(false && "Unexpected instr type to insert");
800 case Mips::ATOMIC_LOAD_ADD_I8:
801 case Mips::ATOMIC_LOAD_ADD_I8_P8:
802 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
803 case Mips::ATOMIC_LOAD_ADD_I16:
804 case Mips::ATOMIC_LOAD_ADD_I16_P8:
805 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
806 case Mips::ATOMIC_LOAD_ADD_I32:
807 case Mips::ATOMIC_LOAD_ADD_I32_P8:
808 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
809 case Mips::ATOMIC_LOAD_ADD_I64:
810 case Mips::ATOMIC_LOAD_ADD_I64_P8:
811 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
813 case Mips::ATOMIC_LOAD_AND_I8:
814 case Mips::ATOMIC_LOAD_AND_I8_P8:
815 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
816 case Mips::ATOMIC_LOAD_AND_I16:
817 case Mips::ATOMIC_LOAD_AND_I16_P8:
818 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
819 case Mips::ATOMIC_LOAD_AND_I32:
820 case Mips::ATOMIC_LOAD_AND_I32_P8:
821 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
822 case Mips::ATOMIC_LOAD_AND_I64:
823 case Mips::ATOMIC_LOAD_AND_I64_P8:
824 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
826 case Mips::ATOMIC_LOAD_OR_I8:
827 case Mips::ATOMIC_LOAD_OR_I8_P8:
828 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
829 case Mips::ATOMIC_LOAD_OR_I16:
830 case Mips::ATOMIC_LOAD_OR_I16_P8:
831 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
832 case Mips::ATOMIC_LOAD_OR_I32:
833 case Mips::ATOMIC_LOAD_OR_I32_P8:
834 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
835 case Mips::ATOMIC_LOAD_OR_I64:
836 case Mips::ATOMIC_LOAD_OR_I64_P8:
837 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
839 case Mips::ATOMIC_LOAD_XOR_I8:
840 case Mips::ATOMIC_LOAD_XOR_I8_P8:
841 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
842 case Mips::ATOMIC_LOAD_XOR_I16:
843 case Mips::ATOMIC_LOAD_XOR_I16_P8:
844 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
845 case Mips::ATOMIC_LOAD_XOR_I32:
846 case Mips::ATOMIC_LOAD_XOR_I32_P8:
847 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
848 case Mips::ATOMIC_LOAD_XOR_I64:
849 case Mips::ATOMIC_LOAD_XOR_I64_P8:
850 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
852 case Mips::ATOMIC_LOAD_NAND_I8:
853 case Mips::ATOMIC_LOAD_NAND_I8_P8:
854 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
855 case Mips::ATOMIC_LOAD_NAND_I16:
856 case Mips::ATOMIC_LOAD_NAND_I16_P8:
857 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
858 case Mips::ATOMIC_LOAD_NAND_I32:
859 case Mips::ATOMIC_LOAD_NAND_I32_P8:
860 return EmitAtomicBinary(MI, BB, 4, 0, true);
861 case Mips::ATOMIC_LOAD_NAND_I64:
862 case Mips::ATOMIC_LOAD_NAND_I64_P8:
863 return EmitAtomicBinary(MI, BB, 8, 0, true);
865 case Mips::ATOMIC_LOAD_SUB_I8:
866 case Mips::ATOMIC_LOAD_SUB_I8_P8:
867 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
868 case Mips::ATOMIC_LOAD_SUB_I16:
869 case Mips::ATOMIC_LOAD_SUB_I16_P8:
870 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
871 case Mips::ATOMIC_LOAD_SUB_I32:
872 case Mips::ATOMIC_LOAD_SUB_I32_P8:
873 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
874 case Mips::ATOMIC_LOAD_SUB_I64:
875 case Mips::ATOMIC_LOAD_SUB_I64_P8:
876 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
878 case Mips::ATOMIC_SWAP_I8:
879 case Mips::ATOMIC_SWAP_I8_P8:
880 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
881 case Mips::ATOMIC_SWAP_I16:
882 case Mips::ATOMIC_SWAP_I16_P8:
883 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
884 case Mips::ATOMIC_SWAP_I32:
885 case Mips::ATOMIC_SWAP_I32_P8:
886 return EmitAtomicBinary(MI, BB, 4, 0);
887 case Mips::ATOMIC_SWAP_I64:
888 case Mips::ATOMIC_SWAP_I64_P8:
889 return EmitAtomicBinary(MI, BB, 8, 0);
891 case Mips::ATOMIC_CMP_SWAP_I8:
892 case Mips::ATOMIC_CMP_SWAP_I8_P8:
893 return EmitAtomicCmpSwapPartword(MI, BB, 1);
894 case Mips::ATOMIC_CMP_SWAP_I16:
895 case Mips::ATOMIC_CMP_SWAP_I16_P8:
896 return EmitAtomicCmpSwapPartword(MI, BB, 2);
897 case Mips::ATOMIC_CMP_SWAP_I32:
898 case Mips::ATOMIC_CMP_SWAP_I32_P8:
899 return EmitAtomicCmpSwap(MI, BB, 4);
900 case Mips::ATOMIC_CMP_SWAP_I64:
901 case Mips::ATOMIC_CMP_SWAP_I64_P8:
902 return EmitAtomicCmpSwap(MI, BB, 8);
906 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
907 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
909 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
910 unsigned Size, unsigned BinOpcode,
912 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
914 MachineFunction *MF = BB->getParent();
915 MachineRegisterInfo &RegInfo = MF->getRegInfo();
916 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
917 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
918 DebugLoc dl = MI->getDebugLoc();
919 unsigned LL, SC, AND, NOR, ZERO, BEQ;
922 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
923 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
930 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
931 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
934 ZERO = Mips::ZERO_64;
938 unsigned OldVal = MI->getOperand(0).getReg();
939 unsigned Ptr = MI->getOperand(1).getReg();
940 unsigned Incr = MI->getOperand(2).getReg();
942 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
943 unsigned AndRes = RegInfo.createVirtualRegister(RC);
944 unsigned Success = RegInfo.createVirtualRegister(RC);
946 // insert new blocks after the current block
947 const BasicBlock *LLVM_BB = BB->getBasicBlock();
948 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
949 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
950 MachineFunction::iterator It = BB;
952 MF->insert(It, loopMBB);
953 MF->insert(It, exitMBB);
955 // Transfer the remainder of BB and its successor edges to exitMBB.
956 exitMBB->splice(exitMBB->begin(), BB,
957 llvm::next(MachineBasicBlock::iterator(MI)),
959 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
963 // fallthrough --> loopMBB
964 BB->addSuccessor(loopMBB);
965 loopMBB->addSuccessor(loopMBB);
966 loopMBB->addSuccessor(exitMBB);
970 // <binop> storeval, oldval, incr
971 // sc success, storeval, 0(ptr)
972 // beq success, $0, loopMBB
974 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
976 // and andres, oldval, incr
977 // nor storeval, $0, andres
978 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
979 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
980 } else if (BinOpcode) {
981 // <binop> storeval, oldval, incr
982 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
986 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
987 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
989 MI->eraseFromParent(); // The instruction is gone now.
995 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
996 MachineBasicBlock *BB,
997 unsigned Size, unsigned BinOpcode,
999 assert((Size == 1 || Size == 2) &&
1000 "Unsupported size for EmitAtomicBinaryPartial.");
1002 MachineFunction *MF = BB->getParent();
1003 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1004 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1005 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1006 DebugLoc dl = MI->getDebugLoc();
1007 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1008 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1010 unsigned Dest = MI->getOperand(0).getReg();
1011 unsigned Ptr = MI->getOperand(1).getReg();
1012 unsigned Incr = MI->getOperand(2).getReg();
1014 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1015 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1016 unsigned Mask = RegInfo.createVirtualRegister(RC);
1017 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1018 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1019 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1020 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1021 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1022 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1023 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1024 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1025 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1026 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1027 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1028 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1029 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1030 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1031 unsigned Success = RegInfo.createVirtualRegister(RC);
1033 // insert new blocks after the current block
1034 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1035 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1036 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1037 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1038 MachineFunction::iterator It = BB;
1040 MF->insert(It, loopMBB);
1041 MF->insert(It, sinkMBB);
1042 MF->insert(It, exitMBB);
1044 // Transfer the remainder of BB and its successor edges to exitMBB.
1045 exitMBB->splice(exitMBB->begin(), BB,
1046 llvm::next(MachineBasicBlock::iterator(MI)),
1048 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1050 BB->addSuccessor(loopMBB);
1051 loopMBB->addSuccessor(loopMBB);
1052 loopMBB->addSuccessor(sinkMBB);
1053 sinkMBB->addSuccessor(exitMBB);
1056 // addiu masklsb2,$0,-4 # 0xfffffffc
1057 // and alignedaddr,ptr,masklsb2
1058 // andi ptrlsb2,ptr,3
1059 // sll shiftamt,ptrlsb2,3
1060 // ori maskupper,$0,255 # 0xff
1061 // sll mask,maskupper,shiftamt
1062 // nor mask2,$0,mask
1063 // sll incr2,incr,shiftamt
1065 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1066 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1067 .addReg(Mips::ZERO).addImm(-4);
1068 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1069 .addReg(Ptr).addReg(MaskLSB2);
1070 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1071 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1072 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1073 .addReg(Mips::ZERO).addImm(MaskImm);
1074 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1075 .addReg(ShiftAmt).addReg(MaskUpper);
1076 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1077 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1080 // atomic.load.binop
1082 // ll oldval,0(alignedaddr)
1083 // binop binopres,oldval,incr2
1084 // and newval,binopres,mask
1085 // and maskedoldval0,oldval,mask2
1086 // or storeval,maskedoldval0,newval
1087 // sc success,storeval,0(alignedaddr)
1088 // beq success,$0,loopMBB
1092 // ll oldval,0(alignedaddr)
1093 // and newval,incr2,mask
1094 // and maskedoldval0,oldval,mask2
1095 // or storeval,maskedoldval0,newval
1096 // sc success,storeval,0(alignedaddr)
1097 // beq success,$0,loopMBB
1100 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1102 // and andres, oldval, incr2
1103 // nor binopres, $0, andres
1104 // and newval, binopres, mask
1105 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1106 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1107 .addReg(Mips::ZERO).addReg(AndRes);
1108 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1109 } else if (BinOpcode) {
1110 // <binop> binopres, oldval, incr2
1111 // and newval, binopres, mask
1112 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1113 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1114 } else {// atomic.swap
1115 // and newval, incr2, mask
1116 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1119 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1120 .addReg(OldVal).addReg(Mask2);
1121 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1122 .addReg(MaskedOldVal0).addReg(NewVal);
1123 BuildMI(BB, dl, TII->get(SC), Success)
1124 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1125 BuildMI(BB, dl, TII->get(Mips::BEQ))
1126 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1129 // and maskedoldval1,oldval,mask
1130 // srl srlres,maskedoldval1,shiftamt
1131 // sll sllres,srlres,24
1132 // sra dest,sllres,24
1134 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1136 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1137 .addReg(OldVal).addReg(Mask);
1138 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1139 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1140 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1141 .addReg(SrlRes).addImm(ShiftImm);
1142 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1143 .addReg(SllRes).addImm(ShiftImm);
1145 MI->eraseFromParent(); // The instruction is gone now.
1151 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1152 MachineBasicBlock *BB,
1153 unsigned Size) const {
1154 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1156 MachineFunction *MF = BB->getParent();
1157 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1158 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1159 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1160 DebugLoc dl = MI->getDebugLoc();
1161 unsigned LL, SC, ZERO, BNE, BEQ;
1164 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1165 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1171 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1172 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1173 ZERO = Mips::ZERO_64;
1178 unsigned Dest = MI->getOperand(0).getReg();
1179 unsigned Ptr = MI->getOperand(1).getReg();
1180 unsigned OldVal = MI->getOperand(2).getReg();
1181 unsigned NewVal = MI->getOperand(3).getReg();
1183 unsigned Success = RegInfo.createVirtualRegister(RC);
1185 // insert new blocks after the current block
1186 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1187 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1188 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1189 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1190 MachineFunction::iterator It = BB;
1192 MF->insert(It, loop1MBB);
1193 MF->insert(It, loop2MBB);
1194 MF->insert(It, exitMBB);
1196 // Transfer the remainder of BB and its successor edges to exitMBB.
1197 exitMBB->splice(exitMBB->begin(), BB,
1198 llvm::next(MachineBasicBlock::iterator(MI)),
1200 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1204 // fallthrough --> loop1MBB
1205 BB->addSuccessor(loop1MBB);
1206 loop1MBB->addSuccessor(exitMBB);
1207 loop1MBB->addSuccessor(loop2MBB);
1208 loop2MBB->addSuccessor(loop1MBB);
1209 loop2MBB->addSuccessor(exitMBB);
1213 // bne dest, oldval, exitMBB
1215 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1216 BuildMI(BB, dl, TII->get(BNE))
1217 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1220 // sc success, newval, 0(ptr)
1221 // beq success, $0, loop1MBB
1223 BuildMI(BB, dl, TII->get(SC), Success)
1224 .addReg(NewVal).addReg(Ptr).addImm(0);
1225 BuildMI(BB, dl, TII->get(BEQ))
1226 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1228 MI->eraseFromParent(); // The instruction is gone now.
1234 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1235 MachineBasicBlock *BB,
1236 unsigned Size) const {
1237 assert((Size == 1 || Size == 2) &&
1238 "Unsupported size for EmitAtomicCmpSwapPartial.");
1240 MachineFunction *MF = BB->getParent();
1241 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1242 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1243 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1244 DebugLoc dl = MI->getDebugLoc();
1245 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1246 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1248 unsigned Dest = MI->getOperand(0).getReg();
1249 unsigned Ptr = MI->getOperand(1).getReg();
1250 unsigned CmpVal = MI->getOperand(2).getReg();
1251 unsigned NewVal = MI->getOperand(3).getReg();
1253 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1254 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1255 unsigned Mask = RegInfo.createVirtualRegister(RC);
1256 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1257 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1258 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1259 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1260 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1261 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1262 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1263 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1264 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1265 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1266 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1267 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1268 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1269 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1270 unsigned Success = RegInfo.createVirtualRegister(RC);
1272 // insert new blocks after the current block
1273 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1274 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1275 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1276 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1277 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1278 MachineFunction::iterator It = BB;
1280 MF->insert(It, loop1MBB);
1281 MF->insert(It, loop2MBB);
1282 MF->insert(It, sinkMBB);
1283 MF->insert(It, exitMBB);
1285 // Transfer the remainder of BB and its successor edges to exitMBB.
1286 exitMBB->splice(exitMBB->begin(), BB,
1287 llvm::next(MachineBasicBlock::iterator(MI)),
1289 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1291 BB->addSuccessor(loop1MBB);
1292 loop1MBB->addSuccessor(sinkMBB);
1293 loop1MBB->addSuccessor(loop2MBB);
1294 loop2MBB->addSuccessor(loop1MBB);
1295 loop2MBB->addSuccessor(sinkMBB);
1296 sinkMBB->addSuccessor(exitMBB);
1298 // FIXME: computation of newval2 can be moved to loop2MBB.
1300 // addiu masklsb2,$0,-4 # 0xfffffffc
1301 // and alignedaddr,ptr,masklsb2
1302 // andi ptrlsb2,ptr,3
1303 // sll shiftamt,ptrlsb2,3
1304 // ori maskupper,$0,255 # 0xff
1305 // sll mask,maskupper,shiftamt
1306 // nor mask2,$0,mask
1307 // andi maskedcmpval,cmpval,255
1308 // sll shiftedcmpval,maskedcmpval,shiftamt
1309 // andi maskednewval,newval,255
1310 // sll shiftednewval,maskednewval,shiftamt
1311 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1312 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1313 .addReg(Mips::ZERO).addImm(-4);
1314 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1315 .addReg(Ptr).addReg(MaskLSB2);
1316 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1317 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1318 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1319 .addReg(Mips::ZERO).addImm(MaskImm);
1320 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1321 .addReg(ShiftAmt).addReg(MaskUpper);
1322 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1323 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1324 .addReg(CmpVal).addImm(MaskImm);
1325 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1326 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1327 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1328 .addReg(NewVal).addImm(MaskImm);
1329 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1330 .addReg(ShiftAmt).addReg(MaskedNewVal);
1333 // ll oldval,0(alginedaddr)
1334 // and maskedoldval0,oldval,mask
1335 // bne maskedoldval0,shiftedcmpval,sinkMBB
1337 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1338 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1339 .addReg(OldVal).addReg(Mask);
1340 BuildMI(BB, dl, TII->get(Mips::BNE))
1341 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1344 // and maskedoldval1,oldval,mask2
1345 // or storeval,maskedoldval1,shiftednewval
1346 // sc success,storeval,0(alignedaddr)
1347 // beq success,$0,loop1MBB
1349 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1350 .addReg(OldVal).addReg(Mask2);
1351 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1352 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1353 BuildMI(BB, dl, TII->get(SC), Success)
1354 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1355 BuildMI(BB, dl, TII->get(Mips::BEQ))
1356 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1359 // srl srlres,maskedoldval0,shiftamt
1360 // sll sllres,srlres,24
1361 // sra dest,sllres,24
1363 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1365 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1366 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1367 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1368 .addReg(SrlRes).addImm(ShiftImm);
1369 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1370 .addReg(SllRes).addImm(ShiftImm);
1372 MI->eraseFromParent(); // The instruction is gone now.
1377 //===----------------------------------------------------------------------===//
1378 // Misc Lower Operation implementation
1379 //===----------------------------------------------------------------------===//
1380 SDValue MipsTargetLowering::
1381 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1383 MachineFunction &MF = DAG.getMachineFunction();
1384 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1385 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1387 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1388 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1389 "Cannot lower if the alignment of the allocated space is larger than \
1390 that of the stack.");
1392 SDValue Chain = Op.getOperand(0);
1393 SDValue Size = Op.getOperand(1);
1394 DebugLoc dl = Op.getDebugLoc();
1396 // Get a reference from Mips stack pointer
1397 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1399 // Subtract the dynamic size from the actual stack size to
1400 // obtain the new stack size.
1401 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1403 // The Sub result contains the new stack start address, so it
1404 // must be placed in the stack pointer register.
1405 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1407 // This node always has two return values: a new stack pointer
1408 // value and a chain
1409 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1410 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1411 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1413 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1416 SDValue MipsTargetLowering::
1417 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1419 // The first operand is the chain, the second is the condition, the third is
1420 // the block to branch to if the condition is true.
1421 SDValue Chain = Op.getOperand(0);
1422 SDValue Dest = Op.getOperand(2);
1423 DebugLoc dl = Op.getDebugLoc();
1425 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1427 // Return if flag is not set by a floating point comparison.
1428 if (CondRes.getOpcode() != MipsISD::FPCmp)
1431 SDValue CCNode = CondRes.getOperand(2);
1433 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1434 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1436 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1440 SDValue MipsTargetLowering::
1441 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1443 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1445 // Return if flag is not set by a floating point comparison.
1446 if (Cond.getOpcode() != MipsISD::FPCmp)
1449 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1453 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1454 SelectionDAG &DAG) const {
1455 // FIXME there isn't actually debug info here
1456 DebugLoc dl = Op.getDebugLoc();
1457 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1459 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1460 SDVTList VTs = DAG.getVTList(MVT::i32);
1462 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1464 // %gp_rel relocation
1465 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1466 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1468 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1469 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1470 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1472 // %hi/%lo relocation
1473 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1475 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1477 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1478 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1479 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1482 EVT ValTy = Op.getValueType();
1483 bool HasGotOfst = (GV->hasInternalLinkage() ||
1484 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1485 unsigned GotFlag = IsN64 ?
1486 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1488 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1489 GA = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
1490 SDValue ResNode = DAG.getLoad(ValTy, dl,
1491 DAG.getEntryNode(), GA, MachinePointerInfo(),
1492 false, false, false, 0);
1493 // On functions and global targets not internal linked only
1494 // a load from got/GP is necessary for PIC to work.
1497 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1498 IsN64 ? MipsII::MO_GOT_OFST :
1500 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1501 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1504 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1505 SelectionDAG &DAG) const {
1506 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1507 // FIXME there isn't actually debug info here
1508 DebugLoc dl = Op.getDebugLoc();
1510 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1511 // %hi/%lo relocation
1512 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1514 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1516 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1517 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1518 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1521 EVT ValTy = Op.getValueType();
1522 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1523 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1524 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1525 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, BAGOTOffset);
1526 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1527 SDValue Load = DAG.getLoad(ValTy, dl,
1528 DAG.getEntryNode(), BAGOTOffset,
1529 MachinePointerInfo(), false, false, false, 0);
1530 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1531 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1534 SDValue MipsTargetLowering::
1535 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1537 // If the relocation model is PIC, use the General Dynamic TLS Model,
1538 // otherwise use the Initial Exec or Local Exec TLS Model.
1539 // TODO: implement Local Dynamic TLS model
1541 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1542 DebugLoc dl = GA->getDebugLoc();
1543 const GlobalValue *GV = GA->getGlobal();
1544 EVT PtrVT = getPointerTy();
1546 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1547 // General Dynamic TLS Model
1548 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1549 0, MipsII::MO_TLSGD);
1550 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1551 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1552 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1556 Entry.Node = Argument;
1557 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1558 Args.push_back(Entry);
1559 std::pair<SDValue, SDValue> CallResult =
1560 LowerCallTo(DAG.getEntryNode(),
1561 (Type *) Type::getInt32Ty(*DAG.getContext()),
1562 false, false, false, false, 0, CallingConv::C, false, true,
1563 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1566 return CallResult.first;
1570 if (GV->isDeclaration()) {
1571 // Initial Exec TLS Model
1572 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1573 MipsII::MO_GOTTPREL);
1574 Offset = DAG.getLoad(MVT::i32, dl,
1575 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1576 false, false, false, 0);
1578 // Local Exec TLS Model
1579 SDVTList VTs = DAG.getVTList(MVT::i32);
1580 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1581 MipsII::MO_TPREL_HI);
1582 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1583 MipsII::MO_TPREL_LO);
1584 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1585 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1586 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1589 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1590 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1593 SDValue MipsTargetLowering::
1594 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1598 // FIXME there isn't actually debug info here
1599 DebugLoc dl = Op.getDebugLoc();
1600 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1601 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1603 EVT PtrVT = Op.getValueType();
1604 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1606 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1609 SDValue Ops[] = { JTI };
1610 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1611 } else {// Emit Load from Global Pointer
1612 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1613 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1614 MachinePointerInfo(),
1615 false, false, false, 0);
1618 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1620 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1621 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1626 SDValue MipsTargetLowering::
1627 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1630 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1631 const Constant *C = N->getConstVal();
1632 // FIXME there isn't actually debug info here
1633 DebugLoc dl = Op.getDebugLoc();
1635 // gp_rel relocation
1636 // FIXME: we should reference the constant pool using small data sections,
1637 // but the asm printer currently doesn't support this feature without
1638 // hacking it. This feature should come soon so we can uncomment the
1640 //if (IsInSmallSection(C->getType())) {
1641 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1642 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1643 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1645 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1646 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1647 N->getOffset(), MipsII::MO_ABS_HI);
1648 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1649 N->getOffset(), MipsII::MO_ABS_LO);
1650 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1651 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1652 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1654 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1655 N->getOffset(), MipsII::MO_GOT);
1656 CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1657 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1658 CP, MachinePointerInfo::getConstantPool(),
1659 false, false, false, 0);
1660 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1661 N->getOffset(), MipsII::MO_ABS_LO);
1662 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1663 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1669 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1670 MachineFunction &MF = DAG.getMachineFunction();
1671 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1673 DebugLoc dl = Op.getDebugLoc();
1674 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1677 // vastart just stores the address of the VarArgsFrameIndex slot into the
1678 // memory location argument.
1679 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1680 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1681 MachinePointerInfo(SV),
1685 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1686 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1687 DebugLoc dl = Op.getDebugLoc();
1688 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1689 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1690 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1691 DAG.getConstant(0x7fffffff, MVT::i32));
1692 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1693 DAG.getConstant(0x80000000, MVT::i32));
1694 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1695 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1698 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1700 // Use ext/ins instructions if target architecture is Mips32r2.
1701 // Eliminate redundant mfc1 and mtc1 instructions.
1702 unsigned LoIdx = 0, HiIdx = 1;
1705 std::swap(LoIdx, HiIdx);
1707 DebugLoc dl = Op.getDebugLoc();
1708 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1710 DAG.getConstant(LoIdx, MVT::i32));
1711 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1712 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1713 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1714 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1715 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1716 DAG.getConstant(0x7fffffff, MVT::i32));
1717 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1718 DAG.getConstant(0x80000000, MVT::i32));
1719 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1722 std::swap(Word0, Word1);
1724 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1727 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1729 EVT Ty = Op.getValueType();
1731 assert(Ty == MVT::f32 || Ty == MVT::f64);
1734 return LowerFCOPYSIGN32(Op, DAG);
1736 return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1739 SDValue MipsTargetLowering::
1740 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1742 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1743 "Frame address can only be determined for current frame.");
1745 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1746 MFI->setFrameAddressIsTaken(true);
1747 EVT VT = Op.getValueType();
1748 DebugLoc dl = Op.getDebugLoc();
1749 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1750 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1754 // TODO: set SType according to the desired memory barrier behavior.
1755 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1756 SelectionDAG& DAG) const {
1758 DebugLoc dl = Op.getDebugLoc();
1759 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1760 DAG.getConstant(SType, MVT::i32));
1763 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1764 SelectionDAG& DAG) const {
1765 // FIXME: Need pseudo-fence for 'singlethread' fences
1766 // FIXME: Set SType for weaker fences where supported/appropriate.
1768 DebugLoc dl = Op.getDebugLoc();
1769 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1770 DAG.getConstant(SType, MVT::i32));
1773 //===----------------------------------------------------------------------===//
1774 // Calling Convention Implementation
1775 //===----------------------------------------------------------------------===//
1777 //===----------------------------------------------------------------------===//
1778 // TODO: Implement a generic logic using tblgen that can support this.
1779 // Mips O32 ABI rules:
1781 // i32 - Passed in A0, A1, A2, A3 and stack
1782 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1783 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1784 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1785 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1786 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1789 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1790 //===----------------------------------------------------------------------===//
1792 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1793 MVT LocVT, CCValAssign::LocInfo LocInfo,
1794 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1796 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1798 static const unsigned IntRegs[] = {
1799 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1801 static const unsigned F32Regs[] = {
1802 Mips::F12, Mips::F14
1804 static const unsigned F64Regs[] = {
1809 if (ArgFlags.isByVal()) {
1810 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1811 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1812 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1813 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1814 r < std::min(IntRegsSize, NextReg); ++r)
1815 State.AllocateReg(IntRegs[r]);
1819 // Promote i8 and i16
1820 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1822 if (ArgFlags.isSExt())
1823 LocInfo = CCValAssign::SExt;
1824 else if (ArgFlags.isZExt())
1825 LocInfo = CCValAssign::ZExt;
1827 LocInfo = CCValAssign::AExt;
1832 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1833 // is true: function is vararg, argument is 3rd or higher, there is previous
1834 // argument which is not f32 or f64.
1835 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1836 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1837 unsigned OrigAlign = ArgFlags.getOrigAlign();
1838 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1840 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1841 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1842 // If this is the first part of an i64 arg,
1843 // the allocated register must be either A0 or A2.
1844 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1845 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1847 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1848 // Allocate int register and shadow next int register. If first
1849 // available register is Mips::A1 or Mips::A3, shadow it too.
1850 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1851 if (Reg == Mips::A1 || Reg == Mips::A3)
1852 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1853 State.AllocateReg(IntRegs, IntRegsSize);
1855 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1856 // we are guaranteed to find an available float register
1857 if (ValVT == MVT::f32) {
1858 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1859 // Shadow int register
1860 State.AllocateReg(IntRegs, IntRegsSize);
1862 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1863 // Shadow int registers
1864 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1865 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1866 State.AllocateReg(IntRegs, IntRegsSize);
1867 State.AllocateReg(IntRegs, IntRegsSize);
1870 llvm_unreachable("Cannot handle this ValVT.");
1872 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1873 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1876 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1878 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1880 return false; // CC must always match
1883 static const unsigned Mips64IntRegs[8] =
1884 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1885 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1886 static const unsigned Mips64DPRegs[8] =
1887 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1888 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1890 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1891 CCValAssign::LocInfo LocInfo,
1892 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1893 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1894 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1895 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1897 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1899 // If byval is 16-byte aligned, the first arg register must be even.
1900 if ((Align == 16) && (FirstIdx % 2)) {
1901 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1905 // Mark the registers allocated.
1906 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1907 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1909 // Allocate space on caller's stack.
1910 unsigned Offset = State.AllocateStack(Size, Align);
1913 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1916 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1921 #include "MipsGenCallingConv.inc"
1924 AnalyzeMips64CallOperands(CCState CCInfo,
1925 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1926 unsigned NumOps = Outs.size();
1927 for (unsigned i = 0; i != NumOps; ++i) {
1928 MVT ArgVT = Outs[i].VT;
1929 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1932 if (Outs[i].IsFixed)
1933 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1935 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1939 dbgs() << "Call operand #" << i << " has unhandled type "
1940 << EVT(ArgVT).getEVTString();
1942 llvm_unreachable(0);
1947 //===----------------------------------------------------------------------===//
1948 // Call Calling Convention Implementation
1949 //===----------------------------------------------------------------------===//
1951 static const unsigned O32IntRegsSize = 4;
1953 static const unsigned O32IntRegs[] = {
1954 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1957 // Return next O32 integer argument register.
1958 static unsigned getNextIntArgReg(unsigned Reg) {
1959 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1960 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1963 // Write ByVal Arg to arg registers and stack.
1965 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1966 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1967 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1968 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1969 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1970 MVT PtrType, bool isLittle) {
1971 unsigned LocMemOffset = VA.getLocMemOffset();
1972 unsigned Offset = 0;
1973 uint32_t RemainingSize = Flags.getByValSize();
1974 unsigned ByValAlign = Flags.getByValAlign();
1976 // Copy the first 4 words of byval arg to registers A0 - A3.
1977 // FIXME: Use a stricter alignment if it enables better optimization in passes
1979 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1980 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1981 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1982 DAG.getConstant(Offset, MVT::i32));
1983 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1984 MachinePointerInfo(),
1985 false, false, false, std::min(ByValAlign,
1987 MemOpChains.push_back(LoadVal.getValue(1));
1988 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1989 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1992 if (RemainingSize == 0)
1995 // If there still is a register available for argument passing, write the
1996 // remaining part of the structure to it using subword loads and shifts.
1997 if (LocMemOffset < 4 * 4) {
1998 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
1999 "There must be one to three bytes remaining.");
2000 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2001 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2002 DAG.getConstant(Offset, MVT::i32));
2003 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2004 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2005 LoadPtr, MachinePointerInfo(),
2006 MVT::getIntegerVT(LoadSize * 8), false,
2008 MemOpChains.push_back(LoadVal.getValue(1));
2010 // If target is big endian, shift it to the most significant half-word or
2013 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2014 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2017 RemainingSize -= LoadSize;
2019 // Read second subword if necessary.
2020 if (RemainingSize != 0) {
2021 assert(RemainingSize == 1 && "There must be one byte remaining.");
2022 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2023 DAG.getConstant(Offset, MVT::i32));
2024 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2025 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2026 LoadPtr, MachinePointerInfo(),
2027 MVT::i8, false, false, Alignment);
2028 MemOpChains.push_back(Subword.getValue(1));
2029 // Insert the loaded byte to LoadVal.
2030 // FIXME: Use INS if supported by target.
2031 unsigned ShiftAmt = isLittle ? 16 : 8;
2032 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2033 DAG.getConstant(ShiftAmt, MVT::i32));
2034 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2037 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2038 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2042 // Create a fixed object on stack at offset LocMemOffset and copy
2043 // remaining part of byval arg to it using memcpy.
2044 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2045 DAG.getConstant(Offset, MVT::i32));
2046 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2047 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2048 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2049 DAG.getConstant(RemainingSize, MVT::i32),
2050 std::min(ByValAlign, (unsigned)4),
2051 /*isVolatile=*/false, /*AlwaysInline=*/false,
2052 MachinePointerInfo(0), MachinePointerInfo(0));
2055 // Copy Mips64 byVal arg to registers and stack.
2057 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2058 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2059 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2060 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2061 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2062 EVT PtrTy, bool isLittle) {
2063 unsigned ByValSize = Flags.getByValSize();
2064 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2065 bool IsRegLoc = VA.isRegLoc();
2066 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2067 unsigned LocMemOffset = 0;
2068 unsigned MemCpySize = ByValSize;
2071 LocMemOffset = VA.getLocMemOffset();
2073 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2075 const unsigned *RegEnd = Mips64IntRegs + 8;
2077 // Copy double words to registers.
2078 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2079 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2080 DAG.getConstant(Offset, PtrTy));
2081 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2082 MachinePointerInfo(), false, false, false,
2084 MemOpChains.push_back(LoadVal.getValue(1));
2085 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2088 // Return if the struct has been fully copied.
2089 if (!(MemCpySize = ByValSize - Offset))
2092 // If there is an argument register available, copy the remainder of the
2093 // byval argument with sub-doubleword loads and shifts.
2094 if (Reg != RegEnd) {
2095 assert((ByValSize < Offset + 8) &&
2096 "Size of the remainder should be smaller than 8-byte.");
2098 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2099 unsigned RemSize = ByValSize - Offset;
2101 if (RemSize < LoadSize)
2104 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2105 DAG.getConstant(Offset, PtrTy));
2107 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2108 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2109 false, false, Alignment);
2110 MemOpChains.push_back(LoadVal.getValue(1));
2112 // Offset in number of bits from double word boundary.
2113 unsigned OffsetDW = (Offset % 8) * 8;
2114 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2115 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2116 DAG.getConstant(Shamt, MVT::i32));
2118 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2121 Alignment = std::min(Alignment, LoadSize);
2124 RegsToPass.push_back(std::make_pair(*Reg, Val));
2129 assert(MemCpySize && "MemCpySize must not be zero.");
2131 // Create a fixed object on stack at offset LocMemOffset and copy
2132 // remainder of byval arg to it with memcpy.
2133 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2134 DAG.getConstant(Offset, PtrTy));
2135 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2136 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2137 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2138 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2139 /*isVolatile=*/false, /*AlwaysInline=*/false,
2140 MachinePointerInfo(0), MachinePointerInfo(0));
2143 /// LowerCall - functions arguments are copied from virtual regs to
2144 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2145 /// TODO: isTailCall.
2147 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2148 CallingConv::ID CallConv, bool isVarArg,
2150 const SmallVectorImpl<ISD::OutputArg> &Outs,
2151 const SmallVectorImpl<SDValue> &OutVals,
2152 const SmallVectorImpl<ISD::InputArg> &Ins,
2153 DebugLoc dl, SelectionDAG &DAG,
2154 SmallVectorImpl<SDValue> &InVals) const {
2155 // MIPs target does not yet support tail call optimization.
2158 MachineFunction &MF = DAG.getMachineFunction();
2159 MachineFrameInfo *MFI = MF.getFrameInfo();
2160 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2161 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2162 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2164 // Analyze operands of the call, assigning locations to each operand.
2165 SmallVector<CCValAssign, 16> ArgLocs;
2166 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2167 getTargetMachine(), ArgLocs, *DAG.getContext());
2170 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2172 AnalyzeMips64CallOperands(CCInfo, Outs);
2174 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2176 // Get a count of how many bytes are to be pushed on the stack.
2177 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2179 // Chain is the output chain of the last Load/Store or CopyToReg node.
2180 // ByValChain is the output chain of the last Memcpy node created for copying
2181 // byval arguments to the stack.
2182 SDValue Chain, CallSeqStart, ByValChain;
2183 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2184 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2185 ByValChain = InChain;
2187 // If this is the first call, create a stack frame object that points to
2188 // a location to which .cprestore saves $gp.
2189 if (IsO32 && IsPIC && !MipsFI->getGPFI())
2190 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2192 // Get the frame index of the stack frame object that points to the location
2193 // of dynamically allocated area on the stack.
2194 int DynAllocFI = MipsFI->getDynAllocFI();
2196 // Update size of the maximum argument space.
2197 // For O32, a minimum of four words (16 bytes) of argument space is
2200 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2202 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2204 if (MaxCallFrameSize < NextStackOffset) {
2205 MipsFI->setMaxCallFrameSize(NextStackOffset);
2207 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2208 // allocated stack space. These offsets must be aligned to a boundary
2209 // determined by the stack alignment of the ABI.
2210 unsigned StackAlignment = TFL->getStackAlignment();
2211 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2212 StackAlignment * StackAlignment;
2214 if (MipsFI->needGPSaveRestore())
2215 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2217 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2220 // With EABI is it possible to have 16 args on registers.
2221 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2222 SmallVector<SDValue, 8> MemOpChains;
2224 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2226 // Walk the register/memloc assignments, inserting copies/loads.
2227 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2228 SDValue Arg = OutVals[i];
2229 CCValAssign &VA = ArgLocs[i];
2230 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2231 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2234 if (Flags.isByVal()) {
2235 assert(Flags.getByValSize() &&
2236 "ByVal args of size 0 should have been ignored by front-end.");
2238 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2239 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2240 Subtarget->isLittle());
2242 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2243 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2244 Subtarget->isLittle());
2248 // Promote the value if needed.
2249 switch (VA.getLocInfo()) {
2250 default: llvm_unreachable("Unknown loc info!");
2251 case CCValAssign::Full:
2252 if (VA.isRegLoc()) {
2253 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2254 (ValVT == MVT::f64 && LocVT == MVT::i64))
2255 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2256 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2257 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2258 Arg, DAG.getConstant(0, MVT::i32));
2259 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2260 Arg, DAG.getConstant(1, MVT::i32));
2261 if (!Subtarget->isLittle())
2263 unsigned LocRegLo = VA.getLocReg();
2264 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2265 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2266 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2271 case CCValAssign::SExt:
2272 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2274 case CCValAssign::ZExt:
2275 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2277 case CCValAssign::AExt:
2278 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2282 // Arguments that can be passed on register must be kept at
2283 // RegsToPass vector
2284 if (VA.isRegLoc()) {
2285 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2289 // Register can't get to this point...
2290 assert(VA.isMemLoc());
2292 // Create the frame index object for this incoming parameter
2293 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2294 VA.getLocMemOffset(), true);
2295 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2297 // emit ISD::STORE whichs stores the
2298 // parameter value to a stack Location
2299 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2300 MachinePointerInfo(),
2304 // Extend range of indices of frame objects for outgoing arguments that were
2305 // created during this function call. Skip this step if no such objects were
2308 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2310 // If a memcpy has been created to copy a byval arg to a stack, replace the
2311 // chain input of CallSeqStart with ByValChain.
2312 if (InChain != ByValChain)
2313 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2314 NextStackOffsetVal);
2316 // Transform all store nodes into one single node because all store
2317 // nodes are independent of each other.
2318 if (!MemOpChains.empty())
2319 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2320 &MemOpChains[0], MemOpChains.size());
2322 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2323 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2324 // node so that legalize doesn't hack it.
2325 unsigned char OpFlag;
2326 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2327 bool LoadSymAddr = false;
2330 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2331 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2332 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2333 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2334 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2336 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2339 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2340 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2341 getPointerTy(), 0, OpFlag);
2346 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2347 if (IsN64 || (!IsO32 && IsPIC))
2348 OpFlag = MipsII::MO_GOT_DISP;
2349 else if (!IsPIC) // !N64 && static
2350 OpFlag = MipsII::MO_NO_FLAG;
2352 OpFlag = MipsII::MO_GOT_CALL;
2353 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2354 getPointerTy(), OpFlag);
2360 // Create nodes that load address of callee and copy it to T9
2363 // Load callee address
2364 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, getPointerTy(), Callee);
2365 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2366 Callee, MachinePointerInfo::getGOT(),
2367 false, false, false, 0);
2369 // Use GOT+LO if callee has internal linkage.
2370 if (CalleeLo.getNode()) {
2371 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2372 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2378 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2379 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2380 InFlag = Chain.getValue(1);
2381 Callee = DAG.getRegister(T9Reg, getPointerTy());
2384 // Build a sequence of copy-to-reg nodes chained together with token
2385 // chain and flag operands which copy the outgoing args into registers.
2386 // The InFlag in necessary since all emitted instructions must be
2388 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2389 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2390 RegsToPass[i].second, InFlag);
2391 InFlag = Chain.getValue(1);
2394 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2395 // = Chain, Callee, Reg#1, Reg#2, ...
2397 // Returns a chain & a flag for retval copy to use.
2398 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2399 SmallVector<SDValue, 8> Ops;
2400 Ops.push_back(Chain);
2401 Ops.push_back(Callee);
2403 // Add argument registers to the end of the list so that they are
2404 // known live into the call.
2405 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2406 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2407 RegsToPass[i].second.getValueType()));
2409 if (InFlag.getNode())
2410 Ops.push_back(InFlag);
2412 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2413 InFlag = Chain.getValue(1);
2415 // Create the CALLSEQ_END node.
2416 Chain = DAG.getCALLSEQ_END(Chain,
2417 DAG.getIntPtrConstant(NextStackOffset, true),
2418 DAG.getIntPtrConstant(0, true), InFlag);
2419 InFlag = Chain.getValue(1);
2421 // Handle result values, copying them out of physregs into vregs that we
2423 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2424 Ins, dl, DAG, InVals);
2427 /// LowerCallResult - Lower the result values of a call into the
2428 /// appropriate copies out of appropriate physical registers.
2430 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2431 CallingConv::ID CallConv, bool isVarArg,
2432 const SmallVectorImpl<ISD::InputArg> &Ins,
2433 DebugLoc dl, SelectionDAG &DAG,
2434 SmallVectorImpl<SDValue> &InVals) const {
2435 // Assign locations to each value returned by this call.
2436 SmallVector<CCValAssign, 16> RVLocs;
2437 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2438 getTargetMachine(), RVLocs, *DAG.getContext());
2440 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2442 // Copy all of the result registers out of their specified physreg.
2443 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2444 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2445 RVLocs[i].getValVT(), InFlag).getValue(1);
2446 InFlag = Chain.getValue(2);
2447 InVals.push_back(Chain.getValue(0));
2453 //===----------------------------------------------------------------------===//
2454 // Formal Arguments Calling Convention Implementation
2455 //===----------------------------------------------------------------------===//
2456 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2457 std::vector<SDValue>& OutChains,
2458 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2459 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2460 unsigned LocMem = VA.getLocMemOffset();
2461 unsigned FirstWord = LocMem / 4;
2463 // copy register A0 - A3 to frame object
2464 for (unsigned i = 0; i < NumWords; ++i) {
2465 unsigned CurWord = FirstWord + i;
2466 if (CurWord >= O32IntRegsSize)
2469 unsigned SrcReg = O32IntRegs[CurWord];
2470 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2471 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2472 DAG.getConstant(i * 4, MVT::i32));
2473 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2474 StorePtr, MachinePointerInfo(), false,
2476 OutChains.push_back(Store);
2480 // Create frame object on stack and copy registers used for byval passing to it.
2482 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2483 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2484 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2485 MachineFrameInfo *MFI, bool IsRegLoc,
2486 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2488 const unsigned *Reg = Mips64IntRegs + 8;
2489 int FOOffset; // Frame object offset from virtual frame pointer.
2492 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2493 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2496 FOOffset = VA.getLocMemOffset();
2498 // Create frame object.
2499 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2500 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2501 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2502 InVals.push_back(FIN);
2504 // Copy arg registers.
2505 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2507 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2508 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2509 DAG.getConstant(I * 8, PtrTy));
2510 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2511 StorePtr, MachinePointerInfo(), false,
2513 OutChains.push_back(Store);
2519 /// LowerFormalArguments - transform physical registers into virtual registers
2520 /// and generate load operations for arguments places on the stack.
2522 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2523 CallingConv::ID CallConv,
2525 const SmallVectorImpl<ISD::InputArg>
2527 DebugLoc dl, SelectionDAG &DAG,
2528 SmallVectorImpl<SDValue> &InVals)
2530 MachineFunction &MF = DAG.getMachineFunction();
2531 MachineFrameInfo *MFI = MF.getFrameInfo();
2532 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2534 MipsFI->setVarArgsFrameIndex(0);
2536 // Used with vargs to acumulate store chains.
2537 std::vector<SDValue> OutChains;
2539 // Assign locations to all of the incoming arguments.
2540 SmallVector<CCValAssign, 16> ArgLocs;
2541 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2542 getTargetMachine(), ArgLocs, *DAG.getContext());
2545 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2547 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2549 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2551 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2552 CCValAssign &VA = ArgLocs[i];
2553 EVT ValVT = VA.getValVT();
2554 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2555 bool IsRegLoc = VA.isRegLoc();
2557 if (Flags.isByVal()) {
2558 assert(Flags.getByValSize() &&
2559 "ByVal args of size 0 should have been ignored by front-end.");
2561 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2562 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2564 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2565 InVals.push_back(FIN);
2566 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2568 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2569 MFI, IsRegLoc, InVals, MipsFI,
2574 // Arguments stored on registers
2576 EVT RegVT = VA.getLocVT();
2577 unsigned ArgReg = VA.getLocReg();
2578 TargetRegisterClass *RC = 0;
2580 if (RegVT == MVT::i32)
2581 RC = Mips::CPURegsRegisterClass;
2582 else if (RegVT == MVT::i64)
2583 RC = Mips::CPU64RegsRegisterClass;
2584 else if (RegVT == MVT::f32)
2585 RC = Mips::FGR32RegisterClass;
2586 else if (RegVT == MVT::f64)
2587 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2589 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2591 // Transform the arguments stored on
2592 // physical registers into virtual ones
2593 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2594 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2596 // If this is an 8 or 16-bit value, it has been passed promoted
2597 // to 32 bits. Insert an assert[sz]ext to capture this, then
2598 // truncate to the right size.
2599 if (VA.getLocInfo() != CCValAssign::Full) {
2600 unsigned Opcode = 0;
2601 if (VA.getLocInfo() == CCValAssign::SExt)
2602 Opcode = ISD::AssertSext;
2603 else if (VA.getLocInfo() == CCValAssign::ZExt)
2604 Opcode = ISD::AssertZext;
2606 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2607 DAG.getValueType(ValVT));
2608 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2611 // Handle floating point arguments passed in integer registers.
2612 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2613 (RegVT == MVT::i64 && ValVT == MVT::f64))
2614 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2615 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2616 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2617 getNextIntArgReg(ArgReg), RC);
2618 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2619 if (!Subtarget->isLittle())
2620 std::swap(ArgValue, ArgValue2);
2621 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2622 ArgValue, ArgValue2);
2625 InVals.push_back(ArgValue);
2626 } else { // VA.isRegLoc()
2629 assert(VA.isMemLoc());
2631 // The stack pointer offset is relative to the caller stack frame.
2632 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2633 VA.getLocMemOffset(), true);
2635 // Create load nodes to retrieve arguments from the stack
2636 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2637 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2638 MachinePointerInfo::getFixedStack(LastFI),
2639 false, false, false, 0));
2643 // The mips ABIs for returning structs by value requires that we copy
2644 // the sret argument into $v0 for the return. Save the argument into
2645 // a virtual register so that we can access it from the return points.
2646 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2647 unsigned Reg = MipsFI->getSRetReturnReg();
2649 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2650 MipsFI->setSRetReturnReg(Reg);
2652 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2653 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2657 unsigned NumOfRegs = IsO32 ? 4 : 8;
2658 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2659 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2660 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2661 TargetRegisterClass *RC
2662 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2663 unsigned RegSize = RC->getSize();
2664 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2666 // Offset of the first variable argument from stack pointer.
2667 int FirstVaArgOffset;
2669 if (IsO32 || (Idx == NumOfRegs)) {
2671 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2673 FirstVaArgOffset = RegSlotOffset;
2675 // Record the frame index of the first variable argument
2676 // which is a value necessary to VASTART.
2677 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2678 MipsFI->setVarArgsFrameIndex(LastFI);
2680 // Copy the integer registers that have not been used for argument passing
2681 // to the argument register save area. For O32, the save area is allocated
2682 // in the caller's stack frame, while for N32/64, it is allocated in the
2683 // callee's stack frame.
2684 for (int StackOffset = RegSlotOffset;
2685 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2686 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2687 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2688 MVT::getIntegerVT(RegSize * 8));
2689 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2690 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2691 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2692 MachinePointerInfo(),
2697 MipsFI->setLastInArgFI(LastFI);
2699 // All stores are grouped in one node to allow the matching between
2700 // the size of Ins and InVals. This only happens when on varg functions
2701 if (!OutChains.empty()) {
2702 OutChains.push_back(Chain);
2703 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2704 &OutChains[0], OutChains.size());
2710 //===----------------------------------------------------------------------===//
2711 // Return Value Calling Convention Implementation
2712 //===----------------------------------------------------------------------===//
2715 MipsTargetLowering::LowerReturn(SDValue Chain,
2716 CallingConv::ID CallConv, bool isVarArg,
2717 const SmallVectorImpl<ISD::OutputArg> &Outs,
2718 const SmallVectorImpl<SDValue> &OutVals,
2719 DebugLoc dl, SelectionDAG &DAG) const {
2721 // CCValAssign - represent the assignment of
2722 // the return value to a location
2723 SmallVector<CCValAssign, 16> RVLocs;
2725 // CCState - Info about the registers and stack slot.
2726 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2727 getTargetMachine(), RVLocs, *DAG.getContext());
2729 // Analize return values.
2730 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2732 // If this is the first return lowered for this function, add
2733 // the regs to the liveout set for the function.
2734 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2735 for (unsigned i = 0; i != RVLocs.size(); ++i)
2736 if (RVLocs[i].isRegLoc())
2737 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2742 // Copy the result values into the output registers.
2743 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2744 CCValAssign &VA = RVLocs[i];
2745 assert(VA.isRegLoc() && "Can only return in registers!");
2747 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2750 // guarantee that all emitted copies are
2751 // stuck together, avoiding something bad
2752 Flag = Chain.getValue(1);
2755 // The mips ABIs for returning structs by value requires that we copy
2756 // the sret argument into $v0 for the return. We saved the argument into
2757 // a virtual register in the entry block, so now we copy the value out
2759 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2760 MachineFunction &MF = DAG.getMachineFunction();
2761 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2762 unsigned Reg = MipsFI->getSRetReturnReg();
2765 llvm_unreachable("sret virtual register not created in the entry block");
2766 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2768 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2769 Flag = Chain.getValue(1);
2772 // Return on Mips is always a "jr $ra"
2774 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2775 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2777 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2778 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2781 //===----------------------------------------------------------------------===//
2782 // Mips Inline Assembly Support
2783 //===----------------------------------------------------------------------===//
2785 /// getConstraintType - Given a constraint letter, return the type of
2786 /// constraint it is for this target.
2787 MipsTargetLowering::ConstraintType MipsTargetLowering::
2788 getConstraintType(const std::string &Constraint) const
2790 // Mips specific constrainy
2791 // GCC config/mips/constraints.md
2793 // 'd' : An address register. Equivalent to r
2794 // unless generating MIPS16 code.
2795 // 'y' : Equivalent to r; retained for
2796 // backwards compatibility.
2797 // 'f' : Floating Point registers.
2798 if (Constraint.size() == 1) {
2799 switch (Constraint[0]) {
2804 return C_RegisterClass;
2808 return TargetLowering::getConstraintType(Constraint);
2811 /// Examine constraint type and operand type and determine a weight value.
2812 /// This object must already have been set up with the operand type
2813 /// and the current alternative constraint selected.
2814 TargetLowering::ConstraintWeight
2815 MipsTargetLowering::getSingleConstraintMatchWeight(
2816 AsmOperandInfo &info, const char *constraint) const {
2817 ConstraintWeight weight = CW_Invalid;
2818 Value *CallOperandVal = info.CallOperandVal;
2819 // If we don't have a value, we can't do a match,
2820 // but allow it at the lowest weight.
2821 if (CallOperandVal == NULL)
2823 Type *type = CallOperandVal->getType();
2824 // Look at the constraint type.
2825 switch (*constraint) {
2827 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2831 if (type->isIntegerTy())
2832 weight = CW_Register;
2835 if (type->isFloatTy())
2836 weight = CW_Register;
2842 /// Given a register class constraint, like 'r', if this corresponds directly
2843 /// to an LLVM register class, return a register of 0 and the register class
2845 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2846 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2848 if (Constraint.size() == 1) {
2849 switch (Constraint[0]) {
2850 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2851 case 'y': // Same as 'r'. Exists for compatibility.
2853 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2856 return std::make_pair(0U, Mips::FGR32RegisterClass);
2858 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2859 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2863 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2867 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2868 // The Mips target isn't yet aware of offsets.
2872 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2873 if (VT != MVT::f32 && VT != MVT::f64)
2875 if (Imm.isNegZero())
2877 return Imm.isZero();