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 (!isShiftedMask_64(I))
46 Size = CountPopulation_64(I);
47 Pos = CountTrailingZeros_64(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::ThreadPointer: return "MipsISD::ThreadPointer";
58 case MipsISD::Ret: return "MipsISD::Ret";
59 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
60 case MipsISD::FPCmp: return "MipsISD::FPCmp";
61 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
62 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
63 case MipsISD::FPRound: return "MipsISD::FPRound";
64 case MipsISD::MAdd: return "MipsISD::MAdd";
65 case MipsISD::MAddu: return "MipsISD::MAddu";
66 case MipsISD::MSub: return "MipsISD::MSub";
67 case MipsISD::MSubu: return "MipsISD::MSubu";
68 case MipsISD::DivRem: return "MipsISD::DivRem";
69 case MipsISD::DivRemU: return "MipsISD::DivRemU";
70 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
71 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
72 case MipsISD::Wrapper: return "MipsISD::Wrapper";
73 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
74 case MipsISD::Sync: return "MipsISD::Sync";
75 case MipsISD::Ext: return "MipsISD::Ext";
76 case MipsISD::Ins: return "MipsISD::Ins";
82 MipsTargetLowering(MipsTargetMachine &TM)
83 : TargetLowering(TM, new MipsTargetObjectFile()),
84 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
85 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
86 IsO32(Subtarget->isABI_O32()) {
88 // Mips does not have i1 type, so use i32 for
89 // setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // Set up the register classes
94 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
95 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
98 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
100 // When dealing with single precision only, use libcalls
101 if (!Subtarget->isSingleFloat()) {
103 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
105 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
108 // Load extented operations for i1 types must be promoted
109 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
110 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
111 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
113 // MIPS doesn't have extending float->double load/store
114 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
115 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
117 // Used by legalize types to correctly generate the setcc result.
118 // Without this, every float setcc comes with a AND/OR with the result,
119 // we don't want this, since the fpcmp result goes to a flag register,
120 // which is used implicitly by brcond and select operations.
121 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
123 // Mips Custom Operations
124 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
125 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
126 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
127 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
128 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
129 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
130 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
131 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
132 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
133 setOperationAction(ISD::ConstantPool, MVT::i64, 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::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
160 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
161 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
162 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
163 setOperationAction(ISD::ROTL, MVT::i32, Expand);
164 setOperationAction(ISD::ROTL, MVT::i64, Expand);
166 if (!Subtarget->hasMips32r2())
167 setOperationAction(ISD::ROTR, MVT::i32, Expand);
169 if (!Subtarget->hasMips64r2())
170 setOperationAction(ISD::ROTR, MVT::i64, Expand);
172 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
173 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
174 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
175 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
176 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
177 setOperationAction(ISD::FSIN, MVT::f32, Expand);
178 setOperationAction(ISD::FSIN, MVT::f64, Expand);
179 setOperationAction(ISD::FCOS, MVT::f32, Expand);
180 setOperationAction(ISD::FCOS, MVT::f64, Expand);
181 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
182 setOperationAction(ISD::FPOW, MVT::f32, Expand);
183 setOperationAction(ISD::FPOW, MVT::f64, Expand);
184 setOperationAction(ISD::FLOG, MVT::f32, Expand);
185 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
186 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
187 setOperationAction(ISD::FEXP, MVT::f32, Expand);
188 setOperationAction(ISD::FMA, MVT::f32, Expand);
189 setOperationAction(ISD::FMA, MVT::f64, Expand);
191 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
192 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
194 setOperationAction(ISD::VAARG, MVT::Other, Expand);
195 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
196 setOperationAction(ISD::VAEND, MVT::Other, Expand);
198 // Use the default for now
199 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
200 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
202 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
203 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
205 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
206 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
208 setInsertFencesForAtomic(true);
210 if (Subtarget->isSingleFloat())
211 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
213 if (!Subtarget->hasSEInReg()) {
214 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
215 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
218 if (!Subtarget->hasBitCount())
219 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
221 if (!Subtarget->hasSwap())
222 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
224 setTargetDAGCombine(ISD::ADDE);
225 setTargetDAGCombine(ISD::SUBE);
226 setTargetDAGCombine(ISD::SDIVREM);
227 setTargetDAGCombine(ISD::UDIVREM);
228 setTargetDAGCombine(ISD::SETCC);
229 setTargetDAGCombine(ISD::AND);
230 setTargetDAGCombine(ISD::OR);
232 setMinFunctionAlignment(2);
234 setStackPointerRegisterToSaveRestore(HasMips64 ? Mips::SP_64 : Mips::SP);
235 computeRegisterProperties();
237 setExceptionPointerRegister(Mips::A0);
238 setExceptionSelectorRegister(Mips::A1);
241 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
242 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
243 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
246 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
251 // Transforms a subgraph in CurDAG if the following pattern is found:
252 // (addc multLo, Lo0), (adde multHi, Hi0),
254 // multHi/Lo: product of multiplication
255 // Lo0: initial value of Lo register
256 // Hi0: initial value of Hi register
257 // Return true if pattern matching was successful.
258 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
259 // ADDENode's second operand must be a flag output of an ADDC node in order
260 // for the matching to be successful.
261 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
263 if (ADDCNode->getOpcode() != ISD::ADDC)
266 SDValue MultHi = ADDENode->getOperand(0);
267 SDValue MultLo = ADDCNode->getOperand(0);
268 SDNode* MultNode = MultHi.getNode();
269 unsigned MultOpc = MultHi.getOpcode();
271 // MultHi and MultLo must be generated by the same node,
272 if (MultLo.getNode() != MultNode)
275 // and it must be a multiplication.
276 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
279 // MultLo amd MultHi must be the first and second output of MultNode
281 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
284 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
285 // of the values of MultNode, in which case MultNode will be removed in later
287 // If there exist users other than ADDENode or ADDCNode, this function returns
288 // here, which will result in MultNode being mapped to a single MULT
289 // instruction node rather than a pair of MULT and MADD instructions being
291 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
294 SDValue Chain = CurDAG->getEntryNode();
295 DebugLoc dl = ADDENode->getDebugLoc();
297 // create MipsMAdd(u) node
298 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
300 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
301 MultNode->getOperand(0),// Factor 0
302 MultNode->getOperand(1),// Factor 1
303 ADDCNode->getOperand(1),// Lo0
304 ADDENode->getOperand(1));// Hi0
306 // create CopyFromReg nodes
307 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
309 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
311 CopyFromLo.getValue(2));
313 // replace uses of adde and addc here
314 if (!SDValue(ADDCNode, 0).use_empty())
315 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
317 if (!SDValue(ADDENode, 0).use_empty())
318 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
324 // Transforms a subgraph in CurDAG if the following pattern is found:
325 // (addc Lo0, multLo), (sube Hi0, multHi),
327 // multHi/Lo: product of multiplication
328 // Lo0: initial value of Lo register
329 // Hi0: initial value of Hi register
330 // Return true if pattern matching was successful.
331 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
332 // SUBENode's second operand must be a flag output of an SUBC node in order
333 // for the matching to be successful.
334 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
336 if (SUBCNode->getOpcode() != ISD::SUBC)
339 SDValue MultHi = SUBENode->getOperand(1);
340 SDValue MultLo = SUBCNode->getOperand(1);
341 SDNode* MultNode = MultHi.getNode();
342 unsigned MultOpc = MultHi.getOpcode();
344 // MultHi and MultLo must be generated by the same node,
345 if (MultLo.getNode() != MultNode)
348 // and it must be a multiplication.
349 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
352 // MultLo amd MultHi must be the first and second output of MultNode
354 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
357 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
358 // of the values of MultNode, in which case MultNode will be removed in later
360 // If there exist users other than SUBENode or SUBCNode, this function returns
361 // here, which will result in MultNode being mapped to a single MULT
362 // instruction node rather than a pair of MULT and MSUB instructions being
364 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
367 SDValue Chain = CurDAG->getEntryNode();
368 DebugLoc dl = SUBENode->getDebugLoc();
370 // create MipsSub(u) node
371 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
373 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
374 MultNode->getOperand(0),// Factor 0
375 MultNode->getOperand(1),// Factor 1
376 SUBCNode->getOperand(0),// Lo0
377 SUBENode->getOperand(0));// Hi0
379 // create CopyFromReg nodes
380 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
382 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
384 CopyFromLo.getValue(2));
386 // replace uses of sube and subc here
387 if (!SDValue(SUBCNode, 0).use_empty())
388 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
390 if (!SDValue(SUBENode, 0).use_empty())
391 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
396 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
397 TargetLowering::DAGCombinerInfo &DCI,
398 const MipsSubtarget* Subtarget) {
399 if (DCI.isBeforeLegalize())
402 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
404 return SDValue(N, 0);
409 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
410 TargetLowering::DAGCombinerInfo &DCI,
411 const MipsSubtarget* Subtarget) {
412 if (DCI.isBeforeLegalize())
415 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
417 return SDValue(N, 0);
422 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
423 TargetLowering::DAGCombinerInfo &DCI,
424 const MipsSubtarget* Subtarget) {
425 if (DCI.isBeforeLegalizeOps())
428 EVT Ty = N->getValueType(0);
429 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
430 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
431 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
433 DebugLoc dl = N->getDebugLoc();
435 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
436 N->getOperand(0), N->getOperand(1));
437 SDValue InChain = DAG.getEntryNode();
438 SDValue InGlue = DivRem;
441 if (N->hasAnyUseOfValue(0)) {
442 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
444 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
445 InChain = CopyFromLo.getValue(1);
446 InGlue = CopyFromLo.getValue(2);
450 if (N->hasAnyUseOfValue(1)) {
451 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
453 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
459 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
461 default: llvm_unreachable("Unknown fp condition code!");
463 case ISD::SETOEQ: return Mips::FCOND_OEQ;
464 case ISD::SETUNE: return Mips::FCOND_UNE;
466 case ISD::SETOLT: return Mips::FCOND_OLT;
468 case ISD::SETOGT: return Mips::FCOND_OGT;
470 case ISD::SETOLE: return Mips::FCOND_OLE;
472 case ISD::SETOGE: return Mips::FCOND_OGE;
473 case ISD::SETULT: return Mips::FCOND_ULT;
474 case ISD::SETULE: return Mips::FCOND_ULE;
475 case ISD::SETUGT: return Mips::FCOND_UGT;
476 case ISD::SETUGE: return Mips::FCOND_UGE;
477 case ISD::SETUO: return Mips::FCOND_UN;
478 case ISD::SETO: return Mips::FCOND_OR;
480 case ISD::SETONE: return Mips::FCOND_ONE;
481 case ISD::SETUEQ: return Mips::FCOND_UEQ;
486 // Returns true if condition code has to be inverted.
487 static bool InvertFPCondCode(Mips::CondCode CC) {
488 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
491 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
492 "Illegal Condition Code");
497 // Creates and returns an FPCmp node from a setcc node.
498 // Returns Op if setcc is not a floating point comparison.
499 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
500 // must be a SETCC node
501 if (Op.getOpcode() != ISD::SETCC)
504 SDValue LHS = Op.getOperand(0);
506 if (!LHS.getValueType().isFloatingPoint())
509 SDValue RHS = Op.getOperand(1);
510 DebugLoc dl = Op.getDebugLoc();
512 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
513 // node if necessary.
514 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
516 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
517 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
520 // Creates and returns a CMovFPT/F node.
521 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
522 SDValue False, DebugLoc DL) {
523 bool invert = InvertFPCondCode((Mips::CondCode)
524 cast<ConstantSDNode>(Cond.getOperand(2))
527 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
528 True.getValueType(), True, False, Cond);
531 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
532 TargetLowering::DAGCombinerInfo &DCI,
533 const MipsSubtarget* Subtarget) {
534 if (DCI.isBeforeLegalizeOps())
537 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
539 if (Cond.getOpcode() != MipsISD::FPCmp)
542 SDValue True = DAG.getConstant(1, MVT::i32);
543 SDValue False = DAG.getConstant(0, MVT::i32);
545 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
548 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
549 TargetLowering::DAGCombinerInfo &DCI,
550 const MipsSubtarget* Subtarget) {
551 // Pattern match EXT.
552 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
553 // => ext $dst, $src, size, pos
554 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
557 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
558 unsigned ShiftRightOpc = ShiftRight.getOpcode();
560 // Op's first operand must be a shift right.
561 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
564 // The second operand of the shift must be an immediate.
566 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
569 uint64_t Pos = CN->getZExtValue();
570 uint64_t SMPos, SMSize;
572 // Op's second operand must be a shifted mask.
573 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
574 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
577 // Return if the shifted mask does not start at bit 0 or the sum of its size
578 // and Pos exceeds the word's size.
579 EVT ValTy = N->getValueType(0);
580 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
583 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
584 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
585 DAG.getConstant(SMSize, MVT::i32));
588 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
589 TargetLowering::DAGCombinerInfo &DCI,
590 const MipsSubtarget* Subtarget) {
591 // Pattern match INS.
592 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
593 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
594 // => ins $dst, $src, size, pos, $src1
595 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
598 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
599 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
602 // See if Op's first operand matches (and $src1 , mask0).
603 if (And0.getOpcode() != ISD::AND)
606 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
607 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
610 // See if Op's second operand matches (and (shl $src, pos), mask1).
611 if (And1.getOpcode() != ISD::AND)
614 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
615 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
618 // The shift masks must have the same position and size.
619 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
622 SDValue Shl = And1.getOperand(0);
623 if (Shl.getOpcode() != ISD::SHL)
626 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
629 unsigned Shamt = CN->getZExtValue();
631 // Return if the shift amount and the first bit position of mask are not the
633 EVT ValTy = N->getValueType(0);
634 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
637 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
638 DAG.getConstant(SMPos0, MVT::i32),
639 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
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 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
711 "Invalid CondCode.");
713 return Mips::BRANCH_F;
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)), BB->end());
1047 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1049 BB->addSuccessor(loopMBB);
1050 loopMBB->addSuccessor(loopMBB);
1051 loopMBB->addSuccessor(sinkMBB);
1052 sinkMBB->addSuccessor(exitMBB);
1055 // addiu masklsb2,$0,-4 # 0xfffffffc
1056 // and alignedaddr,ptr,masklsb2
1057 // andi ptrlsb2,ptr,3
1058 // sll shiftamt,ptrlsb2,3
1059 // ori maskupper,$0,255 # 0xff
1060 // sll mask,maskupper,shiftamt
1061 // nor mask2,$0,mask
1062 // sll incr2,incr,shiftamt
1064 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1065 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1066 .addReg(Mips::ZERO).addImm(-4);
1067 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1068 .addReg(Ptr).addReg(MaskLSB2);
1069 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1070 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1071 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1072 .addReg(Mips::ZERO).addImm(MaskImm);
1073 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1074 .addReg(ShiftAmt).addReg(MaskUpper);
1075 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1076 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1078 // atomic.load.binop
1080 // ll oldval,0(alignedaddr)
1081 // binop binopres,oldval,incr2
1082 // and newval,binopres,mask
1083 // and maskedoldval0,oldval,mask2
1084 // or storeval,maskedoldval0,newval
1085 // sc success,storeval,0(alignedaddr)
1086 // beq success,$0,loopMBB
1090 // ll oldval,0(alignedaddr)
1091 // and newval,incr2,mask
1092 // and maskedoldval0,oldval,mask2
1093 // or storeval,maskedoldval0,newval
1094 // sc success,storeval,0(alignedaddr)
1095 // beq success,$0,loopMBB
1098 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1100 // and andres, oldval, incr2
1101 // nor binopres, $0, andres
1102 // and newval, binopres, mask
1103 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1104 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1105 .addReg(Mips::ZERO).addReg(AndRes);
1106 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1107 } else if (BinOpcode) {
1108 // <binop> binopres, oldval, incr2
1109 // and newval, binopres, mask
1110 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1111 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1112 } else {// atomic.swap
1113 // and newval, incr2, mask
1114 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1117 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1118 .addReg(OldVal).addReg(Mask2);
1119 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1120 .addReg(MaskedOldVal0).addReg(NewVal);
1121 BuildMI(BB, dl, TII->get(SC), Success)
1122 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1123 BuildMI(BB, dl, TII->get(Mips::BEQ))
1124 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1127 // and maskedoldval1,oldval,mask
1128 // srl srlres,maskedoldval1,shiftamt
1129 // sll sllres,srlres,24
1130 // sra dest,sllres,24
1132 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1134 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1135 .addReg(OldVal).addReg(Mask);
1136 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1137 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1138 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1139 .addReg(SrlRes).addImm(ShiftImm);
1140 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1141 .addReg(SllRes).addImm(ShiftImm);
1143 MI->eraseFromParent(); // The instruction is gone now.
1149 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1150 MachineBasicBlock *BB,
1151 unsigned Size) const {
1152 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1154 MachineFunction *MF = BB->getParent();
1155 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1156 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1157 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1158 DebugLoc dl = MI->getDebugLoc();
1159 unsigned LL, SC, ZERO, BNE, BEQ;
1162 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1163 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1169 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1170 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1171 ZERO = Mips::ZERO_64;
1176 unsigned Dest = MI->getOperand(0).getReg();
1177 unsigned Ptr = MI->getOperand(1).getReg();
1178 unsigned OldVal = MI->getOperand(2).getReg();
1179 unsigned NewVal = MI->getOperand(3).getReg();
1181 unsigned Success = RegInfo.createVirtualRegister(RC);
1183 // insert new blocks after the current block
1184 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1185 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1186 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1187 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1188 MachineFunction::iterator It = BB;
1190 MF->insert(It, loop1MBB);
1191 MF->insert(It, loop2MBB);
1192 MF->insert(It, exitMBB);
1194 // Transfer the remainder of BB and its successor edges to exitMBB.
1195 exitMBB->splice(exitMBB->begin(), BB,
1196 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1197 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1201 // fallthrough --> loop1MBB
1202 BB->addSuccessor(loop1MBB);
1203 loop1MBB->addSuccessor(exitMBB);
1204 loop1MBB->addSuccessor(loop2MBB);
1205 loop2MBB->addSuccessor(loop1MBB);
1206 loop2MBB->addSuccessor(exitMBB);
1210 // bne dest, oldval, exitMBB
1212 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1213 BuildMI(BB, dl, TII->get(BNE))
1214 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1217 // sc success, newval, 0(ptr)
1218 // beq success, $0, loop1MBB
1220 BuildMI(BB, dl, TII->get(SC), Success)
1221 .addReg(NewVal).addReg(Ptr).addImm(0);
1222 BuildMI(BB, dl, TII->get(BEQ))
1223 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1225 MI->eraseFromParent(); // The instruction is gone now.
1231 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1232 MachineBasicBlock *BB,
1233 unsigned Size) const {
1234 assert((Size == 1 || Size == 2) &&
1235 "Unsupported size for EmitAtomicCmpSwapPartial.");
1237 MachineFunction *MF = BB->getParent();
1238 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1239 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1240 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1241 DebugLoc dl = MI->getDebugLoc();
1242 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1243 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1245 unsigned Dest = MI->getOperand(0).getReg();
1246 unsigned Ptr = MI->getOperand(1).getReg();
1247 unsigned CmpVal = MI->getOperand(2).getReg();
1248 unsigned NewVal = MI->getOperand(3).getReg();
1250 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1251 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1252 unsigned Mask = RegInfo.createVirtualRegister(RC);
1253 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1254 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1255 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1256 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1257 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1258 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1259 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1260 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1261 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1262 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1263 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1264 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1265 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1266 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1267 unsigned Success = RegInfo.createVirtualRegister(RC);
1269 // insert new blocks after the current block
1270 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1271 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1272 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1273 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1274 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1275 MachineFunction::iterator It = BB;
1277 MF->insert(It, loop1MBB);
1278 MF->insert(It, loop2MBB);
1279 MF->insert(It, sinkMBB);
1280 MF->insert(It, exitMBB);
1282 // Transfer the remainder of BB and its successor edges to exitMBB.
1283 exitMBB->splice(exitMBB->begin(), BB,
1284 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1285 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1287 BB->addSuccessor(loop1MBB);
1288 loop1MBB->addSuccessor(sinkMBB);
1289 loop1MBB->addSuccessor(loop2MBB);
1290 loop2MBB->addSuccessor(loop1MBB);
1291 loop2MBB->addSuccessor(sinkMBB);
1292 sinkMBB->addSuccessor(exitMBB);
1294 // FIXME: computation of newval2 can be moved to loop2MBB.
1296 // addiu masklsb2,$0,-4 # 0xfffffffc
1297 // and alignedaddr,ptr,masklsb2
1298 // andi ptrlsb2,ptr,3
1299 // sll shiftamt,ptrlsb2,3
1300 // ori maskupper,$0,255 # 0xff
1301 // sll mask,maskupper,shiftamt
1302 // nor mask2,$0,mask
1303 // andi maskedcmpval,cmpval,255
1304 // sll shiftedcmpval,maskedcmpval,shiftamt
1305 // andi maskednewval,newval,255
1306 // sll shiftednewval,maskednewval,shiftamt
1307 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1308 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1309 .addReg(Mips::ZERO).addImm(-4);
1310 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1311 .addReg(Ptr).addReg(MaskLSB2);
1312 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1313 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1314 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1315 .addReg(Mips::ZERO).addImm(MaskImm);
1316 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1317 .addReg(ShiftAmt).addReg(MaskUpper);
1318 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1319 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1320 .addReg(CmpVal).addImm(MaskImm);
1321 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1322 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1323 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1324 .addReg(NewVal).addImm(MaskImm);
1325 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1326 .addReg(ShiftAmt).addReg(MaskedNewVal);
1329 // ll oldval,0(alginedaddr)
1330 // and maskedoldval0,oldval,mask
1331 // bne maskedoldval0,shiftedcmpval,sinkMBB
1333 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1334 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1335 .addReg(OldVal).addReg(Mask);
1336 BuildMI(BB, dl, TII->get(Mips::BNE))
1337 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1340 // and maskedoldval1,oldval,mask2
1341 // or storeval,maskedoldval1,shiftednewval
1342 // sc success,storeval,0(alignedaddr)
1343 // beq success,$0,loop1MBB
1345 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1346 .addReg(OldVal).addReg(Mask2);
1347 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1348 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1349 BuildMI(BB, dl, TII->get(SC), Success)
1350 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1351 BuildMI(BB, dl, TII->get(Mips::BEQ))
1352 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1355 // srl srlres,maskedoldval0,shiftamt
1356 // sll sllres,srlres,24
1357 // sra dest,sllres,24
1359 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1361 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1362 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1363 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1364 .addReg(SrlRes).addImm(ShiftImm);
1365 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1366 .addReg(SllRes).addImm(ShiftImm);
1368 MI->eraseFromParent(); // The instruction is gone now.
1373 //===----------------------------------------------------------------------===//
1374 // Misc Lower Operation implementation
1375 //===----------------------------------------------------------------------===//
1376 SDValue MipsTargetLowering::
1377 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1379 MachineFunction &MF = DAG.getMachineFunction();
1380 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1381 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1383 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1384 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1385 "Cannot lower if the alignment of the allocated space is larger than \
1386 that of the stack.");
1388 SDValue Chain = Op.getOperand(0);
1389 SDValue Size = Op.getOperand(1);
1390 DebugLoc dl = Op.getDebugLoc();
1392 // Get a reference from Mips stack pointer
1393 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1395 // Subtract the dynamic size from the actual stack size to
1396 // obtain the new stack size.
1397 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1399 // The Sub result contains the new stack start address, so it
1400 // must be placed in the stack pointer register.
1401 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1403 // This node always has two return values: a new stack pointer
1404 // value and a chain
1405 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1406 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1407 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1409 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1412 SDValue MipsTargetLowering::
1413 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1415 // The first operand is the chain, the second is the condition, the third is
1416 // the block to branch to if the condition is true.
1417 SDValue Chain = Op.getOperand(0);
1418 SDValue Dest = Op.getOperand(2);
1419 DebugLoc dl = Op.getDebugLoc();
1421 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1423 // Return if flag is not set by a floating point comparison.
1424 if (CondRes.getOpcode() != MipsISD::FPCmp)
1427 SDValue CCNode = CondRes.getOperand(2);
1429 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1430 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1432 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1436 SDValue MipsTargetLowering::
1437 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1439 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1441 // Return if flag is not set by a floating point comparison.
1442 if (Cond.getOpcode() != MipsISD::FPCmp)
1445 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1449 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1450 SelectionDAG &DAG) const {
1451 // FIXME there isn't actually debug info here
1452 DebugLoc dl = Op.getDebugLoc();
1453 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1455 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1456 SDVTList VTs = DAG.getVTList(MVT::i32);
1458 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1460 // %gp_rel relocation
1461 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1462 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1464 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1465 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1466 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1468 // %hi/%lo relocation
1469 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1471 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1473 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1474 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1475 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1478 EVT ValTy = Op.getValueType();
1479 bool HasGotOfst = (GV->hasInternalLinkage() ||
1480 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1481 unsigned GotFlag = IsN64 ?
1482 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1483 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1484 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1485 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GA);
1486 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1487 MachinePointerInfo(), false, false, false, 0);
1488 // On functions and global targets not internal linked only
1489 // a load from got/GP is necessary for PIC to work.
1492 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1493 IsN64 ? MipsII::MO_GOT_OFST :
1495 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1496 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1499 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1500 SelectionDAG &DAG) const {
1501 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1502 // FIXME there isn't actually debug info here
1503 DebugLoc dl = Op.getDebugLoc();
1505 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1506 // %hi/%lo relocation
1507 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1508 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1509 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1510 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1511 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1514 EVT ValTy = Op.getValueType();
1515 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1516 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1517 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1518 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy, BAGOTOffset);
1519 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1520 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1521 MachinePointerInfo(), false, false, false, 0);
1522 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1523 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1526 SDValue MipsTargetLowering::
1527 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1529 // If the relocation model is PIC, use the General Dynamic TLS Model or
1530 // Local Dynamic TLS model, otherwise use the Initial Exec or
1531 // Local Exec TLS Model.
1533 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1534 DebugLoc dl = GA->getDebugLoc();
1535 const GlobalValue *GV = GA->getGlobal();
1536 EVT PtrVT = getPointerTy();
1538 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1539 // General Dynamic TLS Model
1540 bool LocalDynamic = GV->hasInternalLinkage();
1541 unsigned Flag = LocalDynamic ? MipsII::MO_TLSLDM :MipsII::MO_TLSGD;
1542 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1543 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1544 unsigned PtrSize = PtrVT.getSizeInBits();
1545 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1547 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1551 Entry.Node = Argument;
1553 Args.push_back(Entry);
1555 std::pair<SDValue, SDValue> CallResult =
1556 LowerCallTo(DAG.getEntryNode(), PtrTy,
1557 false, false, false, false, 0, CallingConv::C, false, true,
1558 TlsGetAddr, Args, DAG, dl);
1560 SDValue Ret = CallResult.first;
1565 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1566 MipsII::MO_DTPREL_HI);
1567 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1568 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1569 MipsII::MO_DTPREL_LO);
1570 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1571 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1572 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1576 if (GV->isDeclaration()) {
1577 // Initial Exec TLS Model
1578 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1579 MipsII::MO_GOTTPREL);
1580 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, TGA);
1581 Offset = DAG.getLoad(PtrVT, dl,
1582 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1583 false, false, false, 0);
1585 // Local Exec TLS Model
1586 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1587 MipsII::MO_TPREL_HI);
1588 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1589 MipsII::MO_TPREL_LO);
1590 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1591 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1592 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1595 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1596 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1599 SDValue MipsTargetLowering::
1600 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1602 SDValue HiPart, JTI, JTILo;
1603 // FIXME there isn't actually debug info here
1604 DebugLoc dl = Op.getDebugLoc();
1605 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1606 EVT PtrVT = Op.getValueType();
1607 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1609 if (!IsPIC && !IsN64) {
1610 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1611 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1612 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1613 } else {// Emit Load from Global Pointer
1614 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1615 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1616 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1617 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, JTI);
1618 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1619 MachinePointerInfo(), false, false, false, 0);
1620 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1623 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1624 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1627 SDValue MipsTargetLowering::
1628 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1631 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1632 const Constant *C = N->getConstVal();
1633 // FIXME there isn't actually debug info here
1634 DebugLoc dl = Op.getDebugLoc();
1636 // gp_rel relocation
1637 // FIXME: we should reference the constant pool using small data sections,
1638 // but the asm printer currently doesn't support this feature without
1639 // hacking it. This feature should come soon so we can uncomment the
1641 //if (IsInSmallSection(C->getType())) {
1642 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1643 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1644 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1646 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1647 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1648 N->getOffset(), MipsII::MO_ABS_HI);
1649 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1650 N->getOffset(), MipsII::MO_ABS_LO);
1651 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1652 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1653 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1655 EVT ValTy = Op.getValueType();
1656 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1657 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1658 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1659 N->getOffset(), GOTFlag);
1660 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, CP);
1661 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1662 MachinePointerInfo::getConstantPool(), false,
1664 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1665 N->getOffset(), OFSTFlag);
1666 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1667 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1673 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1674 MachineFunction &MF = DAG.getMachineFunction();
1675 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1677 DebugLoc dl = Op.getDebugLoc();
1678 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1681 // vastart just stores the address of the VarArgsFrameIndex slot into the
1682 // memory location argument.
1683 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1684 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1685 MachinePointerInfo(SV), false, false, 0);
1688 // Called if the size of integer registers is large enough to hold the whole
1689 // floating point number.
1690 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1691 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1692 EVT ValTy = Op.getValueType();
1693 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1694 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1695 DebugLoc dl = Op.getDebugLoc();
1696 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1697 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1698 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1699 DAG.getConstant(Mask - 1, IntValTy));
1700 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1701 DAG.getConstant(Mask, IntValTy));
1702 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1703 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1706 // Called if the size of integer registers is not large enough to hold the whole
1707 // floating point number (e.g. f64 & 32-bit integer register).
1709 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1711 // Use ext/ins instructions if target architecture is Mips32r2.
1712 // Eliminate redundant mfc1 and mtc1 instructions.
1713 unsigned LoIdx = 0, HiIdx = 1;
1716 std::swap(LoIdx, HiIdx);
1718 DebugLoc dl = Op.getDebugLoc();
1719 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1721 DAG.getConstant(LoIdx, MVT::i32));
1722 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1723 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1724 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1725 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1726 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1727 DAG.getConstant(0x7fffffff, MVT::i32));
1728 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1729 DAG.getConstant(0x80000000, MVT::i32));
1730 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1733 std::swap(Word0, Word1);
1735 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1739 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1740 EVT Ty = Op.getValueType();
1742 assert(Ty == MVT::f32 || Ty == MVT::f64);
1744 if (Ty == MVT::f32 || HasMips64)
1745 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1747 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1750 SDValue MipsTargetLowering::
1751 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1753 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1754 "Frame address can only be determined for current frame.");
1756 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1757 MFI->setFrameAddressIsTaken(true);
1758 EVT VT = Op.getValueType();
1759 DebugLoc dl = Op.getDebugLoc();
1760 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1761 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1765 // TODO: set SType according to the desired memory barrier behavior.
1767 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1769 DebugLoc dl = Op.getDebugLoc();
1770 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1771 DAG.getConstant(SType, MVT::i32));
1774 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1775 SelectionDAG& DAG) const {
1776 // FIXME: Need pseudo-fence for 'singlethread' fences
1777 // FIXME: Set SType for weaker fences where supported/appropriate.
1779 DebugLoc dl = Op.getDebugLoc();
1780 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1781 DAG.getConstant(SType, MVT::i32));
1784 //===----------------------------------------------------------------------===//
1785 // Calling Convention Implementation
1786 //===----------------------------------------------------------------------===//
1788 //===----------------------------------------------------------------------===//
1789 // TODO: Implement a generic logic using tblgen that can support this.
1790 // Mips O32 ABI rules:
1792 // i32 - Passed in A0, A1, A2, A3 and stack
1793 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1794 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1795 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1796 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1797 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1800 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1801 //===----------------------------------------------------------------------===//
1803 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1804 MVT LocVT, CCValAssign::LocInfo LocInfo,
1805 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1807 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1809 static const unsigned IntRegs[] = {
1810 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1812 static const unsigned F32Regs[] = {
1813 Mips::F12, Mips::F14
1815 static const unsigned F64Regs[] = {
1820 if (ArgFlags.isByVal()) {
1821 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1822 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1823 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1824 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1825 r < std::min(IntRegsSize, NextReg); ++r)
1826 State.AllocateReg(IntRegs[r]);
1830 // Promote i8 and i16
1831 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1833 if (ArgFlags.isSExt())
1834 LocInfo = CCValAssign::SExt;
1835 else if (ArgFlags.isZExt())
1836 LocInfo = CCValAssign::ZExt;
1838 LocInfo = CCValAssign::AExt;
1843 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1844 // is true: function is vararg, argument is 3rd or higher, there is previous
1845 // argument which is not f32 or f64.
1846 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1847 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1848 unsigned OrigAlign = ArgFlags.getOrigAlign();
1849 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1851 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1852 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1853 // If this is the first part of an i64 arg,
1854 // the allocated register must be either A0 or A2.
1855 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1856 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1858 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1859 // Allocate int register and shadow next int register. If first
1860 // available register is Mips::A1 or Mips::A3, shadow it too.
1861 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1862 if (Reg == Mips::A1 || Reg == Mips::A3)
1863 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1864 State.AllocateReg(IntRegs, IntRegsSize);
1866 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1867 // we are guaranteed to find an available float register
1868 if (ValVT == MVT::f32) {
1869 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1870 // Shadow int register
1871 State.AllocateReg(IntRegs, IntRegsSize);
1873 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1874 // Shadow int registers
1875 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1876 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1877 State.AllocateReg(IntRegs, IntRegsSize);
1878 State.AllocateReg(IntRegs, IntRegsSize);
1881 llvm_unreachable("Cannot handle this ValVT.");
1883 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1884 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1887 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1889 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1891 return false; // CC must always match
1894 static const unsigned Mips64IntRegs[8] =
1895 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1896 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1897 static const unsigned Mips64DPRegs[8] =
1898 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1899 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1901 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1902 CCValAssign::LocInfo LocInfo,
1903 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1904 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1905 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1906 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1908 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1910 // If byval is 16-byte aligned, the first arg register must be even.
1911 if ((Align == 16) && (FirstIdx % 2)) {
1912 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1916 // Mark the registers allocated.
1917 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1918 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1920 // Allocate space on caller's stack.
1921 unsigned Offset = State.AllocateStack(Size, Align);
1924 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1927 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1932 #include "MipsGenCallingConv.inc"
1935 AnalyzeMips64CallOperands(CCState CCInfo,
1936 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1937 unsigned NumOps = Outs.size();
1938 for (unsigned i = 0; i != NumOps; ++i) {
1939 MVT ArgVT = Outs[i].VT;
1940 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1943 if (Outs[i].IsFixed)
1944 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1946 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1950 dbgs() << "Call operand #" << i << " has unhandled type "
1951 << EVT(ArgVT).getEVTString();
1953 llvm_unreachable(0);
1958 //===----------------------------------------------------------------------===//
1959 // Call Calling Convention Implementation
1960 //===----------------------------------------------------------------------===//
1962 static const unsigned O32IntRegsSize = 4;
1964 static const unsigned O32IntRegs[] = {
1965 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1968 // Return next O32 integer argument register.
1969 static unsigned getNextIntArgReg(unsigned Reg) {
1970 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1971 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1974 // Write ByVal Arg to arg registers and stack.
1976 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1977 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1978 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1979 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1980 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1981 MVT PtrType, bool isLittle) {
1982 unsigned LocMemOffset = VA.getLocMemOffset();
1983 unsigned Offset = 0;
1984 uint32_t RemainingSize = Flags.getByValSize();
1985 unsigned ByValAlign = Flags.getByValAlign();
1987 // Copy the first 4 words of byval arg to registers A0 - A3.
1988 // FIXME: Use a stricter alignment if it enables better optimization in passes
1990 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1991 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1992 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1993 DAG.getConstant(Offset, MVT::i32));
1994 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1995 MachinePointerInfo(), false, false, false,
1996 std::min(ByValAlign, (unsigned )4));
1997 MemOpChains.push_back(LoadVal.getValue(1));
1998 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1999 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2002 if (RemainingSize == 0)
2005 // If there still is a register available for argument passing, write the
2006 // remaining part of the structure to it using subword loads and shifts.
2007 if (LocMemOffset < 4 * 4) {
2008 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2009 "There must be one to three bytes remaining.");
2010 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2011 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2012 DAG.getConstant(Offset, MVT::i32));
2013 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2014 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2015 LoadPtr, MachinePointerInfo(),
2016 MVT::getIntegerVT(LoadSize * 8), false,
2018 MemOpChains.push_back(LoadVal.getValue(1));
2020 // If target is big endian, shift it to the most significant half-word or
2023 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2024 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2027 RemainingSize -= LoadSize;
2029 // Read second subword if necessary.
2030 if (RemainingSize != 0) {
2031 assert(RemainingSize == 1 && "There must be one byte remaining.");
2032 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2033 DAG.getConstant(Offset, MVT::i32));
2034 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2035 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2036 LoadPtr, MachinePointerInfo(),
2037 MVT::i8, false, false, Alignment);
2038 MemOpChains.push_back(Subword.getValue(1));
2039 // Insert the loaded byte to LoadVal.
2040 // FIXME: Use INS if supported by target.
2041 unsigned ShiftAmt = isLittle ? 16 : 8;
2042 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2043 DAG.getConstant(ShiftAmt, MVT::i32));
2044 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2047 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2048 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2052 // Create a fixed object on stack at offset LocMemOffset and copy
2053 // remaining part of byval arg to it using memcpy.
2054 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2055 DAG.getConstant(Offset, MVT::i32));
2056 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2057 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2058 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2059 DAG.getConstant(RemainingSize, MVT::i32),
2060 std::min(ByValAlign, (unsigned)4),
2061 /*isVolatile=*/false, /*AlwaysInline=*/false,
2062 MachinePointerInfo(0), MachinePointerInfo(0));
2065 // Copy Mips64 byVal arg to registers and stack.
2067 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2068 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2069 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2070 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2071 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2072 EVT PtrTy, bool isLittle) {
2073 unsigned ByValSize = Flags.getByValSize();
2074 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2075 bool IsRegLoc = VA.isRegLoc();
2076 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2077 unsigned LocMemOffset = 0;
2078 unsigned MemCpySize = ByValSize;
2081 LocMemOffset = VA.getLocMemOffset();
2083 const unsigned *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2085 const unsigned *RegEnd = Mips64IntRegs + 8;
2087 // Copy double words to registers.
2088 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2089 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2090 DAG.getConstant(Offset, PtrTy));
2091 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2092 MachinePointerInfo(), false, false, false,
2094 MemOpChains.push_back(LoadVal.getValue(1));
2095 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2098 // Return if the struct has been fully copied.
2099 if (!(MemCpySize = ByValSize - Offset))
2102 // If there is an argument register available, copy the remainder of the
2103 // byval argument with sub-doubleword loads and shifts.
2104 if (Reg != RegEnd) {
2105 assert((ByValSize < Offset + 8) &&
2106 "Size of the remainder should be smaller than 8-byte.");
2108 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2109 unsigned RemSize = ByValSize - Offset;
2111 if (RemSize < LoadSize)
2114 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2115 DAG.getConstant(Offset, PtrTy));
2117 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2118 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2119 false, false, Alignment);
2120 MemOpChains.push_back(LoadVal.getValue(1));
2122 // Offset in number of bits from double word boundary.
2123 unsigned OffsetDW = (Offset % 8) * 8;
2124 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2125 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2126 DAG.getConstant(Shamt, MVT::i32));
2128 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2131 Alignment = std::min(Alignment, LoadSize);
2134 RegsToPass.push_back(std::make_pair(*Reg, Val));
2139 assert(MemCpySize && "MemCpySize must not be zero.");
2141 // Create a fixed object on stack at offset LocMemOffset and copy
2142 // remainder of byval arg to it with memcpy.
2143 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2144 DAG.getConstant(Offset, PtrTy));
2145 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2146 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2147 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2148 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2149 /*isVolatile=*/false, /*AlwaysInline=*/false,
2150 MachinePointerInfo(0), MachinePointerInfo(0));
2153 /// LowerCall - functions arguments are copied from virtual regs to
2154 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2155 /// TODO: isTailCall.
2157 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
2158 CallingConv::ID CallConv, bool isVarArg,
2160 const SmallVectorImpl<ISD::OutputArg> &Outs,
2161 const SmallVectorImpl<SDValue> &OutVals,
2162 const SmallVectorImpl<ISD::InputArg> &Ins,
2163 DebugLoc dl, SelectionDAG &DAG,
2164 SmallVectorImpl<SDValue> &InVals) const {
2165 // MIPs target does not yet support tail call optimization.
2168 MachineFunction &MF = DAG.getMachineFunction();
2169 MachineFrameInfo *MFI = MF.getFrameInfo();
2170 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2171 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2172 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2174 // Analyze operands of the call, assigning locations to each operand.
2175 SmallVector<CCValAssign, 16> ArgLocs;
2176 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2177 getTargetMachine(), ArgLocs, *DAG.getContext());
2180 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2182 AnalyzeMips64CallOperands(CCInfo, Outs);
2184 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2186 // Get a count of how many bytes are to be pushed on the stack.
2187 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2189 // Chain is the output chain of the last Load/Store or CopyToReg node.
2190 // ByValChain is the output chain of the last Memcpy node created for copying
2191 // byval arguments to the stack.
2192 SDValue Chain, CallSeqStart, ByValChain;
2193 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2194 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2195 ByValChain = InChain;
2197 // If this is the first call, create a stack frame object that points to
2198 // a location to which .cprestore saves $gp.
2199 if (IsO32 && IsPIC && !MipsFI->getGPFI())
2200 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
2202 // Get the frame index of the stack frame object that points to the location
2203 // of dynamically allocated area on the stack.
2204 int DynAllocFI = MipsFI->getDynAllocFI();
2206 // Update size of the maximum argument space.
2207 // For O32, a minimum of four words (16 bytes) of argument space is
2210 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2212 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2214 if (MaxCallFrameSize < NextStackOffset) {
2215 MipsFI->setMaxCallFrameSize(NextStackOffset);
2217 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2218 // allocated stack space. These offsets must be aligned to a boundary
2219 // determined by the stack alignment of the ABI.
2220 unsigned StackAlignment = TFL->getStackAlignment();
2221 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2222 StackAlignment * StackAlignment;
2224 if (MipsFI->needGPSaveRestore())
2225 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
2227 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2230 // With EABI is it possible to have 16 args on registers.
2231 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2232 SmallVector<SDValue, 8> MemOpChains;
2234 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2236 // Walk the register/memloc assignments, inserting copies/loads.
2237 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2238 SDValue Arg = OutVals[i];
2239 CCValAssign &VA = ArgLocs[i];
2240 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2241 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2244 if (Flags.isByVal()) {
2245 assert(Flags.getByValSize() &&
2246 "ByVal args of size 0 should have been ignored by front-end.");
2248 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2249 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2250 Subtarget->isLittle());
2252 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2253 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2254 Subtarget->isLittle());
2258 // Promote the value if needed.
2259 switch (VA.getLocInfo()) {
2260 default: llvm_unreachable("Unknown loc info!");
2261 case CCValAssign::Full:
2262 if (VA.isRegLoc()) {
2263 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2264 (ValVT == MVT::f64 && LocVT == MVT::i64))
2265 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2266 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2267 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2268 Arg, DAG.getConstant(0, MVT::i32));
2269 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2270 Arg, DAG.getConstant(1, MVT::i32));
2271 if (!Subtarget->isLittle())
2273 unsigned LocRegLo = VA.getLocReg();
2274 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2275 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2276 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2281 case CCValAssign::SExt:
2282 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2284 case CCValAssign::ZExt:
2285 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2287 case CCValAssign::AExt:
2288 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2292 // Arguments that can be passed on register must be kept at
2293 // RegsToPass vector
2294 if (VA.isRegLoc()) {
2295 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2299 // Register can't get to this point...
2300 assert(VA.isMemLoc());
2302 // Create the frame index object for this incoming parameter
2303 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2304 VA.getLocMemOffset(), true);
2305 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2307 // emit ISD::STORE whichs stores the
2308 // parameter value to a stack Location
2309 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2310 MachinePointerInfo(), false, false, 0));
2313 // Extend range of indices of frame objects for outgoing arguments that were
2314 // created during this function call. Skip this step if no such objects were
2317 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2319 // If a memcpy has been created to copy a byval arg to a stack, replace the
2320 // chain input of CallSeqStart with ByValChain.
2321 if (InChain != ByValChain)
2322 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2323 NextStackOffsetVal);
2325 // Transform all store nodes into one single node because all store
2326 // nodes are independent of each other.
2327 if (!MemOpChains.empty())
2328 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2329 &MemOpChains[0], MemOpChains.size());
2331 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2332 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2333 // node so that legalize doesn't hack it.
2334 unsigned char OpFlag;
2335 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2336 bool GlobalOrExternal = false;
2339 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2340 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2341 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2342 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2343 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2345 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2348 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2349 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2350 getPointerTy(), 0, OpFlag);
2353 GlobalOrExternal = true;
2355 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2356 if (IsN64 || (!IsO32 && IsPIC))
2357 OpFlag = MipsII::MO_GOT_DISP;
2358 else if (!IsPIC) // !N64 && static
2359 OpFlag = MipsII::MO_NO_FLAG;
2361 OpFlag = MipsII::MO_GOT_CALL;
2362 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2364 GlobalOrExternal = true;
2369 // Create nodes that load address of callee and copy it to T9
2371 if (GlobalOrExternal) {
2372 // Load callee address
2373 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(), Callee);
2374 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2375 Callee, MachinePointerInfo::getGOT(),
2376 false, false, false, 0);
2378 // Use GOT+LO if callee has internal linkage.
2379 if (CalleeLo.getNode()) {
2380 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2381 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2387 // T9 should contain the address of the callee function if
2388 // -reloction-model=pic or it is an indirect call.
2389 if (IsPICCall || !GlobalOrExternal) {
2391 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2392 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2393 InFlag = Chain.getValue(1);
2394 Callee = DAG.getRegister(T9Reg, getPointerTy());
2397 // Build a sequence of copy-to-reg nodes chained together with token
2398 // chain and flag operands which copy the outgoing args into registers.
2399 // The InFlag in necessary since all emitted instructions must be
2401 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2402 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2403 RegsToPass[i].second, InFlag);
2404 InFlag = Chain.getValue(1);
2407 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2408 // = Chain, Callee, Reg#1, Reg#2, ...
2410 // Returns a chain & a flag for retval copy to use.
2411 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2412 SmallVector<SDValue, 8> Ops;
2413 Ops.push_back(Chain);
2414 Ops.push_back(Callee);
2416 // Add argument registers to the end of the list so that they are
2417 // known live into the call.
2418 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2419 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2420 RegsToPass[i].second.getValueType()));
2422 if (InFlag.getNode())
2423 Ops.push_back(InFlag);
2425 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2426 InFlag = Chain.getValue(1);
2428 // Create the CALLSEQ_END node.
2429 Chain = DAG.getCALLSEQ_END(Chain,
2430 DAG.getIntPtrConstant(NextStackOffset, true),
2431 DAG.getIntPtrConstant(0, true), InFlag);
2432 InFlag = Chain.getValue(1);
2434 // Handle result values, copying them out of physregs into vregs that we
2436 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2437 Ins, dl, DAG, InVals);
2440 /// LowerCallResult - Lower the result values of a call into the
2441 /// appropriate copies out of appropriate physical registers.
2443 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2444 CallingConv::ID CallConv, bool isVarArg,
2445 const SmallVectorImpl<ISD::InputArg> &Ins,
2446 DebugLoc dl, SelectionDAG &DAG,
2447 SmallVectorImpl<SDValue> &InVals) const {
2448 // Assign locations to each value returned by this call.
2449 SmallVector<CCValAssign, 16> RVLocs;
2450 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2451 getTargetMachine(), RVLocs, *DAG.getContext());
2453 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2455 // Copy all of the result registers out of their specified physreg.
2456 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2457 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2458 RVLocs[i].getValVT(), InFlag).getValue(1);
2459 InFlag = Chain.getValue(2);
2460 InVals.push_back(Chain.getValue(0));
2466 //===----------------------------------------------------------------------===//
2467 // Formal Arguments Calling Convention Implementation
2468 //===----------------------------------------------------------------------===//
2469 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2470 std::vector<SDValue>& OutChains,
2471 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2472 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2473 unsigned LocMem = VA.getLocMemOffset();
2474 unsigned FirstWord = LocMem / 4;
2476 // copy register A0 - A3 to frame object
2477 for (unsigned i = 0; i < NumWords; ++i) {
2478 unsigned CurWord = FirstWord + i;
2479 if (CurWord >= O32IntRegsSize)
2482 unsigned SrcReg = O32IntRegs[CurWord];
2483 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2484 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2485 DAG.getConstant(i * 4, MVT::i32));
2486 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2487 StorePtr, MachinePointerInfo(), false,
2489 OutChains.push_back(Store);
2493 // Create frame object on stack and copy registers used for byval passing to it.
2495 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2496 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2497 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2498 MachineFrameInfo *MFI, bool IsRegLoc,
2499 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2501 const unsigned *Reg = Mips64IntRegs + 8;
2502 int FOOffset; // Frame object offset from virtual frame pointer.
2505 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2506 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2509 FOOffset = VA.getLocMemOffset();
2511 // Create frame object.
2512 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2513 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2514 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2515 InVals.push_back(FIN);
2517 // Copy arg registers.
2518 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2520 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2521 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2522 DAG.getConstant(I * 8, PtrTy));
2523 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2524 StorePtr, MachinePointerInfo(), false,
2526 OutChains.push_back(Store);
2532 /// LowerFormalArguments - transform physical registers into virtual registers
2533 /// and generate load operations for arguments places on the stack.
2535 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2536 CallingConv::ID CallConv,
2538 const SmallVectorImpl<ISD::InputArg> &Ins,
2539 DebugLoc dl, SelectionDAG &DAG,
2540 SmallVectorImpl<SDValue> &InVals)
2542 MachineFunction &MF = DAG.getMachineFunction();
2543 MachineFrameInfo *MFI = MF.getFrameInfo();
2544 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2546 MipsFI->setVarArgsFrameIndex(0);
2548 // Used with vargs to acumulate store chains.
2549 std::vector<SDValue> OutChains;
2551 // Assign locations to all of the incoming arguments.
2552 SmallVector<CCValAssign, 16> ArgLocs;
2553 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2554 getTargetMachine(), ArgLocs, *DAG.getContext());
2557 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2559 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2561 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2563 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2564 CCValAssign &VA = ArgLocs[i];
2565 EVT ValVT = VA.getValVT();
2566 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2567 bool IsRegLoc = VA.isRegLoc();
2569 if (Flags.isByVal()) {
2570 assert(Flags.getByValSize() &&
2571 "ByVal args of size 0 should have been ignored by front-end.");
2573 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2574 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2576 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2577 InVals.push_back(FIN);
2578 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2580 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2581 MFI, IsRegLoc, InVals, MipsFI,
2586 // Arguments stored on registers
2588 EVT RegVT = VA.getLocVT();
2589 unsigned ArgReg = VA.getLocReg();
2590 TargetRegisterClass *RC = 0;
2592 if (RegVT == MVT::i32)
2593 RC = Mips::CPURegsRegisterClass;
2594 else if (RegVT == MVT::i64)
2595 RC = Mips::CPU64RegsRegisterClass;
2596 else if (RegVT == MVT::f32)
2597 RC = Mips::FGR32RegisterClass;
2598 else if (RegVT == MVT::f64)
2599 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2601 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2603 // Transform the arguments stored on
2604 // physical registers into virtual ones
2605 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2606 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2608 // If this is an 8 or 16-bit value, it has been passed promoted
2609 // to 32 bits. Insert an assert[sz]ext to capture this, then
2610 // truncate to the right size.
2611 if (VA.getLocInfo() != CCValAssign::Full) {
2612 unsigned Opcode = 0;
2613 if (VA.getLocInfo() == CCValAssign::SExt)
2614 Opcode = ISD::AssertSext;
2615 else if (VA.getLocInfo() == CCValAssign::ZExt)
2616 Opcode = ISD::AssertZext;
2618 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2619 DAG.getValueType(ValVT));
2620 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2623 // Handle floating point arguments passed in integer registers.
2624 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2625 (RegVT == MVT::i64 && ValVT == MVT::f64))
2626 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2627 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2628 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2629 getNextIntArgReg(ArgReg), RC);
2630 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2631 if (!Subtarget->isLittle())
2632 std::swap(ArgValue, ArgValue2);
2633 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2634 ArgValue, ArgValue2);
2637 InVals.push_back(ArgValue);
2638 } else { // VA.isRegLoc()
2641 assert(VA.isMemLoc());
2643 // The stack pointer offset is relative to the caller stack frame.
2644 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2645 VA.getLocMemOffset(), true);
2647 // Create load nodes to retrieve arguments from the stack
2648 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2649 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2650 MachinePointerInfo::getFixedStack(LastFI),
2651 false, false, false, 0));
2655 // The mips ABIs for returning structs by value requires that we copy
2656 // the sret argument into $v0 for the return. Save the argument into
2657 // a virtual register so that we can access it from the return points.
2658 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2659 unsigned Reg = MipsFI->getSRetReturnReg();
2661 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2662 MipsFI->setSRetReturnReg(Reg);
2664 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2665 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2669 unsigned NumOfRegs = IsO32 ? 4 : 8;
2670 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2671 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2672 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2673 TargetRegisterClass *RC
2674 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2675 unsigned RegSize = RC->getSize();
2676 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2678 // Offset of the first variable argument from stack pointer.
2679 int FirstVaArgOffset;
2681 if (IsO32 || (Idx == NumOfRegs)) {
2683 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2685 FirstVaArgOffset = RegSlotOffset;
2687 // Record the frame index of the first variable argument
2688 // which is a value necessary to VASTART.
2689 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2690 MipsFI->setVarArgsFrameIndex(LastFI);
2692 // Copy the integer registers that have not been used for argument passing
2693 // to the argument register save area. For O32, the save area is allocated
2694 // in the caller's stack frame, while for N32/64, it is allocated in the
2695 // callee's stack frame.
2696 for (int StackOffset = RegSlotOffset;
2697 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2698 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2699 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2700 MVT::getIntegerVT(RegSize * 8));
2701 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2702 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2703 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2704 MachinePointerInfo(), false, false, 0));
2708 MipsFI->setLastInArgFI(LastFI);
2710 // All stores are grouped in one node to allow the matching between
2711 // the size of Ins and InVals. This only happens when on varg functions
2712 if (!OutChains.empty()) {
2713 OutChains.push_back(Chain);
2714 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2715 &OutChains[0], OutChains.size());
2721 //===----------------------------------------------------------------------===//
2722 // Return Value Calling Convention Implementation
2723 //===----------------------------------------------------------------------===//
2726 MipsTargetLowering::LowerReturn(SDValue Chain,
2727 CallingConv::ID CallConv, bool isVarArg,
2728 const SmallVectorImpl<ISD::OutputArg> &Outs,
2729 const SmallVectorImpl<SDValue> &OutVals,
2730 DebugLoc dl, SelectionDAG &DAG) const {
2732 // CCValAssign - represent the assignment of
2733 // the return value to a location
2734 SmallVector<CCValAssign, 16> RVLocs;
2736 // CCState - Info about the registers and stack slot.
2737 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2738 getTargetMachine(), RVLocs, *DAG.getContext());
2740 // Analize return values.
2741 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2743 // If this is the first return lowered for this function, add
2744 // the regs to the liveout set for the function.
2745 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2746 for (unsigned i = 0; i != RVLocs.size(); ++i)
2747 if (RVLocs[i].isRegLoc())
2748 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2753 // Copy the result values into the output registers.
2754 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2755 CCValAssign &VA = RVLocs[i];
2756 assert(VA.isRegLoc() && "Can only return in registers!");
2758 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
2760 // guarantee that all emitted copies are
2761 // stuck together, avoiding something bad
2762 Flag = Chain.getValue(1);
2765 // The mips ABIs for returning structs by value requires that we copy
2766 // the sret argument into $v0 for the return. We saved the argument into
2767 // a virtual register in the entry block, so now we copy the value out
2769 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2770 MachineFunction &MF = DAG.getMachineFunction();
2771 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2772 unsigned Reg = MipsFI->getSRetReturnReg();
2775 llvm_unreachable("sret virtual register not created in the entry block");
2776 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2778 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2779 Flag = Chain.getValue(1);
2782 // Return on Mips is always a "jr $ra"
2784 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2785 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2787 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2788 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2791 //===----------------------------------------------------------------------===//
2792 // Mips Inline Assembly Support
2793 //===----------------------------------------------------------------------===//
2795 /// getConstraintType - Given a constraint letter, return the type of
2796 /// constraint it is for this target.
2797 MipsTargetLowering::ConstraintType MipsTargetLowering::
2798 getConstraintType(const std::string &Constraint) const
2800 // Mips specific constrainy
2801 // GCC config/mips/constraints.md
2803 // 'd' : An address register. Equivalent to r
2804 // unless generating MIPS16 code.
2805 // 'y' : Equivalent to r; retained for
2806 // backwards compatibility.
2807 // 'f' : Floating Point registers.
2808 if (Constraint.size() == 1) {
2809 switch (Constraint[0]) {
2814 return C_RegisterClass;
2818 return TargetLowering::getConstraintType(Constraint);
2821 /// Examine constraint type and operand type and determine a weight value.
2822 /// This object must already have been set up with the operand type
2823 /// and the current alternative constraint selected.
2824 TargetLowering::ConstraintWeight
2825 MipsTargetLowering::getSingleConstraintMatchWeight(
2826 AsmOperandInfo &info, const char *constraint) const {
2827 ConstraintWeight weight = CW_Invalid;
2828 Value *CallOperandVal = info.CallOperandVal;
2829 // If we don't have a value, we can't do a match,
2830 // but allow it at the lowest weight.
2831 if (CallOperandVal == NULL)
2833 Type *type = CallOperandVal->getType();
2834 // Look at the constraint type.
2835 switch (*constraint) {
2837 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2841 if (type->isIntegerTy())
2842 weight = CW_Register;
2845 if (type->isFloatTy())
2846 weight = CW_Register;
2852 /// Given a register class constraint, like 'r', if this corresponds directly
2853 /// to an LLVM register class, return a register of 0 and the register class
2855 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2856 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2858 if (Constraint.size() == 1) {
2859 switch (Constraint[0]) {
2860 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2861 case 'y': // Same as 'r'. Exists for compatibility.
2863 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2866 return std::make_pair(0U, Mips::FGR32RegisterClass);
2868 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2869 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2873 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2877 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2878 // The Mips target isn't yet aware of offsets.
2882 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2883 if (VT != MVT::f32 && VT != MVT::f64)
2885 if (Imm.isNegZero())
2887 return Imm.isZero();