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 "llvm/CodeGen/CallingConvLower.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/ValueTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
38 // If I is a shifted mask, set the size (Size) and the first bit of the
39 // mask (Pos), and return true.
40 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
41 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
42 if (!isUInt<32>(I) || !isShiftedMask_32(I))
45 Size = CountPopulation_32(I);
46 Pos = CountTrailingZeros_32(I);
50 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
52 case MipsISD::JmpLink: return "MipsISD::JmpLink";
53 case MipsISD::Hi: return "MipsISD::Hi";
54 case MipsISD::Lo: return "MipsISD::Lo";
55 case MipsISD::GPRel: return "MipsISD::GPRel";
56 case MipsISD::TlsGd: return "MipsISD::TlsGd";
57 case MipsISD::TprelHi: return "MipsISD::TprelHi";
58 case MipsISD::TprelLo: return "MipsISD::TprelLo";
59 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
60 case MipsISD::Ret: return "MipsISD::Ret";
61 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
62 case MipsISD::FPCmp: return "MipsISD::FPCmp";
63 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
64 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
65 case MipsISD::FPRound: return "MipsISD::FPRound";
66 case MipsISD::MAdd: return "MipsISD::MAdd";
67 case MipsISD::MAddu: return "MipsISD::MAddu";
68 case MipsISD::MSub: return "MipsISD::MSub";
69 case MipsISD::MSubu: return "MipsISD::MSubu";
70 case MipsISD::DivRem: return "MipsISD::DivRem";
71 case MipsISD::DivRemU: return "MipsISD::DivRemU";
72 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
73 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
74 case MipsISD::WrapperPIC: return "MipsISD::WrapperPIC";
75 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
76 case MipsISD::Sync: return "MipsISD::Sync";
77 case MipsISD::Ext: return "MipsISD::Ext";
78 case MipsISD::Ins: return "MipsISD::Ins";
84 MipsTargetLowering(MipsTargetMachine &TM)
85 : TargetLowering(TM, new MipsTargetObjectFile()) {
86 Subtarget = &TM.getSubtarget<MipsSubtarget>();
87 bool HasMips64 = Subtarget->hasMips64();
89 // Mips does not have i1 type, so use i32 for
90 // setcc operations results (slt, sgt, ...).
91 setBooleanContents(ZeroOrOneBooleanContent);
92 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
94 // Set up the register classes
95 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
96 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
98 // When dealing with single precision only, use libcalls
99 if (!Subtarget->isSingleFloat()) {
101 addRegisterClass(MVT::f64, Mips::FGR64RegisterClass);
103 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
106 // Load extented operations for i1 types must be promoted
107 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
108 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
109 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
111 // MIPS doesn't have extending float->double load/store
112 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
113 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
115 // Used by legalize types to correctly generate the setcc result.
116 // Without this, every float setcc comes with a AND/OR with the result,
117 // we don't want this, since the fpcmp result goes to a flag register,
118 // which is used implicitly by brcond and select operations.
119 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
121 // Mips Custom Operations
122 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
123 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
124 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
125 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
126 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
127 setOperationAction(ISD::SELECT, MVT::f32, Custom);
128 setOperationAction(ISD::SELECT, MVT::f64, Custom);
129 setOperationAction(ISD::SELECT, MVT::i32, Custom);
130 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
131 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
132 setOperationAction(ISD::VASTART, MVT::Other, Custom);
134 setOperationAction(ISD::SDIV, MVT::i32, Expand);
135 setOperationAction(ISD::SREM, MVT::i32, Expand);
136 setOperationAction(ISD::UDIV, MVT::i32, Expand);
137 setOperationAction(ISD::UREM, MVT::i32, Expand);
139 // Operations not directly supported by Mips.
140 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
141 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
142 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
143 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
144 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
145 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
146 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
147 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
148 setOperationAction(ISD::ROTL, MVT::i32, Expand);
150 if (!Subtarget->hasMips32r2())
151 setOperationAction(ISD::ROTR, MVT::i32, Expand);
153 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
154 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
155 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
156 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
157 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
158 setOperationAction(ISD::FSIN, MVT::f32, Expand);
159 setOperationAction(ISD::FSIN, MVT::f64, Expand);
160 setOperationAction(ISD::FCOS, MVT::f32, Expand);
161 setOperationAction(ISD::FCOS, MVT::f64, Expand);
162 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
163 setOperationAction(ISD::FPOW, MVT::f32, Expand);
164 setOperationAction(ISD::FPOW, MVT::f64, Expand);
165 setOperationAction(ISD::FLOG, MVT::f32, Expand);
166 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
167 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
168 setOperationAction(ISD::FEXP, MVT::f32, Expand);
169 setOperationAction(ISD::FMA, MVT::f32, Expand);
170 setOperationAction(ISD::FMA, MVT::f64, Expand);
172 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
173 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
175 setOperationAction(ISD::VAARG, MVT::Other, Expand);
176 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
177 setOperationAction(ISD::VAEND, MVT::Other, Expand);
179 // Use the default for now
180 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
181 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
183 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
184 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
186 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
187 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
189 setInsertFencesForAtomic(true);
191 if (Subtarget->isSingleFloat())
192 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
194 if (!Subtarget->hasSEInReg()) {
195 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
196 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
199 if (!Subtarget->hasBitCount())
200 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
202 if (!Subtarget->hasSwap())
203 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
205 setTargetDAGCombine(ISD::ADDE);
206 setTargetDAGCombine(ISD::SUBE);
207 setTargetDAGCombine(ISD::SDIVREM);
208 setTargetDAGCombine(ISD::UDIVREM);
209 setTargetDAGCombine(ISD::SETCC);
210 setTargetDAGCombine(ISD::AND);
211 setTargetDAGCombine(ISD::OR);
213 setMinFunctionAlignment(2);
215 setStackPointerRegisterToSaveRestore(Mips::SP);
216 computeRegisterProperties();
218 setExceptionPointerRegister(Mips::A0);
219 setExceptionSelectorRegister(Mips::A1);
222 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
223 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
224 return SVT == MVT::i32 || SVT == MVT::i16;
227 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
232 // Transforms a subgraph in CurDAG if the following pattern is found:
233 // (addc multLo, Lo0), (adde multHi, Hi0),
235 // multHi/Lo: product of multiplication
236 // Lo0: initial value of Lo register
237 // Hi0: initial value of Hi register
238 // Return true if pattern matching was successful.
239 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
240 // ADDENode's second operand must be a flag output of an ADDC node in order
241 // for the matching to be successful.
242 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
244 if (ADDCNode->getOpcode() != ISD::ADDC)
247 SDValue MultHi = ADDENode->getOperand(0);
248 SDValue MultLo = ADDCNode->getOperand(0);
249 SDNode* MultNode = MultHi.getNode();
250 unsigned MultOpc = MultHi.getOpcode();
252 // MultHi and MultLo must be generated by the same node,
253 if (MultLo.getNode() != MultNode)
256 // and it must be a multiplication.
257 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
260 // MultLo amd MultHi must be the first and second output of MultNode
262 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
265 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
266 // of the values of MultNode, in which case MultNode will be removed in later
268 // If there exist users other than ADDENode or ADDCNode, this function returns
269 // here, which will result in MultNode being mapped to a single MULT
270 // instruction node rather than a pair of MULT and MADD instructions being
272 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
275 SDValue Chain = CurDAG->getEntryNode();
276 DebugLoc dl = ADDENode->getDebugLoc();
278 // create MipsMAdd(u) node
279 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
281 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
283 MultNode->getOperand(0),// Factor 0
284 MultNode->getOperand(1),// Factor 1
285 ADDCNode->getOperand(1),// Lo0
286 ADDENode->getOperand(1));// Hi0
288 // create CopyFromReg nodes
289 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
291 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
293 CopyFromLo.getValue(2));
295 // replace uses of adde and addc here
296 if (!SDValue(ADDCNode, 0).use_empty())
297 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
299 if (!SDValue(ADDENode, 0).use_empty())
300 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
306 // Transforms a subgraph in CurDAG if the following pattern is found:
307 // (addc Lo0, multLo), (sube Hi0, multHi),
309 // multHi/Lo: product of multiplication
310 // Lo0: initial value of Lo register
311 // Hi0: initial value of Hi register
312 // Return true if pattern matching was successful.
313 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
314 // SUBENode's second operand must be a flag output of an SUBC node in order
315 // for the matching to be successful.
316 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
318 if (SUBCNode->getOpcode() != ISD::SUBC)
321 SDValue MultHi = SUBENode->getOperand(1);
322 SDValue MultLo = SUBCNode->getOperand(1);
323 SDNode* MultNode = MultHi.getNode();
324 unsigned MultOpc = MultHi.getOpcode();
326 // MultHi and MultLo must be generated by the same node,
327 if (MultLo.getNode() != MultNode)
330 // and it must be a multiplication.
331 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
334 // MultLo amd MultHi must be the first and second output of MultNode
336 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
339 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
340 // of the values of MultNode, in which case MultNode will be removed in later
342 // If there exist users other than SUBENode or SUBCNode, this function returns
343 // here, which will result in MultNode being mapped to a single MULT
344 // instruction node rather than a pair of MULT and MSUB instructions being
346 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
349 SDValue Chain = CurDAG->getEntryNode();
350 DebugLoc dl = SUBENode->getDebugLoc();
352 // create MipsSub(u) node
353 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
355 SDValue MSub = CurDAG->getNode(MultOpc, dl,
357 MultNode->getOperand(0),// Factor 0
358 MultNode->getOperand(1),// Factor 1
359 SUBCNode->getOperand(0),// Lo0
360 SUBENode->getOperand(0));// Hi0
362 // create CopyFromReg nodes
363 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
365 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
367 CopyFromLo.getValue(2));
369 // replace uses of sube and subc here
370 if (!SDValue(SUBCNode, 0).use_empty())
371 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
373 if (!SDValue(SUBENode, 0).use_empty())
374 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
379 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
380 TargetLowering::DAGCombinerInfo &DCI,
381 const MipsSubtarget* Subtarget) {
382 if (DCI.isBeforeLegalize())
385 if (Subtarget->hasMips32() && SelectMadd(N, &DAG))
386 return SDValue(N, 0);
391 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
392 TargetLowering::DAGCombinerInfo &DCI,
393 const MipsSubtarget* Subtarget) {
394 if (DCI.isBeforeLegalize())
397 if (Subtarget->hasMips32() && SelectMsub(N, &DAG))
398 return SDValue(N, 0);
403 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
404 TargetLowering::DAGCombinerInfo &DCI,
405 const MipsSubtarget* Subtarget) {
406 if (DCI.isBeforeLegalizeOps())
409 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
411 DebugLoc dl = N->getDebugLoc();
413 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
414 N->getOperand(0), N->getOperand(1));
415 SDValue InChain = DAG.getEntryNode();
416 SDValue InGlue = DivRem;
419 if (N->hasAnyUseOfValue(0)) {
420 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
422 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
423 InChain = CopyFromLo.getValue(1);
424 InGlue = CopyFromLo.getValue(2);
428 if (N->hasAnyUseOfValue(1)) {
429 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
430 Mips::HI, MVT::i32, InGlue);
431 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
437 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
439 default: llvm_unreachable("Unknown fp condition code!");
441 case ISD::SETOEQ: return Mips::FCOND_OEQ;
442 case ISD::SETUNE: return Mips::FCOND_UNE;
444 case ISD::SETOLT: return Mips::FCOND_OLT;
446 case ISD::SETOGT: return Mips::FCOND_OGT;
448 case ISD::SETOLE: return Mips::FCOND_OLE;
450 case ISD::SETOGE: return Mips::FCOND_OGE;
451 case ISD::SETULT: return Mips::FCOND_ULT;
452 case ISD::SETULE: return Mips::FCOND_ULE;
453 case ISD::SETUGT: return Mips::FCOND_UGT;
454 case ISD::SETUGE: return Mips::FCOND_UGE;
455 case ISD::SETUO: return Mips::FCOND_UN;
456 case ISD::SETO: return Mips::FCOND_OR;
458 case ISD::SETONE: return Mips::FCOND_ONE;
459 case ISD::SETUEQ: return Mips::FCOND_UEQ;
464 // Returns true if condition code has to be inverted.
465 static bool InvertFPCondCode(Mips::CondCode CC) {
466 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
469 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
472 assert(false && "Illegal Condition Code");
476 // Creates and returns an FPCmp node from a setcc node.
477 // Returns Op if setcc is not a floating point comparison.
478 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
479 // must be a SETCC node
480 if (Op.getOpcode() != ISD::SETCC)
483 SDValue LHS = Op.getOperand(0);
485 if (!LHS.getValueType().isFloatingPoint())
488 SDValue RHS = Op.getOperand(1);
489 DebugLoc dl = Op.getDebugLoc();
491 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
492 // node if necessary.
493 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
495 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
496 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
499 // Creates and returns a CMovFPT/F node.
500 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
501 SDValue False, DebugLoc DL) {
502 bool invert = InvertFPCondCode((Mips::CondCode)
503 cast<ConstantSDNode>(Cond.getOperand(2))
506 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
507 True.getValueType(), True, False, Cond);
510 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
511 TargetLowering::DAGCombinerInfo &DCI,
512 const MipsSubtarget* Subtarget) {
513 if (DCI.isBeforeLegalizeOps())
516 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
518 if (Cond.getOpcode() != MipsISD::FPCmp)
521 SDValue True = DAG.getConstant(1, MVT::i32);
522 SDValue False = DAG.getConstant(0, MVT::i32);
524 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
527 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
528 TargetLowering::DAGCombinerInfo &DCI,
529 const MipsSubtarget* Subtarget) {
530 // Pattern match EXT.
531 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
532 // => ext $dst, $src, size, pos
533 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
536 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
538 // Op's first operand must be a shift right.
539 if (ShiftRight.getOpcode() != ISD::SRA && ShiftRight.getOpcode() != ISD::SRL)
542 // The second operand of the shift must be an immediate.
545 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
548 Pos = CN->getZExtValue();
550 uint64_t SMPos, SMSize;
551 // Op's second operand must be a shifted mask.
552 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
553 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
556 // Return if the shifted mask does not start at bit 0 or the sum of its size
557 // and Pos exceeds the word's size.
558 if (SMPos != 0 || Pos + SMSize > 32)
561 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
562 ShiftRight.getOperand(0),
563 DAG.getConstant(Pos, MVT::i32),
564 DAG.getConstant(SMSize, MVT::i32));
567 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
568 TargetLowering::DAGCombinerInfo &DCI,
569 const MipsSubtarget* Subtarget) {
570 // Pattern match INS.
571 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
572 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
573 // => ins $dst, $src, size, pos, $src1
574 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
577 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
578 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
581 // See if Op's first operand matches (and $src1 , mask0).
582 if (And0.getOpcode() != ISD::AND)
585 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
586 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
589 // See if Op's second operand matches (and (shl $src, pos), mask1).
590 if (And1.getOpcode() != ISD::AND)
593 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
594 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
597 // The shift masks must have the same position and size.
598 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
601 SDValue Shl = And1.getOperand(0);
602 if (Shl.getOpcode() != ISD::SHL)
605 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
608 unsigned Shamt = CN->getZExtValue();
610 // Return if the shift amount and the first bit position of mask are not the
615 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
617 DAG.getConstant(SMPos0, MVT::i32),
618 DAG.getConstant(SMSize0, MVT::i32),
622 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
624 SelectionDAG &DAG = DCI.DAG;
625 unsigned opc = N->getOpcode();
630 return PerformADDECombine(N, DAG, DCI, Subtarget);
632 return PerformSUBECombine(N, DAG, DCI, Subtarget);
635 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
637 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
639 return PerformANDCombine(N, DAG, DCI, Subtarget);
641 return PerformORCombine(N, DAG, DCI, Subtarget);
647 SDValue MipsTargetLowering::
648 LowerOperation(SDValue Op, SelectionDAG &DAG) const
650 switch (Op.getOpcode())
652 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
653 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
654 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
655 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
656 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
657 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
658 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
659 case ISD::SELECT: return LowerSELECT(Op, DAG);
660 case ISD::VASTART: return LowerVASTART(Op, DAG);
661 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
662 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
663 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
664 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
669 //===----------------------------------------------------------------------===//
670 // Lower helper functions
671 //===----------------------------------------------------------------------===//
673 // AddLiveIn - This helper function adds the specified physical register to the
674 // MachineFunction as a live in value. It also creates a corresponding
675 // virtual register for it.
677 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
679 assert(RC->contains(PReg) && "Not the correct regclass!");
680 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
681 MF.getRegInfo().addLiveIn(PReg, VReg);
685 // Get fp branch code (not opcode) from condition code.
686 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
687 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
688 return Mips::BRANCH_T;
690 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
691 return Mips::BRANCH_F;
693 return Mips::BRANCH_INVALID;
696 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
698 const MipsSubtarget* Subtarget,
699 const TargetInstrInfo *TII,
700 bool isFPCmp, unsigned Opc) {
701 // There is no need to expand CMov instructions if target has
702 // conditional moves.
703 if (Subtarget->hasCondMov())
706 // To "insert" a SELECT_CC instruction, we actually have to insert the
707 // diamond control-flow pattern. The incoming instruction knows the
708 // destination vreg to set, the condition code register to branch on, the
709 // true/false values to select between, and a branch opcode to use.
710 const BasicBlock *LLVM_BB = BB->getBasicBlock();
711 MachineFunction::iterator It = BB;
718 // bNE r1, r0, copy1MBB
719 // fallthrough --> copy0MBB
720 MachineBasicBlock *thisMBB = BB;
721 MachineFunction *F = BB->getParent();
722 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
723 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
724 F->insert(It, copy0MBB);
725 F->insert(It, sinkMBB);
727 // Transfer the remainder of BB and its successor edges to sinkMBB.
728 sinkMBB->splice(sinkMBB->begin(), BB,
729 llvm::next(MachineBasicBlock::iterator(MI)),
731 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
733 // Next, add the true and fallthrough blocks as its successors.
734 BB->addSuccessor(copy0MBB);
735 BB->addSuccessor(sinkMBB);
737 // Emit the right instruction according to the type of the operands compared
739 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
741 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
742 .addReg(Mips::ZERO).addMBB(sinkMBB);
746 // # fallthrough to sinkMBB
749 // Update machine-CFG edges
750 BB->addSuccessor(sinkMBB);
753 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
758 BuildMI(*BB, BB->begin(), dl,
759 TII->get(Mips::PHI), MI->getOperand(0).getReg())
760 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
761 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
763 BuildMI(*BB, BB->begin(), dl,
764 TII->get(Mips::PHI), MI->getOperand(0).getReg())
765 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
766 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
768 MI->eraseFromParent(); // The pseudo instruction is gone now.
773 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
774 MachineBasicBlock *BB) const {
775 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
776 DebugLoc dl = MI->getDebugLoc();
778 switch (MI->getOpcode()) {
780 assert(false && "Unexpected instr type to insert");
785 return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1F);
789 return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1T);
793 return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BNE);
797 return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BEQ);
799 case Mips::ATOMIC_LOAD_ADD_I8:
800 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
801 case Mips::ATOMIC_LOAD_ADD_I16:
802 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
803 case Mips::ATOMIC_LOAD_ADD_I32:
804 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
806 case Mips::ATOMIC_LOAD_AND_I8:
807 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
808 case Mips::ATOMIC_LOAD_AND_I16:
809 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
810 case Mips::ATOMIC_LOAD_AND_I32:
811 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
813 case Mips::ATOMIC_LOAD_OR_I8:
814 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
815 case Mips::ATOMIC_LOAD_OR_I16:
816 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
817 case Mips::ATOMIC_LOAD_OR_I32:
818 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
820 case Mips::ATOMIC_LOAD_XOR_I8:
821 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
822 case Mips::ATOMIC_LOAD_XOR_I16:
823 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
824 case Mips::ATOMIC_LOAD_XOR_I32:
825 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
827 case Mips::ATOMIC_LOAD_NAND_I8:
828 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
829 case Mips::ATOMIC_LOAD_NAND_I16:
830 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
831 case Mips::ATOMIC_LOAD_NAND_I32:
832 return EmitAtomicBinary(MI, BB, 4, 0, true);
834 case Mips::ATOMIC_LOAD_SUB_I8:
835 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
836 case Mips::ATOMIC_LOAD_SUB_I16:
837 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
838 case Mips::ATOMIC_LOAD_SUB_I32:
839 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
841 case Mips::ATOMIC_SWAP_I8:
842 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
843 case Mips::ATOMIC_SWAP_I16:
844 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
845 case Mips::ATOMIC_SWAP_I32:
846 return EmitAtomicBinary(MI, BB, 4, 0);
848 case Mips::ATOMIC_CMP_SWAP_I8:
849 return EmitAtomicCmpSwapPartword(MI, BB, 1);
850 case Mips::ATOMIC_CMP_SWAP_I16:
851 return EmitAtomicCmpSwapPartword(MI, BB, 2);
852 case Mips::ATOMIC_CMP_SWAP_I32:
853 return EmitAtomicCmpSwap(MI, BB, 4);
857 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
858 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
860 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
861 unsigned Size, unsigned BinOpcode,
863 assert(Size == 4 && "Unsupported size for EmitAtomicBinary.");
865 MachineFunction *MF = BB->getParent();
866 MachineRegisterInfo &RegInfo = MF->getRegInfo();
867 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
868 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
869 DebugLoc dl = MI->getDebugLoc();
871 unsigned OldVal = MI->getOperand(0).getReg();
872 unsigned Ptr = MI->getOperand(1).getReg();
873 unsigned Incr = MI->getOperand(2).getReg();
875 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
876 unsigned AndRes = RegInfo.createVirtualRegister(RC);
877 unsigned Success = RegInfo.createVirtualRegister(RC);
879 // insert new blocks after the current block
880 const BasicBlock *LLVM_BB = BB->getBasicBlock();
881 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
882 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
883 MachineFunction::iterator It = BB;
885 MF->insert(It, loopMBB);
886 MF->insert(It, exitMBB);
888 // Transfer the remainder of BB and its successor edges to exitMBB.
889 exitMBB->splice(exitMBB->begin(), BB,
890 llvm::next(MachineBasicBlock::iterator(MI)),
892 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
896 // fallthrough --> loopMBB
897 BB->addSuccessor(loopMBB);
898 loopMBB->addSuccessor(loopMBB);
899 loopMBB->addSuccessor(exitMBB);
903 // <binop> storeval, oldval, incr
904 // sc success, storeval, 0(ptr)
905 // beq success, $0, loopMBB
907 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(Ptr).addImm(0);
909 // and andres, oldval, incr
910 // nor storeval, $0, andres
911 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr);
912 BuildMI(BB, dl, TII->get(Mips::NOR), StoreVal)
913 .addReg(Mips::ZERO).addReg(AndRes);
914 } else if (BinOpcode) {
915 // <binop> storeval, oldval, incr
916 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
920 BuildMI(BB, dl, TII->get(Mips::SC), Success)
921 .addReg(StoreVal).addReg(Ptr).addImm(0);
922 BuildMI(BB, dl, TII->get(Mips::BEQ))
923 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
925 MI->eraseFromParent(); // The instruction is gone now.
931 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
932 MachineBasicBlock *BB,
933 unsigned Size, unsigned BinOpcode,
935 assert((Size == 1 || Size == 2) &&
936 "Unsupported size for EmitAtomicBinaryPartial.");
938 MachineFunction *MF = BB->getParent();
939 MachineRegisterInfo &RegInfo = MF->getRegInfo();
940 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
941 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
942 DebugLoc dl = MI->getDebugLoc();
944 unsigned Dest = MI->getOperand(0).getReg();
945 unsigned Ptr = MI->getOperand(1).getReg();
946 unsigned Incr = MI->getOperand(2).getReg();
948 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
949 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
950 unsigned Mask = RegInfo.createVirtualRegister(RC);
951 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
952 unsigned NewVal = RegInfo.createVirtualRegister(RC);
953 unsigned OldVal = RegInfo.createVirtualRegister(RC);
954 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
955 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
956 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
957 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
958 unsigned AndRes = RegInfo.createVirtualRegister(RC);
959 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
960 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
961 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
962 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
963 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
964 unsigned SllRes = RegInfo.createVirtualRegister(RC);
965 unsigned Success = RegInfo.createVirtualRegister(RC);
967 // insert new blocks after the current block
968 const BasicBlock *LLVM_BB = BB->getBasicBlock();
969 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
970 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
971 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
972 MachineFunction::iterator It = BB;
974 MF->insert(It, loopMBB);
975 MF->insert(It, sinkMBB);
976 MF->insert(It, exitMBB);
978 // Transfer the remainder of BB and its successor edges to exitMBB.
979 exitMBB->splice(exitMBB->begin(), BB,
980 llvm::next(MachineBasicBlock::iterator(MI)),
982 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
984 BB->addSuccessor(loopMBB);
985 loopMBB->addSuccessor(loopMBB);
986 loopMBB->addSuccessor(sinkMBB);
987 sinkMBB->addSuccessor(exitMBB);
990 // addiu masklsb2,$0,-4 # 0xfffffffc
991 // and alignedaddr,ptr,masklsb2
992 // andi ptrlsb2,ptr,3
993 // sll shiftamt,ptrlsb2,3
994 // ori maskupper,$0,255 # 0xff
995 // sll mask,maskupper,shiftamt
997 // sll incr2,incr,shiftamt
999 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1000 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1001 .addReg(Mips::ZERO).addImm(-4);
1002 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1003 .addReg(Ptr).addReg(MaskLSB2);
1004 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1005 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1006 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1007 .addReg(Mips::ZERO).addImm(MaskImm);
1008 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1009 .addReg(ShiftAmt).addReg(MaskUpper);
1010 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1011 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1014 // atomic.load.binop
1016 // ll oldval,0(alignedaddr)
1017 // binop binopres,oldval,incr2
1018 // and newval,binopres,mask
1019 // and maskedoldval0,oldval,mask2
1020 // or storeval,maskedoldval0,newval
1021 // sc success,storeval,0(alignedaddr)
1022 // beq success,$0,loopMBB
1026 // ll oldval,0(alignedaddr)
1027 // and newval,incr2,mask
1028 // and maskedoldval0,oldval,mask2
1029 // or storeval,maskedoldval0,newval
1030 // sc success,storeval,0(alignedaddr)
1031 // beq success,$0,loopMBB
1034 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1036 // and andres, oldval, incr2
1037 // nor binopres, $0, andres
1038 // and newval, binopres, mask
1039 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1040 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1041 .addReg(Mips::ZERO).addReg(AndRes);
1042 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1043 } else if (BinOpcode) {
1044 // <binop> binopres, oldval, incr2
1045 // and newval, binopres, mask
1046 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1047 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1048 } else {// atomic.swap
1049 // and newval, incr2, mask
1050 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1053 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1054 .addReg(OldVal).addReg(Mask2);
1055 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1056 .addReg(MaskedOldVal0).addReg(NewVal);
1057 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1058 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1059 BuildMI(BB, dl, TII->get(Mips::BEQ))
1060 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1063 // and maskedoldval1,oldval,mask
1064 // srl srlres,maskedoldval1,shiftamt
1065 // sll sllres,srlres,24
1066 // sra dest,sllres,24
1068 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1070 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1071 .addReg(OldVal).addReg(Mask);
1072 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1073 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1074 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1075 .addReg(SrlRes).addImm(ShiftImm);
1076 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1077 .addReg(SllRes).addImm(ShiftImm);
1079 MI->eraseFromParent(); // The instruction is gone now.
1085 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1086 MachineBasicBlock *BB,
1087 unsigned Size) const {
1088 assert(Size == 4 && "Unsupported size for EmitAtomicCmpSwap.");
1090 MachineFunction *MF = BB->getParent();
1091 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1092 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1093 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1094 DebugLoc dl = MI->getDebugLoc();
1096 unsigned Dest = MI->getOperand(0).getReg();
1097 unsigned Ptr = MI->getOperand(1).getReg();
1098 unsigned OldVal = MI->getOperand(2).getReg();
1099 unsigned NewVal = MI->getOperand(3).getReg();
1101 unsigned Success = RegInfo.createVirtualRegister(RC);
1103 // insert new blocks after the current block
1104 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1105 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1106 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1107 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1108 MachineFunction::iterator It = BB;
1110 MF->insert(It, loop1MBB);
1111 MF->insert(It, loop2MBB);
1112 MF->insert(It, exitMBB);
1114 // Transfer the remainder of BB and its successor edges to exitMBB.
1115 exitMBB->splice(exitMBB->begin(), BB,
1116 llvm::next(MachineBasicBlock::iterator(MI)),
1118 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1122 // fallthrough --> loop1MBB
1123 BB->addSuccessor(loop1MBB);
1124 loop1MBB->addSuccessor(exitMBB);
1125 loop1MBB->addSuccessor(loop2MBB);
1126 loop2MBB->addSuccessor(loop1MBB);
1127 loop2MBB->addSuccessor(exitMBB);
1131 // bne dest, oldval, exitMBB
1133 BuildMI(BB, dl, TII->get(Mips::LL), Dest).addReg(Ptr).addImm(0);
1134 BuildMI(BB, dl, TII->get(Mips::BNE))
1135 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1138 // sc success, newval, 0(ptr)
1139 // beq success, $0, loop1MBB
1141 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1142 .addReg(NewVal).addReg(Ptr).addImm(0);
1143 BuildMI(BB, dl, TII->get(Mips::BEQ))
1144 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1146 MI->eraseFromParent(); // The instruction is gone now.
1152 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1153 MachineBasicBlock *BB,
1154 unsigned Size) const {
1155 assert((Size == 1 || Size == 2) &&
1156 "Unsupported size for EmitAtomicCmpSwapPartial.");
1158 MachineFunction *MF = BB->getParent();
1159 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1160 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1161 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1162 DebugLoc dl = MI->getDebugLoc();
1164 unsigned Dest = MI->getOperand(0).getReg();
1165 unsigned Ptr = MI->getOperand(1).getReg();
1166 unsigned CmpVal = MI->getOperand(2).getReg();
1167 unsigned NewVal = MI->getOperand(3).getReg();
1169 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1170 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1171 unsigned Mask = RegInfo.createVirtualRegister(RC);
1172 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1173 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1174 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1175 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1176 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1177 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1178 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1179 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1180 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1181 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1182 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1183 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1184 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1185 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1186 unsigned Success = RegInfo.createVirtualRegister(RC);
1188 // insert new blocks after the current block
1189 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1190 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1191 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1192 MachineBasicBlock *sinkMBB = 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, sinkMBB);
1199 MF->insert(It, exitMBB);
1201 // Transfer the remainder of BB and its successor edges to exitMBB.
1202 exitMBB->splice(exitMBB->begin(), BB,
1203 llvm::next(MachineBasicBlock::iterator(MI)),
1205 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1207 BB->addSuccessor(loop1MBB);
1208 loop1MBB->addSuccessor(sinkMBB);
1209 loop1MBB->addSuccessor(loop2MBB);
1210 loop2MBB->addSuccessor(loop1MBB);
1211 loop2MBB->addSuccessor(sinkMBB);
1212 sinkMBB->addSuccessor(exitMBB);
1214 // FIXME: computation of newval2 can be moved to loop2MBB.
1216 // addiu masklsb2,$0,-4 # 0xfffffffc
1217 // and alignedaddr,ptr,masklsb2
1218 // andi ptrlsb2,ptr,3
1219 // sll shiftamt,ptrlsb2,3
1220 // ori maskupper,$0,255 # 0xff
1221 // sll mask,maskupper,shiftamt
1222 // nor mask2,$0,mask
1223 // andi maskedcmpval,cmpval,255
1224 // sll shiftedcmpval,maskedcmpval,shiftamt
1225 // andi maskednewval,newval,255
1226 // sll shiftednewval,maskednewval,shiftamt
1227 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1228 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1229 .addReg(Mips::ZERO).addImm(-4);
1230 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1231 .addReg(Ptr).addReg(MaskLSB2);
1232 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1233 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1234 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1235 .addReg(Mips::ZERO).addImm(MaskImm);
1236 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1237 .addReg(ShiftAmt).addReg(MaskUpper);
1238 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1239 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1240 .addReg(CmpVal).addImm(MaskImm);
1241 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1242 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1243 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1244 .addReg(NewVal).addImm(MaskImm);
1245 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1246 .addReg(ShiftAmt).addReg(MaskedNewVal);
1249 // ll oldval,0(alginedaddr)
1250 // and maskedoldval0,oldval,mask
1251 // bne maskedoldval0,shiftedcmpval,sinkMBB
1253 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1254 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1255 .addReg(OldVal).addReg(Mask);
1256 BuildMI(BB, dl, TII->get(Mips::BNE))
1257 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1260 // and maskedoldval1,oldval,mask2
1261 // or storeval,maskedoldval1,shiftednewval
1262 // sc success,storeval,0(alignedaddr)
1263 // beq success,$0,loop1MBB
1265 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1266 .addReg(OldVal).addReg(Mask2);
1267 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1268 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1269 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1270 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1271 BuildMI(BB, dl, TII->get(Mips::BEQ))
1272 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1275 // srl srlres,maskedoldval0,shiftamt
1276 // sll sllres,srlres,24
1277 // sra dest,sllres,24
1279 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1281 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1282 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1283 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1284 .addReg(SrlRes).addImm(ShiftImm);
1285 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1286 .addReg(SllRes).addImm(ShiftImm);
1288 MI->eraseFromParent(); // The instruction is gone now.
1293 //===----------------------------------------------------------------------===//
1294 // Misc Lower Operation implementation
1295 //===----------------------------------------------------------------------===//
1296 SDValue MipsTargetLowering::
1297 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1299 MachineFunction &MF = DAG.getMachineFunction();
1300 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1302 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1303 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1304 "Cannot lower if the alignment of the allocated space is larger than \
1305 that of the stack.");
1307 SDValue Chain = Op.getOperand(0);
1308 SDValue Size = Op.getOperand(1);
1309 DebugLoc dl = Op.getDebugLoc();
1311 // Get a reference from Mips stack pointer
1312 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
1314 // Subtract the dynamic size from the actual stack size to
1315 // obtain the new stack size.
1316 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
1318 // The Sub result contains the new stack start address, so it
1319 // must be placed in the stack pointer register.
1320 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
1323 // This node always has two return values: a new stack pointer
1324 // value and a chain
1325 SDVTList VTLs = DAG.getVTList(MVT::i32, MVT::Other);
1326 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1327 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1329 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1332 SDValue MipsTargetLowering::
1333 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1335 // The first operand is the chain, the second is the condition, the third is
1336 // the block to branch to if the condition is true.
1337 SDValue Chain = Op.getOperand(0);
1338 SDValue Dest = Op.getOperand(2);
1339 DebugLoc dl = Op.getDebugLoc();
1341 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1343 // Return if flag is not set by a floating point comparison.
1344 if (CondRes.getOpcode() != MipsISD::FPCmp)
1347 SDValue CCNode = CondRes.getOperand(2);
1349 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1350 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1352 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1356 SDValue MipsTargetLowering::
1357 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1359 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1361 // Return if flag is not set by a floating point comparison.
1362 if (Cond.getOpcode() != MipsISD::FPCmp)
1365 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1369 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1370 SelectionDAG &DAG) const {
1371 // FIXME there isn't actually debug info here
1372 DebugLoc dl = Op.getDebugLoc();
1373 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1375 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1376 SDVTList VTs = DAG.getVTList(MVT::i32);
1378 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1380 // %gp_rel relocation
1381 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1382 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1384 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1385 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1386 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1388 // %hi/%lo relocation
1389 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1391 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1393 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1394 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1395 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1398 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1400 GA = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, GA);
1401 SDValue ResNode = DAG.getLoad(MVT::i32, dl,
1402 DAG.getEntryNode(), GA, MachinePointerInfo(),
1404 // On functions and global targets not internal linked only
1405 // a load from got/GP is necessary for PIC to work.
1406 if (!GV->hasInternalLinkage() &&
1407 (!GV->hasLocalLinkage() || isa<Function>(GV)))
1409 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1411 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1412 return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
1415 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1416 SelectionDAG &DAG) const {
1417 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1418 // FIXME there isn't actually debug info here
1419 DebugLoc dl = Op.getDebugLoc();
1421 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1422 // %hi/%lo relocation
1423 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1425 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1427 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1428 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1429 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1432 SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1434 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1435 SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1437 SDValue Load = DAG.getLoad(MVT::i32, dl,
1438 DAG.getEntryNode(), BAGOTOffset,
1439 MachinePointerInfo(), false, false, 0);
1440 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1441 return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1444 SDValue MipsTargetLowering::
1445 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1447 // If the relocation model is PIC, use the General Dynamic TLS Model,
1448 // otherwise use the Initial Exec or Local Exec TLS Model.
1449 // TODO: implement Local Dynamic TLS model
1451 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1452 DebugLoc dl = GA->getDebugLoc();
1453 const GlobalValue *GV = GA->getGlobal();
1454 EVT PtrVT = getPointerTy();
1456 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1457 // General Dynamic TLS Model
1458 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1459 0, MipsII::MO_TLSGD);
1460 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1461 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1462 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1466 Entry.Node = Argument;
1467 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1468 Args.push_back(Entry);
1469 std::pair<SDValue, SDValue> CallResult =
1470 LowerCallTo(DAG.getEntryNode(),
1471 (Type *) Type::getInt32Ty(*DAG.getContext()),
1472 false, false, false, false, 0, CallingConv::C, false, true,
1473 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1476 return CallResult.first;
1480 if (GV->isDeclaration()) {
1481 // Initial Exec TLS Model
1482 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1483 MipsII::MO_GOTTPREL);
1484 Offset = DAG.getLoad(MVT::i32, dl,
1485 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1488 // Local Exec TLS Model
1489 SDVTList VTs = DAG.getVTList(MVT::i32);
1490 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1491 MipsII::MO_TPREL_HI);
1492 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1493 MipsII::MO_TPREL_LO);
1494 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1495 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1496 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1499 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1500 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1503 SDValue MipsTargetLowering::
1504 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1508 // FIXME there isn't actually debug info here
1509 DebugLoc dl = Op.getDebugLoc();
1510 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1511 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1513 EVT PtrVT = Op.getValueType();
1514 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1516 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1519 SDValue Ops[] = { JTI };
1520 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1521 } else {// Emit Load from Global Pointer
1522 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1523 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1524 MachinePointerInfo(),
1528 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1530 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1531 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1536 SDValue MipsTargetLowering::
1537 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1540 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1541 const Constant *C = N->getConstVal();
1542 // FIXME there isn't actually debug info here
1543 DebugLoc dl = Op.getDebugLoc();
1545 // gp_rel relocation
1546 // FIXME: we should reference the constant pool using small data sections,
1547 // but the asm printer currently doesn't support this feature without
1548 // hacking it. This feature should come soon so we can uncomment the
1550 //if (IsInSmallSection(C->getType())) {
1551 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1552 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1553 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1555 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1556 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1557 N->getOffset(), MipsII::MO_ABS_HI);
1558 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1559 N->getOffset(), MipsII::MO_ABS_LO);
1560 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1561 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1562 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1564 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1565 N->getOffset(), MipsII::MO_GOT);
1566 CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1567 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1568 CP, MachinePointerInfo::getConstantPool(),
1570 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1571 N->getOffset(), MipsII::MO_ABS_LO);
1572 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1573 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1579 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1580 MachineFunction &MF = DAG.getMachineFunction();
1581 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1583 DebugLoc dl = Op.getDebugLoc();
1584 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1587 // vastart just stores the address of the VarArgsFrameIndex slot into the
1588 // memory location argument.
1589 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1590 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1591 MachinePointerInfo(SV),
1595 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1596 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1597 DebugLoc dl = Op.getDebugLoc();
1598 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1599 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1600 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1601 DAG.getConstant(0x7fffffff, MVT::i32));
1602 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1603 DAG.getConstant(0x80000000, MVT::i32));
1604 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1605 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1608 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1610 // Use ext/ins instructions if target architecture is Mips32r2.
1611 // Eliminate redundant mfc1 and mtc1 instructions.
1612 unsigned LoIdx = 0, HiIdx = 1;
1615 std::swap(LoIdx, HiIdx);
1617 DebugLoc dl = Op.getDebugLoc();
1618 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1620 DAG.getConstant(LoIdx, MVT::i32));
1621 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1622 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1623 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1624 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1625 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1626 DAG.getConstant(0x7fffffff, MVT::i32));
1627 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1628 DAG.getConstant(0x80000000, MVT::i32));
1629 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1632 std::swap(Word0, Word1);
1634 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1637 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1639 EVT Ty = Op.getValueType();
1641 assert(Ty == MVT::f32 || Ty == MVT::f64);
1644 return LowerFCOPYSIGN32(Op, DAG);
1646 return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1649 SDValue MipsTargetLowering::
1650 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1652 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1653 "Frame address can only be determined for current frame.");
1655 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1656 MFI->setFrameAddressIsTaken(true);
1657 EVT VT = Op.getValueType();
1658 DebugLoc dl = Op.getDebugLoc();
1659 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Mips::FP, VT);
1663 // TODO: set SType according to the desired memory barrier behavior.
1664 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1665 SelectionDAG& DAG) const {
1667 DebugLoc dl = Op.getDebugLoc();
1668 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1669 DAG.getConstant(SType, MVT::i32));
1672 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1673 SelectionDAG& DAG) const {
1674 // FIXME: Need pseudo-fence for 'singlethread' fences
1675 // FIXME: Set SType for weaker fences where supported/appropriate.
1677 DebugLoc dl = Op.getDebugLoc();
1678 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1679 DAG.getConstant(SType, MVT::i32));
1682 //===----------------------------------------------------------------------===//
1683 // Calling Convention Implementation
1684 //===----------------------------------------------------------------------===//
1686 #include "MipsGenCallingConv.inc"
1688 //===----------------------------------------------------------------------===//
1689 // TODO: Implement a generic logic using tblgen that can support this.
1690 // Mips O32 ABI rules:
1692 // i32 - Passed in A0, A1, A2, A3 and stack
1693 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1694 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1695 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1696 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1697 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1700 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1701 //===----------------------------------------------------------------------===//
1703 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1704 MVT LocVT, CCValAssign::LocInfo LocInfo,
1705 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1707 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1709 static const unsigned IntRegs[] = {
1710 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1712 static const unsigned F32Regs[] = {
1713 Mips::F12, Mips::F14
1715 static const unsigned F64Regs[] = {
1720 if (ArgFlags.isByVal()) {
1721 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1722 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1723 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1724 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1725 r < std::min(IntRegsSize, NextReg); ++r)
1726 State.AllocateReg(IntRegs[r]);
1730 // Promote i8 and i16
1731 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1733 if (ArgFlags.isSExt())
1734 LocInfo = CCValAssign::SExt;
1735 else if (ArgFlags.isZExt())
1736 LocInfo = CCValAssign::ZExt;
1738 LocInfo = CCValAssign::AExt;
1743 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1744 // is true: function is vararg, argument is 3rd or higher, there is previous
1745 // argument which is not f32 or f64.
1746 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1747 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1748 unsigned OrigAlign = ArgFlags.getOrigAlign();
1749 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1751 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1752 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1753 // If this is the first part of an i64 arg,
1754 // the allocated register must be either A0 or A2.
1755 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1756 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1758 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1759 // Allocate int register and shadow next int register. If first
1760 // available register is Mips::A1 or Mips::A3, shadow it too.
1761 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1762 if (Reg == Mips::A1 || Reg == Mips::A3)
1763 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1764 State.AllocateReg(IntRegs, IntRegsSize);
1766 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1767 // we are guaranteed to find an available float register
1768 if (ValVT == MVT::f32) {
1769 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1770 // Shadow int register
1771 State.AllocateReg(IntRegs, IntRegsSize);
1773 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1774 // Shadow int registers
1775 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1776 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1777 State.AllocateReg(IntRegs, IntRegsSize);
1778 State.AllocateReg(IntRegs, IntRegsSize);
1781 llvm_unreachable("Cannot handle this ValVT.");
1783 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1784 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1787 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1789 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1791 return false; // CC must always match
1794 //===----------------------------------------------------------------------===//
1795 // Call Calling Convention Implementation
1796 //===----------------------------------------------------------------------===//
1798 static const unsigned O32IntRegsSize = 4;
1800 static const unsigned O32IntRegs[] = {
1801 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1804 // Return next O32 integer argument register.
1805 static unsigned getNextIntArgReg(unsigned Reg) {
1806 assert((Reg == Mips::A0) || (Reg == Mips::A2));
1807 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
1810 // Write ByVal Arg to arg registers and stack.
1812 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1813 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1814 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1815 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1816 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1817 MVT PtrType, bool isLittle) {
1818 unsigned LocMemOffset = VA.getLocMemOffset();
1819 unsigned Offset = 0;
1820 uint32_t RemainingSize = Flags.getByValSize();
1821 unsigned ByValAlign = Flags.getByValAlign();
1823 // Copy the first 4 words of byval arg to registers A0 - A3.
1824 // FIXME: Use a stricter alignment if it enables better optimization in passes
1826 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1827 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1828 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1829 DAG.getConstant(Offset, MVT::i32));
1830 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1831 MachinePointerInfo(),
1832 false, false, std::min(ByValAlign,
1834 MemOpChains.push_back(LoadVal.getValue(1));
1835 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1836 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1839 if (RemainingSize == 0)
1842 // If there still is a register available for argument passing, write the
1843 // remaining part of the structure to it using subword loads and shifts.
1844 if (LocMemOffset < 4 * 4) {
1845 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
1846 "There must be one to three bytes remaining.");
1847 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
1848 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1849 DAG.getConstant(Offset, MVT::i32));
1850 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
1851 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
1852 LoadPtr, MachinePointerInfo(),
1853 MVT::getIntegerVT(LoadSize * 8), false,
1855 MemOpChains.push_back(LoadVal.getValue(1));
1857 // If target is big endian, shift it to the most significant half-word or
1860 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
1861 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
1864 RemainingSize -= LoadSize;
1866 // Read second subword if necessary.
1867 if (RemainingSize != 0) {
1868 assert(RemainingSize == 1 && "There must be one byte remaining.");
1869 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1870 DAG.getConstant(Offset, MVT::i32));
1871 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
1872 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
1873 LoadPtr, MachinePointerInfo(),
1874 MVT::i8, false, false, Alignment);
1875 MemOpChains.push_back(Subword.getValue(1));
1876 // Insert the loaded byte to LoadVal.
1877 // FIXME: Use INS if supported by target.
1878 unsigned ShiftAmt = isLittle ? 16 : 8;
1879 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
1880 DAG.getConstant(ShiftAmt, MVT::i32));
1881 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
1884 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1885 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1889 // Create a fixed object on stack at offset LocMemOffset and copy
1890 // remaining part of byval arg to it using memcpy.
1891 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1892 DAG.getConstant(Offset, MVT::i32));
1893 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
1894 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
1895 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
1896 DAG.getConstant(RemainingSize, MVT::i32),
1897 std::min(ByValAlign, (unsigned)4),
1898 /*isVolatile=*/false, /*AlwaysInline=*/false,
1899 MachinePointerInfo(0), MachinePointerInfo(0));
1902 /// LowerCall - functions arguments are copied from virtual regs to
1903 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1904 /// TODO: isTailCall.
1906 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
1907 CallingConv::ID CallConv, bool isVarArg,
1909 const SmallVectorImpl<ISD::OutputArg> &Outs,
1910 const SmallVectorImpl<SDValue> &OutVals,
1911 const SmallVectorImpl<ISD::InputArg> &Ins,
1912 DebugLoc dl, SelectionDAG &DAG,
1913 SmallVectorImpl<SDValue> &InVals) const {
1914 // MIPs target does not yet support tail call optimization.
1917 MachineFunction &MF = DAG.getMachineFunction();
1918 MachineFrameInfo *MFI = MF.getFrameInfo();
1919 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1920 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1921 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1923 // Analyze operands of the call, assigning locations to each operand.
1924 SmallVector<CCValAssign, 16> ArgLocs;
1925 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1926 getTargetMachine(), ArgLocs, *DAG.getContext());
1928 if (Subtarget->isABI_O32())
1929 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1931 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1933 // Get a count of how many bytes are to be pushed on the stack.
1934 unsigned NextStackOffset = CCInfo.getNextStackOffset();
1936 // Chain is the output chain of the last Load/Store or CopyToReg node.
1937 // ByValChain is the output chain of the last Memcpy node created for copying
1938 // byval arguments to the stack.
1939 SDValue Chain, CallSeqStart, ByValChain;
1940 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
1941 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
1942 ByValChain = InChain;
1944 // If this is the first call, create a stack frame object that points to
1945 // a location to which .cprestore saves $gp.
1946 if (IsPIC && !MipsFI->getGPFI())
1947 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1949 // Get the frame index of the stack frame object that points to the location
1950 // of dynamically allocated area on the stack.
1951 int DynAllocFI = MipsFI->getDynAllocFI();
1953 // Update size of the maximum argument space.
1954 // For O32, a minimum of four words (16 bytes) of argument space is
1956 if (Subtarget->isABI_O32())
1957 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
1959 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1961 if (MaxCallFrameSize < NextStackOffset) {
1962 MipsFI->setMaxCallFrameSize(NextStackOffset);
1964 // Set the offsets relative to $sp of the $gp restore slot and dynamically
1965 // allocated stack space. These offsets must be aligned to a boundary
1966 // determined by the stack alignment of the ABI.
1967 unsigned StackAlignment = TFL->getStackAlignment();
1968 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
1969 StackAlignment * StackAlignment;
1972 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
1974 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
1977 // With EABI is it possible to have 16 args on registers.
1978 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1979 SmallVector<SDValue, 8> MemOpChains;
1981 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
1983 // Walk the register/memloc assignments, inserting copies/loads.
1984 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1985 SDValue Arg = OutVals[i];
1986 CCValAssign &VA = ArgLocs[i];
1988 // Promote the value if needed.
1989 switch (VA.getLocInfo()) {
1990 default: llvm_unreachable("Unknown loc info!");
1991 case CCValAssign::Full:
1992 if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1993 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1994 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1995 if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1996 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1997 Arg, DAG.getConstant(0, MVT::i32));
1998 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1999 Arg, DAG.getConstant(1, MVT::i32));
2000 if (!Subtarget->isLittle())
2002 unsigned LocRegLo = VA.getLocReg();
2003 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2004 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2005 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2010 case CCValAssign::SExt:
2011 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2013 case CCValAssign::ZExt:
2014 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2016 case CCValAssign::AExt:
2017 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2021 // Arguments that can be passed on register must be kept at
2022 // RegsToPass vector
2023 if (VA.isRegLoc()) {
2024 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2028 // Register can't get to this point...
2029 assert(VA.isMemLoc());
2032 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2033 if (Flags.isByVal()) {
2034 assert(Subtarget->isABI_O32() &&
2035 "No support for ByVal args by ABIs other than O32 yet.");
2036 assert(Flags.getByValSize() &&
2037 "ByVal args of size 0 should have been ignored by front-end.");
2038 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI, MFI,
2039 DAG, Arg, VA, Flags, getPointerTy(), Subtarget->isLittle());
2043 // Create the frame index object for this incoming parameter
2044 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2045 VA.getLocMemOffset(), true);
2046 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2048 // emit ISD::STORE whichs stores the
2049 // parameter value to a stack Location
2050 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2051 MachinePointerInfo(),
2055 // Extend range of indices of frame objects for outgoing arguments that were
2056 // created during this function call. Skip this step if no such objects were
2059 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2061 // If a memcpy has been created to copy a byval arg to a stack, replace the
2062 // chain input of CallSeqStart with ByValChain.
2063 if (InChain != ByValChain)
2064 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2065 NextStackOffsetVal);
2067 // Transform all store nodes into one single node because all store
2068 // nodes are independent of each other.
2069 if (!MemOpChains.empty())
2070 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2071 &MemOpChains[0], MemOpChains.size());
2073 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2074 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2075 // node so that legalize doesn't hack it.
2076 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2077 bool LoadSymAddr = false;
2080 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2081 if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
2082 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2083 getPointerTy(), 0,MipsII:: MO_GOT);
2084 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2085 0, MipsII::MO_ABS_LO);
2087 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2088 getPointerTy(), 0, OpFlag);
2093 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2094 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2095 getPointerTy(), OpFlag);
2101 // Create nodes that load address of callee and copy it to T9
2104 // Load callee address
2105 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, Callee);
2106 SDValue LoadValue = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), Callee,
2107 MachinePointerInfo::getGOT(),
2110 // Use GOT+LO if callee has internal linkage.
2111 if (CalleeLo.getNode()) {
2112 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
2113 Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
2119 Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
2120 InFlag = Chain.getValue(1);
2121 Callee = DAG.getRegister(Mips::T9, MVT::i32);
2124 // Build a sequence of copy-to-reg nodes chained together with token
2125 // chain and flag operands which copy the outgoing args into registers.
2126 // The InFlag in necessary since all emitted instructions must be
2128 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2129 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2130 RegsToPass[i].second, InFlag);
2131 InFlag = Chain.getValue(1);
2134 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2135 // = Chain, Callee, Reg#1, Reg#2, ...
2137 // Returns a chain & a flag for retval copy to use.
2138 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2139 SmallVector<SDValue, 8> Ops;
2140 Ops.push_back(Chain);
2141 Ops.push_back(Callee);
2143 // Add argument registers to the end of the list so that they are
2144 // known live into the call.
2145 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2146 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2147 RegsToPass[i].second.getValueType()));
2149 if (InFlag.getNode())
2150 Ops.push_back(InFlag);
2152 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2153 InFlag = Chain.getValue(1);
2155 // Create the CALLSEQ_END node.
2156 Chain = DAG.getCALLSEQ_END(Chain,
2157 DAG.getIntPtrConstant(NextStackOffset, true),
2158 DAG.getIntPtrConstant(0, true), InFlag);
2159 InFlag = Chain.getValue(1);
2161 // Handle result values, copying them out of physregs into vregs that we
2163 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2164 Ins, dl, DAG, InVals);
2167 /// LowerCallResult - Lower the result values of a call into the
2168 /// appropriate copies out of appropriate physical registers.
2170 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2171 CallingConv::ID CallConv, bool isVarArg,
2172 const SmallVectorImpl<ISD::InputArg> &Ins,
2173 DebugLoc dl, SelectionDAG &DAG,
2174 SmallVectorImpl<SDValue> &InVals) const {
2175 // Assign locations to each value returned by this call.
2176 SmallVector<CCValAssign, 16> RVLocs;
2177 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2178 getTargetMachine(), RVLocs, *DAG.getContext());
2180 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2182 // Copy all of the result registers out of their specified physreg.
2183 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2184 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2185 RVLocs[i].getValVT(), InFlag).getValue(1);
2186 InFlag = Chain.getValue(2);
2187 InVals.push_back(Chain.getValue(0));
2193 //===----------------------------------------------------------------------===//
2194 // Formal Arguments Calling Convention Implementation
2195 //===----------------------------------------------------------------------===//
2196 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2197 std::vector<SDValue>& OutChains,
2198 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2199 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2200 unsigned LocMem = VA.getLocMemOffset();
2201 unsigned FirstWord = LocMem / 4;
2203 // copy register A0 - A3 to frame object
2204 for (unsigned i = 0; i < NumWords; ++i) {
2205 unsigned CurWord = FirstWord + i;
2206 if (CurWord >= O32IntRegsSize)
2209 unsigned SrcReg = O32IntRegs[CurWord];
2210 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2211 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2212 DAG.getConstant(i * 4, MVT::i32));
2213 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2214 StorePtr, MachinePointerInfo(), false,
2216 OutChains.push_back(Store);
2220 /// LowerFormalArguments - transform physical registers into virtual registers
2221 /// and generate load operations for arguments places on the stack.
2223 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2224 CallingConv::ID CallConv,
2226 const SmallVectorImpl<ISD::InputArg>
2228 DebugLoc dl, SelectionDAG &DAG,
2229 SmallVectorImpl<SDValue> &InVals)
2231 MachineFunction &MF = DAG.getMachineFunction();
2232 MachineFrameInfo *MFI = MF.getFrameInfo();
2233 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2235 MipsFI->setVarArgsFrameIndex(0);
2237 // Used with vargs to acumulate store chains.
2238 std::vector<SDValue> OutChains;
2240 // Assign locations to all of the incoming arguments.
2241 SmallVector<CCValAssign, 16> ArgLocs;
2242 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2243 getTargetMachine(), ArgLocs, *DAG.getContext());
2245 if (Subtarget->isABI_O32())
2246 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2248 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2250 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2252 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2253 CCValAssign &VA = ArgLocs[i];
2255 // Arguments stored on registers
2256 if (VA.isRegLoc()) {
2257 EVT RegVT = VA.getLocVT();
2258 unsigned ArgReg = VA.getLocReg();
2259 TargetRegisterClass *RC = 0;
2261 if (RegVT == MVT::i32)
2262 RC = Mips::CPURegsRegisterClass;
2263 else if (RegVT == MVT::f32)
2264 RC = Mips::FGR32RegisterClass;
2265 else if (RegVT == MVT::f64) {
2266 if (!Subtarget->isSingleFloat())
2267 RC = Mips::AFGR64RegisterClass;
2269 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2271 // Transform the arguments stored on
2272 // physical registers into virtual ones
2273 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2274 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2276 // If this is an 8 or 16-bit value, it has been passed promoted
2277 // to 32 bits. Insert an assert[sz]ext to capture this, then
2278 // truncate to the right size.
2279 if (VA.getLocInfo() != CCValAssign::Full) {
2280 unsigned Opcode = 0;
2281 if (VA.getLocInfo() == CCValAssign::SExt)
2282 Opcode = ISD::AssertSext;
2283 else if (VA.getLocInfo() == CCValAssign::ZExt)
2284 Opcode = ISD::AssertZext;
2286 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2287 DAG.getValueType(VA.getValVT()));
2288 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2291 // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
2292 if (Subtarget->isABI_O32()) {
2293 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
2294 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
2295 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
2296 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2297 getNextIntArgReg(ArgReg), RC);
2298 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2299 if (!Subtarget->isLittle())
2300 std::swap(ArgValue, ArgValue2);
2301 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2302 ArgValue, ArgValue2);
2306 InVals.push_back(ArgValue);
2307 } else { // VA.isRegLoc()
2310 assert(VA.isMemLoc());
2312 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2314 if (Flags.isByVal()) {
2315 assert(Subtarget->isABI_O32() &&
2316 "No support for ByVal args by ABIs other than O32 yet.");
2317 assert(Flags.getByValSize() &&
2318 "ByVal args of size 0 should have been ignored by front-end.");
2319 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2320 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2322 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2323 InVals.push_back(FIN);
2324 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2329 // The stack pointer offset is relative to the caller stack frame.
2330 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2331 VA.getLocMemOffset(), true);
2333 // Create load nodes to retrieve arguments from the stack
2334 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2335 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2336 MachinePointerInfo::getFixedStack(LastFI),
2341 // The mips ABIs for returning structs by value requires that we copy
2342 // the sret argument into $v0 for the return. Save the argument into
2343 // a virtual register so that we can access it from the return points.
2344 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2345 unsigned Reg = MipsFI->getSRetReturnReg();
2347 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2348 MipsFI->setSRetReturnReg(Reg);
2350 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2351 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2354 if (isVarArg && Subtarget->isABI_O32()) {
2355 // Record the frame index of the first variable argument
2356 // which is a value necessary to VASTART.
2357 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2358 assert(NextStackOffset % 4 == 0 &&
2359 "NextStackOffset must be aligned to 4-byte boundaries.");
2360 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2361 MipsFI->setVarArgsFrameIndex(LastFI);
2363 // If NextStackOffset is smaller than o32's 16-byte reserved argument area,
2364 // copy the integer registers that have not been used for argument passing
2365 // to the caller's stack frame.
2366 for (; NextStackOffset < 16; NextStackOffset += 4) {
2367 TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
2368 unsigned Idx = NextStackOffset / 4;
2369 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx], RC);
2370 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
2371 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2372 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2373 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2374 MachinePointerInfo(),
2379 MipsFI->setLastInArgFI(LastFI);
2381 // All stores are grouped in one node to allow the matching between
2382 // the size of Ins and InVals. This only happens when on varg functions
2383 if (!OutChains.empty()) {
2384 OutChains.push_back(Chain);
2385 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2386 &OutChains[0], OutChains.size());
2392 //===----------------------------------------------------------------------===//
2393 // Return Value Calling Convention Implementation
2394 //===----------------------------------------------------------------------===//
2397 MipsTargetLowering::LowerReturn(SDValue Chain,
2398 CallingConv::ID CallConv, bool isVarArg,
2399 const SmallVectorImpl<ISD::OutputArg> &Outs,
2400 const SmallVectorImpl<SDValue> &OutVals,
2401 DebugLoc dl, SelectionDAG &DAG) const {
2403 // CCValAssign - represent the assignment of
2404 // the return value to a location
2405 SmallVector<CCValAssign, 16> RVLocs;
2407 // CCState - Info about the registers and stack slot.
2408 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2409 getTargetMachine(), RVLocs, *DAG.getContext());
2411 // Analize return values.
2412 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2414 // If this is the first return lowered for this function, add
2415 // the regs to the liveout set for the function.
2416 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2417 for (unsigned i = 0; i != RVLocs.size(); ++i)
2418 if (RVLocs[i].isRegLoc())
2419 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2424 // Copy the result values into the output registers.
2425 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2426 CCValAssign &VA = RVLocs[i];
2427 assert(VA.isRegLoc() && "Can only return in registers!");
2429 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2432 // guarantee that all emitted copies are
2433 // stuck together, avoiding something bad
2434 Flag = Chain.getValue(1);
2437 // The mips ABIs for returning structs by value requires that we copy
2438 // the sret argument into $v0 for the return. We saved the argument into
2439 // a virtual register in the entry block, so now we copy the value out
2441 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2442 MachineFunction &MF = DAG.getMachineFunction();
2443 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2444 unsigned Reg = MipsFI->getSRetReturnReg();
2447 llvm_unreachable("sret virtual register not created in the entry block");
2448 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2450 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2451 Flag = Chain.getValue(1);
2454 // Return on Mips is always a "jr $ra"
2456 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2457 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2459 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2460 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2463 //===----------------------------------------------------------------------===//
2464 // Mips Inline Assembly Support
2465 //===----------------------------------------------------------------------===//
2467 /// getConstraintType - Given a constraint letter, return the type of
2468 /// constraint it is for this target.
2469 MipsTargetLowering::ConstraintType MipsTargetLowering::
2470 getConstraintType(const std::string &Constraint) const
2472 // Mips specific constrainy
2473 // GCC config/mips/constraints.md
2475 // 'd' : An address register. Equivalent to r
2476 // unless generating MIPS16 code.
2477 // 'y' : Equivalent to r; retained for
2478 // backwards compatibility.
2479 // 'f' : Floating Point registers.
2480 if (Constraint.size() == 1) {
2481 switch (Constraint[0]) {
2486 return C_RegisterClass;
2490 return TargetLowering::getConstraintType(Constraint);
2493 /// Examine constraint type and operand type and determine a weight value.
2494 /// This object must already have been set up with the operand type
2495 /// and the current alternative constraint selected.
2496 TargetLowering::ConstraintWeight
2497 MipsTargetLowering::getSingleConstraintMatchWeight(
2498 AsmOperandInfo &info, const char *constraint) const {
2499 ConstraintWeight weight = CW_Invalid;
2500 Value *CallOperandVal = info.CallOperandVal;
2501 // If we don't have a value, we can't do a match,
2502 // but allow it at the lowest weight.
2503 if (CallOperandVal == NULL)
2505 Type *type = CallOperandVal->getType();
2506 // Look at the constraint type.
2507 switch (*constraint) {
2509 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2513 if (type->isIntegerTy())
2514 weight = CW_Register;
2517 if (type->isFloatTy())
2518 weight = CW_Register;
2524 /// Given a register class constraint, like 'r', if this corresponds directly
2525 /// to an LLVM register class, return a register of 0 and the register class
2527 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2528 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2530 if (Constraint.size() == 1) {
2531 switch (Constraint[0]) {
2532 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2533 case 'y': // Same as 'r'. Exists for compatibility.
2535 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2538 return std::make_pair(0U, Mips::FGR32RegisterClass);
2540 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2541 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2545 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2549 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2550 // The Mips target isn't yet aware of offsets.
2554 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2555 if (VT != MVT::f32 && VT != MVT::f64)
2557 if (Imm.isNegZero())
2559 return Imm.isZero();