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::TlsGd: return "MipsISD::TlsGd";
58 case MipsISD::TprelHi: return "MipsISD::TprelHi";
59 case MipsISD::TprelLo: return "MipsISD::TprelLo";
60 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
61 case MipsISD::Ret: return "MipsISD::Ret";
62 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
63 case MipsISD::FPCmp: return "MipsISD::FPCmp";
64 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
65 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
66 case MipsISD::FPRound: return "MipsISD::FPRound";
67 case MipsISD::MAdd: return "MipsISD::MAdd";
68 case MipsISD::MAddu: return "MipsISD::MAddu";
69 case MipsISD::MSub: return "MipsISD::MSub";
70 case MipsISD::MSubu: return "MipsISD::MSubu";
71 case MipsISD::DivRem: return "MipsISD::DivRem";
72 case MipsISD::DivRemU: return "MipsISD::DivRemU";
73 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
74 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
75 case MipsISD::WrapperPIC: return "MipsISD::WrapperPIC";
76 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
77 case MipsISD::Sync: return "MipsISD::Sync";
78 case MipsISD::Ext: return "MipsISD::Ext";
79 case MipsISD::Ins: return "MipsISD::Ins";
85 MipsTargetLowering(MipsTargetMachine &TM)
86 : TargetLowering(TM, new MipsTargetObjectFile()),
87 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
88 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
89 IsO32(Subtarget->isABI_O32()) {
91 // Mips does not have i1 type, so use i32 for
92 // setcc operations results (slt, sgt, ...).
93 setBooleanContents(ZeroOrOneBooleanContent);
94 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
96 // Set up the register classes
97 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
98 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
101 addRegisterClass(MVT::i64, Mips::CPU64RegsRegisterClass);
103 // When dealing with single precision only, use libcalls
104 if (!Subtarget->isSingleFloat()) {
106 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
108 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
111 // Load extented operations for i1 types must be promoted
112 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
113 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
114 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
116 // MIPS doesn't have extending float->double load/store
117 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
118 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
120 // Used by legalize types to correctly generate the setcc result.
121 // Without this, every float setcc comes with a AND/OR with the result,
122 // we don't want this, since the fpcmp result goes to a flag register,
123 // which is used implicitly by brcond and select operations.
124 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
126 // Mips Custom Operations
127 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
128 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
129 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
130 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
131 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
132 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
133 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
134 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
135 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
136 setOperationAction(ISD::SELECT, MVT::f32, Custom);
137 setOperationAction(ISD::SELECT, MVT::f64, Custom);
138 setOperationAction(ISD::SELECT, MVT::i32, Custom);
139 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
140 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
141 setOperationAction(ISD::VASTART, MVT::Other, Custom);
143 setOperationAction(ISD::SDIV, MVT::i32, Expand);
144 setOperationAction(ISD::SREM, MVT::i32, Expand);
145 setOperationAction(ISD::UDIV, MVT::i32, Expand);
146 setOperationAction(ISD::UREM, MVT::i32, Expand);
147 setOperationAction(ISD::SDIV, MVT::i64, Expand);
148 setOperationAction(ISD::SREM, MVT::i64, Expand);
149 setOperationAction(ISD::UDIV, MVT::i64, Expand);
150 setOperationAction(ISD::UREM, MVT::i64, Expand);
152 // Operations not directly supported by Mips.
153 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
154 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
155 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
156 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
157 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
158 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
159 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
160 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
161 setOperationAction(ISD::ROTL, MVT::i32, Expand);
162 setOperationAction(ISD::ROTL, MVT::i64, Expand);
164 if (!Subtarget->hasMips32r2())
165 setOperationAction(ISD::ROTR, MVT::i32, Expand);
167 if (!Subtarget->hasMips64r2())
168 setOperationAction(ISD::ROTR, MVT::i64, Expand);
170 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
171 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
172 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
173 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
174 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
175 setOperationAction(ISD::FSIN, MVT::f32, Expand);
176 setOperationAction(ISD::FSIN, MVT::f64, Expand);
177 setOperationAction(ISD::FCOS, MVT::f32, Expand);
178 setOperationAction(ISD::FCOS, MVT::f64, Expand);
179 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
180 setOperationAction(ISD::FPOW, MVT::f32, Expand);
181 setOperationAction(ISD::FPOW, MVT::f64, Expand);
182 setOperationAction(ISD::FLOG, MVT::f32, Expand);
183 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
184 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
185 setOperationAction(ISD::FEXP, MVT::f32, Expand);
186 setOperationAction(ISD::FMA, MVT::f32, Expand);
187 setOperationAction(ISD::FMA, MVT::f64, Expand);
189 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
190 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
192 setOperationAction(ISD::VAARG, MVT::Other, Expand);
193 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
194 setOperationAction(ISD::VAEND, MVT::Other, Expand);
196 // Use the default for now
197 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
198 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
200 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
201 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
203 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
204 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
206 setInsertFencesForAtomic(true);
208 if (Subtarget->isSingleFloat())
209 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
211 if (!Subtarget->hasSEInReg()) {
212 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
213 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
216 if (!Subtarget->hasBitCount())
217 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
219 if (!Subtarget->hasSwap())
220 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
222 setTargetDAGCombine(ISD::ADDE);
223 setTargetDAGCombine(ISD::SUBE);
224 setTargetDAGCombine(ISD::SDIVREM);
225 setTargetDAGCombine(ISD::UDIVREM);
226 setTargetDAGCombine(ISD::SETCC);
227 setTargetDAGCombine(ISD::AND);
228 setTargetDAGCombine(ISD::OR);
230 setMinFunctionAlignment(2);
232 setStackPointerRegisterToSaveRestore(Mips::SP);
233 computeRegisterProperties();
235 setExceptionPointerRegister(Mips::A0);
236 setExceptionSelectorRegister(Mips::A1);
239 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
240 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
241 return SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16;
244 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
249 // Transforms a subgraph in CurDAG if the following pattern is found:
250 // (addc multLo, Lo0), (adde multHi, Hi0),
252 // multHi/Lo: product of multiplication
253 // Lo0: initial value of Lo register
254 // Hi0: initial value of Hi register
255 // Return true if pattern matching was successful.
256 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
257 // ADDENode's second operand must be a flag output of an ADDC node in order
258 // for the matching to be successful.
259 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
261 if (ADDCNode->getOpcode() != ISD::ADDC)
264 SDValue MultHi = ADDENode->getOperand(0);
265 SDValue MultLo = ADDCNode->getOperand(0);
266 SDNode* MultNode = MultHi.getNode();
267 unsigned MultOpc = MultHi.getOpcode();
269 // MultHi and MultLo must be generated by the same node,
270 if (MultLo.getNode() != MultNode)
273 // and it must be a multiplication.
274 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
277 // MultLo amd MultHi must be the first and second output of MultNode
279 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
282 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
283 // of the values of MultNode, in which case MultNode will be removed in later
285 // If there exist users other than ADDENode or ADDCNode, this function returns
286 // here, which will result in MultNode being mapped to a single MULT
287 // instruction node rather than a pair of MULT and MADD instructions being
289 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
292 SDValue Chain = CurDAG->getEntryNode();
293 DebugLoc dl = ADDENode->getDebugLoc();
295 // create MipsMAdd(u) node
296 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
298 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
300 MultNode->getOperand(0),// Factor 0
301 MultNode->getOperand(1),// Factor 1
302 ADDCNode->getOperand(1),// Lo0
303 ADDENode->getOperand(1));// Hi0
305 // create CopyFromReg nodes
306 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
308 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
310 CopyFromLo.getValue(2));
312 // replace uses of adde and addc here
313 if (!SDValue(ADDCNode, 0).use_empty())
314 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
316 if (!SDValue(ADDENode, 0).use_empty())
317 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
323 // Transforms a subgraph in CurDAG if the following pattern is found:
324 // (addc Lo0, multLo), (sube Hi0, multHi),
326 // multHi/Lo: product of multiplication
327 // Lo0: initial value of Lo register
328 // Hi0: initial value of Hi register
329 // Return true if pattern matching was successful.
330 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
331 // SUBENode's second operand must be a flag output of an SUBC node in order
332 // for the matching to be successful.
333 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
335 if (SUBCNode->getOpcode() != ISD::SUBC)
338 SDValue MultHi = SUBENode->getOperand(1);
339 SDValue MultLo = SUBCNode->getOperand(1);
340 SDNode* MultNode = MultHi.getNode();
341 unsigned MultOpc = MultHi.getOpcode();
343 // MultHi and MultLo must be generated by the same node,
344 if (MultLo.getNode() != MultNode)
347 // and it must be a multiplication.
348 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
351 // MultLo amd MultHi must be the first and second output of MultNode
353 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
356 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
357 // of the values of MultNode, in which case MultNode will be removed in later
359 // If there exist users other than SUBENode or SUBCNode, this function returns
360 // here, which will result in MultNode being mapped to a single MULT
361 // instruction node rather than a pair of MULT and MSUB instructions being
363 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
366 SDValue Chain = CurDAG->getEntryNode();
367 DebugLoc dl = SUBENode->getDebugLoc();
369 // create MipsSub(u) node
370 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
372 SDValue MSub = CurDAG->getNode(MultOpc, dl,
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 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
494 assert(false && "Illegal Condition Code");
498 // Creates and returns an FPCmp node from a setcc node.
499 // Returns Op if setcc is not a floating point comparison.
500 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
501 // must be a SETCC node
502 if (Op.getOpcode() != ISD::SETCC)
505 SDValue LHS = Op.getOperand(0);
507 if (!LHS.getValueType().isFloatingPoint())
510 SDValue RHS = Op.getOperand(1);
511 DebugLoc dl = Op.getDebugLoc();
513 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
514 // node if necessary.
515 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
517 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
518 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
521 // Creates and returns a CMovFPT/F node.
522 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
523 SDValue False, DebugLoc DL) {
524 bool invert = InvertFPCondCode((Mips::CondCode)
525 cast<ConstantSDNode>(Cond.getOperand(2))
528 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
529 True.getValueType(), True, False, Cond);
532 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
533 TargetLowering::DAGCombinerInfo &DCI,
534 const MipsSubtarget* Subtarget) {
535 if (DCI.isBeforeLegalizeOps())
538 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
540 if (Cond.getOpcode() != MipsISD::FPCmp)
543 SDValue True = DAG.getConstant(1, MVT::i32);
544 SDValue False = DAG.getConstant(0, MVT::i32);
546 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
549 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
550 TargetLowering::DAGCombinerInfo &DCI,
551 const MipsSubtarget* Subtarget) {
552 // Pattern match EXT.
553 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
554 // => ext $dst, $src, size, pos
555 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
558 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
559 unsigned ShiftRightOpc = ShiftRight.getOpcode();
561 // Op's first operand must be a shift right.
562 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
565 // The second operand of the shift must be an immediate.
567 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
570 uint64_t Pos = CN->getZExtValue();
571 uint64_t SMPos, SMSize;
573 // Op's second operand must be a shifted mask.
574 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
575 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
578 // Return if the shifted mask does not start at bit 0 or the sum of its size
579 // and Pos exceeds the word's size.
580 EVT ValTy = N->getValueType(0);
581 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
584 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
585 ShiftRight.getOperand(0),
586 DAG.getConstant(Pos, MVT::i32),
587 DAG.getConstant(SMSize, MVT::i32));
590 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
591 TargetLowering::DAGCombinerInfo &DCI,
592 const MipsSubtarget* Subtarget) {
593 // Pattern match INS.
594 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
595 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
596 // => ins $dst, $src, size, pos, $src1
597 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
600 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
601 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
604 // See if Op's first operand matches (and $src1 , mask0).
605 if (And0.getOpcode() != ISD::AND)
608 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
609 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
612 // See if Op's second operand matches (and (shl $src, pos), mask1).
613 if (And1.getOpcode() != ISD::AND)
616 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
617 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
620 // The shift masks must have the same position and size.
621 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
624 SDValue Shl = And1.getOperand(0);
625 if (Shl.getOpcode() != ISD::SHL)
628 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
631 unsigned Shamt = CN->getZExtValue();
633 // Return if the shift amount and the first bit position of mask are not the
635 EVT ValTy = N->getValueType(0);
636 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
639 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy,
641 DAG.getConstant(SMPos0, MVT::i32),
642 DAG.getConstant(SMSize0, MVT::i32),
646 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
648 SelectionDAG &DAG = DCI.DAG;
649 unsigned opc = N->getOpcode();
654 return PerformADDECombine(N, DAG, DCI, Subtarget);
656 return PerformSUBECombine(N, DAG, DCI, Subtarget);
659 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
661 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
663 return PerformANDCombine(N, DAG, DCI, Subtarget);
665 return PerformORCombine(N, DAG, DCI, Subtarget);
671 SDValue MipsTargetLowering::
672 LowerOperation(SDValue Op, SelectionDAG &DAG) const
674 switch (Op.getOpcode())
676 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
677 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
678 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
679 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
680 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
681 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
682 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
683 case ISD::SELECT: return LowerSELECT(Op, DAG);
684 case ISD::VASTART: return LowerVASTART(Op, DAG);
685 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
686 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
687 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
688 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
693 //===----------------------------------------------------------------------===//
694 // Lower helper functions
695 //===----------------------------------------------------------------------===//
697 // AddLiveIn - This helper function adds the specified physical register to the
698 // MachineFunction as a live in value. It also creates a corresponding
699 // virtual register for it.
701 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
703 assert(RC->contains(PReg) && "Not the correct regclass!");
704 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
705 MF.getRegInfo().addLiveIn(PReg, VReg);
709 // Get fp branch code (not opcode) from condition code.
710 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
711 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
712 return Mips::BRANCH_T;
714 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
715 return Mips::BRANCH_F;
717 return Mips::BRANCH_INVALID;
721 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
723 const MipsSubtarget* Subtarget,
724 const TargetInstrInfo *TII,
725 bool isFPCmp, unsigned Opc) {
726 // There is no need to expand CMov instructions if target has
727 // conditional moves.
728 if (Subtarget->hasCondMov())
731 // To "insert" a SELECT_CC instruction, we actually have to insert the
732 // diamond control-flow pattern. The incoming instruction knows the
733 // destination vreg to set, the condition code register to branch on, the
734 // true/false values to select between, and a branch opcode to use.
735 const BasicBlock *LLVM_BB = BB->getBasicBlock();
736 MachineFunction::iterator It = BB;
743 // bNE r1, r0, copy1MBB
744 // fallthrough --> copy0MBB
745 MachineBasicBlock *thisMBB = BB;
746 MachineFunction *F = BB->getParent();
747 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
748 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
749 F->insert(It, copy0MBB);
750 F->insert(It, sinkMBB);
752 // Transfer the remainder of BB and its successor edges to sinkMBB.
753 sinkMBB->splice(sinkMBB->begin(), BB,
754 llvm::next(MachineBasicBlock::iterator(MI)),
756 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
758 // Next, add the true and fallthrough blocks as its successors.
759 BB->addSuccessor(copy0MBB);
760 BB->addSuccessor(sinkMBB);
762 // Emit the right instruction according to the type of the operands compared
764 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
766 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
767 .addReg(Mips::ZERO).addMBB(sinkMBB);
771 // # fallthrough to sinkMBB
774 // Update machine-CFG edges
775 BB->addSuccessor(sinkMBB);
778 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
783 BuildMI(*BB, BB->begin(), dl,
784 TII->get(Mips::PHI), MI->getOperand(0).getReg())
785 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
786 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
788 BuildMI(*BB, BB->begin(), dl,
789 TII->get(Mips::PHI), MI->getOperand(0).getReg())
790 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
791 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
793 MI->eraseFromParent(); // The pseudo instruction is gone now.
798 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
799 MachineBasicBlock *BB) const {
800 switch (MI->getOpcode()) {
802 assert(false && "Unexpected instr type to insert");
804 case Mips::ATOMIC_LOAD_ADD_I8:
805 case Mips::ATOMIC_LOAD_ADD_I8_P8:
806 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
807 case Mips::ATOMIC_LOAD_ADD_I16:
808 case Mips::ATOMIC_LOAD_ADD_I16_P8:
809 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
810 case Mips::ATOMIC_LOAD_ADD_I32:
811 case Mips::ATOMIC_LOAD_ADD_I32_P8:
812 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
813 case Mips::ATOMIC_LOAD_ADD_I64:
814 case Mips::ATOMIC_LOAD_ADD_I64_P8:
815 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
817 case Mips::ATOMIC_LOAD_AND_I8:
818 case Mips::ATOMIC_LOAD_AND_I8_P8:
819 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
820 case Mips::ATOMIC_LOAD_AND_I16:
821 case Mips::ATOMIC_LOAD_AND_I16_P8:
822 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
823 case Mips::ATOMIC_LOAD_AND_I32:
824 case Mips::ATOMIC_LOAD_AND_I32_P8:
825 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
826 case Mips::ATOMIC_LOAD_AND_I64:
827 case Mips::ATOMIC_LOAD_AND_I64_P8:
828 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
830 case Mips::ATOMIC_LOAD_OR_I8:
831 case Mips::ATOMIC_LOAD_OR_I8_P8:
832 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
833 case Mips::ATOMIC_LOAD_OR_I16:
834 case Mips::ATOMIC_LOAD_OR_I16_P8:
835 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
836 case Mips::ATOMIC_LOAD_OR_I32:
837 case Mips::ATOMIC_LOAD_OR_I32_P8:
838 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
839 case Mips::ATOMIC_LOAD_OR_I64:
840 case Mips::ATOMIC_LOAD_OR_I64_P8:
841 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
843 case Mips::ATOMIC_LOAD_XOR_I8:
844 case Mips::ATOMIC_LOAD_XOR_I8_P8:
845 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
846 case Mips::ATOMIC_LOAD_XOR_I16:
847 case Mips::ATOMIC_LOAD_XOR_I16_P8:
848 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
849 case Mips::ATOMIC_LOAD_XOR_I32:
850 case Mips::ATOMIC_LOAD_XOR_I32_P8:
851 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
852 case Mips::ATOMIC_LOAD_XOR_I64:
853 case Mips::ATOMIC_LOAD_XOR_I64_P8:
854 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
856 case Mips::ATOMIC_LOAD_NAND_I8:
857 case Mips::ATOMIC_LOAD_NAND_I8_P8:
858 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
859 case Mips::ATOMIC_LOAD_NAND_I16:
860 case Mips::ATOMIC_LOAD_NAND_I16_P8:
861 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
862 case Mips::ATOMIC_LOAD_NAND_I32:
863 case Mips::ATOMIC_LOAD_NAND_I32_P8:
864 return EmitAtomicBinary(MI, BB, 4, 0, true);
865 case Mips::ATOMIC_LOAD_NAND_I64:
866 case Mips::ATOMIC_LOAD_NAND_I64_P8:
867 return EmitAtomicBinary(MI, BB, 8, 0, true);
869 case Mips::ATOMIC_LOAD_SUB_I8:
870 case Mips::ATOMIC_LOAD_SUB_I8_P8:
871 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
872 case Mips::ATOMIC_LOAD_SUB_I16:
873 case Mips::ATOMIC_LOAD_SUB_I16_P8:
874 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
875 case Mips::ATOMIC_LOAD_SUB_I32:
876 case Mips::ATOMIC_LOAD_SUB_I32_P8:
877 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
878 case Mips::ATOMIC_LOAD_SUB_I64:
879 case Mips::ATOMIC_LOAD_SUB_I64_P8:
880 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
882 case Mips::ATOMIC_SWAP_I8:
883 case Mips::ATOMIC_SWAP_I8_P8:
884 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
885 case Mips::ATOMIC_SWAP_I16:
886 case Mips::ATOMIC_SWAP_I16_P8:
887 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
888 case Mips::ATOMIC_SWAP_I32:
889 case Mips::ATOMIC_SWAP_I32_P8:
890 return EmitAtomicBinary(MI, BB, 4, 0);
891 case Mips::ATOMIC_SWAP_I64:
892 case Mips::ATOMIC_SWAP_I64_P8:
893 return EmitAtomicBinary(MI, BB, 8, 0);
895 case Mips::ATOMIC_CMP_SWAP_I8:
896 case Mips::ATOMIC_CMP_SWAP_I8_P8:
897 return EmitAtomicCmpSwapPartword(MI, BB, 1);
898 case Mips::ATOMIC_CMP_SWAP_I16:
899 case Mips::ATOMIC_CMP_SWAP_I16_P8:
900 return EmitAtomicCmpSwapPartword(MI, BB, 2);
901 case Mips::ATOMIC_CMP_SWAP_I32:
902 case Mips::ATOMIC_CMP_SWAP_I32_P8:
903 return EmitAtomicCmpSwap(MI, BB, 4);
904 case Mips::ATOMIC_CMP_SWAP_I64:
905 case Mips::ATOMIC_CMP_SWAP_I64_P8:
906 return EmitAtomicCmpSwap(MI, BB, 8);
910 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
911 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
913 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
914 unsigned Size, unsigned BinOpcode,
916 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
918 MachineFunction *MF = BB->getParent();
919 MachineRegisterInfo &RegInfo = MF->getRegInfo();
920 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
921 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
922 DebugLoc dl = MI->getDebugLoc();
923 unsigned LL, SC, AND, NOR, ZERO, BEQ;
926 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
927 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
934 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
935 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
938 ZERO = Mips::ZERO_64;
942 unsigned OldVal = MI->getOperand(0).getReg();
943 unsigned Ptr = MI->getOperand(1).getReg();
944 unsigned Incr = MI->getOperand(2).getReg();
946 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
947 unsigned AndRes = RegInfo.createVirtualRegister(RC);
948 unsigned Success = RegInfo.createVirtualRegister(RC);
950 // insert new blocks after the current block
951 const BasicBlock *LLVM_BB = BB->getBasicBlock();
952 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
953 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
954 MachineFunction::iterator It = BB;
956 MF->insert(It, loopMBB);
957 MF->insert(It, exitMBB);
959 // Transfer the remainder of BB and its successor edges to exitMBB.
960 exitMBB->splice(exitMBB->begin(), BB,
961 llvm::next(MachineBasicBlock::iterator(MI)),
963 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
967 // fallthrough --> loopMBB
968 BB->addSuccessor(loopMBB);
969 loopMBB->addSuccessor(loopMBB);
970 loopMBB->addSuccessor(exitMBB);
974 // <binop> storeval, oldval, incr
975 // sc success, storeval, 0(ptr)
976 // beq success, $0, loopMBB
978 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
980 // and andres, oldval, incr
981 // nor storeval, $0, andres
982 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
983 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
984 } else if (BinOpcode) {
985 // <binop> storeval, oldval, incr
986 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
990 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
991 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
993 MI->eraseFromParent(); // The instruction is gone now.
999 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1000 MachineBasicBlock *BB,
1001 unsigned Size, unsigned BinOpcode,
1003 assert((Size == 1 || Size == 2) &&
1004 "Unsupported size for EmitAtomicBinaryPartial.");
1006 MachineFunction *MF = BB->getParent();
1007 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1008 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1009 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1010 DebugLoc dl = MI->getDebugLoc();
1011 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1012 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1014 unsigned Dest = MI->getOperand(0).getReg();
1015 unsigned Ptr = MI->getOperand(1).getReg();
1016 unsigned Incr = MI->getOperand(2).getReg();
1018 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1019 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1020 unsigned Mask = RegInfo.createVirtualRegister(RC);
1021 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1022 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1023 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1024 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1025 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1026 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1027 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1028 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1029 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1030 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1031 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1032 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1033 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1034 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1035 unsigned Success = RegInfo.createVirtualRegister(RC);
1037 // insert new blocks after the current block
1038 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1039 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1040 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1041 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1042 MachineFunction::iterator It = BB;
1044 MF->insert(It, loopMBB);
1045 MF->insert(It, sinkMBB);
1046 MF->insert(It, exitMBB);
1048 // Transfer the remainder of BB and its successor edges to exitMBB.
1049 exitMBB->splice(exitMBB->begin(), BB,
1050 llvm::next(MachineBasicBlock::iterator(MI)),
1052 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1054 BB->addSuccessor(loopMBB);
1055 loopMBB->addSuccessor(loopMBB);
1056 loopMBB->addSuccessor(sinkMBB);
1057 sinkMBB->addSuccessor(exitMBB);
1060 // addiu masklsb2,$0,-4 # 0xfffffffc
1061 // and alignedaddr,ptr,masklsb2
1062 // andi ptrlsb2,ptr,3
1063 // sll shiftamt,ptrlsb2,3
1064 // ori maskupper,$0,255 # 0xff
1065 // sll mask,maskupper,shiftamt
1066 // nor mask2,$0,mask
1067 // sll incr2,incr,shiftamt
1069 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1070 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1071 .addReg(Mips::ZERO).addImm(-4);
1072 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1073 .addReg(Ptr).addReg(MaskLSB2);
1074 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1075 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1076 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1077 .addReg(Mips::ZERO).addImm(MaskImm);
1078 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1079 .addReg(ShiftAmt).addReg(MaskUpper);
1080 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1081 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1084 // atomic.load.binop
1086 // ll oldval,0(alignedaddr)
1087 // binop binopres,oldval,incr2
1088 // and newval,binopres,mask
1089 // and maskedoldval0,oldval,mask2
1090 // or storeval,maskedoldval0,newval
1091 // sc success,storeval,0(alignedaddr)
1092 // beq success,$0,loopMBB
1096 // ll oldval,0(alignedaddr)
1097 // and newval,incr2,mask
1098 // and maskedoldval0,oldval,mask2
1099 // or storeval,maskedoldval0,newval
1100 // sc success,storeval,0(alignedaddr)
1101 // beq success,$0,loopMBB
1104 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1106 // and andres, oldval, incr2
1107 // nor binopres, $0, andres
1108 // and newval, binopres, mask
1109 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1110 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1111 .addReg(Mips::ZERO).addReg(AndRes);
1112 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1113 } else if (BinOpcode) {
1114 // <binop> binopres, oldval, incr2
1115 // and newval, binopres, mask
1116 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1117 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1118 } else {// atomic.swap
1119 // and newval, incr2, mask
1120 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1123 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1124 .addReg(OldVal).addReg(Mask2);
1125 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1126 .addReg(MaskedOldVal0).addReg(NewVal);
1127 BuildMI(BB, dl, TII->get(SC), Success)
1128 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1129 BuildMI(BB, dl, TII->get(Mips::BEQ))
1130 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1133 // and maskedoldval1,oldval,mask
1134 // srl srlres,maskedoldval1,shiftamt
1135 // sll sllres,srlres,24
1136 // sra dest,sllres,24
1138 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1140 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1141 .addReg(OldVal).addReg(Mask);
1142 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1143 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1144 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1145 .addReg(SrlRes).addImm(ShiftImm);
1146 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1147 .addReg(SllRes).addImm(ShiftImm);
1149 MI->eraseFromParent(); // The instruction is gone now.
1155 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1156 MachineBasicBlock *BB,
1157 unsigned Size) const {
1158 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1160 MachineFunction *MF = BB->getParent();
1161 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1162 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1163 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1164 DebugLoc dl = MI->getDebugLoc();
1165 unsigned LL, SC, ZERO, BNE, BEQ;
1168 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1169 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1175 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1176 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1177 ZERO = Mips::ZERO_64;
1182 unsigned Dest = MI->getOperand(0).getReg();
1183 unsigned Ptr = MI->getOperand(1).getReg();
1184 unsigned OldVal = MI->getOperand(2).getReg();
1185 unsigned NewVal = MI->getOperand(3).getReg();
1187 unsigned Success = RegInfo.createVirtualRegister(RC);
1189 // insert new blocks after the current block
1190 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1191 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1192 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1193 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1194 MachineFunction::iterator It = BB;
1196 MF->insert(It, loop1MBB);
1197 MF->insert(It, loop2MBB);
1198 MF->insert(It, exitMBB);
1200 // Transfer the remainder of BB and its successor edges to exitMBB.
1201 exitMBB->splice(exitMBB->begin(), BB,
1202 llvm::next(MachineBasicBlock::iterator(MI)),
1204 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1208 // fallthrough --> loop1MBB
1209 BB->addSuccessor(loop1MBB);
1210 loop1MBB->addSuccessor(exitMBB);
1211 loop1MBB->addSuccessor(loop2MBB);
1212 loop2MBB->addSuccessor(loop1MBB);
1213 loop2MBB->addSuccessor(exitMBB);
1217 // bne dest, oldval, exitMBB
1219 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1220 BuildMI(BB, dl, TII->get(BNE))
1221 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1224 // sc success, newval, 0(ptr)
1225 // beq success, $0, loop1MBB
1227 BuildMI(BB, dl, TII->get(SC), Success)
1228 .addReg(NewVal).addReg(Ptr).addImm(0);
1229 BuildMI(BB, dl, TII->get(BEQ))
1230 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1232 MI->eraseFromParent(); // The instruction is gone now.
1238 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1239 MachineBasicBlock *BB,
1240 unsigned Size) const {
1241 assert((Size == 1 || Size == 2) &&
1242 "Unsupported size for EmitAtomicCmpSwapPartial.");
1244 MachineFunction *MF = BB->getParent();
1245 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1246 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1247 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1248 DebugLoc dl = MI->getDebugLoc();
1249 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1250 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1252 unsigned Dest = MI->getOperand(0).getReg();
1253 unsigned Ptr = MI->getOperand(1).getReg();
1254 unsigned CmpVal = MI->getOperand(2).getReg();
1255 unsigned NewVal = MI->getOperand(3).getReg();
1257 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1258 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1259 unsigned Mask = RegInfo.createVirtualRegister(RC);
1260 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1261 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1262 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1263 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1264 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1265 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1266 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1267 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1268 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1269 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1270 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1271 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1272 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1273 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1274 unsigned Success = RegInfo.createVirtualRegister(RC);
1276 // insert new blocks after the current block
1277 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1278 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1279 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1280 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1281 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1282 MachineFunction::iterator It = BB;
1284 MF->insert(It, loop1MBB);
1285 MF->insert(It, loop2MBB);
1286 MF->insert(It, sinkMBB);
1287 MF->insert(It, exitMBB);
1289 // Transfer the remainder of BB and its successor edges to exitMBB.
1290 exitMBB->splice(exitMBB->begin(), BB,
1291 llvm::next(MachineBasicBlock::iterator(MI)),
1293 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1295 BB->addSuccessor(loop1MBB);
1296 loop1MBB->addSuccessor(sinkMBB);
1297 loop1MBB->addSuccessor(loop2MBB);
1298 loop2MBB->addSuccessor(loop1MBB);
1299 loop2MBB->addSuccessor(sinkMBB);
1300 sinkMBB->addSuccessor(exitMBB);
1302 // FIXME: computation of newval2 can be moved to loop2MBB.
1304 // addiu masklsb2,$0,-4 # 0xfffffffc
1305 // and alignedaddr,ptr,masklsb2
1306 // andi ptrlsb2,ptr,3
1307 // sll shiftamt,ptrlsb2,3
1308 // ori maskupper,$0,255 # 0xff
1309 // sll mask,maskupper,shiftamt
1310 // nor mask2,$0,mask
1311 // andi maskedcmpval,cmpval,255
1312 // sll shiftedcmpval,maskedcmpval,shiftamt
1313 // andi maskednewval,newval,255
1314 // sll shiftednewval,maskednewval,shiftamt
1315 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1316 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1317 .addReg(Mips::ZERO).addImm(-4);
1318 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1319 .addReg(Ptr).addReg(MaskLSB2);
1320 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1321 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1322 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1323 .addReg(Mips::ZERO).addImm(MaskImm);
1324 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1325 .addReg(ShiftAmt).addReg(MaskUpper);
1326 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1327 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1328 .addReg(CmpVal).addImm(MaskImm);
1329 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1330 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1331 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1332 .addReg(NewVal).addImm(MaskImm);
1333 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1334 .addReg(ShiftAmt).addReg(MaskedNewVal);
1337 // ll oldval,0(alginedaddr)
1338 // and maskedoldval0,oldval,mask
1339 // bne maskedoldval0,shiftedcmpval,sinkMBB
1341 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1342 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1343 .addReg(OldVal).addReg(Mask);
1344 BuildMI(BB, dl, TII->get(Mips::BNE))
1345 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1348 // and maskedoldval1,oldval,mask2
1349 // or storeval,maskedoldval1,shiftednewval
1350 // sc success,storeval,0(alignedaddr)
1351 // beq success,$0,loop1MBB
1353 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1354 .addReg(OldVal).addReg(Mask2);
1355 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1356 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1357 BuildMI(BB, dl, TII->get(SC), Success)
1358 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1359 BuildMI(BB, dl, TII->get(Mips::BEQ))
1360 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1363 // srl srlres,maskedoldval0,shiftamt
1364 // sll sllres,srlres,24
1365 // sra dest,sllres,24
1367 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1369 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1370 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1371 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1372 .addReg(SrlRes).addImm(ShiftImm);
1373 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1374 .addReg(SllRes).addImm(ShiftImm);
1376 MI->eraseFromParent(); // The instruction is gone now.
1381 //===----------------------------------------------------------------------===//
1382 // Misc Lower Operation implementation
1383 //===----------------------------------------------------------------------===//
1384 SDValue MipsTargetLowering::
1385 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1387 MachineFunction &MF = DAG.getMachineFunction();
1388 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1389 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1391 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1392 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1393 "Cannot lower if the alignment of the allocated space is larger than \
1394 that of the stack.");
1396 SDValue Chain = Op.getOperand(0);
1397 SDValue Size = Op.getOperand(1);
1398 DebugLoc dl = Op.getDebugLoc();
1400 // Get a reference from Mips stack pointer
1401 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1403 // Subtract the dynamic size from the actual stack size to
1404 // obtain the new stack size.
1405 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1407 // The Sub result contains the new stack start address, so it
1408 // must be placed in the stack pointer register.
1409 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1411 // This node always has two return values: a new stack pointer
1412 // value and a chain
1413 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1414 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1415 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1417 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1420 SDValue MipsTargetLowering::
1421 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1423 // The first operand is the chain, the second is the condition, the third is
1424 // the block to branch to if the condition is true.
1425 SDValue Chain = Op.getOperand(0);
1426 SDValue Dest = Op.getOperand(2);
1427 DebugLoc dl = Op.getDebugLoc();
1429 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1431 // Return if flag is not set by a floating point comparison.
1432 if (CondRes.getOpcode() != MipsISD::FPCmp)
1435 SDValue CCNode = CondRes.getOperand(2);
1437 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1438 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1440 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1444 SDValue MipsTargetLowering::
1445 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1447 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1449 // Return if flag is not set by a floating point comparison.
1450 if (Cond.getOpcode() != MipsISD::FPCmp)
1453 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1457 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1458 SelectionDAG &DAG) const {
1459 // FIXME there isn't actually debug info here
1460 DebugLoc dl = Op.getDebugLoc();
1461 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1463 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1464 SDVTList VTs = DAG.getVTList(MVT::i32);
1466 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1468 // %gp_rel relocation
1469 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1470 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1472 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1473 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1474 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1476 // %hi/%lo relocation
1477 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1479 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1481 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1482 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1483 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1486 EVT ValTy = Op.getValueType();
1487 bool HasGotOfst = (GV->hasInternalLinkage() ||
1488 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1489 unsigned GotFlag = IsN64 ?
1490 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1491 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1492 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1493 GA = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, GA);
1494 SDValue ResNode = DAG.getLoad(ValTy, dl,
1495 DAG.getEntryNode(), GA, MachinePointerInfo(),
1496 false, false, false, 0);
1497 // On functions and global targets not internal linked only
1498 // a load from got/GP is necessary for PIC to work.
1501 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1502 IsN64 ? MipsII::MO_GOT_OFST :
1504 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1505 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1508 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1509 SelectionDAG &DAG) const {
1510 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1511 // FIXME there isn't actually debug info here
1512 DebugLoc dl = Op.getDebugLoc();
1514 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1515 // %hi/%lo relocation
1516 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1518 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1520 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1521 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1522 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1525 EVT ValTy = Op.getValueType();
1526 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1527 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1528 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1529 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, BAGOTOffset);
1530 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1531 SDValue Load = DAG.getLoad(ValTy, dl,
1532 DAG.getEntryNode(), BAGOTOffset,
1533 MachinePointerInfo(), false, false, false, 0);
1534 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1535 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1538 SDValue MipsTargetLowering::
1539 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1541 // If the relocation model is PIC, use the General Dynamic TLS Model,
1542 // otherwise use the Initial Exec or Local Exec TLS Model.
1543 // TODO: implement Local Dynamic TLS model
1545 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1546 DebugLoc dl = GA->getDebugLoc();
1547 const GlobalValue *GV = GA->getGlobal();
1548 EVT PtrVT = getPointerTy();
1550 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1551 // General Dynamic TLS Model
1552 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1553 0, MipsII::MO_TLSGD);
1554 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1555 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1556 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1560 Entry.Node = Argument;
1561 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1562 Args.push_back(Entry);
1563 std::pair<SDValue, SDValue> CallResult =
1564 LowerCallTo(DAG.getEntryNode(),
1565 (Type *) Type::getInt32Ty(*DAG.getContext()),
1566 false, false, false, false, 0, CallingConv::C, false, true,
1567 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1570 return CallResult.first;
1574 if (GV->isDeclaration()) {
1575 // Initial Exec TLS Model
1576 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1577 MipsII::MO_GOTTPREL);
1578 Offset = DAG.getLoad(MVT::i32, dl,
1579 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1580 false, false, false, 0);
1582 // Local Exec TLS Model
1583 SDVTList VTs = DAG.getVTList(MVT::i32);
1584 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1585 MipsII::MO_TPREL_HI);
1586 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1587 MipsII::MO_TPREL_LO);
1588 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1589 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1590 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1593 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1594 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1597 SDValue MipsTargetLowering::
1598 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1600 SDValue HiPart, JTI, JTILo;
1601 // FIXME there isn't actually debug info here
1602 DebugLoc dl = Op.getDebugLoc();
1603 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1604 EVT PtrVT = Op.getValueType();
1605 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1607 if (!IsPIC && !IsN64) {
1608 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1609 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1610 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1611 } else {// Emit Load from Global Pointer
1612 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1613 unsigned OfstFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1614 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1615 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, PtrVT, JTI);
1616 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1617 MachinePointerInfo(), false, false, false, 0);
1618 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1621 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1622 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1625 SDValue MipsTargetLowering::
1626 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1629 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1630 const Constant *C = N->getConstVal();
1631 // FIXME there isn't actually debug info here
1632 DebugLoc dl = Op.getDebugLoc();
1634 // gp_rel relocation
1635 // FIXME: we should reference the constant pool using small data sections,
1636 // but the asm printer currently doesn't support this feature without
1637 // hacking it. This feature should come soon so we can uncomment the
1639 //if (IsInSmallSection(C->getType())) {
1640 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1641 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1642 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1644 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1645 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1646 N->getOffset(), MipsII::MO_ABS_HI);
1647 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1648 N->getOffset(), MipsII::MO_ABS_LO);
1649 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1650 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1651 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1653 EVT ValTy = Op.getValueType();
1654 unsigned GOTFlag = IsN64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1655 unsigned OFSTFlag = IsN64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1656 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1657 N->getOffset(), GOTFlag);
1658 CP = DAG.getNode(MipsISD::WrapperPIC, dl, ValTy, CP);
1659 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(),
1660 CP, MachinePointerInfo::getConstantPool(),
1661 false, false, false, 0);
1662 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1663 N->getOffset(), OFSTFlag);
1664 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1665 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1671 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1672 MachineFunction &MF = DAG.getMachineFunction();
1673 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1675 DebugLoc dl = Op.getDebugLoc();
1676 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1679 // vastart just stores the address of the VarArgsFrameIndex slot into the
1680 // memory location argument.
1681 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1682 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1683 MachinePointerInfo(SV),
1687 // Called if the size of integer registers is large enough to hold the whole
1688 // floating point number.
1689 static SDValue LowerFCOPYSIGNLargeIntReg(SDValue Op, SelectionDAG &DAG) {
1690 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1691 EVT ValTy = Op.getValueType();
1692 EVT IntValTy = MVT::getIntegerVT(ValTy.getSizeInBits());
1693 uint64_t Mask = (uint64_t)1 << (ValTy.getSizeInBits() - 1);
1694 DebugLoc dl = Op.getDebugLoc();
1695 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(0));
1696 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, IntValTy, Op.getOperand(1));
1697 SDValue And0 = DAG.getNode(ISD::AND, dl, IntValTy, Op0,
1698 DAG.getConstant(Mask - 1, IntValTy));
1699 SDValue And1 = DAG.getNode(ISD::AND, dl, IntValTy, Op1,
1700 DAG.getConstant(Mask, IntValTy));
1701 SDValue Result = DAG.getNode(ISD::OR, dl, IntValTy, And0, And1);
1702 return DAG.getNode(ISD::BITCAST, dl, ValTy, Result);
1705 // Called if the size of integer registers is not large enough to hold the whole
1706 // floating point number (e.g. f64 & 32-bit integer register).
1708 LowerFCOPYSIGNSmallIntReg(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1710 // Use ext/ins instructions if target architecture is Mips32r2.
1711 // Eliminate redundant mfc1 and mtc1 instructions.
1712 unsigned LoIdx = 0, HiIdx = 1;
1715 std::swap(LoIdx, HiIdx);
1717 DebugLoc dl = Op.getDebugLoc();
1718 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1720 DAG.getConstant(LoIdx, MVT::i32));
1721 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1722 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1723 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1724 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1725 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1726 DAG.getConstant(0x7fffffff, MVT::i32));
1727 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1728 DAG.getConstant(0x80000000, MVT::i32));
1729 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1732 std::swap(Word0, Word1);
1734 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1737 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1739 EVT Ty = Op.getValueType();
1741 assert(Ty == MVT::f32 || Ty == MVT::f64);
1743 if (Ty == MVT::f32 || HasMips64)
1744 return LowerFCOPYSIGNLargeIntReg(Op, DAG);
1746 return LowerFCOPYSIGNSmallIntReg(Op, DAG, Subtarget->isLittle());
1749 SDValue MipsTargetLowering::
1750 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1752 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1753 "Frame address can only be determined for current frame.");
1755 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1756 MFI->setFrameAddressIsTaken(true);
1757 EVT VT = Op.getValueType();
1758 DebugLoc dl = Op.getDebugLoc();
1759 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1760 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1764 // TODO: set SType according to the desired memory barrier behavior.
1765 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1766 SelectionDAG& DAG) const {
1768 DebugLoc dl = Op.getDebugLoc();
1769 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1770 DAG.getConstant(SType, MVT::i32));
1773 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1774 SelectionDAG& DAG) const {
1775 // FIXME: Need pseudo-fence for 'singlethread' fences
1776 // FIXME: Set SType for weaker fences where supported/appropriate.
1778 DebugLoc dl = Op.getDebugLoc();
1779 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1780 DAG.getConstant(SType, MVT::i32));
1783 //===----------------------------------------------------------------------===//
1784 // Calling Convention Implementation
1785 //===----------------------------------------------------------------------===//
1787 //===----------------------------------------------------------------------===//
1788 // TODO: Implement a generic logic using tblgen that can support this.
1789 // Mips O32 ABI rules:
1791 // i32 - Passed in A0, A1, A2, A3 and stack
1792 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1793 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1794 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1795 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1796 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1799 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1800 //===----------------------------------------------------------------------===//
1802 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1803 MVT LocVT, CCValAssign::LocInfo LocInfo,
1804 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1806 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1808 static const unsigned IntRegs[] = {
1809 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1811 static const unsigned F32Regs[] = {
1812 Mips::F12, Mips::F14
1814 static const unsigned F64Regs[] = {
1819 if (ArgFlags.isByVal()) {
1820 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1821 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1822 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1823 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1824 r < std::min(IntRegsSize, NextReg); ++r)
1825 State.AllocateReg(IntRegs[r]);
1829 // Promote i8 and i16
1830 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1832 if (ArgFlags.isSExt())
1833 LocInfo = CCValAssign::SExt;
1834 else if (ArgFlags.isZExt())
1835 LocInfo = CCValAssign::ZExt;
1837 LocInfo = CCValAssign::AExt;
1842 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1843 // is true: function is vararg, argument is 3rd or higher, there is previous
1844 // argument which is not f32 or f64.
1845 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1846 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1847 unsigned OrigAlign = ArgFlags.getOrigAlign();
1848 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1850 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1851 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1852 // If this is the first part of an i64 arg,
1853 // the allocated register must be either A0 or A2.
1854 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1855 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1857 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1858 // Allocate int register and shadow next int register. If first
1859 // available register is Mips::A1 or Mips::A3, shadow it too.
1860 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1861 if (Reg == Mips::A1 || Reg == Mips::A3)
1862 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1863 State.AllocateReg(IntRegs, IntRegsSize);
1865 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1866 // we are guaranteed to find an available float register
1867 if (ValVT == MVT::f32) {
1868 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1869 // Shadow int register
1870 State.AllocateReg(IntRegs, IntRegsSize);
1872 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1873 // Shadow int registers
1874 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1875 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1876 State.AllocateReg(IntRegs, IntRegsSize);
1877 State.AllocateReg(IntRegs, IntRegsSize);
1880 llvm_unreachable("Cannot handle this ValVT.");
1882 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1883 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1886 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1888 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1890 return false; // CC must always match
1893 static const unsigned Mips64IntRegs[8] =
1894 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
1895 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
1896 static const unsigned Mips64DPRegs[8] =
1897 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
1898 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
1900 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
1901 CCValAssign::LocInfo LocInfo,
1902 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1903 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
1904 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
1905 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
1907 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
1909 // If byval is 16-byte aligned, the first arg register must be even.
1910 if ((Align == 16) && (FirstIdx % 2)) {
1911 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
1915 // Mark the registers allocated.
1916 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
1917 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
1919 // Allocate space on caller's stack.
1920 unsigned Offset = State.AllocateStack(Size, Align);
1923 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
1926 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1931 #include "MipsGenCallingConv.inc"
1934 AnalyzeMips64CallOperands(CCState CCInfo,
1935 const SmallVectorImpl<ISD::OutputArg> &Outs) {
1936 unsigned NumOps = Outs.size();
1937 for (unsigned i = 0; i != NumOps; ++i) {
1938 MVT ArgVT = Outs[i].VT;
1939 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
1942 if (Outs[i].IsFixed)
1943 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1945 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
1949 dbgs() << "Call operand #" << i << " has unhandled type "
1950 << EVT(ArgVT).getEVTString();
1952 llvm_unreachable(0);
1957 //===----------------------------------------------------------------------===//
1958 // Call Calling Convention Implementation
1959 //===----------------------------------------------------------------------===//
1961 static const unsigned O32IntRegsSize = 4;
1963 static const unsigned O32IntRegs[] = {
1964 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1967 // Return next O32 integer argument register.
1968 static unsigned getNextIntArgReg(unsigned Reg) {
1969 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1970 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1973 // Write ByVal Arg to arg registers and stack.
1975 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1976 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1977 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1978 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1979 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1980 MVT PtrType, bool isLittle) {
1981 unsigned LocMemOffset = VA.getLocMemOffset();
1982 unsigned Offset = 0;
1983 uint32_t RemainingSize = Flags.getByValSize();
1984 unsigned ByValAlign = Flags.getByValAlign();
1986 // Copy the first 4 words of byval arg to registers A0 - A3.
1987 // FIXME: Use a stricter alignment if it enables better optimization in passes
1989 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1990 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1991 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1992 DAG.getConstant(Offset, MVT::i32));
1993 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1994 MachinePointerInfo(),
1995 false, false, false, std::min(ByValAlign,
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(),
2314 // Extend range of indices of frame objects for outgoing arguments that were
2315 // created during this function call. Skip this step if no such objects were
2318 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2320 // If a memcpy has been created to copy a byval arg to a stack, replace the
2321 // chain input of CallSeqStart with ByValChain.
2322 if (InChain != ByValChain)
2323 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2324 NextStackOffsetVal);
2326 // Transform all store nodes into one single node because all store
2327 // nodes are independent of each other.
2328 if (!MemOpChains.empty())
2329 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2330 &MemOpChains[0], MemOpChains.size());
2332 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2333 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2334 // node so that legalize doesn't hack it.
2335 unsigned char OpFlag;
2336 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2337 bool LoadSymAddr = false;
2340 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2341 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2342 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2343 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2344 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2346 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2349 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2350 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2351 getPointerTy(), 0, OpFlag);
2356 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2357 if (IsN64 || (!IsO32 && IsPIC))
2358 OpFlag = MipsII::MO_GOT_DISP;
2359 else if (!IsPIC) // !N64 && static
2360 OpFlag = MipsII::MO_NO_FLAG;
2362 OpFlag = MipsII::MO_GOT_CALL;
2363 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2364 getPointerTy(), OpFlag);
2370 // Create nodes that load address of callee and copy it to T9
2373 // Load callee address
2374 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, getPointerTy(), Callee);
2375 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2376 Callee, MachinePointerInfo::getGOT(),
2377 false, false, false, 0);
2379 // Use GOT+LO if callee has internal linkage.
2380 if (CalleeLo.getNode()) {
2381 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2382 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2388 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2389 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2390 InFlag = Chain.getValue(1);
2391 Callee = DAG.getRegister(T9Reg, getPointerTy());
2394 // Build a sequence of copy-to-reg nodes chained together with token
2395 // chain and flag operands which copy the outgoing args into registers.
2396 // The InFlag in necessary since all emitted instructions must be
2398 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2399 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2400 RegsToPass[i].second, InFlag);
2401 InFlag = Chain.getValue(1);
2404 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2405 // = Chain, Callee, Reg#1, Reg#2, ...
2407 // Returns a chain & a flag for retval copy to use.
2408 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2409 SmallVector<SDValue, 8> Ops;
2410 Ops.push_back(Chain);
2411 Ops.push_back(Callee);
2413 // Add argument registers to the end of the list so that they are
2414 // known live into the call.
2415 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2416 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2417 RegsToPass[i].second.getValueType()));
2419 if (InFlag.getNode())
2420 Ops.push_back(InFlag);
2422 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2423 InFlag = Chain.getValue(1);
2425 // Create the CALLSEQ_END node.
2426 Chain = DAG.getCALLSEQ_END(Chain,
2427 DAG.getIntPtrConstant(NextStackOffset, true),
2428 DAG.getIntPtrConstant(0, true), InFlag);
2429 InFlag = Chain.getValue(1);
2431 // Handle result values, copying them out of physregs into vregs that we
2433 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2434 Ins, dl, DAG, InVals);
2437 /// LowerCallResult - Lower the result values of a call into the
2438 /// appropriate copies out of appropriate physical registers.
2440 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2441 CallingConv::ID CallConv, bool isVarArg,
2442 const SmallVectorImpl<ISD::InputArg> &Ins,
2443 DebugLoc dl, SelectionDAG &DAG,
2444 SmallVectorImpl<SDValue> &InVals) const {
2445 // Assign locations to each value returned by this call.
2446 SmallVector<CCValAssign, 16> RVLocs;
2447 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2448 getTargetMachine(), RVLocs, *DAG.getContext());
2450 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2452 // Copy all of the result registers out of their specified physreg.
2453 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2454 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2455 RVLocs[i].getValVT(), InFlag).getValue(1);
2456 InFlag = Chain.getValue(2);
2457 InVals.push_back(Chain.getValue(0));
2463 //===----------------------------------------------------------------------===//
2464 // Formal Arguments Calling Convention Implementation
2465 //===----------------------------------------------------------------------===//
2466 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2467 std::vector<SDValue>& OutChains,
2468 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2469 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2470 unsigned LocMem = VA.getLocMemOffset();
2471 unsigned FirstWord = LocMem / 4;
2473 // copy register A0 - A3 to frame object
2474 for (unsigned i = 0; i < NumWords; ++i) {
2475 unsigned CurWord = FirstWord + i;
2476 if (CurWord >= O32IntRegsSize)
2479 unsigned SrcReg = O32IntRegs[CurWord];
2480 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2481 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2482 DAG.getConstant(i * 4, MVT::i32));
2483 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2484 StorePtr, MachinePointerInfo(), false,
2486 OutChains.push_back(Store);
2490 // Create frame object on stack and copy registers used for byval passing to it.
2492 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2493 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2494 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2495 MachineFrameInfo *MFI, bool IsRegLoc,
2496 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2498 const unsigned *Reg = Mips64IntRegs + 8;
2499 int FOOffset; // Frame object offset from virtual frame pointer.
2502 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2503 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2506 FOOffset = VA.getLocMemOffset();
2508 // Create frame object.
2509 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2510 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2511 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2512 InVals.push_back(FIN);
2514 // Copy arg registers.
2515 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2517 unsigned VReg = AddLiveIn(MF, *Reg, Mips::CPU64RegsRegisterClass);
2518 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2519 DAG.getConstant(I * 8, PtrTy));
2520 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2521 StorePtr, MachinePointerInfo(), false,
2523 OutChains.push_back(Store);
2529 /// LowerFormalArguments - transform physical registers into virtual registers
2530 /// and generate load operations for arguments places on the stack.
2532 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2533 CallingConv::ID CallConv,
2535 const SmallVectorImpl<ISD::InputArg>
2537 DebugLoc dl, SelectionDAG &DAG,
2538 SmallVectorImpl<SDValue> &InVals)
2540 MachineFunction &MF = DAG.getMachineFunction();
2541 MachineFrameInfo *MFI = MF.getFrameInfo();
2542 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2544 MipsFI->setVarArgsFrameIndex(0);
2546 // Used with vargs to acumulate store chains.
2547 std::vector<SDValue> OutChains;
2549 // Assign locations to all of the incoming arguments.
2550 SmallVector<CCValAssign, 16> ArgLocs;
2551 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2552 getTargetMachine(), ArgLocs, *DAG.getContext());
2555 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2557 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2559 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2561 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2562 CCValAssign &VA = ArgLocs[i];
2563 EVT ValVT = VA.getValVT();
2564 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2565 bool IsRegLoc = VA.isRegLoc();
2567 if (Flags.isByVal()) {
2568 assert(Flags.getByValSize() &&
2569 "ByVal args of size 0 should have been ignored by front-end.");
2571 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2572 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2574 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2575 InVals.push_back(FIN);
2576 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2578 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
2579 MFI, IsRegLoc, InVals, MipsFI,
2584 // Arguments stored on registers
2586 EVT RegVT = VA.getLocVT();
2587 unsigned ArgReg = VA.getLocReg();
2588 TargetRegisterClass *RC = 0;
2590 if (RegVT == MVT::i32)
2591 RC = Mips::CPURegsRegisterClass;
2592 else if (RegVT == MVT::i64)
2593 RC = Mips::CPU64RegsRegisterClass;
2594 else if (RegVT == MVT::f32)
2595 RC = Mips::FGR32RegisterClass;
2596 else if (RegVT == MVT::f64)
2597 RC = HasMips64 ? Mips::FGR64RegisterClass : Mips::AFGR64RegisterClass;
2599 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2601 // Transform the arguments stored on
2602 // physical registers into virtual ones
2603 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2604 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2606 // If this is an 8 or 16-bit value, it has been passed promoted
2607 // to 32 bits. Insert an assert[sz]ext to capture this, then
2608 // truncate to the right size.
2609 if (VA.getLocInfo() != CCValAssign::Full) {
2610 unsigned Opcode = 0;
2611 if (VA.getLocInfo() == CCValAssign::SExt)
2612 Opcode = ISD::AssertSext;
2613 else if (VA.getLocInfo() == CCValAssign::ZExt)
2614 Opcode = ISD::AssertZext;
2616 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2617 DAG.getValueType(ValVT));
2618 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
2621 // Handle floating point arguments passed in integer registers.
2622 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2623 (RegVT == MVT::i64 && ValVT == MVT::f64))
2624 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
2625 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2626 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2627 getNextIntArgReg(ArgReg), RC);
2628 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2629 if (!Subtarget->isLittle())
2630 std::swap(ArgValue, ArgValue2);
2631 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2632 ArgValue, ArgValue2);
2635 InVals.push_back(ArgValue);
2636 } else { // VA.isRegLoc()
2639 assert(VA.isMemLoc());
2641 // The stack pointer offset is relative to the caller stack frame.
2642 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2643 VA.getLocMemOffset(), true);
2645 // Create load nodes to retrieve arguments from the stack
2646 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2647 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
2648 MachinePointerInfo::getFixedStack(LastFI),
2649 false, false, false, 0));
2653 // The mips ABIs for returning structs by value requires that we copy
2654 // the sret argument into $v0 for the return. Save the argument into
2655 // a virtual register so that we can access it from the return points.
2656 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2657 unsigned Reg = MipsFI->getSRetReturnReg();
2659 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2660 MipsFI->setSRetReturnReg(Reg);
2662 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2663 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2667 unsigned NumOfRegs = IsO32 ? 4 : 8;
2668 const unsigned *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
2669 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
2670 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
2671 TargetRegisterClass *RC
2672 = IsO32 ? Mips::CPURegsRegisterClass : Mips::CPU64RegsRegisterClass;
2673 unsigned RegSize = RC->getSize();
2674 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
2676 // Offset of the first variable argument from stack pointer.
2677 int FirstVaArgOffset;
2679 if (IsO32 || (Idx == NumOfRegs)) {
2681 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
2683 FirstVaArgOffset = RegSlotOffset;
2685 // Record the frame index of the first variable argument
2686 // which is a value necessary to VASTART.
2687 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
2688 MipsFI->setVarArgsFrameIndex(LastFI);
2690 // Copy the integer registers that have not been used for argument passing
2691 // to the argument register save area. For O32, the save area is allocated
2692 // in the caller's stack frame, while for N32/64, it is allocated in the
2693 // callee's stack frame.
2694 for (int StackOffset = RegSlotOffset;
2695 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
2696 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
2697 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
2698 MVT::getIntegerVT(RegSize * 8));
2699 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
2700 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2701 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2702 MachinePointerInfo(),
2707 MipsFI->setLastInArgFI(LastFI);
2709 // All stores are grouped in one node to allow the matching between
2710 // the size of Ins and InVals. This only happens when on varg functions
2711 if (!OutChains.empty()) {
2712 OutChains.push_back(Chain);
2713 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2714 &OutChains[0], OutChains.size());
2720 //===----------------------------------------------------------------------===//
2721 // Return Value Calling Convention Implementation
2722 //===----------------------------------------------------------------------===//
2725 MipsTargetLowering::LowerReturn(SDValue Chain,
2726 CallingConv::ID CallConv, bool isVarArg,
2727 const SmallVectorImpl<ISD::OutputArg> &Outs,
2728 const SmallVectorImpl<SDValue> &OutVals,
2729 DebugLoc dl, SelectionDAG &DAG) const {
2731 // CCValAssign - represent the assignment of
2732 // the return value to a location
2733 SmallVector<CCValAssign, 16> RVLocs;
2735 // CCState - Info about the registers and stack slot.
2736 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2737 getTargetMachine(), RVLocs, *DAG.getContext());
2739 // Analize return values.
2740 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2742 // If this is the first return lowered for this function, add
2743 // the regs to the liveout set for the function.
2744 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2745 for (unsigned i = 0; i != RVLocs.size(); ++i)
2746 if (RVLocs[i].isRegLoc())
2747 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2752 // Copy the result values into the output registers.
2753 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2754 CCValAssign &VA = RVLocs[i];
2755 assert(VA.isRegLoc() && "Can only return in registers!");
2757 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
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();