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 "InstPrinter/MipsInstPrinter.h"
22 #include "MCTargetDesc/MipsBaseInfo.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
41 // If I is a shifted mask, set the size (Size) and the first bit of the
42 // mask (Pos), and return true.
43 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
44 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
45 if (!isShiftedMask_64(I))
48 Size = CountPopulation_64(I);
49 Pos = CountTrailingZeros_64(I);
53 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
54 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
55 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
58 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
60 case MipsISD::JmpLink: return "MipsISD::JmpLink";
61 case MipsISD::Hi: return "MipsISD::Hi";
62 case MipsISD::Lo: return "MipsISD::Lo";
63 case MipsISD::GPRel: return "MipsISD::GPRel";
64 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
65 case MipsISD::Ret: return "MipsISD::Ret";
66 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
67 case MipsISD::FPCmp: return "MipsISD::FPCmp";
68 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
69 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
70 case MipsISD::FPRound: return "MipsISD::FPRound";
71 case MipsISD::MAdd: return "MipsISD::MAdd";
72 case MipsISD::MAddu: return "MipsISD::MAddu";
73 case MipsISD::MSub: return "MipsISD::MSub";
74 case MipsISD::MSubu: return "MipsISD::MSubu";
75 case MipsISD::DivRem: return "MipsISD::DivRem";
76 case MipsISD::DivRemU: return "MipsISD::DivRemU";
77 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
78 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
79 case MipsISD::Wrapper: return "MipsISD::Wrapper";
80 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
81 case MipsISD::Sync: return "MipsISD::Sync";
82 case MipsISD::Ext: return "MipsISD::Ext";
83 case MipsISD::Ins: return "MipsISD::Ins";
84 case MipsISD::LWL: return "MipsISD::LWL";
85 case MipsISD::LWR: return "MipsISD::LWR";
86 case MipsISD::SWL: return "MipsISD::SWL";
87 case MipsISD::SWR: return "MipsISD::SWR";
88 case MipsISD::LDL: return "MipsISD::LDL";
89 case MipsISD::LDR: return "MipsISD::LDR";
90 case MipsISD::SDL: return "MipsISD::SDL";
91 case MipsISD::SDR: return "MipsISD::SDR";
97 MipsTargetLowering(MipsTargetMachine &TM)
98 : TargetLowering(TM, new MipsTargetObjectFile()),
99 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
100 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
101 IsO32(Subtarget->isABI_O32()) {
103 // Mips does not have i1 type, so use i32 for
104 // setcc operations results (slt, sgt, ...).
105 setBooleanContents(ZeroOrOneBooleanContent);
106 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
108 // Set up the register classes
109 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
112 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
114 if (Subtarget->inMips16Mode()) {
115 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
116 addRegisterClass(MVT::i32, &Mips::CPURARegRegClass);
119 if (!TM.Options.UseSoftFloat) {
120 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
122 // When dealing with single precision only, use libcalls
123 if (!Subtarget->isSingleFloat()) {
125 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
127 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
131 // Load extented operations for i1 types must be promoted
132 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
133 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
136 // MIPS doesn't have extending float->double load/store
137 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
138 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
140 // Used by legalize types to correctly generate the setcc result.
141 // Without this, every float setcc comes with a AND/OR with the result,
142 // we don't want this, since the fpcmp result goes to a flag register,
143 // which is used implicitly by brcond and select operations.
144 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
146 // Mips Custom Operations
147 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
148 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
149 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
150 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
151 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
152 setOperationAction(ISD::SELECT, MVT::f32, Custom);
153 setOperationAction(ISD::SELECT, MVT::f64, Custom);
154 setOperationAction(ISD::SELECT, MVT::i32, Custom);
155 setOperationAction(ISD::SETCC, MVT::f32, Custom);
156 setOperationAction(ISD::SETCC, MVT::f64, Custom);
157 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
158 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
159 setOperationAction(ISD::VASTART, MVT::Other, Custom);
160 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
161 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
162 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
163 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
164 setOperationAction(ISD::LOAD, MVT::i32, Custom);
165 setOperationAction(ISD::STORE, MVT::i32, Custom);
167 if (!TM.Options.NoNaNsFPMath) {
168 setOperationAction(ISD::FABS, MVT::f32, Custom);
169 setOperationAction(ISD::FABS, MVT::f64, Custom);
173 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
174 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
175 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
176 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
177 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
178 setOperationAction(ISD::SELECT, MVT::i64, Custom);
179 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
180 setOperationAction(ISD::LOAD, MVT::i64, Custom);
181 setOperationAction(ISD::STORE, MVT::i64, Custom);
185 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
186 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
187 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
190 setOperationAction(ISD::SDIV, MVT::i32, Expand);
191 setOperationAction(ISD::SREM, MVT::i32, Expand);
192 setOperationAction(ISD::UDIV, MVT::i32, Expand);
193 setOperationAction(ISD::UREM, MVT::i32, Expand);
194 setOperationAction(ISD::SDIV, MVT::i64, Expand);
195 setOperationAction(ISD::SREM, MVT::i64, Expand);
196 setOperationAction(ISD::UDIV, MVT::i64, Expand);
197 setOperationAction(ISD::UREM, MVT::i64, Expand);
199 // Operations not directly supported by Mips.
200 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
201 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
202 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
203 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
204 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
205 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
206 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
207 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
208 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
209 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
210 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
211 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
212 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
213 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
214 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
215 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::ROTL, MVT::i32, Expand);
217 setOperationAction(ISD::ROTL, MVT::i64, Expand);
219 if (!Subtarget->hasMips32r2())
220 setOperationAction(ISD::ROTR, MVT::i32, Expand);
222 if (!Subtarget->hasMips64r2())
223 setOperationAction(ISD::ROTR, MVT::i64, Expand);
225 setOperationAction(ISD::FSIN, MVT::f32, Expand);
226 setOperationAction(ISD::FSIN, MVT::f64, Expand);
227 setOperationAction(ISD::FCOS, MVT::f32, Expand);
228 setOperationAction(ISD::FCOS, MVT::f64, Expand);
229 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
230 setOperationAction(ISD::FPOW, MVT::f32, Expand);
231 setOperationAction(ISD::FPOW, MVT::f64, Expand);
232 setOperationAction(ISD::FLOG, MVT::f32, Expand);
233 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
234 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
235 setOperationAction(ISD::FEXP, MVT::f32, Expand);
236 setOperationAction(ISD::FMA, MVT::f32, Expand);
237 setOperationAction(ISD::FMA, MVT::f64, Expand);
238 setOperationAction(ISD::FREM, MVT::f32, Expand);
239 setOperationAction(ISD::FREM, MVT::f64, Expand);
241 if (!TM.Options.NoNaNsFPMath) {
242 setOperationAction(ISD::FNEG, MVT::f32, Expand);
243 setOperationAction(ISD::FNEG, MVT::f64, Expand);
246 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
247 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
248 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
249 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
251 setOperationAction(ISD::VAARG, MVT::Other, Expand);
252 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
253 setOperationAction(ISD::VAEND, MVT::Other, Expand);
255 // Use the default for now
256 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
257 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
259 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
260 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
261 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
262 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
264 setInsertFencesForAtomic(true);
266 if (Subtarget->isSingleFloat())
267 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
269 if (!Subtarget->hasSEInReg()) {
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
271 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
274 if (!Subtarget->hasBitCount()) {
275 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
276 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
279 if (!Subtarget->hasSwap()) {
280 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
281 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
285 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
286 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
287 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
288 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
291 setTargetDAGCombine(ISD::ADDE);
292 setTargetDAGCombine(ISD::SUBE);
293 setTargetDAGCombine(ISD::SDIVREM);
294 setTargetDAGCombine(ISD::UDIVREM);
295 setTargetDAGCombine(ISD::SELECT);
296 setTargetDAGCombine(ISD::AND);
297 setTargetDAGCombine(ISD::OR);
298 setTargetDAGCombine(ISD::ADD);
300 setMinFunctionAlignment(HasMips64 ? 3 : 2);
302 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
303 computeRegisterProperties();
305 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
306 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
308 maxStoresPerMemcpy = 16;
311 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
312 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
319 return Subtarget->hasMips32r2Or64();
325 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
330 // Transforms a subgraph in CurDAG if the following pattern is found:
331 // (addc multLo, Lo0), (adde multHi, Hi0),
333 // multHi/Lo: product of multiplication
334 // Lo0: initial value of Lo register
335 // Hi0: initial value of Hi register
336 // Return true if pattern matching was successful.
337 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
338 // ADDENode's second operand must be a flag output of an ADDC node in order
339 // for the matching to be successful.
340 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
342 if (ADDCNode->getOpcode() != ISD::ADDC)
345 SDValue MultHi = ADDENode->getOperand(0);
346 SDValue MultLo = ADDCNode->getOperand(0);
347 SDNode *MultNode = MultHi.getNode();
348 unsigned MultOpc = MultHi.getOpcode();
350 // MultHi and MultLo must be generated by the same node,
351 if (MultLo.getNode() != MultNode)
354 // and it must be a multiplication.
355 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
358 // MultLo amd MultHi must be the first and second output of MultNode
360 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
363 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
364 // of the values of MultNode, in which case MultNode will be removed in later
366 // If there exist users other than ADDENode or ADDCNode, this function returns
367 // here, which will result in MultNode being mapped to a single MULT
368 // instruction node rather than a pair of MULT and MADD instructions being
370 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
373 SDValue Chain = CurDAG->getEntryNode();
374 DebugLoc dl = ADDENode->getDebugLoc();
376 // create MipsMAdd(u) node
377 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
379 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
380 MultNode->getOperand(0),// Factor 0
381 MultNode->getOperand(1),// Factor 1
382 ADDCNode->getOperand(1),// Lo0
383 ADDENode->getOperand(1));// Hi0
385 // create CopyFromReg nodes
386 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
388 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
390 CopyFromLo.getValue(2));
392 // replace uses of adde and addc here
393 if (!SDValue(ADDCNode, 0).use_empty())
394 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
396 if (!SDValue(ADDENode, 0).use_empty())
397 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
403 // Transforms a subgraph in CurDAG if the following pattern is found:
404 // (addc Lo0, multLo), (sube Hi0, multHi),
406 // multHi/Lo: product of multiplication
407 // Lo0: initial value of Lo register
408 // Hi0: initial value of Hi register
409 // Return true if pattern matching was successful.
410 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
411 // SUBENode's second operand must be a flag output of an SUBC node in order
412 // for the matching to be successful.
413 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
415 if (SUBCNode->getOpcode() != ISD::SUBC)
418 SDValue MultHi = SUBENode->getOperand(1);
419 SDValue MultLo = SUBCNode->getOperand(1);
420 SDNode *MultNode = MultHi.getNode();
421 unsigned MultOpc = MultHi.getOpcode();
423 // MultHi and MultLo must be generated by the same node,
424 if (MultLo.getNode() != MultNode)
427 // and it must be a multiplication.
428 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
431 // MultLo amd MultHi must be the first and second output of MultNode
433 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
436 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
437 // of the values of MultNode, in which case MultNode will be removed in later
439 // If there exist users other than SUBENode or SUBCNode, this function returns
440 // here, which will result in MultNode being mapped to a single MULT
441 // instruction node rather than a pair of MULT and MSUB instructions being
443 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
446 SDValue Chain = CurDAG->getEntryNode();
447 DebugLoc dl = SUBENode->getDebugLoc();
449 // create MipsSub(u) node
450 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
452 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
453 MultNode->getOperand(0),// Factor 0
454 MultNode->getOperand(1),// Factor 1
455 SUBCNode->getOperand(0),// Lo0
456 SUBENode->getOperand(0));// Hi0
458 // create CopyFromReg nodes
459 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
461 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
463 CopyFromLo.getValue(2));
465 // replace uses of sube and subc here
466 if (!SDValue(SUBCNode, 0).use_empty())
467 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
469 if (!SDValue(SUBENode, 0).use_empty())
470 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
475 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
476 TargetLowering::DAGCombinerInfo &DCI,
477 const MipsSubtarget *Subtarget) {
478 if (DCI.isBeforeLegalize())
481 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
483 return SDValue(N, 0);
488 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
489 TargetLowering::DAGCombinerInfo &DCI,
490 const MipsSubtarget *Subtarget) {
491 if (DCI.isBeforeLegalize())
494 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
496 return SDValue(N, 0);
501 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
502 TargetLowering::DAGCombinerInfo &DCI,
503 const MipsSubtarget *Subtarget) {
504 if (DCI.isBeforeLegalizeOps())
507 EVT Ty = N->getValueType(0);
508 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
509 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
510 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
512 DebugLoc dl = N->getDebugLoc();
514 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
515 N->getOperand(0), N->getOperand(1));
516 SDValue InChain = DAG.getEntryNode();
517 SDValue InGlue = DivRem;
520 if (N->hasAnyUseOfValue(0)) {
521 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
523 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
524 InChain = CopyFromLo.getValue(1);
525 InGlue = CopyFromLo.getValue(2);
529 if (N->hasAnyUseOfValue(1)) {
530 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
532 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
538 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
540 default: llvm_unreachable("Unknown fp condition code!");
542 case ISD::SETOEQ: return Mips::FCOND_OEQ;
543 case ISD::SETUNE: return Mips::FCOND_UNE;
545 case ISD::SETOLT: return Mips::FCOND_OLT;
547 case ISD::SETOGT: return Mips::FCOND_OGT;
549 case ISD::SETOLE: return Mips::FCOND_OLE;
551 case ISD::SETOGE: return Mips::FCOND_OGE;
552 case ISD::SETULT: return Mips::FCOND_ULT;
553 case ISD::SETULE: return Mips::FCOND_ULE;
554 case ISD::SETUGT: return Mips::FCOND_UGT;
555 case ISD::SETUGE: return Mips::FCOND_UGE;
556 case ISD::SETUO: return Mips::FCOND_UN;
557 case ISD::SETO: return Mips::FCOND_OR;
559 case ISD::SETONE: return Mips::FCOND_ONE;
560 case ISD::SETUEQ: return Mips::FCOND_UEQ;
565 // Returns true if condition code has to be inverted.
566 static bool InvertFPCondCode(Mips::CondCode CC) {
567 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
570 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
571 "Illegal Condition Code");
576 // Creates and returns an FPCmp node from a setcc node.
577 // Returns Op if setcc is not a floating point comparison.
578 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
579 // must be a SETCC node
580 if (Op.getOpcode() != ISD::SETCC)
583 SDValue LHS = Op.getOperand(0);
585 if (!LHS.getValueType().isFloatingPoint())
588 SDValue RHS = Op.getOperand(1);
589 DebugLoc dl = Op.getDebugLoc();
591 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
592 // node if necessary.
593 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
595 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
596 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
599 // Creates and returns a CMovFPT/F node.
600 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
601 SDValue False, DebugLoc DL) {
602 bool invert = InvertFPCondCode((Mips::CondCode)
603 cast<ConstantSDNode>(Cond.getOperand(2))
606 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
607 True.getValueType(), True, False, Cond);
610 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
611 TargetLowering::DAGCombinerInfo &DCI,
612 const MipsSubtarget *Subtarget) {
613 if (DCI.isBeforeLegalizeOps())
616 SDValue SetCC = N->getOperand(0);
618 if ((SetCC.getOpcode() != ISD::SETCC) ||
619 !SetCC.getOperand(0).getValueType().isInteger())
622 SDValue False = N->getOperand(2);
623 EVT FalseTy = False.getValueType();
625 if (!FalseTy.isInteger())
628 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
630 if (!CN || CN->getZExtValue())
633 const DebugLoc DL = N->getDebugLoc();
634 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
635 SDValue True = N->getOperand(1);
637 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
638 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
640 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
643 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
644 TargetLowering::DAGCombinerInfo &DCI,
645 const MipsSubtarget *Subtarget) {
646 // Pattern match EXT.
647 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
648 // => ext $dst, $src, size, pos
649 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
652 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
653 unsigned ShiftRightOpc = ShiftRight.getOpcode();
655 // Op's first operand must be a shift right.
656 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
659 // The second operand of the shift must be an immediate.
661 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
664 uint64_t Pos = CN->getZExtValue();
665 uint64_t SMPos, SMSize;
667 // Op's second operand must be a shifted mask.
668 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
669 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
672 // Return if the shifted mask does not start at bit 0 or the sum of its size
673 // and Pos exceeds the word's size.
674 EVT ValTy = N->getValueType(0);
675 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
678 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
679 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
680 DAG.getConstant(SMSize, MVT::i32));
683 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
684 TargetLowering::DAGCombinerInfo &DCI,
685 const MipsSubtarget *Subtarget) {
686 // Pattern match INS.
687 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
688 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
689 // => ins $dst, $src, size, pos, $src1
690 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
693 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
694 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
697 // See if Op's first operand matches (and $src1 , mask0).
698 if (And0.getOpcode() != ISD::AND)
701 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
702 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
705 // See if Op's second operand matches (and (shl $src, pos), mask1).
706 if (And1.getOpcode() != ISD::AND)
709 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
710 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
713 // The shift masks must have the same position and size.
714 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
717 SDValue Shl = And1.getOperand(0);
718 if (Shl.getOpcode() != ISD::SHL)
721 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
724 unsigned Shamt = CN->getZExtValue();
726 // Return if the shift amount and the first bit position of mask are not the
728 EVT ValTy = N->getValueType(0);
729 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
732 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
733 DAG.getConstant(SMPos0, MVT::i32),
734 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
737 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
738 TargetLowering::DAGCombinerInfo &DCI,
739 const MipsSubtarget *Subtarget) {
740 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
742 if (DCI.isBeforeLegalizeOps())
745 SDValue Add = N->getOperand(1);
747 if (Add.getOpcode() != ISD::ADD)
750 SDValue Lo = Add.getOperand(1);
752 if ((Lo.getOpcode() != MipsISD::Lo) ||
753 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
756 EVT ValTy = N->getValueType(0);
757 DebugLoc DL = N->getDebugLoc();
759 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
761 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
764 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
766 SelectionDAG &DAG = DCI.DAG;
767 unsigned opc = N->getOpcode();
772 return PerformADDECombine(N, DAG, DCI, Subtarget);
774 return PerformSUBECombine(N, DAG, DCI, Subtarget);
777 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
779 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
781 return PerformANDCombine(N, DAG, DCI, Subtarget);
783 return PerformORCombine(N, DAG, DCI, Subtarget);
785 return PerformADDCombine(N, DAG, DCI, Subtarget);
791 SDValue MipsTargetLowering::
792 LowerOperation(SDValue Op, SelectionDAG &DAG) const
794 switch (Op.getOpcode())
796 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
797 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
798 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
799 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
800 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
801 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
802 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
803 case ISD::SELECT: return LowerSELECT(Op, DAG);
804 case ISD::SETCC: return LowerSETCC(Op, DAG);
805 case ISD::VASTART: return LowerVASTART(Op, DAG);
806 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
807 case ISD::FABS: return LowerFABS(Op, DAG);
808 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
809 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
810 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
811 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
812 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
813 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
814 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
815 case ISD::LOAD: return LowerLOAD(Op, DAG);
816 case ISD::STORE: return LowerSTORE(Op, DAG);
821 //===----------------------------------------------------------------------===//
822 // Lower helper functions
823 //===----------------------------------------------------------------------===//
825 // AddLiveIn - This helper function adds the specified physical register to the
826 // MachineFunction as a live in value. It also creates a corresponding
827 // virtual register for it.
829 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
831 assert(RC->contains(PReg) && "Not the correct regclass!");
832 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
833 MF.getRegInfo().addLiveIn(PReg, VReg);
837 // Get fp branch code (not opcode) from condition code.
838 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
839 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
840 return Mips::BRANCH_T;
842 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
843 "Invalid CondCode.");
845 return Mips::BRANCH_F;
849 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
851 const MipsSubtarget *Subtarget,
852 const TargetInstrInfo *TII,
853 bool isFPCmp, unsigned Opc) {
854 // There is no need to expand CMov instructions if target has
855 // conditional moves.
856 if (Subtarget->hasCondMov())
859 // To "insert" a SELECT_CC instruction, we actually have to insert the
860 // diamond control-flow pattern. The incoming instruction knows the
861 // destination vreg to set, the condition code register to branch on, the
862 // true/false values to select between, and a branch opcode to use.
863 const BasicBlock *LLVM_BB = BB->getBasicBlock();
864 MachineFunction::iterator It = BB;
871 // bNE r1, r0, copy1MBB
872 // fallthrough --> copy0MBB
873 MachineBasicBlock *thisMBB = BB;
874 MachineFunction *F = BB->getParent();
875 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
876 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
877 F->insert(It, copy0MBB);
878 F->insert(It, sinkMBB);
880 // Transfer the remainder of BB and its successor edges to sinkMBB.
881 sinkMBB->splice(sinkMBB->begin(), BB,
882 llvm::next(MachineBasicBlock::iterator(MI)),
884 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
886 // Next, add the true and fallthrough blocks as its successors.
887 BB->addSuccessor(copy0MBB);
888 BB->addSuccessor(sinkMBB);
890 // Emit the right instruction according to the type of the operands compared
892 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
894 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
895 .addReg(Mips::ZERO).addMBB(sinkMBB);
899 // # fallthrough to sinkMBB
902 // Update machine-CFG edges
903 BB->addSuccessor(sinkMBB);
906 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
911 BuildMI(*BB, BB->begin(), dl,
912 TII->get(Mips::PHI), MI->getOperand(0).getReg())
913 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
914 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
916 BuildMI(*BB, BB->begin(), dl,
917 TII->get(Mips::PHI), MI->getOperand(0).getReg())
918 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
919 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
921 MI->eraseFromParent(); // The pseudo instruction is gone now.
926 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
927 MachineBasicBlock *BB) const {
928 switch (MI->getOpcode()) {
929 default: llvm_unreachable("Unexpected instr type to insert");
930 case Mips::ATOMIC_LOAD_ADD_I8:
931 case Mips::ATOMIC_LOAD_ADD_I8_P8:
932 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
933 case Mips::ATOMIC_LOAD_ADD_I16:
934 case Mips::ATOMIC_LOAD_ADD_I16_P8:
935 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
936 case Mips::ATOMIC_LOAD_ADD_I32:
937 case Mips::ATOMIC_LOAD_ADD_I32_P8:
938 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
939 case Mips::ATOMIC_LOAD_ADD_I64:
940 case Mips::ATOMIC_LOAD_ADD_I64_P8:
941 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
943 case Mips::ATOMIC_LOAD_AND_I8:
944 case Mips::ATOMIC_LOAD_AND_I8_P8:
945 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
946 case Mips::ATOMIC_LOAD_AND_I16:
947 case Mips::ATOMIC_LOAD_AND_I16_P8:
948 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
949 case Mips::ATOMIC_LOAD_AND_I32:
950 case Mips::ATOMIC_LOAD_AND_I32_P8:
951 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
952 case Mips::ATOMIC_LOAD_AND_I64:
953 case Mips::ATOMIC_LOAD_AND_I64_P8:
954 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
956 case Mips::ATOMIC_LOAD_OR_I8:
957 case Mips::ATOMIC_LOAD_OR_I8_P8:
958 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
959 case Mips::ATOMIC_LOAD_OR_I16:
960 case Mips::ATOMIC_LOAD_OR_I16_P8:
961 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
962 case Mips::ATOMIC_LOAD_OR_I32:
963 case Mips::ATOMIC_LOAD_OR_I32_P8:
964 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
965 case Mips::ATOMIC_LOAD_OR_I64:
966 case Mips::ATOMIC_LOAD_OR_I64_P8:
967 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
969 case Mips::ATOMIC_LOAD_XOR_I8:
970 case Mips::ATOMIC_LOAD_XOR_I8_P8:
971 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
972 case Mips::ATOMIC_LOAD_XOR_I16:
973 case Mips::ATOMIC_LOAD_XOR_I16_P8:
974 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
975 case Mips::ATOMIC_LOAD_XOR_I32:
976 case Mips::ATOMIC_LOAD_XOR_I32_P8:
977 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
978 case Mips::ATOMIC_LOAD_XOR_I64:
979 case Mips::ATOMIC_LOAD_XOR_I64_P8:
980 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
982 case Mips::ATOMIC_LOAD_NAND_I8:
983 case Mips::ATOMIC_LOAD_NAND_I8_P8:
984 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
985 case Mips::ATOMIC_LOAD_NAND_I16:
986 case Mips::ATOMIC_LOAD_NAND_I16_P8:
987 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
988 case Mips::ATOMIC_LOAD_NAND_I32:
989 case Mips::ATOMIC_LOAD_NAND_I32_P8:
990 return EmitAtomicBinary(MI, BB, 4, 0, true);
991 case Mips::ATOMIC_LOAD_NAND_I64:
992 case Mips::ATOMIC_LOAD_NAND_I64_P8:
993 return EmitAtomicBinary(MI, BB, 8, 0, true);
995 case Mips::ATOMIC_LOAD_SUB_I8:
996 case Mips::ATOMIC_LOAD_SUB_I8_P8:
997 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
998 case Mips::ATOMIC_LOAD_SUB_I16:
999 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1000 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1001 case Mips::ATOMIC_LOAD_SUB_I32:
1002 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1003 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1004 case Mips::ATOMIC_LOAD_SUB_I64:
1005 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1006 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1008 case Mips::ATOMIC_SWAP_I8:
1009 case Mips::ATOMIC_SWAP_I8_P8:
1010 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1011 case Mips::ATOMIC_SWAP_I16:
1012 case Mips::ATOMIC_SWAP_I16_P8:
1013 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1014 case Mips::ATOMIC_SWAP_I32:
1015 case Mips::ATOMIC_SWAP_I32_P8:
1016 return EmitAtomicBinary(MI, BB, 4, 0);
1017 case Mips::ATOMIC_SWAP_I64:
1018 case Mips::ATOMIC_SWAP_I64_P8:
1019 return EmitAtomicBinary(MI, BB, 8, 0);
1021 case Mips::ATOMIC_CMP_SWAP_I8:
1022 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1023 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1024 case Mips::ATOMIC_CMP_SWAP_I16:
1025 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1026 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1027 case Mips::ATOMIC_CMP_SWAP_I32:
1028 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1029 return EmitAtomicCmpSwap(MI, BB, 4);
1030 case Mips::ATOMIC_CMP_SWAP_I64:
1031 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1032 return EmitAtomicCmpSwap(MI, BB, 8);
1036 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1037 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1039 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1040 unsigned Size, unsigned BinOpcode,
1042 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1044 MachineFunction *MF = BB->getParent();
1045 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1046 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1047 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1048 DebugLoc dl = MI->getDebugLoc();
1049 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1052 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1053 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1060 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1061 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1064 ZERO = Mips::ZERO_64;
1068 unsigned OldVal = MI->getOperand(0).getReg();
1069 unsigned Ptr = MI->getOperand(1).getReg();
1070 unsigned Incr = MI->getOperand(2).getReg();
1072 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1073 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1074 unsigned Success = RegInfo.createVirtualRegister(RC);
1076 // insert new blocks after the current block
1077 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1078 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1079 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1080 MachineFunction::iterator It = BB;
1082 MF->insert(It, loopMBB);
1083 MF->insert(It, exitMBB);
1085 // Transfer the remainder of BB and its successor edges to exitMBB.
1086 exitMBB->splice(exitMBB->begin(), BB,
1087 llvm::next(MachineBasicBlock::iterator(MI)),
1089 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1093 // fallthrough --> loopMBB
1094 BB->addSuccessor(loopMBB);
1095 loopMBB->addSuccessor(loopMBB);
1096 loopMBB->addSuccessor(exitMBB);
1099 // ll oldval, 0(ptr)
1100 // <binop> storeval, oldval, incr
1101 // sc success, storeval, 0(ptr)
1102 // beq success, $0, loopMBB
1104 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1106 // and andres, oldval, incr
1107 // nor storeval, $0, andres
1108 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1109 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1110 } else if (BinOpcode) {
1111 // <binop> storeval, oldval, incr
1112 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1116 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1117 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1119 MI->eraseFromParent(); // The instruction is gone now.
1125 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1126 MachineBasicBlock *BB,
1127 unsigned Size, unsigned BinOpcode,
1129 assert((Size == 1 || Size == 2) &&
1130 "Unsupported size for EmitAtomicBinaryPartial.");
1132 MachineFunction *MF = BB->getParent();
1133 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1134 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1135 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1136 DebugLoc dl = MI->getDebugLoc();
1137 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1138 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1140 unsigned Dest = MI->getOperand(0).getReg();
1141 unsigned Ptr = MI->getOperand(1).getReg();
1142 unsigned Incr = MI->getOperand(2).getReg();
1144 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1145 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1146 unsigned Mask = RegInfo.createVirtualRegister(RC);
1147 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1148 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1149 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1150 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1151 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1152 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1153 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1154 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1155 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1156 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1157 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1158 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1159 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1160 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1161 unsigned Success = RegInfo.createVirtualRegister(RC);
1163 // insert new blocks after the current block
1164 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1165 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1166 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1167 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1168 MachineFunction::iterator It = BB;
1170 MF->insert(It, loopMBB);
1171 MF->insert(It, sinkMBB);
1172 MF->insert(It, exitMBB);
1174 // Transfer the remainder of BB and its successor edges to exitMBB.
1175 exitMBB->splice(exitMBB->begin(), BB,
1176 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1177 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1179 BB->addSuccessor(loopMBB);
1180 loopMBB->addSuccessor(loopMBB);
1181 loopMBB->addSuccessor(sinkMBB);
1182 sinkMBB->addSuccessor(exitMBB);
1185 // addiu masklsb2,$0,-4 # 0xfffffffc
1186 // and alignedaddr,ptr,masklsb2
1187 // andi ptrlsb2,ptr,3
1188 // sll shiftamt,ptrlsb2,3
1189 // ori maskupper,$0,255 # 0xff
1190 // sll mask,maskupper,shiftamt
1191 // nor mask2,$0,mask
1192 // sll incr2,incr,shiftamt
1194 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1195 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1196 .addReg(Mips::ZERO).addImm(-4);
1197 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1198 .addReg(Ptr).addReg(MaskLSB2);
1199 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1200 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1201 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1202 .addReg(Mips::ZERO).addImm(MaskImm);
1203 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1204 .addReg(ShiftAmt).addReg(MaskUpper);
1205 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1206 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1208 // atomic.load.binop
1210 // ll oldval,0(alignedaddr)
1211 // binop binopres,oldval,incr2
1212 // and newval,binopres,mask
1213 // and maskedoldval0,oldval,mask2
1214 // or storeval,maskedoldval0,newval
1215 // sc success,storeval,0(alignedaddr)
1216 // beq success,$0,loopMBB
1220 // ll oldval,0(alignedaddr)
1221 // and newval,incr2,mask
1222 // and maskedoldval0,oldval,mask2
1223 // or storeval,maskedoldval0,newval
1224 // sc success,storeval,0(alignedaddr)
1225 // beq success,$0,loopMBB
1228 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1230 // and andres, oldval, incr2
1231 // nor binopres, $0, andres
1232 // and newval, binopres, mask
1233 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1234 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1235 .addReg(Mips::ZERO).addReg(AndRes);
1236 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1237 } else if (BinOpcode) {
1238 // <binop> binopres, oldval, incr2
1239 // and newval, binopres, mask
1240 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1241 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1242 } else {// atomic.swap
1243 // and newval, incr2, mask
1244 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1247 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1248 .addReg(OldVal).addReg(Mask2);
1249 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1250 .addReg(MaskedOldVal0).addReg(NewVal);
1251 BuildMI(BB, dl, TII->get(SC), Success)
1252 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1253 BuildMI(BB, dl, TII->get(Mips::BEQ))
1254 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1257 // and maskedoldval1,oldval,mask
1258 // srl srlres,maskedoldval1,shiftamt
1259 // sll sllres,srlres,24
1260 // sra dest,sllres,24
1262 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1264 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1265 .addReg(OldVal).addReg(Mask);
1266 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1267 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1268 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1269 .addReg(SrlRes).addImm(ShiftImm);
1270 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1271 .addReg(SllRes).addImm(ShiftImm);
1273 MI->eraseFromParent(); // The instruction is gone now.
1279 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1280 MachineBasicBlock *BB,
1281 unsigned Size) const {
1282 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1284 MachineFunction *MF = BB->getParent();
1285 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1286 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1287 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1288 DebugLoc dl = MI->getDebugLoc();
1289 unsigned LL, SC, ZERO, BNE, BEQ;
1292 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1293 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1299 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1300 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1301 ZERO = Mips::ZERO_64;
1306 unsigned Dest = MI->getOperand(0).getReg();
1307 unsigned Ptr = MI->getOperand(1).getReg();
1308 unsigned OldVal = MI->getOperand(2).getReg();
1309 unsigned NewVal = MI->getOperand(3).getReg();
1311 unsigned Success = RegInfo.createVirtualRegister(RC);
1313 // insert new blocks after the current block
1314 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1315 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1316 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1317 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1318 MachineFunction::iterator It = BB;
1320 MF->insert(It, loop1MBB);
1321 MF->insert(It, loop2MBB);
1322 MF->insert(It, exitMBB);
1324 // Transfer the remainder of BB and its successor edges to exitMBB.
1325 exitMBB->splice(exitMBB->begin(), BB,
1326 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1327 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1331 // fallthrough --> loop1MBB
1332 BB->addSuccessor(loop1MBB);
1333 loop1MBB->addSuccessor(exitMBB);
1334 loop1MBB->addSuccessor(loop2MBB);
1335 loop2MBB->addSuccessor(loop1MBB);
1336 loop2MBB->addSuccessor(exitMBB);
1340 // bne dest, oldval, exitMBB
1342 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1343 BuildMI(BB, dl, TII->get(BNE))
1344 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1347 // sc success, newval, 0(ptr)
1348 // beq success, $0, loop1MBB
1350 BuildMI(BB, dl, TII->get(SC), Success)
1351 .addReg(NewVal).addReg(Ptr).addImm(0);
1352 BuildMI(BB, dl, TII->get(BEQ))
1353 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1355 MI->eraseFromParent(); // The instruction is gone now.
1361 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1362 MachineBasicBlock *BB,
1363 unsigned Size) const {
1364 assert((Size == 1 || Size == 2) &&
1365 "Unsupported size for EmitAtomicCmpSwapPartial.");
1367 MachineFunction *MF = BB->getParent();
1368 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1369 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1370 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1371 DebugLoc dl = MI->getDebugLoc();
1372 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1373 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1375 unsigned Dest = MI->getOperand(0).getReg();
1376 unsigned Ptr = MI->getOperand(1).getReg();
1377 unsigned CmpVal = MI->getOperand(2).getReg();
1378 unsigned NewVal = MI->getOperand(3).getReg();
1380 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1381 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1382 unsigned Mask = RegInfo.createVirtualRegister(RC);
1383 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1384 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1385 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1386 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1387 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1388 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1389 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1390 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1391 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1392 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1393 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1394 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1395 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1396 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1397 unsigned Success = RegInfo.createVirtualRegister(RC);
1399 // insert new blocks after the current block
1400 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1401 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1402 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1403 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1404 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1405 MachineFunction::iterator It = BB;
1407 MF->insert(It, loop1MBB);
1408 MF->insert(It, loop2MBB);
1409 MF->insert(It, sinkMBB);
1410 MF->insert(It, exitMBB);
1412 // Transfer the remainder of BB and its successor edges to exitMBB.
1413 exitMBB->splice(exitMBB->begin(), BB,
1414 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1415 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1417 BB->addSuccessor(loop1MBB);
1418 loop1MBB->addSuccessor(sinkMBB);
1419 loop1MBB->addSuccessor(loop2MBB);
1420 loop2MBB->addSuccessor(loop1MBB);
1421 loop2MBB->addSuccessor(sinkMBB);
1422 sinkMBB->addSuccessor(exitMBB);
1424 // FIXME: computation of newval2 can be moved to loop2MBB.
1426 // addiu masklsb2,$0,-4 # 0xfffffffc
1427 // and alignedaddr,ptr,masklsb2
1428 // andi ptrlsb2,ptr,3
1429 // sll shiftamt,ptrlsb2,3
1430 // ori maskupper,$0,255 # 0xff
1431 // sll mask,maskupper,shiftamt
1432 // nor mask2,$0,mask
1433 // andi maskedcmpval,cmpval,255
1434 // sll shiftedcmpval,maskedcmpval,shiftamt
1435 // andi maskednewval,newval,255
1436 // sll shiftednewval,maskednewval,shiftamt
1437 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1438 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1439 .addReg(Mips::ZERO).addImm(-4);
1440 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1441 .addReg(Ptr).addReg(MaskLSB2);
1442 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1443 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1444 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1445 .addReg(Mips::ZERO).addImm(MaskImm);
1446 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1447 .addReg(ShiftAmt).addReg(MaskUpper);
1448 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1449 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1450 .addReg(CmpVal).addImm(MaskImm);
1451 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1452 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1453 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1454 .addReg(NewVal).addImm(MaskImm);
1455 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1456 .addReg(ShiftAmt).addReg(MaskedNewVal);
1459 // ll oldval,0(alginedaddr)
1460 // and maskedoldval0,oldval,mask
1461 // bne maskedoldval0,shiftedcmpval,sinkMBB
1463 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1464 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1465 .addReg(OldVal).addReg(Mask);
1466 BuildMI(BB, dl, TII->get(Mips::BNE))
1467 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1470 // and maskedoldval1,oldval,mask2
1471 // or storeval,maskedoldval1,shiftednewval
1472 // sc success,storeval,0(alignedaddr)
1473 // beq success,$0,loop1MBB
1475 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1476 .addReg(OldVal).addReg(Mask2);
1477 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1478 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1479 BuildMI(BB, dl, TII->get(SC), Success)
1480 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1481 BuildMI(BB, dl, TII->get(Mips::BEQ))
1482 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1485 // srl srlres,maskedoldval0,shiftamt
1486 // sll sllres,srlres,24
1487 // sra dest,sllres,24
1489 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1491 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1492 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1493 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1494 .addReg(SrlRes).addImm(ShiftImm);
1495 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1496 .addReg(SllRes).addImm(ShiftImm);
1498 MI->eraseFromParent(); // The instruction is gone now.
1503 //===----------------------------------------------------------------------===//
1504 // Misc Lower Operation implementation
1505 //===----------------------------------------------------------------------===//
1506 SDValue MipsTargetLowering::
1507 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1509 MachineFunction &MF = DAG.getMachineFunction();
1510 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1511 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1513 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1514 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1515 "Cannot lower if the alignment of the allocated space is larger than \
1516 that of the stack.");
1518 SDValue Chain = Op.getOperand(0);
1519 SDValue Size = Op.getOperand(1);
1520 DebugLoc dl = Op.getDebugLoc();
1522 // Get a reference from Mips stack pointer
1523 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1525 // Subtract the dynamic size from the actual stack size to
1526 // obtain the new stack size.
1527 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1529 // The Sub result contains the new stack start address, so it
1530 // must be placed in the stack pointer register.
1531 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1533 // This node always has two return values: a new stack pointer
1534 // value and a chain
1535 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1536 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1537 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1539 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1542 SDValue MipsTargetLowering::
1543 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1545 // The first operand is the chain, the second is the condition, the third is
1546 // the block to branch to if the condition is true.
1547 SDValue Chain = Op.getOperand(0);
1548 SDValue Dest = Op.getOperand(2);
1549 DebugLoc dl = Op.getDebugLoc();
1551 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1553 // Return if flag is not set by a floating point comparison.
1554 if (CondRes.getOpcode() != MipsISD::FPCmp)
1557 SDValue CCNode = CondRes.getOperand(2);
1559 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1560 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1562 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1566 SDValue MipsTargetLowering::
1567 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1569 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1571 // Return if flag is not set by a floating point comparison.
1572 if (Cond.getOpcode() != MipsISD::FPCmp)
1575 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1579 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1580 SDValue Cond = CreateFPCmp(DAG, Op);
1582 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1583 "Floating point operand expected.");
1585 SDValue True = DAG.getConstant(1, MVT::i32);
1586 SDValue False = DAG.getConstant(0, MVT::i32);
1588 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1591 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1592 SelectionDAG &DAG) const {
1593 // FIXME there isn't actually debug info here
1594 DebugLoc dl = Op.getDebugLoc();
1595 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1597 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1598 SDVTList VTs = DAG.getVTList(MVT::i32);
1600 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1602 // %gp_rel relocation
1603 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1604 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1606 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1607 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1608 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1610 // %hi/%lo relocation
1611 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1613 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1615 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1616 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1617 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1620 EVT ValTy = Op.getValueType();
1621 bool HasGotOfst = (GV->hasInternalLinkage() ||
1622 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1623 unsigned GotFlag = HasMips64 ?
1624 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1625 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1626 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1627 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1628 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1629 MachinePointerInfo(), false, false, false, 0);
1630 // On functions and global targets not internal linked only
1631 // a load from got/GP is necessary for PIC to work.
1634 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1635 HasMips64 ? MipsII::MO_GOT_OFST :
1637 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1638 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1641 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1642 SelectionDAG &DAG) const {
1643 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1644 // FIXME there isn't actually debug info here
1645 DebugLoc dl = Op.getDebugLoc();
1647 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1648 // %hi/%lo relocation
1649 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1650 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1651 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1652 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1653 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1656 EVT ValTy = Op.getValueType();
1657 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1658 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1659 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1660 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1661 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1662 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1663 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1664 MachinePointerInfo(), false, false, false, 0);
1665 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1666 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1669 SDValue MipsTargetLowering::
1670 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1672 // If the relocation model is PIC, use the General Dynamic TLS Model or
1673 // Local Dynamic TLS model, otherwise use the Initial Exec or
1674 // Local Exec TLS Model.
1676 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1677 DebugLoc dl = GA->getDebugLoc();
1678 const GlobalValue *GV = GA->getGlobal();
1679 EVT PtrVT = getPointerTy();
1681 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1683 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1684 // General Dynamic and Local Dynamic TLS Model.
1685 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1688 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1689 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1690 GetGlobalReg(DAG, PtrVT), TGA);
1691 unsigned PtrSize = PtrVT.getSizeInBits();
1692 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1694 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1698 Entry.Node = Argument;
1700 Args.push_back(Entry);
1702 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1703 false, false, false, false, 0, CallingConv::C,
1704 /*isTailCall=*/false, /*doesNotRet=*/false,
1705 /*isReturnValueUsed=*/true,
1706 TlsGetAddr, Args, DAG, dl);
1707 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1709 SDValue Ret = CallResult.first;
1711 if (model != TLSModel::LocalDynamic)
1714 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1715 MipsII::MO_DTPREL_HI);
1716 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1717 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1718 MipsII::MO_DTPREL_LO);
1719 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1720 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1721 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1725 if (model == TLSModel::InitialExec) {
1726 // Initial Exec TLS Model
1727 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1728 MipsII::MO_GOTTPREL);
1729 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1731 Offset = DAG.getLoad(PtrVT, dl,
1732 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1733 false, false, false, 0);
1735 // Local Exec TLS Model
1736 assert(model == TLSModel::LocalExec);
1737 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1738 MipsII::MO_TPREL_HI);
1739 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1740 MipsII::MO_TPREL_LO);
1741 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1742 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1743 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1746 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1747 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1750 SDValue MipsTargetLowering::
1751 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1753 SDValue HiPart, JTI, JTILo;
1754 // FIXME there isn't actually debug info here
1755 DebugLoc dl = Op.getDebugLoc();
1756 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1757 EVT PtrVT = Op.getValueType();
1758 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1760 if (!IsPIC && !IsN64) {
1761 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1762 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1763 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1764 } else {// Emit Load from Global Pointer
1765 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1766 unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1767 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1768 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1770 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1771 MachinePointerInfo(), false, false, false, 0);
1772 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1775 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1776 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1779 SDValue MipsTargetLowering::
1780 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1783 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1784 const Constant *C = N->getConstVal();
1785 // FIXME there isn't actually debug info here
1786 DebugLoc dl = Op.getDebugLoc();
1788 // gp_rel relocation
1789 // FIXME: we should reference the constant pool using small data sections,
1790 // but the asm printer currently doesn't support this feature without
1791 // hacking it. This feature should come soon so we can uncomment the
1793 //if (IsInSmallSection(C->getType())) {
1794 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1795 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1796 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1798 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1799 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1800 N->getOffset(), MipsII::MO_ABS_HI);
1801 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1802 N->getOffset(), MipsII::MO_ABS_LO);
1803 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1804 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1805 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1807 EVT ValTy = Op.getValueType();
1808 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1809 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1810 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1811 N->getOffset(), GOTFlag);
1812 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1813 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1814 MachinePointerInfo::getConstantPool(), false,
1816 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1817 N->getOffset(), OFSTFlag);
1818 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1819 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1825 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1826 MachineFunction &MF = DAG.getMachineFunction();
1827 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1829 DebugLoc dl = Op.getDebugLoc();
1830 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1833 // vastart just stores the address of the VarArgsFrameIndex slot into the
1834 // memory location argument.
1835 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1836 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1837 MachinePointerInfo(SV), false, false, 0);
1840 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1841 EVT TyX = Op.getOperand(0).getValueType();
1842 EVT TyY = Op.getOperand(1).getValueType();
1843 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1844 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1845 DebugLoc DL = Op.getDebugLoc();
1848 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1850 SDValue X = (TyX == MVT::f32) ?
1851 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1852 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1854 SDValue Y = (TyY == MVT::f32) ?
1855 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1856 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1860 // ext E, Y, 31, 1 ; extract bit31 of Y
1861 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1862 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1863 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1866 // srl SrlX, SllX, 1
1868 // sll SllY, SrlX, 31
1869 // or Or, SrlX, SllY
1870 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1871 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1872 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1873 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1874 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1877 if (TyX == MVT::f32)
1878 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1880 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1881 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1882 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1885 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1886 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1887 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1888 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1889 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1890 DebugLoc DL = Op.getDebugLoc();
1892 // Bitcast to integer nodes.
1893 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1894 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1897 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1898 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1899 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1900 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1902 if (WidthX > WidthY)
1903 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1904 else if (WidthY > WidthX)
1905 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1907 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1908 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1909 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1912 // (d)sll SllX, X, 1
1913 // (d)srl SrlX, SllX, 1
1914 // (d)srl SrlY, Y, width(Y)-1
1915 // (d)sll SllY, SrlX, width(Y)-1
1916 // or Or, SrlX, SllY
1917 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1918 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1919 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1920 DAG.getConstant(WidthY - 1, MVT::i32));
1922 if (WidthX > WidthY)
1923 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1924 else if (WidthY > WidthX)
1925 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1927 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1928 DAG.getConstant(WidthX - 1, MVT::i32));
1929 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1930 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1934 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1935 if (Subtarget->hasMips64())
1936 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1938 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1941 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1942 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1943 DebugLoc DL = Op.getDebugLoc();
1945 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1947 SDValue X = (Op.getValueType() == MVT::f32) ?
1948 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1949 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1954 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1955 DAG.getRegister(Mips::ZERO, MVT::i32),
1956 DAG.getConstant(31, MVT::i32), Const1, X);
1958 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1959 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1962 if (Op.getValueType() == MVT::f32)
1963 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1965 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1966 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1967 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1970 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1971 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1972 DebugLoc DL = Op.getDebugLoc();
1974 // Bitcast to integer node.
1975 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1979 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1980 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1981 DAG.getConstant(63, MVT::i32), Const1, X);
1983 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1984 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1987 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1991 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
1992 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1993 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1995 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1998 SDValue MipsTargetLowering::
1999 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2001 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2002 "Frame address can only be determined for current frame.");
2004 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2005 MFI->setFrameAddressIsTaken(true);
2006 EVT VT = Op.getValueType();
2007 DebugLoc dl = Op.getDebugLoc();
2008 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2009 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2013 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2014 SelectionDAG &DAG) const {
2016 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2017 "Return address can be determined only for current frame.");
2019 MachineFunction &MF = DAG.getMachineFunction();
2020 MachineFrameInfo *MFI = MF.getFrameInfo();
2021 EVT VT = Op.getValueType();
2022 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2023 MFI->setReturnAddressIsTaken(true);
2025 // Return RA, which contains the return address. Mark it an implicit live-in.
2026 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2027 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2030 // TODO: set SType according to the desired memory barrier behavior.
2032 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2034 DebugLoc dl = Op.getDebugLoc();
2035 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2036 DAG.getConstant(SType, MVT::i32));
2039 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2040 SelectionDAG &DAG) const {
2041 // FIXME: Need pseudo-fence for 'singlethread' fences
2042 // FIXME: Set SType for weaker fences where supported/appropriate.
2044 DebugLoc dl = Op.getDebugLoc();
2045 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2046 DAG.getConstant(SType, MVT::i32));
2049 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2050 SelectionDAG &DAG) const {
2051 DebugLoc DL = Op.getDebugLoc();
2052 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2053 SDValue Shamt = Op.getOperand(2);
2056 // lo = (shl lo, shamt)
2057 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2060 // hi = (shl lo, shamt[4:0])
2061 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2062 DAG.getConstant(-1, MVT::i32));
2063 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2064 DAG.getConstant(1, MVT::i32));
2065 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2067 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2068 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2069 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2070 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2071 DAG.getConstant(0x20, MVT::i32));
2072 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2073 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2074 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2076 SDValue Ops[2] = {Lo, Hi};
2077 return DAG.getMergeValues(Ops, 2, DL);
2080 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2082 DebugLoc DL = Op.getDebugLoc();
2083 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2084 SDValue Shamt = Op.getOperand(2);
2087 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2089 // hi = (sra hi, shamt)
2091 // hi = (srl hi, shamt)
2094 // lo = (sra hi, shamt[4:0])
2095 // hi = (sra hi, 31)
2097 // lo = (srl hi, shamt[4:0])
2099 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2100 DAG.getConstant(-1, MVT::i32));
2101 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2102 DAG.getConstant(1, MVT::i32));
2103 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2104 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2105 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2106 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2108 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2109 DAG.getConstant(0x20, MVT::i32));
2110 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2111 DAG.getConstant(31, MVT::i32));
2112 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2113 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2114 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2117 SDValue Ops[2] = {Lo, Hi};
2118 return DAG.getMergeValues(Ops, 2, DL);
2121 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2122 SDValue Chain, SDValue Src, unsigned Offset) {
2123 SDValue Ptr = LD->getBasePtr();
2124 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2125 EVT BasePtrVT = Ptr.getValueType();
2126 DebugLoc DL = LD->getDebugLoc();
2127 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2130 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2131 DAG.getConstant(Offset, BasePtrVT));
2133 SDValue Ops[] = { Chain, Ptr, Src };
2134 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2135 LD->getMemOperand());
2138 // Expand an unaligned 32 or 64-bit integer load node.
2139 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2140 LoadSDNode *LD = cast<LoadSDNode>(Op);
2141 EVT MemVT = LD->getMemoryVT();
2143 // Return if load is aligned or if MemVT is neither i32 nor i64.
2144 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2145 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2148 bool IsLittle = Subtarget->isLittle();
2149 EVT VT = Op.getValueType();
2150 ISD::LoadExtType ExtType = LD->getExtensionType();
2151 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2153 assert((VT == MVT::i32) || (VT == MVT::i64));
2156 // (set dst, (i64 (load baseptr)))
2158 // (set tmp, (ldl (add baseptr, 7), undef))
2159 // (set dst, (ldr baseptr, tmp))
2160 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2161 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2163 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2167 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2169 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2173 // (set dst, (i32 (load baseptr))) or
2174 // (set dst, (i64 (sextload baseptr))) or
2175 // (set dst, (i64 (extload baseptr)))
2177 // (set tmp, (lwl (add baseptr, 3), undef))
2178 // (set dst, (lwr baseptr, tmp))
2179 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2180 (ExtType == ISD::EXTLOAD))
2183 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2186 // (set dst, (i64 (zextload baseptr)))
2188 // (set tmp0, (lwl (add baseptr, 3), undef))
2189 // (set tmp1, (lwr baseptr, tmp0))
2190 // (set tmp2, (shl tmp1, 32))
2191 // (set dst, (srl tmp2, 32))
2192 DebugLoc DL = LD->getDebugLoc();
2193 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2194 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2195 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2196 SDValue Ops[] = { SRL, LWR.getValue(1) };
2197 return DAG.getMergeValues(Ops, 2, DL);
2200 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2201 SDValue Chain, unsigned Offset) {
2202 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2203 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2204 DebugLoc DL = SD->getDebugLoc();
2205 SDVTList VTList = DAG.getVTList(MVT::Other);
2208 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2209 DAG.getConstant(Offset, BasePtrVT));
2211 SDValue Ops[] = { Chain, Value, Ptr };
2212 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2213 SD->getMemOperand());
2216 // Expand an unaligned 32 or 64-bit integer store node.
2217 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2218 StoreSDNode *SD = cast<StoreSDNode>(Op);
2219 EVT MemVT = SD->getMemoryVT();
2221 // Return if store is aligned or if MemVT is neither i32 nor i64.
2222 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2223 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2226 bool IsLittle = Subtarget->isLittle();
2227 SDValue Value = SD->getValue(), Chain = SD->getChain();
2228 EVT VT = Value.getValueType();
2231 // (store val, baseptr) or
2232 // (truncstore val, baseptr)
2234 // (swl val, (add baseptr, 3))
2235 // (swr val, baseptr)
2236 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2237 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2239 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2242 assert(VT == MVT::i64);
2245 // (store val, baseptr)
2247 // (sdl val, (add baseptr, 7))
2248 // (sdr val, baseptr)
2249 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2250 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2253 //===----------------------------------------------------------------------===//
2254 // Calling Convention Implementation
2255 //===----------------------------------------------------------------------===//
2257 //===----------------------------------------------------------------------===//
2258 // TODO: Implement a generic logic using tblgen that can support this.
2259 // Mips O32 ABI rules:
2261 // i32 - Passed in A0, A1, A2, A3 and stack
2262 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2263 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2264 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2265 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2266 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2269 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2270 //===----------------------------------------------------------------------===//
2272 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2273 MVT LocVT, CCValAssign::LocInfo LocInfo,
2274 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2276 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2278 static const uint16_t IntRegs[] = {
2279 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2281 static const uint16_t F32Regs[] = {
2282 Mips::F12, Mips::F14
2284 static const uint16_t F64Regs[] = {
2289 if (ArgFlags.isByVal()) {
2290 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
2291 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
2292 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
2293 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
2294 r < std::min(IntRegsSize, NextReg); ++r)
2295 State.AllocateReg(IntRegs[r]);
2299 // Promote i8 and i16
2300 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2302 if (ArgFlags.isSExt())
2303 LocInfo = CCValAssign::SExt;
2304 else if (ArgFlags.isZExt())
2305 LocInfo = CCValAssign::ZExt;
2307 LocInfo = CCValAssign::AExt;
2312 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2313 // is true: function is vararg, argument is 3rd or higher, there is previous
2314 // argument which is not f32 or f64.
2315 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2316 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2317 unsigned OrigAlign = ArgFlags.getOrigAlign();
2318 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2320 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2321 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2322 // If this is the first part of an i64 arg,
2323 // the allocated register must be either A0 or A2.
2324 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2325 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2327 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2328 // Allocate int register and shadow next int register. If first
2329 // available register is Mips::A1 or Mips::A3, shadow it too.
2330 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2331 if (Reg == Mips::A1 || Reg == Mips::A3)
2332 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2333 State.AllocateReg(IntRegs, IntRegsSize);
2335 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2336 // we are guaranteed to find an available float register
2337 if (ValVT == MVT::f32) {
2338 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2339 // Shadow int register
2340 State.AllocateReg(IntRegs, IntRegsSize);
2342 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2343 // Shadow int registers
2344 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2345 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2346 State.AllocateReg(IntRegs, IntRegsSize);
2347 State.AllocateReg(IntRegs, IntRegsSize);
2350 llvm_unreachable("Cannot handle this ValVT.");
2352 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
2353 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
2356 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2358 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2360 return false; // CC must always match
2363 static const uint16_t Mips64IntRegs[8] =
2364 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
2365 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
2366 static const uint16_t Mips64DPRegs[8] =
2367 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
2368 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
2370 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
2371 CCValAssign::LocInfo LocInfo,
2372 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2373 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
2374 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
2375 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
2377 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
2379 // If byval is 16-byte aligned, the first arg register must be even.
2380 if ((Align == 16) && (FirstIdx % 2)) {
2381 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
2385 // Mark the registers allocated.
2386 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
2387 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
2389 // Allocate space on caller's stack.
2390 unsigned Offset = State.AllocateStack(Size, Align);
2393 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
2396 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2401 #include "MipsGenCallingConv.inc"
2404 AnalyzeMips64CallOperands(CCState &CCInfo,
2405 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2406 unsigned NumOps = Outs.size();
2407 for (unsigned i = 0; i != NumOps; ++i) {
2408 MVT ArgVT = Outs[i].VT;
2409 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2412 if (Outs[i].IsFixed)
2413 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2415 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2419 dbgs() << "Call operand #" << i << " has unhandled type "
2420 << EVT(ArgVT).getEVTString();
2422 llvm_unreachable(0);
2427 //===----------------------------------------------------------------------===//
2428 // Call Calling Convention Implementation
2429 //===----------------------------------------------------------------------===//
2431 static const unsigned O32IntRegsSize = 4;
2433 static const uint16_t O32IntRegs[] = {
2434 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2437 // Return next O32 integer argument register.
2438 static unsigned getNextIntArgReg(unsigned Reg) {
2439 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2440 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2443 // Write ByVal Arg to arg registers and stack.
2445 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2446 SmallVector<std::pair<unsigned, SDValue>, 16> &RegsToPass,
2447 SmallVector<SDValue, 8> &MemOpChains, int &LastFI,
2448 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2449 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2450 MVT PtrType, bool isLittle) {
2451 unsigned LocMemOffset = VA.getLocMemOffset();
2452 unsigned Offset = 0;
2453 uint32_t RemainingSize = Flags.getByValSize();
2454 unsigned ByValAlign = Flags.getByValAlign();
2456 // Copy the first 4 words of byval arg to registers A0 - A3.
2457 // FIXME: Use a stricter alignment if it enables better optimization in passes
2459 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2460 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2461 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2462 DAG.getConstant(Offset, MVT::i32));
2463 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2464 MachinePointerInfo(), false, false, false,
2465 std::min(ByValAlign, (unsigned )4));
2466 MemOpChains.push_back(LoadVal.getValue(1));
2467 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2468 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2471 if (RemainingSize == 0)
2474 // If there still is a register available for argument passing, write the
2475 // remaining part of the structure to it using subword loads and shifts.
2476 if (LocMemOffset < 4 * 4) {
2477 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2478 "There must be one to three bytes remaining.");
2479 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2480 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2481 DAG.getConstant(Offset, MVT::i32));
2482 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2483 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2484 LoadPtr, MachinePointerInfo(),
2485 MVT::getIntegerVT(LoadSize * 8), false,
2487 MemOpChains.push_back(LoadVal.getValue(1));
2489 // If target is big endian, shift it to the most significant half-word or
2492 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2493 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2496 RemainingSize -= LoadSize;
2498 // Read second subword if necessary.
2499 if (RemainingSize != 0) {
2500 assert(RemainingSize == 1 && "There must be one byte remaining.");
2501 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2502 DAG.getConstant(Offset, MVT::i32));
2503 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2504 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2505 LoadPtr, MachinePointerInfo(),
2506 MVT::i8, false, false, Alignment);
2507 MemOpChains.push_back(Subword.getValue(1));
2508 // Insert the loaded byte to LoadVal.
2509 // FIXME: Use INS if supported by target.
2510 unsigned ShiftAmt = isLittle ? 16 : 8;
2511 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2512 DAG.getConstant(ShiftAmt, MVT::i32));
2513 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2516 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2517 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2521 // Create a fixed object on stack at offset LocMemOffset and copy
2522 // remaining part of byval arg to it using memcpy.
2523 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2524 DAG.getConstant(Offset, MVT::i32));
2525 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2526 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2527 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2528 DAG.getConstant(RemainingSize, MVT::i32),
2529 std::min(ByValAlign, (unsigned)4),
2530 /*isVolatile=*/false, /*AlwaysInline=*/false,
2531 MachinePointerInfo(0), MachinePointerInfo(0));
2534 // Copy Mips64 byVal arg to registers and stack.
2536 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2537 SmallVector<std::pair<unsigned, SDValue>, 16> &RegsToPass,
2538 SmallVector<SDValue, 8> &MemOpChains, int &LastFI,
2539 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2540 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2541 EVT PtrTy, bool isLittle) {
2542 unsigned ByValSize = Flags.getByValSize();
2543 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2544 bool IsRegLoc = VA.isRegLoc();
2545 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2546 unsigned LocMemOffset = 0;
2547 unsigned MemCpySize = ByValSize;
2550 LocMemOffset = VA.getLocMemOffset();
2552 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2554 const uint16_t *RegEnd = Mips64IntRegs + 8;
2556 // Copy double words to registers.
2557 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2558 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2559 DAG.getConstant(Offset, PtrTy));
2560 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2561 MachinePointerInfo(), false, false, false,
2563 MemOpChains.push_back(LoadVal.getValue(1));
2564 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2567 // Return if the struct has been fully copied.
2568 if (!(MemCpySize = ByValSize - Offset))
2571 // If there is an argument register available, copy the remainder of the
2572 // byval argument with sub-doubleword loads and shifts.
2573 if (Reg != RegEnd) {
2574 assert((ByValSize < Offset + 8) &&
2575 "Size of the remainder should be smaller than 8-byte.");
2577 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2578 unsigned RemSize = ByValSize - Offset;
2580 if (RemSize < LoadSize)
2583 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2584 DAG.getConstant(Offset, PtrTy));
2586 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2587 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2588 false, false, Alignment);
2589 MemOpChains.push_back(LoadVal.getValue(1));
2591 // Offset in number of bits from double word boundary.
2592 unsigned OffsetDW = (Offset % 8) * 8;
2593 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2594 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2595 DAG.getConstant(Shamt, MVT::i32));
2597 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2600 Alignment = std::min(Alignment, LoadSize);
2603 RegsToPass.push_back(std::make_pair(*Reg, Val));
2608 assert(MemCpySize && "MemCpySize must not be zero.");
2610 // Create a fixed object on stack at offset LocMemOffset and copy
2611 // remainder of byval arg to it with memcpy.
2612 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2613 DAG.getConstant(Offset, PtrTy));
2614 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2615 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2616 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2617 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2618 /*isVolatile=*/false, /*AlwaysInline=*/false,
2619 MachinePointerInfo(0), MachinePointerInfo(0));
2622 /// LowerCall - functions arguments are copied from virtual regs to
2623 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2624 /// TODO: isTailCall.
2626 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2627 SmallVectorImpl<SDValue> &InVals) const {
2628 SelectionDAG &DAG = CLI.DAG;
2629 DebugLoc &dl = CLI.DL;
2630 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2631 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2632 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2633 SDValue InChain = CLI.Chain;
2634 SDValue Callee = CLI.Callee;
2635 bool &isTailCall = CLI.IsTailCall;
2636 CallingConv::ID CallConv = CLI.CallConv;
2637 bool isVarArg = CLI.IsVarArg;
2639 // MIPs target does not yet support tail call optimization.
2642 MachineFunction &MF = DAG.getMachineFunction();
2643 MachineFrameInfo *MFI = MF.getFrameInfo();
2644 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2645 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2646 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2648 // Analyze operands of the call, assigning locations to each operand.
2649 SmallVector<CCValAssign, 16> ArgLocs;
2650 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2651 getTargetMachine(), ArgLocs, *DAG.getContext());
2653 if (CallConv == CallingConv::Fast)
2654 CCInfo.AnalyzeCallOperands(Outs, CC_Mips_FastCC);
2656 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2658 AnalyzeMips64CallOperands(CCInfo, Outs);
2660 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2662 // Get a count of how many bytes are to be pushed on the stack.
2663 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2665 // Chain is the output chain of the last Load/Store or CopyToReg node.
2666 // ByValChain is the output chain of the last Memcpy node created for copying
2667 // byval arguments to the stack.
2668 SDValue Chain, CallSeqStart, ByValChain;
2669 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2670 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2671 ByValChain = InChain;
2673 // Get the frame index of the stack frame object that points to the location
2674 // of dynamically allocated area on the stack.
2675 int DynAllocFI = MipsFI->getDynAllocFI();
2677 // Update size of the maximum argument space.
2678 // For O32, a minimum of four words (16 bytes) of argument space is
2680 if (IsO32 && (CallConv != CallingConv::Fast))
2681 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2683 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2685 if (MaxCallFrameSize < NextStackOffset) {
2686 MipsFI->setMaxCallFrameSize(NextStackOffset);
2688 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2689 // allocated stack space. These offsets must be aligned to a boundary
2690 // determined by the stack alignment of the ABI.
2691 unsigned StackAlignment = TFL->getStackAlignment();
2692 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2693 StackAlignment * StackAlignment;
2695 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2698 // With EABI is it possible to have 16 args on registers.
2699 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2700 SmallVector<SDValue, 8> MemOpChains;
2702 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2704 // Walk the register/memloc assignments, inserting copies/loads.
2705 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2706 SDValue Arg = OutVals[i];
2707 CCValAssign &VA = ArgLocs[i];
2708 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2709 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2712 if (Flags.isByVal()) {
2713 assert(Flags.getByValSize() &&
2714 "ByVal args of size 0 should have been ignored by front-end.");
2716 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2717 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2718 Subtarget->isLittle());
2720 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2721 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2722 Subtarget->isLittle());
2726 // Promote the value if needed.
2727 switch (VA.getLocInfo()) {
2728 default: llvm_unreachable("Unknown loc info!");
2729 case CCValAssign::Full:
2730 if (VA.isRegLoc()) {
2731 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2732 (ValVT == MVT::f64 && LocVT == MVT::i64))
2733 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2734 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2735 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2736 Arg, DAG.getConstant(0, MVT::i32));
2737 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2738 Arg, DAG.getConstant(1, MVT::i32));
2739 if (!Subtarget->isLittle())
2741 unsigned LocRegLo = VA.getLocReg();
2742 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2743 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2744 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2749 case CCValAssign::SExt:
2750 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2752 case CCValAssign::ZExt:
2753 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2755 case CCValAssign::AExt:
2756 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2760 // Arguments that can be passed on register must be kept at
2761 // RegsToPass vector
2762 if (VA.isRegLoc()) {
2763 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2767 // Register can't get to this point...
2768 assert(VA.isMemLoc());
2770 // Create the frame index object for this incoming parameter
2771 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2772 VA.getLocMemOffset(), true);
2773 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2775 // emit ISD::STORE whichs stores the
2776 // parameter value to a stack Location
2777 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2778 MachinePointerInfo(), false, false, 0));
2781 // Extend range of indices of frame objects for outgoing arguments that were
2782 // created during this function call. Skip this step if no such objects were
2785 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2787 // If a memcpy has been created to copy a byval arg to a stack, replace the
2788 // chain input of CallSeqStart with ByValChain.
2789 if (InChain != ByValChain)
2790 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2791 NextStackOffsetVal);
2793 // Transform all store nodes into one single node because all store
2794 // nodes are independent of each other.
2795 if (!MemOpChains.empty())
2796 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2797 &MemOpChains[0], MemOpChains.size());
2799 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2800 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2801 // node so that legalize doesn't hack it.
2802 unsigned char OpFlag;
2803 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2804 bool GlobalOrExternal = false;
2807 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2808 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2809 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2810 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2811 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2813 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2816 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2817 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2818 getPointerTy(), 0, OpFlag);
2821 GlobalOrExternal = true;
2823 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2824 if (IsN64 || (!IsO32 && IsPIC))
2825 OpFlag = MipsII::MO_GOT_DISP;
2826 else if (!IsPIC) // !N64 && static
2827 OpFlag = MipsII::MO_NO_FLAG;
2829 OpFlag = MipsII::MO_GOT_CALL;
2830 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2832 GlobalOrExternal = true;
2837 // Create nodes that load address of callee and copy it to T9
2839 if (GlobalOrExternal) {
2840 // Load callee address
2841 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2842 GetGlobalReg(DAG, getPointerTy()), Callee);
2843 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2844 Callee, MachinePointerInfo::getGOT(),
2845 false, false, false, 0);
2847 // Use GOT+LO if callee has internal linkage.
2848 if (CalleeLo.getNode()) {
2849 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2850 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2856 // T9 should contain the address of the callee function if
2857 // -reloction-model=pic or it is an indirect call.
2858 if (IsPICCall || !GlobalOrExternal) {
2860 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2861 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2862 InFlag = Chain.getValue(1);
2863 Callee = DAG.getRegister(T9Reg, getPointerTy());
2866 // Insert node "GP copy globalreg" before call to function.
2867 // Lazy-binding stubs require GP to point to the GOT.
2869 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2870 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2871 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2874 // Build a sequence of copy-to-reg nodes chained together with token
2875 // chain and flag operands which copy the outgoing args into registers.
2876 // The InFlag in necessary since all emitted instructions must be
2878 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2879 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2880 RegsToPass[i].second, InFlag);
2881 InFlag = Chain.getValue(1);
2884 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2885 // = Chain, Callee, Reg#1, Reg#2, ...
2887 // Returns a chain & a flag for retval copy to use.
2888 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2889 SmallVector<SDValue, 8> Ops;
2890 Ops.push_back(Chain);
2891 Ops.push_back(Callee);
2893 // Add argument registers to the end of the list so that they are
2894 // known live into the call.
2895 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2896 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2897 RegsToPass[i].second.getValueType()));
2899 // Add a register mask operand representing the call-preserved registers.
2900 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2901 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2902 assert(Mask && "Missing call preserved mask for calling convention");
2903 Ops.push_back(DAG.getRegisterMask(Mask));
2905 if (InFlag.getNode())
2906 Ops.push_back(InFlag);
2908 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2909 InFlag = Chain.getValue(1);
2911 // Create the CALLSEQ_END node.
2912 Chain = DAG.getCALLSEQ_END(Chain,
2913 DAG.getIntPtrConstant(NextStackOffset, true),
2914 DAG.getIntPtrConstant(0, true), InFlag);
2915 InFlag = Chain.getValue(1);
2917 // Handle result values, copying them out of physregs into vregs that we
2919 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2920 Ins, dl, DAG, InVals);
2923 /// LowerCallResult - Lower the result values of a call into the
2924 /// appropriate copies out of appropriate physical registers.
2926 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2927 CallingConv::ID CallConv, bool isVarArg,
2928 const SmallVectorImpl<ISD::InputArg> &Ins,
2929 DebugLoc dl, SelectionDAG &DAG,
2930 SmallVectorImpl<SDValue> &InVals) const {
2931 // Assign locations to each value returned by this call.
2932 SmallVector<CCValAssign, 16> RVLocs;
2933 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2934 getTargetMachine(), RVLocs, *DAG.getContext());
2936 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2938 // Copy all of the result registers out of their specified physreg.
2939 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2940 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2941 RVLocs[i].getValVT(), InFlag).getValue(1);
2942 InFlag = Chain.getValue(2);
2943 InVals.push_back(Chain.getValue(0));
2949 //===----------------------------------------------------------------------===//
2950 // Formal Arguments Calling Convention Implementation
2951 //===----------------------------------------------------------------------===//
2952 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2953 std::vector<SDValue> &OutChains,
2954 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2955 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2956 const Argument *FuncArg) {
2957 unsigned LocMem = VA.getLocMemOffset();
2958 unsigned FirstWord = LocMem / 4;
2960 // copy register A0 - A3 to frame object
2961 for (unsigned i = 0; i < NumWords; ++i) {
2962 unsigned CurWord = FirstWord + i;
2963 if (CurWord >= O32IntRegsSize)
2966 unsigned SrcReg = O32IntRegs[CurWord];
2967 unsigned Reg = AddLiveIn(MF, SrcReg, &Mips::CPURegsRegClass);
2968 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2969 DAG.getConstant(i * 4, MVT::i32));
2970 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2971 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2973 OutChains.push_back(Store);
2977 // Create frame object on stack and copy registers used for byval passing to it.
2979 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2980 std::vector<SDValue> &OutChains, SelectionDAG &DAG,
2981 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2982 MachineFrameInfo *MFI, bool IsRegLoc,
2983 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2984 EVT PtrTy, const Argument *FuncArg) {
2985 const uint16_t *Reg = Mips64IntRegs + 8;
2986 int FOOffset; // Frame object offset from virtual frame pointer.
2989 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2990 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2993 FOOffset = VA.getLocMemOffset();
2995 // Create frame object.
2996 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2997 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2998 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2999 InVals.push_back(FIN);
3001 // Copy arg registers.
3002 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
3004 unsigned VReg = AddLiveIn(MF, *Reg, &Mips::CPU64RegsRegClass);
3005 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
3006 DAG.getConstant(I * 8, PtrTy));
3007 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
3008 StorePtr, MachinePointerInfo(FuncArg, I * 8),
3010 OutChains.push_back(Store);
3016 /// LowerFormalArguments - transform physical registers into virtual registers
3017 /// and generate load operations for arguments places on the stack.
3019 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3020 CallingConv::ID CallConv,
3022 const SmallVectorImpl<ISD::InputArg> &Ins,
3023 DebugLoc dl, SelectionDAG &DAG,
3024 SmallVectorImpl<SDValue> &InVals)
3026 MachineFunction &MF = DAG.getMachineFunction();
3027 MachineFrameInfo *MFI = MF.getFrameInfo();
3028 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3030 MipsFI->setVarArgsFrameIndex(0);
3032 // Used with vargs to acumulate store chains.
3033 std::vector<SDValue> OutChains;
3035 // Assign locations to all of the incoming arguments.
3036 SmallVector<CCValAssign, 16> ArgLocs;
3037 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3038 getTargetMachine(), ArgLocs, *DAG.getContext());
3040 if (CallConv == CallingConv::Fast)
3041 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FastCC);
3043 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
3045 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
3047 Function::const_arg_iterator FuncArg =
3048 DAG.getMachineFunction().getFunction()->arg_begin();
3049 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
3051 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
3052 CCValAssign &VA = ArgLocs[i];
3053 EVT ValVT = VA.getValVT();
3054 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3055 bool IsRegLoc = VA.isRegLoc();
3057 if (Flags.isByVal()) {
3058 assert(Flags.getByValSize() &&
3059 "ByVal args of size 0 should have been ignored by front-end.");
3061 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
3062 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
3064 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3065 InVals.push_back(FIN);
3066 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
3069 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
3070 MFI, IsRegLoc, InVals, MipsFI,
3071 getPointerTy(), &*FuncArg);
3075 // Arguments stored on registers
3077 EVT RegVT = VA.getLocVT();
3078 unsigned ArgReg = VA.getLocReg();
3079 const TargetRegisterClass *RC;
3081 if (RegVT == MVT::i32)
3082 RC = &Mips::CPURegsRegClass;
3083 else if (RegVT == MVT::i64)
3084 RC = &Mips::CPU64RegsRegClass;
3085 else if (RegVT == MVT::f32)
3086 RC = &Mips::FGR32RegClass;
3087 else if (RegVT == MVT::f64)
3088 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3090 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3092 // Transform the arguments stored on
3093 // physical registers into virtual ones
3094 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3095 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3097 // If this is an 8 or 16-bit value, it has been passed promoted
3098 // to 32 bits. Insert an assert[sz]ext to capture this, then
3099 // truncate to the right size.
3100 if (VA.getLocInfo() != CCValAssign::Full) {
3101 unsigned Opcode = 0;
3102 if (VA.getLocInfo() == CCValAssign::SExt)
3103 Opcode = ISD::AssertSext;
3104 else if (VA.getLocInfo() == CCValAssign::ZExt)
3105 Opcode = ISD::AssertZext;
3107 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3108 DAG.getValueType(ValVT));
3109 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3112 // Handle floating point arguments passed in integer registers.
3113 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3114 (RegVT == MVT::i64 && ValVT == MVT::f64))
3115 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3116 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3117 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3118 getNextIntArgReg(ArgReg), RC);
3119 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3120 if (!Subtarget->isLittle())
3121 std::swap(ArgValue, ArgValue2);
3122 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3123 ArgValue, ArgValue2);
3126 InVals.push_back(ArgValue);
3127 } else { // VA.isRegLoc()
3130 assert(VA.isMemLoc());
3132 // The stack pointer offset is relative to the caller stack frame.
3133 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3134 VA.getLocMemOffset(), true);
3136 // Create load nodes to retrieve arguments from the stack
3137 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3138 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3139 MachinePointerInfo::getFixedStack(LastFI),
3140 false, false, false, 0));
3144 // The mips ABIs for returning structs by value requires that we copy
3145 // the sret argument into $v0 for the return. Save the argument into
3146 // a virtual register so that we can access it from the return points.
3147 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3148 unsigned Reg = MipsFI->getSRetReturnReg();
3150 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
3151 MipsFI->setSRetReturnReg(Reg);
3153 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3154 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3158 unsigned NumOfRegs = IsO32 ? 4 : 8;
3159 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
3160 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
3161 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
3162 const TargetRegisterClass *RC = IsO32 ?
3163 (const TargetRegisterClass*)&Mips::CPURegsRegClass :
3164 (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
3165 unsigned RegSize = RC->getSize();
3166 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
3168 // Offset of the first variable argument from stack pointer.
3169 int FirstVaArgOffset;
3171 if (IsO32 || (Idx == NumOfRegs)) {
3173 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
3175 FirstVaArgOffset = RegSlotOffset;
3177 // Record the frame index of the first variable argument
3178 // which is a value necessary to VASTART.
3179 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
3180 MipsFI->setVarArgsFrameIndex(LastFI);
3182 // Copy the integer registers that have not been used for argument passing
3183 // to the argument register save area. For O32, the save area is allocated
3184 // in the caller's stack frame, while for N32/64, it is allocated in the
3185 // callee's stack frame.
3186 for (int StackOffset = RegSlotOffset;
3187 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
3188 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
3189 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3190 MVT::getIntegerVT(RegSize * 8));
3191 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
3192 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
3193 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
3194 MachinePointerInfo(), false, false, 0));
3198 MipsFI->setLastInArgFI(LastFI);
3200 // All stores are grouped in one node to allow the matching between
3201 // the size of Ins and InVals. This only happens when on varg functions
3202 if (!OutChains.empty()) {
3203 OutChains.push_back(Chain);
3204 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3205 &OutChains[0], OutChains.size());
3211 //===----------------------------------------------------------------------===//
3212 // Return Value Calling Convention Implementation
3213 //===----------------------------------------------------------------------===//
3216 MipsTargetLowering::LowerReturn(SDValue Chain,
3217 CallingConv::ID CallConv, bool isVarArg,
3218 const SmallVectorImpl<ISD::OutputArg> &Outs,
3219 const SmallVectorImpl<SDValue> &OutVals,
3220 DebugLoc dl, SelectionDAG &DAG) const {
3222 // CCValAssign - represent the assignment of
3223 // the return value to a location
3224 SmallVector<CCValAssign, 16> RVLocs;
3226 // CCState - Info about the registers and stack slot.
3227 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3228 getTargetMachine(), RVLocs, *DAG.getContext());
3230 // Analize return values.
3231 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3233 // If this is the first return lowered for this function, add
3234 // the regs to the liveout set for the function.
3235 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3236 for (unsigned i = 0; i != RVLocs.size(); ++i)
3237 if (RVLocs[i].isRegLoc())
3238 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3243 // Copy the result values into the output registers.
3244 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3245 CCValAssign &VA = RVLocs[i];
3246 assert(VA.isRegLoc() && "Can only return in registers!");
3248 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3250 // guarantee that all emitted copies are
3251 // stuck together, avoiding something bad
3252 Flag = Chain.getValue(1);
3255 // The mips ABIs for returning structs by value requires that we copy
3256 // the sret argument into $v0 for the return. We saved the argument into
3257 // a virtual register in the entry block, so now we copy the value out
3259 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3260 MachineFunction &MF = DAG.getMachineFunction();
3261 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3262 unsigned Reg = MipsFI->getSRetReturnReg();
3265 llvm_unreachable("sret virtual register not created in the entry block");
3266 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3268 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
3269 Flag = Chain.getValue(1);
3272 // Return on Mips is always a "jr $ra"
3274 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3277 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3280 //===----------------------------------------------------------------------===//
3281 // Mips Inline Assembly Support
3282 //===----------------------------------------------------------------------===//
3284 /// getConstraintType - Given a constraint letter, return the type of
3285 /// constraint it is for this target.
3286 MipsTargetLowering::ConstraintType MipsTargetLowering::
3287 getConstraintType(const std::string &Constraint) const
3289 // Mips specific constrainy
3290 // GCC config/mips/constraints.md
3292 // 'd' : An address register. Equivalent to r
3293 // unless generating MIPS16 code.
3294 // 'y' : Equivalent to r; retained for
3295 // backwards compatibility.
3296 // 'c' : A register suitable for use in an indirect
3297 // jump. This will always be $25 for -mabicalls.
3298 // 'l' : The lo register. 1 word storage.
3299 // 'x' : The hilo register pair. Double word storage.
3300 if (Constraint.size() == 1) {
3301 switch (Constraint[0]) {
3309 return C_RegisterClass;
3312 return TargetLowering::getConstraintType(Constraint);
3315 /// Examine constraint type and operand type and determine a weight value.
3316 /// This object must already have been set up with the operand type
3317 /// and the current alternative constraint selected.
3318 TargetLowering::ConstraintWeight
3319 MipsTargetLowering::getSingleConstraintMatchWeight(
3320 AsmOperandInfo &info, const char *constraint) const {
3321 ConstraintWeight weight = CW_Invalid;
3322 Value *CallOperandVal = info.CallOperandVal;
3323 // If we don't have a value, we can't do a match,
3324 // but allow it at the lowest weight.
3325 if (CallOperandVal == NULL)
3327 Type *type = CallOperandVal->getType();
3328 // Look at the constraint type.
3329 switch (*constraint) {
3331 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3335 if (type->isIntegerTy())
3336 weight = CW_Register;
3339 if (type->isFloatTy())
3340 weight = CW_Register;
3342 case 'c': // $25 for indirect jumps
3343 case 'l': // lo register
3344 case 'x': // hilo register pair
3345 if (type->isIntegerTy())
3346 weight = CW_SpecificReg;
3348 case 'I': // signed 16 bit immediate
3349 case 'J': // integer zero
3350 case 'K': // unsigned 16 bit immediate
3351 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3352 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3353 case 'O': // signed 15 bit immediate (+- 16383)
3354 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3355 if (isa<ConstantInt>(CallOperandVal))
3356 weight = CW_Constant;
3362 /// Given a register class constraint, like 'r', if this corresponds directly
3363 /// to an LLVM register class, return a register of 0 and the register class
3365 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3366 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3368 if (Constraint.size() == 1) {
3369 switch (Constraint[0]) {
3370 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3371 case 'y': // Same as 'r'. Exists for compatibility.
3373 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
3374 return std::make_pair(0U, &Mips::CPURegsRegClass);
3375 if (VT == MVT::i64 && !HasMips64)
3376 return std::make_pair(0U, &Mips::CPURegsRegClass);
3377 if (VT == MVT::i64 && HasMips64)
3378 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3379 // This will generate an error message
3380 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3383 return std::make_pair(0U, &Mips::FGR32RegClass);
3384 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3385 if (Subtarget->isFP64bit())
3386 return std::make_pair(0U, &Mips::FGR64RegClass);
3387 return std::make_pair(0U, &Mips::AFGR64RegClass);
3390 case 'c': // register suitable for indirect jump
3392 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3393 assert(VT == MVT::i64 && "Unexpected type.");
3394 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3395 case 'l': // register suitable for indirect jump
3397 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3398 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3399 case 'x': // register suitable for indirect jump
3400 // Fixme: Not triggering the use of both hi and low
3401 // This will generate an error message
3402 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3405 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3408 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3409 /// vector. If it is invalid, don't add anything to Ops.
3410 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3411 std::string &Constraint,
3412 std::vector<SDValue>&Ops,
3413 SelectionDAG &DAG) const {
3414 SDValue Result(0, 0);
3416 // Only support length 1 constraints for now.
3417 if (Constraint.length() > 1) return;
3419 char ConstraintLetter = Constraint[0];
3420 switch (ConstraintLetter) {
3421 default: break; // This will fall through to the generic implementation
3422 case 'I': // Signed 16 bit constant
3423 // If this fails, the parent routine will give an error
3424 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3425 EVT Type = Op.getValueType();
3426 int64_t Val = C->getSExtValue();
3427 if (isInt<16>(Val)) {
3428 Result = DAG.getTargetConstant(Val, Type);
3433 case 'J': // integer zero
3434 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3435 EVT Type = Op.getValueType();
3436 int64_t Val = C->getZExtValue();
3438 Result = DAG.getTargetConstant(0, Type);
3443 case 'K': // unsigned 16 bit immediate
3444 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3445 EVT Type = Op.getValueType();
3446 uint64_t Val = (uint64_t)C->getZExtValue();
3447 if (isUInt<16>(Val)) {
3448 Result = DAG.getTargetConstant(Val, Type);
3453 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3454 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3455 EVT Type = Op.getValueType();
3456 int64_t Val = C->getSExtValue();
3457 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3458 Result = DAG.getTargetConstant(Val, Type);
3463 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3464 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3465 EVT Type = Op.getValueType();
3466 int64_t Val = C->getSExtValue();
3467 if ((Val >= -65535) && (Val <= -1)) {
3468 Result = DAG.getTargetConstant(Val, Type);
3473 case 'O': // signed 15 bit immediate
3474 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3475 EVT Type = Op.getValueType();
3476 int64_t Val = C->getSExtValue();
3477 if ((isInt<15>(Val))) {
3478 Result = DAG.getTargetConstant(Val, Type);
3483 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3484 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3485 EVT Type = Op.getValueType();
3486 int64_t Val = C->getSExtValue();
3487 if ((Val <= 65535) && (Val >= 1)) {
3488 Result = DAG.getTargetConstant(Val, Type);
3495 if (Result.getNode()) {
3496 Ops.push_back(Result);
3500 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3504 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3505 // The Mips target isn't yet aware of offsets.
3509 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3510 unsigned SrcAlign, bool IsZeroVal,
3512 MachineFunction &MF) const {
3513 if (Subtarget->hasMips64())
3519 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3520 if (VT != MVT::f32 && VT != MVT::f64)
3522 if (Imm.isNegZero())
3524 return Imm.isZero();
3527 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3529 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3531 return TargetLowering::getJumpTableEncoding();