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>();
88 // Mips does not have i1 type, so use i32 for
89 // setcc operations results (slt, sgt, ...).
90 setBooleanContents(ZeroOrOneBooleanContent);
91 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
93 // Set up the register classes
94 addRegisterClass(MVT::i32, Mips::CPURegsRegisterClass);
95 addRegisterClass(MVT::f32, Mips::FGR32RegisterClass);
97 // When dealing with single precision only, use libcalls
98 if (!Subtarget->isSingleFloat())
99 if (!Subtarget->isFP64bit())
100 addRegisterClass(MVT::f64, Mips::AFGR64RegisterClass);
102 // Load extented operations for i1 types must be promoted
103 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
104 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
105 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
107 // MIPS doesn't have extending float->double load/store
108 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
109 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
111 // Used by legalize types to correctly generate the setcc result.
112 // Without this, every float setcc comes with a AND/OR with the result,
113 // we don't want this, since the fpcmp result goes to a flag register,
114 // which is used implicitly by brcond and select operations.
115 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
117 // Mips Custom Operations
118 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
119 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
120 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
121 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
122 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
123 setOperationAction(ISD::SELECT, MVT::f32, Custom);
124 setOperationAction(ISD::SELECT, MVT::f64, Custom);
125 setOperationAction(ISD::SELECT, MVT::i32, Custom);
126 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
127 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
128 setOperationAction(ISD::VASTART, MVT::Other, Custom);
130 setOperationAction(ISD::SDIV, MVT::i32, Expand);
131 setOperationAction(ISD::SREM, MVT::i32, Expand);
132 setOperationAction(ISD::UDIV, MVT::i32, Expand);
133 setOperationAction(ISD::UREM, MVT::i32, Expand);
135 // Operations not directly supported by Mips.
136 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
137 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
138 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
139 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
140 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
141 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
142 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
143 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
144 setOperationAction(ISD::ROTL, MVT::i32, Expand);
146 if (!Subtarget->isMips32r2())
147 setOperationAction(ISD::ROTR, MVT::i32, Expand);
149 setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
150 setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
151 setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
152 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
153 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
154 setOperationAction(ISD::FSIN, MVT::f32, Expand);
155 setOperationAction(ISD::FSIN, MVT::f64, Expand);
156 setOperationAction(ISD::FCOS, MVT::f32, Expand);
157 setOperationAction(ISD::FCOS, MVT::f64, Expand);
158 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
159 setOperationAction(ISD::FPOW, MVT::f32, Expand);
160 setOperationAction(ISD::FPOW, MVT::f64, Expand);
161 setOperationAction(ISD::FLOG, MVT::f32, Expand);
162 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
163 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
164 setOperationAction(ISD::FEXP, MVT::f32, Expand);
165 setOperationAction(ISD::FMA, MVT::f32, Expand);
166 setOperationAction(ISD::FMA, MVT::f64, Expand);
168 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
169 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
171 setOperationAction(ISD::VAARG, MVT::Other, Expand);
172 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
173 setOperationAction(ISD::VAEND, MVT::Other, Expand);
175 // Use the default for now
176 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
177 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
179 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
180 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
182 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
183 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
185 setInsertFencesForAtomic(true);
187 if (Subtarget->isSingleFloat())
188 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
190 if (!Subtarget->hasSEInReg()) {
191 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
192 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
195 if (!Subtarget->hasBitCount())
196 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
198 if (!Subtarget->hasSwap())
199 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
201 setTargetDAGCombine(ISD::ADDE);
202 setTargetDAGCombine(ISD::SUBE);
203 setTargetDAGCombine(ISD::SDIVREM);
204 setTargetDAGCombine(ISD::UDIVREM);
205 setTargetDAGCombine(ISD::SETCC);
206 setTargetDAGCombine(ISD::AND);
207 setTargetDAGCombine(ISD::OR);
209 setMinFunctionAlignment(2);
211 setStackPointerRegisterToSaveRestore(Mips::SP);
212 computeRegisterProperties();
214 setExceptionPointerRegister(Mips::A0);
215 setExceptionSelectorRegister(Mips::A1);
218 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
219 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
220 return SVT == MVT::i32 || SVT == MVT::i16;
223 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
228 // Transforms a subgraph in CurDAG if the following pattern is found:
229 // (addc multLo, Lo0), (adde multHi, Hi0),
231 // multHi/Lo: product of multiplication
232 // Lo0: initial value of Lo register
233 // Hi0: initial value of Hi register
234 // Return true if pattern matching was successful.
235 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
236 // ADDENode's second operand must be a flag output of an ADDC node in order
237 // for the matching to be successful.
238 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
240 if (ADDCNode->getOpcode() != ISD::ADDC)
243 SDValue MultHi = ADDENode->getOperand(0);
244 SDValue MultLo = ADDCNode->getOperand(0);
245 SDNode* MultNode = MultHi.getNode();
246 unsigned MultOpc = MultHi.getOpcode();
248 // MultHi and MultLo must be generated by the same node,
249 if (MultLo.getNode() != MultNode)
252 // and it must be a multiplication.
253 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
256 // MultLo amd MultHi must be the first and second output of MultNode
258 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
261 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
262 // of the values of MultNode, in which case MultNode will be removed in later
264 // If there exist users other than ADDENode or ADDCNode, this function returns
265 // here, which will result in MultNode being mapped to a single MULT
266 // instruction node rather than a pair of MULT and MADD instructions being
268 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
271 SDValue Chain = CurDAG->getEntryNode();
272 DebugLoc dl = ADDENode->getDebugLoc();
274 // create MipsMAdd(u) node
275 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
277 SDValue MAdd = CurDAG->getNode(MultOpc, dl,
279 MultNode->getOperand(0),// Factor 0
280 MultNode->getOperand(1),// Factor 1
281 ADDCNode->getOperand(1),// Lo0
282 ADDENode->getOperand(1));// Hi0
284 // create CopyFromReg nodes
285 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
287 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
289 CopyFromLo.getValue(2));
291 // replace uses of adde and addc here
292 if (!SDValue(ADDCNode, 0).use_empty())
293 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
295 if (!SDValue(ADDENode, 0).use_empty())
296 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
302 // Transforms a subgraph in CurDAG if the following pattern is found:
303 // (addc Lo0, multLo), (sube Hi0, multHi),
305 // multHi/Lo: product of multiplication
306 // Lo0: initial value of Lo register
307 // Hi0: initial value of Hi register
308 // Return true if pattern matching was successful.
309 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
310 // SUBENode's second operand must be a flag output of an SUBC node in order
311 // for the matching to be successful.
312 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
314 if (SUBCNode->getOpcode() != ISD::SUBC)
317 SDValue MultHi = SUBENode->getOperand(1);
318 SDValue MultLo = SUBCNode->getOperand(1);
319 SDNode* MultNode = MultHi.getNode();
320 unsigned MultOpc = MultHi.getOpcode();
322 // MultHi and MultLo must be generated by the same node,
323 if (MultLo.getNode() != MultNode)
326 // and it must be a multiplication.
327 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
330 // MultLo amd MultHi must be the first and second output of MultNode
332 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
335 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
336 // of the values of MultNode, in which case MultNode will be removed in later
338 // If there exist users other than SUBENode or SUBCNode, this function returns
339 // here, which will result in MultNode being mapped to a single MULT
340 // instruction node rather than a pair of MULT and MSUB instructions being
342 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
345 SDValue Chain = CurDAG->getEntryNode();
346 DebugLoc dl = SUBENode->getDebugLoc();
348 // create MipsSub(u) node
349 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
351 SDValue MSub = CurDAG->getNode(MultOpc, dl,
353 MultNode->getOperand(0),// Factor 0
354 MultNode->getOperand(1),// Factor 1
355 SUBCNode->getOperand(0),// Lo0
356 SUBENode->getOperand(0));// Hi0
358 // create CopyFromReg nodes
359 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
361 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
363 CopyFromLo.getValue(2));
365 // replace uses of sube and subc here
366 if (!SDValue(SUBCNode, 0).use_empty())
367 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
369 if (!SDValue(SUBENode, 0).use_empty())
370 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
375 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
376 TargetLowering::DAGCombinerInfo &DCI,
377 const MipsSubtarget* Subtarget) {
378 if (DCI.isBeforeLegalize())
381 if (Subtarget->isMips32() && SelectMadd(N, &DAG))
382 return SDValue(N, 0);
387 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
388 TargetLowering::DAGCombinerInfo &DCI,
389 const MipsSubtarget* Subtarget) {
390 if (DCI.isBeforeLegalize())
393 if (Subtarget->isMips32() && SelectMsub(N, &DAG))
394 return SDValue(N, 0);
399 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
400 TargetLowering::DAGCombinerInfo &DCI,
401 const MipsSubtarget* Subtarget) {
402 if (DCI.isBeforeLegalizeOps())
405 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
407 DebugLoc dl = N->getDebugLoc();
409 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
410 N->getOperand(0), N->getOperand(1));
411 SDValue InChain = DAG.getEntryNode();
412 SDValue InGlue = DivRem;
415 if (N->hasAnyUseOfValue(0)) {
416 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, Mips::LO, MVT::i32,
418 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
419 InChain = CopyFromLo.getValue(1);
420 InGlue = CopyFromLo.getValue(2);
424 if (N->hasAnyUseOfValue(1)) {
425 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
426 Mips::HI, MVT::i32, InGlue);
427 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
433 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
435 default: llvm_unreachable("Unknown fp condition code!");
437 case ISD::SETOEQ: return Mips::FCOND_OEQ;
438 case ISD::SETUNE: return Mips::FCOND_UNE;
440 case ISD::SETOLT: return Mips::FCOND_OLT;
442 case ISD::SETOGT: return Mips::FCOND_OGT;
444 case ISD::SETOLE: return Mips::FCOND_OLE;
446 case ISD::SETOGE: return Mips::FCOND_OGE;
447 case ISD::SETULT: return Mips::FCOND_ULT;
448 case ISD::SETULE: return Mips::FCOND_ULE;
449 case ISD::SETUGT: return Mips::FCOND_UGT;
450 case ISD::SETUGE: return Mips::FCOND_UGE;
451 case ISD::SETUO: return Mips::FCOND_UN;
452 case ISD::SETO: return Mips::FCOND_OR;
454 case ISD::SETONE: return Mips::FCOND_ONE;
455 case ISD::SETUEQ: return Mips::FCOND_UEQ;
460 // Returns true if condition code has to be inverted.
461 static bool InvertFPCondCode(Mips::CondCode CC) {
462 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
465 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
468 assert(false && "Illegal Condition Code");
472 // Creates and returns an FPCmp node from a setcc node.
473 // Returns Op if setcc is not a floating point comparison.
474 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
475 // must be a SETCC node
476 if (Op.getOpcode() != ISD::SETCC)
479 SDValue LHS = Op.getOperand(0);
481 if (!LHS.getValueType().isFloatingPoint())
484 SDValue RHS = Op.getOperand(1);
485 DebugLoc dl = Op.getDebugLoc();
487 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
488 // node if necessary.
489 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
491 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
492 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
495 // Creates and returns a CMovFPT/F node.
496 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
497 SDValue False, DebugLoc DL) {
498 bool invert = InvertFPCondCode((Mips::CondCode)
499 cast<ConstantSDNode>(Cond.getOperand(2))
502 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
503 True.getValueType(), True, False, Cond);
506 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG& DAG,
507 TargetLowering::DAGCombinerInfo &DCI,
508 const MipsSubtarget* Subtarget) {
509 if (DCI.isBeforeLegalizeOps())
512 SDValue Cond = CreateFPCmp(DAG, SDValue(N, 0));
514 if (Cond.getOpcode() != MipsISD::FPCmp)
517 SDValue True = DAG.getConstant(1, MVT::i32);
518 SDValue False = DAG.getConstant(0, MVT::i32);
520 return CreateCMovFP(DAG, Cond, True, False, N->getDebugLoc());
523 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
524 TargetLowering::DAGCombinerInfo &DCI,
525 const MipsSubtarget* Subtarget) {
526 // Pattern match EXT.
527 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
528 // => ext $dst, $src, size, pos
529 if (DCI.isBeforeLegalizeOps() || !Subtarget->isMips32r2())
532 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
534 // Op's first operand must be a shift right.
535 if (ShiftRight.getOpcode() != ISD::SRA && ShiftRight.getOpcode() != ISD::SRL)
538 // The second operand of the shift must be an immediate.
541 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
544 Pos = CN->getZExtValue();
546 uint64_t SMPos, SMSize;
547 // Op's second operand must be a shifted mask.
548 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
549 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
552 // Return if the shifted mask does not start at bit 0 or the sum of its size
553 // and Pos exceeds the word's size.
554 if (SMPos != 0 || Pos + SMSize > 32)
557 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), MVT::i32,
558 ShiftRight.getOperand(0),
559 DAG.getConstant(Pos, MVT::i32),
560 DAG.getConstant(SMSize, MVT::i32));
563 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
564 TargetLowering::DAGCombinerInfo &DCI,
565 const MipsSubtarget* Subtarget) {
566 // Pattern match INS.
567 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
568 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
569 // => ins $dst, $src, size, pos, $src1
570 if (DCI.isBeforeLegalizeOps() || !Subtarget->isMips32r2())
573 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
574 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
577 // See if Op's first operand matches (and $src1 , mask0).
578 if (And0.getOpcode() != ISD::AND)
581 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
582 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
585 // See if Op's second operand matches (and (shl $src, pos), mask1).
586 if (And1.getOpcode() != ISD::AND)
589 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
590 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
593 // The shift masks must have the same position and size.
594 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
597 SDValue Shl = And1.getOperand(0);
598 if (Shl.getOpcode() != ISD::SHL)
601 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
604 unsigned Shamt = CN->getZExtValue();
606 // Return if the shift amount and the first bit position of mask are not the
611 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), MVT::i32,
613 DAG.getConstant(SMPos0, MVT::i32),
614 DAG.getConstant(SMSize0, MVT::i32),
618 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
620 SelectionDAG &DAG = DCI.DAG;
621 unsigned opc = N->getOpcode();
626 return PerformADDECombine(N, DAG, DCI, Subtarget);
628 return PerformSUBECombine(N, DAG, DCI, Subtarget);
631 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
633 return PerformSETCCCombine(N, DAG, DCI, Subtarget);
635 return PerformANDCombine(N, DAG, DCI, Subtarget);
637 return PerformORCombine(N, DAG, DCI, Subtarget);
643 SDValue MipsTargetLowering::
644 LowerOperation(SDValue Op, SelectionDAG &DAG) const
646 switch (Op.getOpcode())
648 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
649 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
650 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
651 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
652 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
653 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
654 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
655 case ISD::SELECT: return LowerSELECT(Op, DAG);
656 case ISD::VASTART: return LowerVASTART(Op, DAG);
657 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
658 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
659 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
660 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
665 //===----------------------------------------------------------------------===//
666 // Lower helper functions
667 //===----------------------------------------------------------------------===//
669 // AddLiveIn - This helper function adds the specified physical register to the
670 // MachineFunction as a live in value. It also creates a corresponding
671 // virtual register for it.
673 AddLiveIn(MachineFunction &MF, unsigned PReg, TargetRegisterClass *RC)
675 assert(RC->contains(PReg) && "Not the correct regclass!");
676 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
677 MF.getRegInfo().addLiveIn(PReg, VReg);
681 // Get fp branch code (not opcode) from condition code.
682 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
683 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
684 return Mips::BRANCH_T;
686 if (CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT)
687 return Mips::BRANCH_F;
689 return Mips::BRANCH_INVALID;
692 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
694 const MipsSubtarget* Subtarget,
695 const TargetInstrInfo *TII,
696 bool isFPCmp, unsigned Opc) {
697 // There is no need to expand CMov instructions if target has
698 // conditional moves.
699 if (Subtarget->hasCondMov())
702 // To "insert" a SELECT_CC instruction, we actually have to insert the
703 // diamond control-flow pattern. The incoming instruction knows the
704 // destination vreg to set, the condition code register to branch on, the
705 // true/false values to select between, and a branch opcode to use.
706 const BasicBlock *LLVM_BB = BB->getBasicBlock();
707 MachineFunction::iterator It = BB;
714 // bNE r1, r0, copy1MBB
715 // fallthrough --> copy0MBB
716 MachineBasicBlock *thisMBB = BB;
717 MachineFunction *F = BB->getParent();
718 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
719 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
720 F->insert(It, copy0MBB);
721 F->insert(It, sinkMBB);
723 // Transfer the remainder of BB and its successor edges to sinkMBB.
724 sinkMBB->splice(sinkMBB->begin(), BB,
725 llvm::next(MachineBasicBlock::iterator(MI)),
727 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
729 // Next, add the true and fallthrough blocks as its successors.
730 BB->addSuccessor(copy0MBB);
731 BB->addSuccessor(sinkMBB);
733 // Emit the right instruction according to the type of the operands compared
735 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
737 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
738 .addReg(Mips::ZERO).addMBB(sinkMBB);
742 // # fallthrough to sinkMBB
745 // Update machine-CFG edges
746 BB->addSuccessor(sinkMBB);
749 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
754 BuildMI(*BB, BB->begin(), dl,
755 TII->get(Mips::PHI), MI->getOperand(0).getReg())
756 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
757 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
759 BuildMI(*BB, BB->begin(), dl,
760 TII->get(Mips::PHI), MI->getOperand(0).getReg())
761 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
762 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
764 MI->eraseFromParent(); // The pseudo instruction is gone now.
769 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
770 MachineBasicBlock *BB) const {
771 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
772 DebugLoc dl = MI->getDebugLoc();
774 switch (MI->getOpcode()) {
776 assert(false && "Unexpected instr type to insert");
781 return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1F);
785 return ExpandCondMov(MI, BB, dl, Subtarget, TII, true, Mips::BC1T);
789 return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BNE);
793 return ExpandCondMov(MI, BB, dl, Subtarget, TII, false, Mips::BEQ);
795 case Mips::ATOMIC_LOAD_ADD_I8:
796 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
797 case Mips::ATOMIC_LOAD_ADD_I16:
798 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
799 case Mips::ATOMIC_LOAD_ADD_I32:
800 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
802 case Mips::ATOMIC_LOAD_AND_I8:
803 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
804 case Mips::ATOMIC_LOAD_AND_I16:
805 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
806 case Mips::ATOMIC_LOAD_AND_I32:
807 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
809 case Mips::ATOMIC_LOAD_OR_I8:
810 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
811 case Mips::ATOMIC_LOAD_OR_I16:
812 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
813 case Mips::ATOMIC_LOAD_OR_I32:
814 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
816 case Mips::ATOMIC_LOAD_XOR_I8:
817 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
818 case Mips::ATOMIC_LOAD_XOR_I16:
819 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
820 case Mips::ATOMIC_LOAD_XOR_I32:
821 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
823 case Mips::ATOMIC_LOAD_NAND_I8:
824 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
825 case Mips::ATOMIC_LOAD_NAND_I16:
826 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
827 case Mips::ATOMIC_LOAD_NAND_I32:
828 return EmitAtomicBinary(MI, BB, 4, 0, true);
830 case Mips::ATOMIC_LOAD_SUB_I8:
831 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
832 case Mips::ATOMIC_LOAD_SUB_I16:
833 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
834 case Mips::ATOMIC_LOAD_SUB_I32:
835 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
837 case Mips::ATOMIC_SWAP_I8:
838 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
839 case Mips::ATOMIC_SWAP_I16:
840 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
841 case Mips::ATOMIC_SWAP_I32:
842 return EmitAtomicBinary(MI, BB, 4, 0);
844 case Mips::ATOMIC_CMP_SWAP_I8:
845 return EmitAtomicCmpSwapPartword(MI, BB, 1);
846 case Mips::ATOMIC_CMP_SWAP_I16:
847 return EmitAtomicCmpSwapPartword(MI, BB, 2);
848 case Mips::ATOMIC_CMP_SWAP_I32:
849 return EmitAtomicCmpSwap(MI, BB, 4);
853 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
854 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
856 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
857 unsigned Size, unsigned BinOpcode,
859 assert(Size == 4 && "Unsupported size for EmitAtomicBinary.");
861 MachineFunction *MF = BB->getParent();
862 MachineRegisterInfo &RegInfo = MF->getRegInfo();
863 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
864 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
865 DebugLoc dl = MI->getDebugLoc();
867 unsigned OldVal = MI->getOperand(0).getReg();
868 unsigned Ptr = MI->getOperand(1).getReg();
869 unsigned Incr = MI->getOperand(2).getReg();
871 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
872 unsigned AndRes = RegInfo.createVirtualRegister(RC);
873 unsigned Success = RegInfo.createVirtualRegister(RC);
875 // insert new blocks after the current block
876 const BasicBlock *LLVM_BB = BB->getBasicBlock();
877 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
878 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
879 MachineFunction::iterator It = BB;
881 MF->insert(It, loopMBB);
882 MF->insert(It, exitMBB);
884 // Transfer the remainder of BB and its successor edges to exitMBB.
885 exitMBB->splice(exitMBB->begin(), BB,
886 llvm::next(MachineBasicBlock::iterator(MI)),
888 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
892 // fallthrough --> loopMBB
893 BB->addSuccessor(loopMBB);
894 loopMBB->addSuccessor(loopMBB);
895 loopMBB->addSuccessor(exitMBB);
899 // <binop> storeval, oldval, incr
900 // sc success, storeval, 0(ptr)
901 // beq success, $0, loopMBB
903 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(Ptr).addImm(0);
905 // and andres, oldval, incr
906 // nor storeval, $0, andres
907 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr);
908 BuildMI(BB, dl, TII->get(Mips::NOR), StoreVal)
909 .addReg(Mips::ZERO).addReg(AndRes);
910 } else if (BinOpcode) {
911 // <binop> storeval, oldval, incr
912 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
916 BuildMI(BB, dl, TII->get(Mips::SC), Success)
917 .addReg(StoreVal).addReg(Ptr).addImm(0);
918 BuildMI(BB, dl, TII->get(Mips::BEQ))
919 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
921 MI->eraseFromParent(); // The instruction is gone now.
927 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
928 MachineBasicBlock *BB,
929 unsigned Size, unsigned BinOpcode,
931 assert((Size == 1 || Size == 2) &&
932 "Unsupported size for EmitAtomicBinaryPartial.");
934 MachineFunction *MF = BB->getParent();
935 MachineRegisterInfo &RegInfo = MF->getRegInfo();
936 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
937 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
938 DebugLoc dl = MI->getDebugLoc();
940 unsigned Dest = MI->getOperand(0).getReg();
941 unsigned Ptr = MI->getOperand(1).getReg();
942 unsigned Incr = MI->getOperand(2).getReg();
944 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
945 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
946 unsigned Mask = RegInfo.createVirtualRegister(RC);
947 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
948 unsigned NewVal = RegInfo.createVirtualRegister(RC);
949 unsigned OldVal = RegInfo.createVirtualRegister(RC);
950 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
951 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
952 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
953 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
954 unsigned AndRes = RegInfo.createVirtualRegister(RC);
955 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
956 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
957 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
958 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
959 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
960 unsigned SllRes = RegInfo.createVirtualRegister(RC);
961 unsigned Success = RegInfo.createVirtualRegister(RC);
963 // insert new blocks after the current block
964 const BasicBlock *LLVM_BB = BB->getBasicBlock();
965 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
966 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
967 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
968 MachineFunction::iterator It = BB;
970 MF->insert(It, loopMBB);
971 MF->insert(It, sinkMBB);
972 MF->insert(It, exitMBB);
974 // Transfer the remainder of BB and its successor edges to exitMBB.
975 exitMBB->splice(exitMBB->begin(), BB,
976 llvm::next(MachineBasicBlock::iterator(MI)),
978 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
980 BB->addSuccessor(loopMBB);
981 loopMBB->addSuccessor(loopMBB);
982 loopMBB->addSuccessor(sinkMBB);
983 sinkMBB->addSuccessor(exitMBB);
986 // addiu masklsb2,$0,-4 # 0xfffffffc
987 // and alignedaddr,ptr,masklsb2
988 // andi ptrlsb2,ptr,3
989 // sll shiftamt,ptrlsb2,3
990 // ori maskupper,$0,255 # 0xff
991 // sll mask,maskupper,shiftamt
993 // sll incr2,incr,shiftamt
995 int64_t MaskImm = (Size == 1) ? 255 : 65535;
996 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
997 .addReg(Mips::ZERO).addImm(-4);
998 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
999 .addReg(Ptr).addReg(MaskLSB2);
1000 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1001 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1002 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1003 .addReg(Mips::ZERO).addImm(MaskImm);
1004 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1005 .addReg(ShiftAmt).addReg(MaskUpper);
1006 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1007 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1010 // atomic.load.binop
1012 // ll oldval,0(alignedaddr)
1013 // binop binopres,oldval,incr2
1014 // and newval,binopres,mask
1015 // and maskedoldval0,oldval,mask2
1016 // or storeval,maskedoldval0,newval
1017 // sc success,storeval,0(alignedaddr)
1018 // beq success,$0,loopMBB
1022 // ll oldval,0(alignedaddr)
1023 // and newval,incr2,mask
1024 // and maskedoldval0,oldval,mask2
1025 // or storeval,maskedoldval0,newval
1026 // sc success,storeval,0(alignedaddr)
1027 // beq success,$0,loopMBB
1030 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1032 // and andres, oldval, incr2
1033 // nor binopres, $0, andres
1034 // and newval, binopres, mask
1035 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1036 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1037 .addReg(Mips::ZERO).addReg(AndRes);
1038 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1039 } else if (BinOpcode) {
1040 // <binop> binopres, oldval, incr2
1041 // and newval, binopres, mask
1042 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1043 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1044 } else {// atomic.swap
1045 // and newval, incr2, mask
1046 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1049 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1050 .addReg(OldVal).addReg(Mask2);
1051 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1052 .addReg(MaskedOldVal0).addReg(NewVal);
1053 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1054 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1055 BuildMI(BB, dl, TII->get(Mips::BEQ))
1056 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1059 // and maskedoldval1,oldval,mask
1060 // srl srlres,maskedoldval1,shiftamt
1061 // sll sllres,srlres,24
1062 // sra dest,sllres,24
1064 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1066 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1067 .addReg(OldVal).addReg(Mask);
1068 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1069 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1070 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1071 .addReg(SrlRes).addImm(ShiftImm);
1072 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1073 .addReg(SllRes).addImm(ShiftImm);
1075 MI->eraseFromParent(); // The instruction is gone now.
1081 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1082 MachineBasicBlock *BB,
1083 unsigned Size) const {
1084 assert(Size == 4 && "Unsupported size for EmitAtomicCmpSwap.");
1086 MachineFunction *MF = BB->getParent();
1087 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1088 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1089 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1090 DebugLoc dl = MI->getDebugLoc();
1092 unsigned Dest = MI->getOperand(0).getReg();
1093 unsigned Ptr = MI->getOperand(1).getReg();
1094 unsigned OldVal = MI->getOperand(2).getReg();
1095 unsigned NewVal = MI->getOperand(3).getReg();
1097 unsigned Success = RegInfo.createVirtualRegister(RC);
1099 // insert new blocks after the current block
1100 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1101 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1102 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1103 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1104 MachineFunction::iterator It = BB;
1106 MF->insert(It, loop1MBB);
1107 MF->insert(It, loop2MBB);
1108 MF->insert(It, exitMBB);
1110 // Transfer the remainder of BB and its successor edges to exitMBB.
1111 exitMBB->splice(exitMBB->begin(), BB,
1112 llvm::next(MachineBasicBlock::iterator(MI)),
1114 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1118 // fallthrough --> loop1MBB
1119 BB->addSuccessor(loop1MBB);
1120 loop1MBB->addSuccessor(exitMBB);
1121 loop1MBB->addSuccessor(loop2MBB);
1122 loop2MBB->addSuccessor(loop1MBB);
1123 loop2MBB->addSuccessor(exitMBB);
1127 // bne dest, oldval, exitMBB
1129 BuildMI(BB, dl, TII->get(Mips::LL), Dest).addReg(Ptr).addImm(0);
1130 BuildMI(BB, dl, TII->get(Mips::BNE))
1131 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1134 // sc success, newval, 0(ptr)
1135 // beq success, $0, loop1MBB
1137 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1138 .addReg(NewVal).addReg(Ptr).addImm(0);
1139 BuildMI(BB, dl, TII->get(Mips::BEQ))
1140 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1142 MI->eraseFromParent(); // The instruction is gone now.
1148 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1149 MachineBasicBlock *BB,
1150 unsigned Size) const {
1151 assert((Size == 1 || Size == 2) &&
1152 "Unsupported size for EmitAtomicCmpSwapPartial.");
1154 MachineFunction *MF = BB->getParent();
1155 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1156 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1157 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1158 DebugLoc dl = MI->getDebugLoc();
1160 unsigned Dest = MI->getOperand(0).getReg();
1161 unsigned Ptr = MI->getOperand(1).getReg();
1162 unsigned CmpVal = MI->getOperand(2).getReg();
1163 unsigned NewVal = MI->getOperand(3).getReg();
1165 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1166 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1167 unsigned Mask = RegInfo.createVirtualRegister(RC);
1168 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1169 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1170 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1171 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1172 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1173 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1174 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1175 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1176 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1177 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1178 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1179 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1180 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1181 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1182 unsigned Success = RegInfo.createVirtualRegister(RC);
1184 // insert new blocks after the current block
1185 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1186 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1187 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1188 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1189 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1190 MachineFunction::iterator It = BB;
1192 MF->insert(It, loop1MBB);
1193 MF->insert(It, loop2MBB);
1194 MF->insert(It, sinkMBB);
1195 MF->insert(It, exitMBB);
1197 // Transfer the remainder of BB and its successor edges to exitMBB.
1198 exitMBB->splice(exitMBB->begin(), BB,
1199 llvm::next(MachineBasicBlock::iterator(MI)),
1201 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1203 BB->addSuccessor(loop1MBB);
1204 loop1MBB->addSuccessor(sinkMBB);
1205 loop1MBB->addSuccessor(loop2MBB);
1206 loop2MBB->addSuccessor(loop1MBB);
1207 loop2MBB->addSuccessor(sinkMBB);
1208 sinkMBB->addSuccessor(exitMBB);
1210 // FIXME: computation of newval2 can be moved to loop2MBB.
1212 // addiu masklsb2,$0,-4 # 0xfffffffc
1213 // and alignedaddr,ptr,masklsb2
1214 // andi ptrlsb2,ptr,3
1215 // sll shiftamt,ptrlsb2,3
1216 // ori maskupper,$0,255 # 0xff
1217 // sll mask,maskupper,shiftamt
1218 // nor mask2,$0,mask
1219 // andi maskedcmpval,cmpval,255
1220 // sll shiftedcmpval,maskedcmpval,shiftamt
1221 // andi maskednewval,newval,255
1222 // sll shiftednewval,maskednewval,shiftamt
1223 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1224 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1225 .addReg(Mips::ZERO).addImm(-4);
1226 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1227 .addReg(Ptr).addReg(MaskLSB2);
1228 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1229 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1230 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1231 .addReg(Mips::ZERO).addImm(MaskImm);
1232 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1233 .addReg(ShiftAmt).addReg(MaskUpper);
1234 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1235 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1236 .addReg(CmpVal).addImm(MaskImm);
1237 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1238 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1239 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1240 .addReg(NewVal).addImm(MaskImm);
1241 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1242 .addReg(ShiftAmt).addReg(MaskedNewVal);
1245 // ll oldval,0(alginedaddr)
1246 // and maskedoldval0,oldval,mask
1247 // bne maskedoldval0,shiftedcmpval,sinkMBB
1249 BuildMI(BB, dl, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1250 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1251 .addReg(OldVal).addReg(Mask);
1252 BuildMI(BB, dl, TII->get(Mips::BNE))
1253 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1256 // and maskedoldval1,oldval,mask2
1257 // or storeval,maskedoldval1,shiftednewval
1258 // sc success,storeval,0(alignedaddr)
1259 // beq success,$0,loop1MBB
1261 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1262 .addReg(OldVal).addReg(Mask2);
1263 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1264 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1265 BuildMI(BB, dl, TII->get(Mips::SC), Success)
1266 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1267 BuildMI(BB, dl, TII->get(Mips::BEQ))
1268 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1271 // srl srlres,maskedoldval0,shiftamt
1272 // sll sllres,srlres,24
1273 // sra dest,sllres,24
1275 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1277 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1278 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1279 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1280 .addReg(SrlRes).addImm(ShiftImm);
1281 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1282 .addReg(SllRes).addImm(ShiftImm);
1284 MI->eraseFromParent(); // The instruction is gone now.
1289 //===----------------------------------------------------------------------===//
1290 // Misc Lower Operation implementation
1291 //===----------------------------------------------------------------------===//
1292 SDValue MipsTargetLowering::
1293 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1295 MachineFunction &MF = DAG.getMachineFunction();
1296 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1298 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1299 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1300 "Cannot lower if the alignment of the allocated space is larger than \
1301 that of the stack.");
1303 SDValue Chain = Op.getOperand(0);
1304 SDValue Size = Op.getOperand(1);
1305 DebugLoc dl = Op.getDebugLoc();
1307 // Get a reference from Mips stack pointer
1308 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, Mips::SP, MVT::i32);
1310 // Subtract the dynamic size from the actual stack size to
1311 // obtain the new stack size.
1312 SDValue Sub = DAG.getNode(ISD::SUB, dl, MVT::i32, StackPointer, Size);
1314 // The Sub result contains the new stack start address, so it
1315 // must be placed in the stack pointer register.
1316 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, Mips::SP, Sub,
1319 // This node always has two return values: a new stack pointer
1320 // value and a chain
1321 SDVTList VTLs = DAG.getVTList(MVT::i32, MVT::Other);
1322 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1323 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1325 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1328 SDValue MipsTargetLowering::
1329 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1331 // The first operand is the chain, the second is the condition, the third is
1332 // the block to branch to if the condition is true.
1333 SDValue Chain = Op.getOperand(0);
1334 SDValue Dest = Op.getOperand(2);
1335 DebugLoc dl = Op.getDebugLoc();
1337 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1339 // Return if flag is not set by a floating point comparison.
1340 if (CondRes.getOpcode() != MipsISD::FPCmp)
1343 SDValue CCNode = CondRes.getOperand(2);
1345 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1346 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1348 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1352 SDValue MipsTargetLowering::
1353 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1355 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1357 // Return if flag is not set by a floating point comparison.
1358 if (Cond.getOpcode() != MipsISD::FPCmp)
1361 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1365 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1366 SelectionDAG &DAG) const {
1367 // FIXME there isn't actually debug info here
1368 DebugLoc dl = Op.getDebugLoc();
1369 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1371 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1372 SDVTList VTs = DAG.getVTList(MVT::i32);
1374 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1376 // %gp_rel relocation
1377 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1378 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1380 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1381 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1382 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1384 // %hi/%lo relocation
1385 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1387 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1389 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1390 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1391 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1394 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1396 GA = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, GA);
1397 SDValue ResNode = DAG.getLoad(MVT::i32, dl,
1398 DAG.getEntryNode(), GA, MachinePointerInfo(),
1400 // On functions and global targets not internal linked only
1401 // a load from got/GP is necessary for PIC to work.
1402 if (!GV->hasInternalLinkage() &&
1403 (!GV->hasLocalLinkage() || isa<Function>(GV)))
1405 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1407 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1408 return DAG.getNode(ISD::ADD, dl, MVT::i32, ResNode, Lo);
1411 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1412 SelectionDAG &DAG) const {
1413 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1414 // FIXME there isn't actually debug info here
1415 DebugLoc dl = Op.getDebugLoc();
1417 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1418 // %hi/%lo relocation
1419 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true,
1421 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true,
1423 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1424 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1425 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1428 SDValue BAGOTOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1430 BAGOTOffset = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, BAGOTOffset);
1431 SDValue BALOOffset = DAG.getBlockAddress(BA, MVT::i32, true,
1433 SDValue Load = DAG.getLoad(MVT::i32, dl,
1434 DAG.getEntryNode(), BAGOTOffset,
1435 MachinePointerInfo(), false, false, 0);
1436 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALOOffset);
1437 return DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1440 SDValue MipsTargetLowering::
1441 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1443 // If the relocation model is PIC, use the General Dynamic TLS Model,
1444 // otherwise use the Initial Exec or Local Exec TLS Model.
1445 // TODO: implement Local Dynamic TLS model
1447 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1448 DebugLoc dl = GA->getDebugLoc();
1449 const GlobalValue *GV = GA->getGlobal();
1450 EVT PtrVT = getPointerTy();
1452 if (getTargetMachine().getRelocationModel() == Reloc::PIC_) {
1453 // General Dynamic TLS Model
1454 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32,
1455 0, MipsII::MO_TLSGD);
1456 SDValue Tlsgd = DAG.getNode(MipsISD::TlsGd, dl, MVT::i32, TGA);
1457 SDValue GP = DAG.getRegister(Mips::GP, MVT::i32);
1458 SDValue Argument = DAG.getNode(ISD::ADD, dl, MVT::i32, GP, Tlsgd);
1462 Entry.Node = Argument;
1463 Entry.Ty = (Type *) Type::getInt32Ty(*DAG.getContext());
1464 Args.push_back(Entry);
1465 std::pair<SDValue, SDValue> CallResult =
1466 LowerCallTo(DAG.getEntryNode(),
1467 (Type *) Type::getInt32Ty(*DAG.getContext()),
1468 false, false, false, false, 0, CallingConv::C, false, true,
1469 DAG.getExternalSymbol("__tls_get_addr", PtrVT), Args, DAG,
1472 return CallResult.first;
1476 if (GV->isDeclaration()) {
1477 // Initial Exec TLS Model
1478 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1479 MipsII::MO_GOTTPREL);
1480 Offset = DAG.getLoad(MVT::i32, dl,
1481 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1484 // Local Exec TLS Model
1485 SDVTList VTs = DAG.getVTList(MVT::i32);
1486 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1487 MipsII::MO_TPREL_HI);
1488 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1489 MipsII::MO_TPREL_LO);
1490 SDValue Hi = DAG.getNode(MipsISD::TprelHi, dl, VTs, &TGAHi, 1);
1491 SDValue Lo = DAG.getNode(MipsISD::TprelLo, dl, MVT::i32, TGALo);
1492 Offset = DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1495 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1496 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1499 SDValue MipsTargetLowering::
1500 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1504 // FIXME there isn't actually debug info here
1505 DebugLoc dl = Op.getDebugLoc();
1506 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1507 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT : MipsII::MO_ABS_HI;
1509 EVT PtrVT = Op.getValueType();
1510 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1512 SDValue JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
1515 SDValue Ops[] = { JTI };
1516 HiPart = DAG.getNode(MipsISD::Hi, dl, DAG.getVTList(MVT::i32), Ops, 1);
1517 } else {// Emit Load from Global Pointer
1518 JTI = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, JTI);
1519 HiPart = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), JTI,
1520 MachinePointerInfo(),
1524 SDValue JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT,
1526 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, JTILo);
1527 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1532 SDValue MipsTargetLowering::
1533 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1536 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1537 const Constant *C = N->getConstVal();
1538 // FIXME there isn't actually debug info here
1539 DebugLoc dl = Op.getDebugLoc();
1541 // gp_rel relocation
1542 // FIXME: we should reference the constant pool using small data sections,
1543 // but the asm printer currently doesn't support this feature without
1544 // hacking it. This feature should come soon so we can uncomment the
1546 //if (IsInSmallSection(C->getType())) {
1547 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1548 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1549 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1551 if (getTargetMachine().getRelocationModel() != Reloc::PIC_) {
1552 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1553 N->getOffset(), MipsII::MO_ABS_HI);
1554 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1555 N->getOffset(), MipsII::MO_ABS_LO);
1556 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1557 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1558 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1560 SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1561 N->getOffset(), MipsII::MO_GOT);
1562 CP = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, CP);
1563 SDValue Load = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(),
1564 CP, MachinePointerInfo::getConstantPool(),
1566 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1567 N->getOffset(), MipsII::MO_ABS_LO);
1568 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1569 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, Load, Lo);
1575 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1576 MachineFunction &MF = DAG.getMachineFunction();
1577 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1579 DebugLoc dl = Op.getDebugLoc();
1580 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1583 // vastart just stores the address of the VarArgsFrameIndex slot into the
1584 // memory location argument.
1585 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1586 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1587 MachinePointerInfo(SV),
1591 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG) {
1592 // FIXME: Use ext/ins instructions if target architecture is Mips32r2.
1593 DebugLoc dl = Op.getDebugLoc();
1594 SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(0));
1595 SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op.getOperand(1));
1596 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Op0,
1597 DAG.getConstant(0x7fffffff, MVT::i32));
1598 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Op1,
1599 DAG.getConstant(0x80000000, MVT::i32));
1600 SDValue Result = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1601 return DAG.getNode(ISD::BITCAST, dl, MVT::f32, Result);
1604 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool isLittle) {
1606 // Use ext/ins instructions if target architecture is Mips32r2.
1607 // Eliminate redundant mfc1 and mtc1 instructions.
1608 unsigned LoIdx = 0, HiIdx = 1;
1611 std::swap(LoIdx, HiIdx);
1613 DebugLoc dl = Op.getDebugLoc();
1614 SDValue Word0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1616 DAG.getConstant(LoIdx, MVT::i32));
1617 SDValue Hi0 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1618 Op.getOperand(0), DAG.getConstant(HiIdx, MVT::i32));
1619 SDValue Hi1 = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1620 Op.getOperand(1), DAG.getConstant(HiIdx, MVT::i32));
1621 SDValue And0 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi0,
1622 DAG.getConstant(0x7fffffff, MVT::i32));
1623 SDValue And1 = DAG.getNode(ISD::AND, dl, MVT::i32, Hi1,
1624 DAG.getConstant(0x80000000, MVT::i32));
1625 SDValue Word1 = DAG.getNode(ISD::OR, dl, MVT::i32, And0, And1);
1628 std::swap(Word0, Word1);
1630 return DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64, Word0, Word1);
1633 SDValue MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG)
1635 EVT Ty = Op.getValueType();
1637 assert(Ty == MVT::f32 || Ty == MVT::f64);
1640 return LowerFCOPYSIGN32(Op, DAG);
1642 return LowerFCOPYSIGN64(Op, DAG, Subtarget->isLittle());
1645 SDValue MipsTargetLowering::
1646 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1648 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1649 "Frame address can only be determined for current frame.");
1651 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1652 MFI->setFrameAddressIsTaken(true);
1653 EVT VT = Op.getValueType();
1654 DebugLoc dl = Op.getDebugLoc();
1655 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, Mips::FP, VT);
1659 // TODO: set SType according to the desired memory barrier behavior.
1660 SDValue MipsTargetLowering::LowerMEMBARRIER(SDValue Op,
1661 SelectionDAG& DAG) const {
1663 DebugLoc dl = Op.getDebugLoc();
1664 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1665 DAG.getConstant(SType, MVT::i32));
1668 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1669 SelectionDAG& DAG) const {
1670 // FIXME: Need pseudo-fence for 'singlethread' fences
1671 // FIXME: Set SType for weaker fences where supported/appropriate.
1673 DebugLoc dl = Op.getDebugLoc();
1674 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1675 DAG.getConstant(SType, MVT::i32));
1678 //===----------------------------------------------------------------------===//
1679 // Calling Convention Implementation
1680 //===----------------------------------------------------------------------===//
1682 #include "MipsGenCallingConv.inc"
1684 //===----------------------------------------------------------------------===//
1685 // TODO: Implement a generic logic using tblgen that can support this.
1686 // Mips O32 ABI rules:
1688 // i32 - Passed in A0, A1, A2, A3 and stack
1689 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
1690 // an argument. Otherwise, passed in A1, A2, A3 and stack.
1691 // f64 - Only passed in two aliased f32 registers if no int reg has been used
1692 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
1693 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
1696 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
1697 //===----------------------------------------------------------------------===//
1699 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
1700 MVT LocVT, CCValAssign::LocInfo LocInfo,
1701 ISD::ArgFlagsTy ArgFlags, CCState &State) {
1703 static const unsigned IntRegsSize=4, FloatRegsSize=2;
1705 static const unsigned IntRegs[] = {
1706 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1708 static const unsigned F32Regs[] = {
1709 Mips::F12, Mips::F14
1711 static const unsigned F64Regs[] = {
1716 if (ArgFlags.isByVal()) {
1717 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
1718 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
1719 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
1720 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
1721 r < std::min(IntRegsSize, NextReg); ++r)
1722 State.AllocateReg(IntRegs[r]);
1726 // Promote i8 and i16
1727 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
1729 if (ArgFlags.isSExt())
1730 LocInfo = CCValAssign::SExt;
1731 else if (ArgFlags.isZExt())
1732 LocInfo = CCValAssign::ZExt;
1734 LocInfo = CCValAssign::AExt;
1739 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
1740 // is true: function is vararg, argument is 3rd or higher, there is previous
1741 // argument which is not f32 or f64.
1742 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
1743 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
1744 unsigned OrigAlign = ArgFlags.getOrigAlign();
1745 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
1747 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
1748 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1749 // If this is the first part of an i64 arg,
1750 // the allocated register must be either A0 or A2.
1751 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
1752 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1754 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
1755 // Allocate int register and shadow next int register. If first
1756 // available register is Mips::A1 or Mips::A3, shadow it too.
1757 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1758 if (Reg == Mips::A1 || Reg == Mips::A3)
1759 Reg = State.AllocateReg(IntRegs, IntRegsSize);
1760 State.AllocateReg(IntRegs, IntRegsSize);
1762 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
1763 // we are guaranteed to find an available float register
1764 if (ValVT == MVT::f32) {
1765 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
1766 // Shadow int register
1767 State.AllocateReg(IntRegs, IntRegsSize);
1769 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
1770 // Shadow int registers
1771 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
1772 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
1773 State.AllocateReg(IntRegs, IntRegsSize);
1774 State.AllocateReg(IntRegs, IntRegsSize);
1777 llvm_unreachable("Cannot handle this ValVT.");
1779 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
1780 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
1783 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
1785 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
1787 return false; // CC must always match
1790 //===----------------------------------------------------------------------===//
1791 // Call Calling Convention Implementation
1792 //===----------------------------------------------------------------------===//
1794 static const unsigned O32IntRegsSize = 4;
1796 static const unsigned O32IntRegs[] = {
1797 Mips::A0, Mips::A1, Mips::A2, Mips::A3
1800 // Write ByVal Arg to arg registers and stack.
1802 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
1803 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
1804 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
1805 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
1806 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
1807 MVT PtrType, bool isLittle) {
1808 unsigned LocMemOffset = VA.getLocMemOffset();
1809 unsigned Offset = 0;
1810 uint32_t RemainingSize = Flags.getByValSize();
1811 unsigned ByValAlign = Flags.getByValAlign();
1813 // Copy the first 4 words of byval arg to registers A0 - A3.
1814 // FIXME: Use a stricter alignment if it enables better optimization in passes
1816 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
1817 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
1818 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1819 DAG.getConstant(Offset, MVT::i32));
1820 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
1821 MachinePointerInfo(),
1822 false, false, std::min(ByValAlign,
1824 MemOpChains.push_back(LoadVal.getValue(1));
1825 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1826 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1829 if (RemainingSize == 0)
1832 // If there still is a register available for argument passing, write the
1833 // remaining part of the structure to it using subword loads and shifts.
1834 if (LocMemOffset < 4 * 4) {
1835 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
1836 "There must be one to three bytes remaining.");
1837 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
1838 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1839 DAG.getConstant(Offset, MVT::i32));
1840 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
1841 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
1842 LoadPtr, MachinePointerInfo(),
1843 MVT::getIntegerVT(LoadSize * 8), false,
1845 MemOpChains.push_back(LoadVal.getValue(1));
1847 // If target is big endian, shift it to the most significant half-word or
1850 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
1851 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
1854 RemainingSize -= LoadSize;
1856 // Read second subword if necessary.
1857 if (RemainingSize != 0) {
1858 assert(RemainingSize == 1 && "There must be one byte remaining.");
1859 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1860 DAG.getConstant(Offset, MVT::i32));
1861 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
1862 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
1863 LoadPtr, MachinePointerInfo(),
1864 MVT::i8, false, false, Alignment);
1865 MemOpChains.push_back(Subword.getValue(1));
1866 // Insert the loaded byte to LoadVal.
1867 // FIXME: Use INS if supported by target.
1868 unsigned ShiftAmt = isLittle ? 16 : 8;
1869 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
1870 DAG.getConstant(ShiftAmt, MVT::i32));
1871 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
1874 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
1875 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
1879 // Create a fixed object on stack at offset LocMemOffset and copy
1880 // remaining part of byval arg to it using memcpy.
1881 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
1882 DAG.getConstant(Offset, MVT::i32));
1883 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
1884 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
1885 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
1886 DAG.getConstant(RemainingSize, MVT::i32),
1887 std::min(ByValAlign, (unsigned)4),
1888 /*isVolatile=*/false, /*AlwaysInline=*/false,
1889 MachinePointerInfo(0), MachinePointerInfo(0));
1892 /// LowerCall - functions arguments are copied from virtual regs to
1893 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
1894 /// TODO: isTailCall.
1896 MipsTargetLowering::LowerCall(SDValue InChain, SDValue Callee,
1897 CallingConv::ID CallConv, bool isVarArg,
1899 const SmallVectorImpl<ISD::OutputArg> &Outs,
1900 const SmallVectorImpl<SDValue> &OutVals,
1901 const SmallVectorImpl<ISD::InputArg> &Ins,
1902 DebugLoc dl, SelectionDAG &DAG,
1903 SmallVectorImpl<SDValue> &InVals) const {
1904 // MIPs target does not yet support tail call optimization.
1907 MachineFunction &MF = DAG.getMachineFunction();
1908 MachineFrameInfo *MFI = MF.getFrameInfo();
1909 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
1910 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1911 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1913 // Analyze operands of the call, assigning locations to each operand.
1914 SmallVector<CCValAssign, 16> ArgLocs;
1915 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
1916 getTargetMachine(), ArgLocs, *DAG.getContext());
1918 if (Subtarget->isABI_O32())
1919 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
1921 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
1923 // Get a count of how many bytes are to be pushed on the stack.
1924 unsigned NextStackOffset = CCInfo.getNextStackOffset();
1926 // Chain is the output chain of the last Load/Store or CopyToReg node.
1927 // ByValChain is the output chain of the last Memcpy node created for copying
1928 // byval arguments to the stack.
1929 SDValue Chain, CallSeqStart, ByValChain;
1930 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
1931 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
1932 ByValChain = InChain;
1934 // If this is the first call, create a stack frame object that points to
1935 // a location to which .cprestore saves $gp.
1936 if (IsPIC && !MipsFI->getGPFI())
1937 MipsFI->setGPFI(MFI->CreateFixedObject(4, 0, true));
1939 // Get the frame index of the stack frame object that points to the location
1940 // of dynamically allocated area on the stack.
1941 int DynAllocFI = MipsFI->getDynAllocFI();
1943 // Update size of the maximum argument space.
1944 // For O32, a minimum of four words (16 bytes) of argument space is
1946 if (Subtarget->isABI_O32())
1947 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
1949 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
1951 if (MaxCallFrameSize < NextStackOffset) {
1952 MipsFI->setMaxCallFrameSize(NextStackOffset);
1954 // Set the offsets relative to $sp of the $gp restore slot and dynamically
1955 // allocated stack space. These offsets must be aligned to a boundary
1956 // determined by the stack alignment of the ABI.
1957 unsigned StackAlignment = TFL->getStackAlignment();
1958 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
1959 StackAlignment * StackAlignment;
1962 MFI->setObjectOffset(MipsFI->getGPFI(), NextStackOffset);
1964 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
1967 // With EABI is it possible to have 16 args on registers.
1968 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
1969 SmallVector<SDValue, 8> MemOpChains;
1971 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
1973 // Walk the register/memloc assignments, inserting copies/loads.
1974 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1975 SDValue Arg = OutVals[i];
1976 CCValAssign &VA = ArgLocs[i];
1978 // Promote the value if needed.
1979 switch (VA.getLocInfo()) {
1980 default: llvm_unreachable("Unknown loc info!");
1981 case CCValAssign::Full:
1982 if (Subtarget->isABI_O32() && VA.isRegLoc()) {
1983 if (VA.getValVT() == MVT::f32 && VA.getLocVT() == MVT::i32)
1984 Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
1985 if (VA.getValVT() == MVT::f64 && VA.getLocVT() == MVT::i32) {
1986 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1987 Arg, DAG.getConstant(0, MVT::i32));
1988 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
1989 Arg, DAG.getConstant(1, MVT::i32));
1990 if (!Subtarget->isLittle())
1992 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Lo));
1993 RegsToPass.push_back(std::make_pair(VA.getLocReg()+1, Hi));
1998 case CCValAssign::SExt:
1999 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
2001 case CCValAssign::ZExt:
2002 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
2004 case CCValAssign::AExt:
2005 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
2009 // Arguments that can be passed on register must be kept at
2010 // RegsToPass vector
2011 if (VA.isRegLoc()) {
2012 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2016 // Register can't get to this point...
2017 assert(VA.isMemLoc());
2020 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2021 if (Flags.isByVal()) {
2022 assert(Subtarget->isABI_O32() &&
2023 "No support for ByVal args by ABIs other than O32 yet.");
2024 assert(Flags.getByValSize() &&
2025 "ByVal args of size 0 should have been ignored by front-end.");
2026 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI, MFI,
2027 DAG, Arg, VA, Flags, getPointerTy(), Subtarget->isLittle());
2031 // Create the frame index object for this incoming parameter
2032 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2033 VA.getLocMemOffset(), true);
2034 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2036 // emit ISD::STORE whichs stores the
2037 // parameter value to a stack Location
2038 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2039 MachinePointerInfo(),
2043 // Extend range of indices of frame objects for outgoing arguments that were
2044 // created during this function call. Skip this step if no such objects were
2047 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2049 // If a memcpy has been created to copy a byval arg to a stack, replace the
2050 // chain input of CallSeqStart with ByValChain.
2051 if (InChain != ByValChain)
2052 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2053 NextStackOffsetVal);
2055 // Transform all store nodes into one single node because all store
2056 // nodes are independent of each other.
2057 if (!MemOpChains.empty())
2058 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2059 &MemOpChains[0], MemOpChains.size());
2061 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2062 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2063 // node so that legalize doesn't hack it.
2064 unsigned char OpFlag = IsPIC ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2065 bool LoadSymAddr = false;
2068 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2069 if (IsPIC && G->getGlobal()->hasInternalLinkage()) {
2070 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2071 getPointerTy(), 0,MipsII:: MO_GOT);
2072 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2073 0, MipsII::MO_ABS_LO);
2075 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2076 getPointerTy(), 0, OpFlag);
2081 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2082 Callee = DAG.getTargetExternalSymbol(S->getSymbol(),
2083 getPointerTy(), OpFlag);
2089 // Create nodes that load address of callee and copy it to T9
2092 // Load callee address
2093 Callee = DAG.getNode(MipsISD::WrapperPIC, dl, MVT::i32, Callee);
2094 SDValue LoadValue = DAG.getLoad(MVT::i32, dl, DAG.getEntryNode(), Callee,
2095 MachinePointerInfo::getGOT(),
2098 // Use GOT+LO if callee has internal linkage.
2099 if (CalleeLo.getNode()) {
2100 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CalleeLo);
2101 Callee = DAG.getNode(ISD::ADD, dl, MVT::i32, LoadValue, Lo);
2107 Chain = DAG.getCopyToReg(Chain, dl, Mips::T9, Callee, SDValue(0, 0));
2108 InFlag = Chain.getValue(1);
2109 Callee = DAG.getRegister(Mips::T9, MVT::i32);
2112 // Build a sequence of copy-to-reg nodes chained together with token
2113 // chain and flag operands which copy the outgoing args into registers.
2114 // The InFlag in necessary since all emitted instructions must be
2116 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2117 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2118 RegsToPass[i].second, InFlag);
2119 InFlag = Chain.getValue(1);
2122 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2123 // = Chain, Callee, Reg#1, Reg#2, ...
2125 // Returns a chain & a flag for retval copy to use.
2126 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2127 SmallVector<SDValue, 8> Ops;
2128 Ops.push_back(Chain);
2129 Ops.push_back(Callee);
2131 // Add argument registers to the end of the list so that they are
2132 // known live into the call.
2133 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2134 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2135 RegsToPass[i].second.getValueType()));
2137 if (InFlag.getNode())
2138 Ops.push_back(InFlag);
2140 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2141 InFlag = Chain.getValue(1);
2143 // Create the CALLSEQ_END node.
2144 Chain = DAG.getCALLSEQ_END(Chain,
2145 DAG.getIntPtrConstant(NextStackOffset, true),
2146 DAG.getIntPtrConstant(0, true), InFlag);
2147 InFlag = Chain.getValue(1);
2149 // Handle result values, copying them out of physregs into vregs that we
2151 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2152 Ins, dl, DAG, InVals);
2155 /// LowerCallResult - Lower the result values of a call into the
2156 /// appropriate copies out of appropriate physical registers.
2158 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2159 CallingConv::ID CallConv, bool isVarArg,
2160 const SmallVectorImpl<ISD::InputArg> &Ins,
2161 DebugLoc dl, SelectionDAG &DAG,
2162 SmallVectorImpl<SDValue> &InVals) const {
2163 // Assign locations to each value returned by this call.
2164 SmallVector<CCValAssign, 16> RVLocs;
2165 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2166 getTargetMachine(), RVLocs, *DAG.getContext());
2168 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2170 // Copy all of the result registers out of their specified physreg.
2171 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2172 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2173 RVLocs[i].getValVT(), InFlag).getValue(1);
2174 InFlag = Chain.getValue(2);
2175 InVals.push_back(Chain.getValue(0));
2181 //===----------------------------------------------------------------------===//
2182 // Formal Arguments Calling Convention Implementation
2183 //===----------------------------------------------------------------------===//
2184 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2185 std::vector<SDValue>& OutChains,
2186 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2187 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags) {
2188 unsigned LocMem = VA.getLocMemOffset();
2189 unsigned FirstWord = LocMem / 4;
2191 // copy register A0 - A3 to frame object
2192 for (unsigned i = 0; i < NumWords; ++i) {
2193 unsigned CurWord = FirstWord + i;
2194 if (CurWord >= O32IntRegsSize)
2197 unsigned SrcReg = O32IntRegs[CurWord];
2198 unsigned Reg = AddLiveIn(MF, SrcReg, Mips::CPURegsRegisterClass);
2199 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2200 DAG.getConstant(i * 4, MVT::i32));
2201 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2202 StorePtr, MachinePointerInfo(), false,
2204 OutChains.push_back(Store);
2208 /// LowerFormalArguments - transform physical registers into virtual registers
2209 /// and generate load operations for arguments places on the stack.
2211 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2212 CallingConv::ID CallConv,
2214 const SmallVectorImpl<ISD::InputArg>
2216 DebugLoc dl, SelectionDAG &DAG,
2217 SmallVectorImpl<SDValue> &InVals)
2219 MachineFunction &MF = DAG.getMachineFunction();
2220 MachineFrameInfo *MFI = MF.getFrameInfo();
2221 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2223 MipsFI->setVarArgsFrameIndex(0);
2225 // Used with vargs to acumulate store chains.
2226 std::vector<SDValue> OutChains;
2228 // Assign locations to all of the incoming arguments.
2229 SmallVector<CCValAssign, 16> ArgLocs;
2230 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2231 getTargetMachine(), ArgLocs, *DAG.getContext());
2233 if (Subtarget->isABI_O32())
2234 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2236 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2238 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
2240 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2241 CCValAssign &VA = ArgLocs[i];
2243 // Arguments stored on registers
2244 if (VA.isRegLoc()) {
2245 EVT RegVT = VA.getLocVT();
2246 unsigned ArgReg = VA.getLocReg();
2247 TargetRegisterClass *RC = 0;
2249 if (RegVT == MVT::i32)
2250 RC = Mips::CPURegsRegisterClass;
2251 else if (RegVT == MVT::f32)
2252 RC = Mips::FGR32RegisterClass;
2253 else if (RegVT == MVT::f64) {
2254 if (!Subtarget->isSingleFloat())
2255 RC = Mips::AFGR64RegisterClass;
2257 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2259 // Transform the arguments stored on
2260 // physical registers into virtual ones
2261 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2262 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2264 // If this is an 8 or 16-bit value, it has been passed promoted
2265 // to 32 bits. Insert an assert[sz]ext to capture this, then
2266 // truncate to the right size.
2267 if (VA.getLocInfo() != CCValAssign::Full) {
2268 unsigned Opcode = 0;
2269 if (VA.getLocInfo() == CCValAssign::SExt)
2270 Opcode = ISD::AssertSext;
2271 else if (VA.getLocInfo() == CCValAssign::ZExt)
2272 Opcode = ISD::AssertZext;
2274 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
2275 DAG.getValueType(VA.getValVT()));
2276 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2279 // Handle O32 ABI cases: i32->f32 and (i32,i32)->f64
2280 if (Subtarget->isABI_O32()) {
2281 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f32)
2282 ArgValue = DAG.getNode(ISD::BITCAST, dl, MVT::f32, ArgValue);
2283 if (RegVT == MVT::i32 && VA.getValVT() == MVT::f64) {
2284 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
2285 VA.getLocReg()+1, RC);
2286 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
2287 if (!Subtarget->isLittle())
2288 std::swap(ArgValue, ArgValue2);
2289 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
2290 ArgValue, ArgValue2);
2294 InVals.push_back(ArgValue);
2295 } else { // VA.isRegLoc()
2298 assert(VA.isMemLoc());
2300 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2302 if (Flags.isByVal()) {
2303 assert(Subtarget->isABI_O32() &&
2304 "No support for ByVal args by ABIs other than O32 yet.");
2305 assert(Flags.getByValSize() &&
2306 "ByVal args of size 0 should have been ignored by front-end.");
2307 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
2308 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
2310 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2311 InVals.push_back(FIN);
2312 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags);
2317 // The stack pointer offset is relative to the caller stack frame.
2318 LastFI = MFI->CreateFixedObject(VA.getValVT().getSizeInBits()/8,
2319 VA.getLocMemOffset(), true);
2321 // Create load nodes to retrieve arguments from the stack
2322 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
2323 InVals.push_back(DAG.getLoad(VA.getValVT(), dl, Chain, FIN,
2324 MachinePointerInfo::getFixedStack(LastFI),
2329 // The mips ABIs for returning structs by value requires that we copy
2330 // the sret argument into $v0 for the return. Save the argument into
2331 // a virtual register so that we can access it from the return points.
2332 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2333 unsigned Reg = MipsFI->getSRetReturnReg();
2335 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
2336 MipsFI->setSRetReturnReg(Reg);
2338 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
2339 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2342 if (isVarArg && Subtarget->isABI_O32()) {
2343 // Record the frame index of the first variable argument
2344 // which is a value necessary to VASTART.
2345 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2346 assert(NextStackOffset % 4 == 0 &&
2347 "NextStackOffset must be aligned to 4-byte boundaries.");
2348 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2349 MipsFI->setVarArgsFrameIndex(LastFI);
2351 // If NextStackOffset is smaller than o32's 16-byte reserved argument area,
2352 // copy the integer registers that have not been used for argument passing
2353 // to the caller's stack frame.
2354 for (; NextStackOffset < 16; NextStackOffset += 4) {
2355 TargetRegisterClass *RC = Mips::CPURegsRegisterClass;
2356 unsigned Idx = NextStackOffset / 4;
2357 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), O32IntRegs[Idx], RC);
2358 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, MVT::i32);
2359 LastFI = MFI->CreateFixedObject(4, NextStackOffset, true);
2360 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2361 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
2362 MachinePointerInfo(),
2367 MipsFI->setLastInArgFI(LastFI);
2369 // All stores are grouped in one node to allow the matching between
2370 // the size of Ins and InVals. This only happens when on varg functions
2371 if (!OutChains.empty()) {
2372 OutChains.push_back(Chain);
2373 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2374 &OutChains[0], OutChains.size());
2380 //===----------------------------------------------------------------------===//
2381 // Return Value Calling Convention Implementation
2382 //===----------------------------------------------------------------------===//
2385 MipsTargetLowering::LowerReturn(SDValue Chain,
2386 CallingConv::ID CallConv, bool isVarArg,
2387 const SmallVectorImpl<ISD::OutputArg> &Outs,
2388 const SmallVectorImpl<SDValue> &OutVals,
2389 DebugLoc dl, SelectionDAG &DAG) const {
2391 // CCValAssign - represent the assignment of
2392 // the return value to a location
2393 SmallVector<CCValAssign, 16> RVLocs;
2395 // CCState - Info about the registers and stack slot.
2396 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2397 getTargetMachine(), RVLocs, *DAG.getContext());
2399 // Analize return values.
2400 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2402 // If this is the first return lowered for this function, add
2403 // the regs to the liveout set for the function.
2404 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
2405 for (unsigned i = 0; i != RVLocs.size(); ++i)
2406 if (RVLocs[i].isRegLoc())
2407 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
2412 // Copy the result values into the output registers.
2413 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2414 CCValAssign &VA = RVLocs[i];
2415 assert(VA.isRegLoc() && "Can only return in registers!");
2417 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
2420 // guarantee that all emitted copies are
2421 // stuck together, avoiding something bad
2422 Flag = Chain.getValue(1);
2425 // The mips ABIs for returning structs by value requires that we copy
2426 // the sret argument into $v0 for the return. We saved the argument into
2427 // a virtual register in the entry block, so now we copy the value out
2429 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2430 MachineFunction &MF = DAG.getMachineFunction();
2431 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2432 unsigned Reg = MipsFI->getSRetReturnReg();
2435 llvm_unreachable("sret virtual register not created in the entry block");
2436 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
2438 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
2439 Flag = Chain.getValue(1);
2442 // Return on Mips is always a "jr $ra"
2444 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2445 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
2447 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
2448 Chain, DAG.getRegister(Mips::RA, MVT::i32));
2451 //===----------------------------------------------------------------------===//
2452 // Mips Inline Assembly Support
2453 //===----------------------------------------------------------------------===//
2455 /// getConstraintType - Given a constraint letter, return the type of
2456 /// constraint it is for this target.
2457 MipsTargetLowering::ConstraintType MipsTargetLowering::
2458 getConstraintType(const std::string &Constraint) const
2460 // Mips specific constrainy
2461 // GCC config/mips/constraints.md
2463 // 'd' : An address register. Equivalent to r
2464 // unless generating MIPS16 code.
2465 // 'y' : Equivalent to r; retained for
2466 // backwards compatibility.
2467 // 'f' : Floating Point registers.
2468 if (Constraint.size() == 1) {
2469 switch (Constraint[0]) {
2474 return C_RegisterClass;
2478 return TargetLowering::getConstraintType(Constraint);
2481 /// Examine constraint type and operand type and determine a weight value.
2482 /// This object must already have been set up with the operand type
2483 /// and the current alternative constraint selected.
2484 TargetLowering::ConstraintWeight
2485 MipsTargetLowering::getSingleConstraintMatchWeight(
2486 AsmOperandInfo &info, const char *constraint) const {
2487 ConstraintWeight weight = CW_Invalid;
2488 Value *CallOperandVal = info.CallOperandVal;
2489 // If we don't have a value, we can't do a match,
2490 // but allow it at the lowest weight.
2491 if (CallOperandVal == NULL)
2493 Type *type = CallOperandVal->getType();
2494 // Look at the constraint type.
2495 switch (*constraint) {
2497 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2501 if (type->isIntegerTy())
2502 weight = CW_Register;
2505 if (type->isFloatTy())
2506 weight = CW_Register;
2512 /// Given a register class constraint, like 'r', if this corresponds directly
2513 /// to an LLVM register class, return a register of 0 and the register class
2515 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2516 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2518 if (Constraint.size() == 1) {
2519 switch (Constraint[0]) {
2520 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2521 case 'y': // Same as 'r'. Exists for compatibility.
2523 return std::make_pair(0U, Mips::CPURegsRegisterClass);
2526 return std::make_pair(0U, Mips::FGR32RegisterClass);
2528 if ((!Subtarget->isSingleFloat()) && (!Subtarget->isFP64bit()))
2529 return std::make_pair(0U, Mips::AFGR64RegisterClass);
2533 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2537 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2538 // The Mips target isn't yet aware of offsets.
2542 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2543 if (VT != MVT::f32 && VT != MVT::f64)
2545 if (Imm.isNegZero())
2547 return Imm.isZero();