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);
299 setMinFunctionAlignment(HasMips64 ? 3 : 2);
301 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
302 computeRegisterProperties();
304 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
305 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
307 maxStoresPerMemcpy = 16;
310 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
311 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
318 return Subtarget->hasMips32r2Or64();
324 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
329 // Transforms a subgraph in CurDAG if the following pattern is found:
330 // (addc multLo, Lo0), (adde multHi, Hi0),
332 // multHi/Lo: product of multiplication
333 // Lo0: initial value of Lo register
334 // Hi0: initial value of Hi register
335 // Return true if pattern matching was successful.
336 static bool SelectMadd(SDNode* ADDENode, SelectionDAG* CurDAG) {
337 // ADDENode's second operand must be a flag output of an ADDC node in order
338 // for the matching to be successful.
339 SDNode* ADDCNode = ADDENode->getOperand(2).getNode();
341 if (ADDCNode->getOpcode() != ISD::ADDC)
344 SDValue MultHi = ADDENode->getOperand(0);
345 SDValue MultLo = ADDCNode->getOperand(0);
346 SDNode* MultNode = MultHi.getNode();
347 unsigned MultOpc = MultHi.getOpcode();
349 // MultHi and MultLo must be generated by the same node,
350 if (MultLo.getNode() != MultNode)
353 // and it must be a multiplication.
354 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
357 // MultLo amd MultHi must be the first and second output of MultNode
359 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
362 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
363 // of the values of MultNode, in which case MultNode will be removed in later
365 // If there exist users other than ADDENode or ADDCNode, this function returns
366 // here, which will result in MultNode being mapped to a single MULT
367 // instruction node rather than a pair of MULT and MADD instructions being
369 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
372 SDValue Chain = CurDAG->getEntryNode();
373 DebugLoc dl = ADDENode->getDebugLoc();
375 // create MipsMAdd(u) node
376 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
378 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
379 MultNode->getOperand(0),// Factor 0
380 MultNode->getOperand(1),// Factor 1
381 ADDCNode->getOperand(1),// Lo0
382 ADDENode->getOperand(1));// Hi0
384 // create CopyFromReg nodes
385 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
387 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
389 CopyFromLo.getValue(2));
391 // replace uses of adde and addc here
392 if (!SDValue(ADDCNode, 0).use_empty())
393 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
395 if (!SDValue(ADDENode, 0).use_empty())
396 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
402 // Transforms a subgraph in CurDAG if the following pattern is found:
403 // (addc Lo0, multLo), (sube Hi0, multHi),
405 // multHi/Lo: product of multiplication
406 // Lo0: initial value of Lo register
407 // Hi0: initial value of Hi register
408 // Return true if pattern matching was successful.
409 static bool SelectMsub(SDNode* SUBENode, SelectionDAG* CurDAG) {
410 // SUBENode's second operand must be a flag output of an SUBC node in order
411 // for the matching to be successful.
412 SDNode* SUBCNode = SUBENode->getOperand(2).getNode();
414 if (SUBCNode->getOpcode() != ISD::SUBC)
417 SDValue MultHi = SUBENode->getOperand(1);
418 SDValue MultLo = SUBCNode->getOperand(1);
419 SDNode* MultNode = MultHi.getNode();
420 unsigned MultOpc = MultHi.getOpcode();
422 // MultHi and MultLo must be generated by the same node,
423 if (MultLo.getNode() != MultNode)
426 // and it must be a multiplication.
427 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
430 // MultLo amd MultHi must be the first and second output of MultNode
432 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
435 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
436 // of the values of MultNode, in which case MultNode will be removed in later
438 // If there exist users other than SUBENode or SUBCNode, this function returns
439 // here, which will result in MultNode being mapped to a single MULT
440 // instruction node rather than a pair of MULT and MSUB instructions being
442 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
445 SDValue Chain = CurDAG->getEntryNode();
446 DebugLoc dl = SUBENode->getDebugLoc();
448 // create MipsSub(u) node
449 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
451 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
452 MultNode->getOperand(0),// Factor 0
453 MultNode->getOperand(1),// Factor 1
454 SUBCNode->getOperand(0),// Lo0
455 SUBENode->getOperand(0));// Hi0
457 // create CopyFromReg nodes
458 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
460 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
462 CopyFromLo.getValue(2));
464 // replace uses of sube and subc here
465 if (!SDValue(SUBCNode, 0).use_empty())
466 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
468 if (!SDValue(SUBENode, 0).use_empty())
469 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
474 static SDValue PerformADDECombine(SDNode *N, SelectionDAG& DAG,
475 TargetLowering::DAGCombinerInfo &DCI,
476 const MipsSubtarget* Subtarget) {
477 if (DCI.isBeforeLegalize())
480 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
482 return SDValue(N, 0);
487 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG& DAG,
488 TargetLowering::DAGCombinerInfo &DCI,
489 const MipsSubtarget* Subtarget) {
490 if (DCI.isBeforeLegalize())
493 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
495 return SDValue(N, 0);
500 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG& DAG,
501 TargetLowering::DAGCombinerInfo &DCI,
502 const MipsSubtarget* Subtarget) {
503 if (DCI.isBeforeLegalizeOps())
506 EVT Ty = N->getValueType(0);
507 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
508 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
509 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
511 DebugLoc dl = N->getDebugLoc();
513 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
514 N->getOperand(0), N->getOperand(1));
515 SDValue InChain = DAG.getEntryNode();
516 SDValue InGlue = DivRem;
519 if (N->hasAnyUseOfValue(0)) {
520 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
523 InChain = CopyFromLo.getValue(1);
524 InGlue = CopyFromLo.getValue(2);
528 if (N->hasAnyUseOfValue(1)) {
529 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
531 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
537 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
539 default: llvm_unreachable("Unknown fp condition code!");
541 case ISD::SETOEQ: return Mips::FCOND_OEQ;
542 case ISD::SETUNE: return Mips::FCOND_UNE;
544 case ISD::SETOLT: return Mips::FCOND_OLT;
546 case ISD::SETOGT: return Mips::FCOND_OGT;
548 case ISD::SETOLE: return Mips::FCOND_OLE;
550 case ISD::SETOGE: return Mips::FCOND_OGE;
551 case ISD::SETULT: return Mips::FCOND_ULT;
552 case ISD::SETULE: return Mips::FCOND_ULE;
553 case ISD::SETUGT: return Mips::FCOND_UGT;
554 case ISD::SETUGE: return Mips::FCOND_UGE;
555 case ISD::SETUO: return Mips::FCOND_UN;
556 case ISD::SETO: return Mips::FCOND_OR;
558 case ISD::SETONE: return Mips::FCOND_ONE;
559 case ISD::SETUEQ: return Mips::FCOND_UEQ;
564 // Returns true if condition code has to be inverted.
565 static bool InvertFPCondCode(Mips::CondCode CC) {
566 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
569 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
570 "Illegal Condition Code");
575 // Creates and returns an FPCmp node from a setcc node.
576 // Returns Op if setcc is not a floating point comparison.
577 static SDValue CreateFPCmp(SelectionDAG& DAG, const SDValue& Op) {
578 // must be a SETCC node
579 if (Op.getOpcode() != ISD::SETCC)
582 SDValue LHS = Op.getOperand(0);
584 if (!LHS.getValueType().isFloatingPoint())
587 SDValue RHS = Op.getOperand(1);
588 DebugLoc dl = Op.getDebugLoc();
590 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
591 // node if necessary.
592 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
594 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
595 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
598 // Creates and returns a CMovFPT/F node.
599 static SDValue CreateCMovFP(SelectionDAG& DAG, SDValue Cond, SDValue True,
600 SDValue False, DebugLoc DL) {
601 bool invert = InvertFPCondCode((Mips::CondCode)
602 cast<ConstantSDNode>(Cond.getOperand(2))
605 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
606 True.getValueType(), True, False, Cond);
609 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG& DAG,
610 TargetLowering::DAGCombinerInfo &DCI,
611 const MipsSubtarget* Subtarget) {
612 if (DCI.isBeforeLegalizeOps())
615 SDValue SetCC = N->getOperand(0);
617 if ((SetCC.getOpcode() != ISD::SETCC) ||
618 !SetCC.getOperand(0).getValueType().isInteger())
621 SDValue False = N->getOperand(2);
622 EVT FalseTy = False.getValueType();
624 if (!FalseTy.isInteger())
627 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
629 if (!CN || CN->getZExtValue())
632 const DebugLoc DL = N->getDebugLoc();
633 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
634 SDValue True = N->getOperand(1);
636 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
637 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
639 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
642 static SDValue PerformANDCombine(SDNode *N, SelectionDAG& DAG,
643 TargetLowering::DAGCombinerInfo &DCI,
644 const MipsSubtarget* Subtarget) {
645 // Pattern match EXT.
646 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
647 // => ext $dst, $src, size, pos
648 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
651 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
652 unsigned ShiftRightOpc = ShiftRight.getOpcode();
654 // Op's first operand must be a shift right.
655 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
658 // The second operand of the shift must be an immediate.
660 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
663 uint64_t Pos = CN->getZExtValue();
664 uint64_t SMPos, SMSize;
666 // Op's second operand must be a shifted mask.
667 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
668 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
671 // Return if the shifted mask does not start at bit 0 or the sum of its size
672 // and Pos exceeds the word's size.
673 EVT ValTy = N->getValueType(0);
674 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
677 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
678 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
679 DAG.getConstant(SMSize, MVT::i32));
682 static SDValue PerformORCombine(SDNode *N, SelectionDAG& DAG,
683 TargetLowering::DAGCombinerInfo &DCI,
684 const MipsSubtarget* Subtarget) {
685 // Pattern match INS.
686 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
687 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
688 // => ins $dst, $src, size, pos, $src1
689 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
692 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
693 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
696 // See if Op's first operand matches (and $src1 , mask0).
697 if (And0.getOpcode() != ISD::AND)
700 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
701 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
704 // See if Op's second operand matches (and (shl $src, pos), mask1).
705 if (And1.getOpcode() != ISD::AND)
708 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
709 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
712 // The shift masks must have the same position and size.
713 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
716 SDValue Shl = And1.getOperand(0);
717 if (Shl.getOpcode() != ISD::SHL)
720 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
723 unsigned Shamt = CN->getZExtValue();
725 // Return if the shift amount and the first bit position of mask are not the
727 EVT ValTy = N->getValueType(0);
728 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
731 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
732 DAG.getConstant(SMPos0, MVT::i32),
733 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
736 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
738 SelectionDAG &DAG = DCI.DAG;
739 unsigned opc = N->getOpcode();
744 return PerformADDECombine(N, DAG, DCI, Subtarget);
746 return PerformSUBECombine(N, DAG, DCI, Subtarget);
749 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
751 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
753 return PerformANDCombine(N, DAG, DCI, Subtarget);
755 return PerformORCombine(N, DAG, DCI, Subtarget);
761 SDValue MipsTargetLowering::
762 LowerOperation(SDValue Op, SelectionDAG &DAG) const
764 switch (Op.getOpcode())
766 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
767 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
768 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
769 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
770 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
771 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
772 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
773 case ISD::SELECT: return LowerSELECT(Op, DAG);
774 case ISD::SETCC: return LowerSETCC(Op, DAG);
775 case ISD::VASTART: return LowerVASTART(Op, DAG);
776 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
777 case ISD::FABS: return LowerFABS(Op, DAG);
778 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
779 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
780 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
781 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
782 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
783 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
784 case ISD::LOAD: return LowerLOAD(Op, DAG);
785 case ISD::STORE: return LowerSTORE(Op, DAG);
790 //===----------------------------------------------------------------------===//
791 // Lower helper functions
792 //===----------------------------------------------------------------------===//
794 // AddLiveIn - This helper function adds the specified physical register to the
795 // MachineFunction as a live in value. It also creates a corresponding
796 // virtual register for it.
798 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
800 assert(RC->contains(PReg) && "Not the correct regclass!");
801 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
802 MF.getRegInfo().addLiveIn(PReg, VReg);
806 // Get fp branch code (not opcode) from condition code.
807 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
808 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
809 return Mips::BRANCH_T;
811 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
812 "Invalid CondCode.");
814 return Mips::BRANCH_F;
818 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
820 const MipsSubtarget* Subtarget,
821 const TargetInstrInfo *TII,
822 bool isFPCmp, unsigned Opc) {
823 // There is no need to expand CMov instructions if target has
824 // conditional moves.
825 if (Subtarget->hasCondMov())
828 // To "insert" a SELECT_CC instruction, we actually have to insert the
829 // diamond control-flow pattern. The incoming instruction knows the
830 // destination vreg to set, the condition code register to branch on, the
831 // true/false values to select between, and a branch opcode to use.
832 const BasicBlock *LLVM_BB = BB->getBasicBlock();
833 MachineFunction::iterator It = BB;
840 // bNE r1, r0, copy1MBB
841 // fallthrough --> copy0MBB
842 MachineBasicBlock *thisMBB = BB;
843 MachineFunction *F = BB->getParent();
844 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
845 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
846 F->insert(It, copy0MBB);
847 F->insert(It, sinkMBB);
849 // Transfer the remainder of BB and its successor edges to sinkMBB.
850 sinkMBB->splice(sinkMBB->begin(), BB,
851 llvm::next(MachineBasicBlock::iterator(MI)),
853 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
855 // Next, add the true and fallthrough blocks as its successors.
856 BB->addSuccessor(copy0MBB);
857 BB->addSuccessor(sinkMBB);
859 // Emit the right instruction according to the type of the operands compared
861 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
863 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
864 .addReg(Mips::ZERO).addMBB(sinkMBB);
868 // # fallthrough to sinkMBB
871 // Update machine-CFG edges
872 BB->addSuccessor(sinkMBB);
875 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
880 BuildMI(*BB, BB->begin(), dl,
881 TII->get(Mips::PHI), MI->getOperand(0).getReg())
882 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
883 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
885 BuildMI(*BB, BB->begin(), dl,
886 TII->get(Mips::PHI), MI->getOperand(0).getReg())
887 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
888 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
890 MI->eraseFromParent(); // The pseudo instruction is gone now.
895 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
896 MachineBasicBlock *BB) const {
897 switch (MI->getOpcode()) {
898 default: llvm_unreachable("Unexpected instr type to insert");
899 case Mips::ATOMIC_LOAD_ADD_I8:
900 case Mips::ATOMIC_LOAD_ADD_I8_P8:
901 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
902 case Mips::ATOMIC_LOAD_ADD_I16:
903 case Mips::ATOMIC_LOAD_ADD_I16_P8:
904 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
905 case Mips::ATOMIC_LOAD_ADD_I32:
906 case Mips::ATOMIC_LOAD_ADD_I32_P8:
907 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
908 case Mips::ATOMIC_LOAD_ADD_I64:
909 case Mips::ATOMIC_LOAD_ADD_I64_P8:
910 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
912 case Mips::ATOMIC_LOAD_AND_I8:
913 case Mips::ATOMIC_LOAD_AND_I8_P8:
914 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
915 case Mips::ATOMIC_LOAD_AND_I16:
916 case Mips::ATOMIC_LOAD_AND_I16_P8:
917 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
918 case Mips::ATOMIC_LOAD_AND_I32:
919 case Mips::ATOMIC_LOAD_AND_I32_P8:
920 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
921 case Mips::ATOMIC_LOAD_AND_I64:
922 case Mips::ATOMIC_LOAD_AND_I64_P8:
923 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
925 case Mips::ATOMIC_LOAD_OR_I8:
926 case Mips::ATOMIC_LOAD_OR_I8_P8:
927 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
928 case Mips::ATOMIC_LOAD_OR_I16:
929 case Mips::ATOMIC_LOAD_OR_I16_P8:
930 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
931 case Mips::ATOMIC_LOAD_OR_I32:
932 case Mips::ATOMIC_LOAD_OR_I32_P8:
933 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
934 case Mips::ATOMIC_LOAD_OR_I64:
935 case Mips::ATOMIC_LOAD_OR_I64_P8:
936 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
938 case Mips::ATOMIC_LOAD_XOR_I8:
939 case Mips::ATOMIC_LOAD_XOR_I8_P8:
940 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
941 case Mips::ATOMIC_LOAD_XOR_I16:
942 case Mips::ATOMIC_LOAD_XOR_I16_P8:
943 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
944 case Mips::ATOMIC_LOAD_XOR_I32:
945 case Mips::ATOMIC_LOAD_XOR_I32_P8:
946 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
947 case Mips::ATOMIC_LOAD_XOR_I64:
948 case Mips::ATOMIC_LOAD_XOR_I64_P8:
949 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
951 case Mips::ATOMIC_LOAD_NAND_I8:
952 case Mips::ATOMIC_LOAD_NAND_I8_P8:
953 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
954 case Mips::ATOMIC_LOAD_NAND_I16:
955 case Mips::ATOMIC_LOAD_NAND_I16_P8:
956 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
957 case Mips::ATOMIC_LOAD_NAND_I32:
958 case Mips::ATOMIC_LOAD_NAND_I32_P8:
959 return EmitAtomicBinary(MI, BB, 4, 0, true);
960 case Mips::ATOMIC_LOAD_NAND_I64:
961 case Mips::ATOMIC_LOAD_NAND_I64_P8:
962 return EmitAtomicBinary(MI, BB, 8, 0, true);
964 case Mips::ATOMIC_LOAD_SUB_I8:
965 case Mips::ATOMIC_LOAD_SUB_I8_P8:
966 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
967 case Mips::ATOMIC_LOAD_SUB_I16:
968 case Mips::ATOMIC_LOAD_SUB_I16_P8:
969 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
970 case Mips::ATOMIC_LOAD_SUB_I32:
971 case Mips::ATOMIC_LOAD_SUB_I32_P8:
972 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
973 case Mips::ATOMIC_LOAD_SUB_I64:
974 case Mips::ATOMIC_LOAD_SUB_I64_P8:
975 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
977 case Mips::ATOMIC_SWAP_I8:
978 case Mips::ATOMIC_SWAP_I8_P8:
979 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
980 case Mips::ATOMIC_SWAP_I16:
981 case Mips::ATOMIC_SWAP_I16_P8:
982 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
983 case Mips::ATOMIC_SWAP_I32:
984 case Mips::ATOMIC_SWAP_I32_P8:
985 return EmitAtomicBinary(MI, BB, 4, 0);
986 case Mips::ATOMIC_SWAP_I64:
987 case Mips::ATOMIC_SWAP_I64_P8:
988 return EmitAtomicBinary(MI, BB, 8, 0);
990 case Mips::ATOMIC_CMP_SWAP_I8:
991 case Mips::ATOMIC_CMP_SWAP_I8_P8:
992 return EmitAtomicCmpSwapPartword(MI, BB, 1);
993 case Mips::ATOMIC_CMP_SWAP_I16:
994 case Mips::ATOMIC_CMP_SWAP_I16_P8:
995 return EmitAtomicCmpSwapPartword(MI, BB, 2);
996 case Mips::ATOMIC_CMP_SWAP_I32:
997 case Mips::ATOMIC_CMP_SWAP_I32_P8:
998 return EmitAtomicCmpSwap(MI, BB, 4);
999 case Mips::ATOMIC_CMP_SWAP_I64:
1000 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1001 return EmitAtomicCmpSwap(MI, BB, 8);
1005 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1006 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1008 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1009 unsigned Size, unsigned BinOpcode,
1011 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1013 MachineFunction *MF = BB->getParent();
1014 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1015 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1016 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1017 DebugLoc dl = MI->getDebugLoc();
1018 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1021 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1022 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1029 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1030 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1033 ZERO = Mips::ZERO_64;
1037 unsigned OldVal = MI->getOperand(0).getReg();
1038 unsigned Ptr = MI->getOperand(1).getReg();
1039 unsigned Incr = MI->getOperand(2).getReg();
1041 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1042 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1043 unsigned Success = RegInfo.createVirtualRegister(RC);
1045 // insert new blocks after the current block
1046 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1047 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1049 MachineFunction::iterator It = BB;
1051 MF->insert(It, loopMBB);
1052 MF->insert(It, exitMBB);
1054 // Transfer the remainder of BB and its successor edges to exitMBB.
1055 exitMBB->splice(exitMBB->begin(), BB,
1056 llvm::next(MachineBasicBlock::iterator(MI)),
1058 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1062 // fallthrough --> loopMBB
1063 BB->addSuccessor(loopMBB);
1064 loopMBB->addSuccessor(loopMBB);
1065 loopMBB->addSuccessor(exitMBB);
1068 // ll oldval, 0(ptr)
1069 // <binop> storeval, oldval, incr
1070 // sc success, storeval, 0(ptr)
1071 // beq success, $0, loopMBB
1073 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1075 // and andres, oldval, incr
1076 // nor storeval, $0, andres
1077 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1078 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1079 } else if (BinOpcode) {
1080 // <binop> storeval, oldval, incr
1081 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1085 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1086 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1088 MI->eraseFromParent(); // The instruction is gone now.
1094 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1095 MachineBasicBlock *BB,
1096 unsigned Size, unsigned BinOpcode,
1098 assert((Size == 1 || Size == 2) &&
1099 "Unsupported size for EmitAtomicBinaryPartial.");
1101 MachineFunction *MF = BB->getParent();
1102 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1103 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1104 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1105 DebugLoc dl = MI->getDebugLoc();
1106 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1107 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1109 unsigned Dest = MI->getOperand(0).getReg();
1110 unsigned Ptr = MI->getOperand(1).getReg();
1111 unsigned Incr = MI->getOperand(2).getReg();
1113 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1114 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1115 unsigned Mask = RegInfo.createVirtualRegister(RC);
1116 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1117 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1118 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1119 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1120 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1121 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1122 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1123 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1124 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1125 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1126 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1127 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1128 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1129 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1130 unsigned Success = RegInfo.createVirtualRegister(RC);
1132 // insert new blocks after the current block
1133 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1134 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1135 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1136 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1137 MachineFunction::iterator It = BB;
1139 MF->insert(It, loopMBB);
1140 MF->insert(It, sinkMBB);
1141 MF->insert(It, exitMBB);
1143 // Transfer the remainder of BB and its successor edges to exitMBB.
1144 exitMBB->splice(exitMBB->begin(), BB,
1145 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1146 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1148 BB->addSuccessor(loopMBB);
1149 loopMBB->addSuccessor(loopMBB);
1150 loopMBB->addSuccessor(sinkMBB);
1151 sinkMBB->addSuccessor(exitMBB);
1154 // addiu masklsb2,$0,-4 # 0xfffffffc
1155 // and alignedaddr,ptr,masklsb2
1156 // andi ptrlsb2,ptr,3
1157 // sll shiftamt,ptrlsb2,3
1158 // ori maskupper,$0,255 # 0xff
1159 // sll mask,maskupper,shiftamt
1160 // nor mask2,$0,mask
1161 // sll incr2,incr,shiftamt
1163 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1164 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1165 .addReg(Mips::ZERO).addImm(-4);
1166 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1167 .addReg(Ptr).addReg(MaskLSB2);
1168 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1169 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1170 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1171 .addReg(Mips::ZERO).addImm(MaskImm);
1172 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1173 .addReg(ShiftAmt).addReg(MaskUpper);
1174 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1175 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1177 // atomic.load.binop
1179 // ll oldval,0(alignedaddr)
1180 // binop binopres,oldval,incr2
1181 // and newval,binopres,mask
1182 // and maskedoldval0,oldval,mask2
1183 // or storeval,maskedoldval0,newval
1184 // sc success,storeval,0(alignedaddr)
1185 // beq success,$0,loopMBB
1189 // ll oldval,0(alignedaddr)
1190 // and newval,incr2,mask
1191 // and maskedoldval0,oldval,mask2
1192 // or storeval,maskedoldval0,newval
1193 // sc success,storeval,0(alignedaddr)
1194 // beq success,$0,loopMBB
1197 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1199 // and andres, oldval, incr2
1200 // nor binopres, $0, andres
1201 // and newval, binopres, mask
1202 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1203 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1204 .addReg(Mips::ZERO).addReg(AndRes);
1205 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1206 } else if (BinOpcode) {
1207 // <binop> binopres, oldval, incr2
1208 // and newval, binopres, mask
1209 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1210 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1211 } else {// atomic.swap
1212 // and newval, incr2, mask
1213 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1216 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1217 .addReg(OldVal).addReg(Mask2);
1218 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1219 .addReg(MaskedOldVal0).addReg(NewVal);
1220 BuildMI(BB, dl, TII->get(SC), Success)
1221 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1222 BuildMI(BB, dl, TII->get(Mips::BEQ))
1223 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1226 // and maskedoldval1,oldval,mask
1227 // srl srlres,maskedoldval1,shiftamt
1228 // sll sllres,srlres,24
1229 // sra dest,sllres,24
1231 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1233 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1234 .addReg(OldVal).addReg(Mask);
1235 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1236 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1237 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1238 .addReg(SrlRes).addImm(ShiftImm);
1239 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1240 .addReg(SllRes).addImm(ShiftImm);
1242 MI->eraseFromParent(); // The instruction is gone now.
1248 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1249 MachineBasicBlock *BB,
1250 unsigned Size) const {
1251 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1253 MachineFunction *MF = BB->getParent();
1254 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1255 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1257 DebugLoc dl = MI->getDebugLoc();
1258 unsigned LL, SC, ZERO, BNE, BEQ;
1261 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1262 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1268 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1269 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1270 ZERO = Mips::ZERO_64;
1275 unsigned Dest = MI->getOperand(0).getReg();
1276 unsigned Ptr = MI->getOperand(1).getReg();
1277 unsigned OldVal = MI->getOperand(2).getReg();
1278 unsigned NewVal = MI->getOperand(3).getReg();
1280 unsigned Success = RegInfo.createVirtualRegister(RC);
1282 // insert new blocks after the current block
1283 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1284 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1285 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1286 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1287 MachineFunction::iterator It = BB;
1289 MF->insert(It, loop1MBB);
1290 MF->insert(It, loop2MBB);
1291 MF->insert(It, exitMBB);
1293 // Transfer the remainder of BB and its successor edges to exitMBB.
1294 exitMBB->splice(exitMBB->begin(), BB,
1295 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1296 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1300 // fallthrough --> loop1MBB
1301 BB->addSuccessor(loop1MBB);
1302 loop1MBB->addSuccessor(exitMBB);
1303 loop1MBB->addSuccessor(loop2MBB);
1304 loop2MBB->addSuccessor(loop1MBB);
1305 loop2MBB->addSuccessor(exitMBB);
1309 // bne dest, oldval, exitMBB
1311 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1312 BuildMI(BB, dl, TII->get(BNE))
1313 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1316 // sc success, newval, 0(ptr)
1317 // beq success, $0, loop1MBB
1319 BuildMI(BB, dl, TII->get(SC), Success)
1320 .addReg(NewVal).addReg(Ptr).addImm(0);
1321 BuildMI(BB, dl, TII->get(BEQ))
1322 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1324 MI->eraseFromParent(); // The instruction is gone now.
1330 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1331 MachineBasicBlock *BB,
1332 unsigned Size) const {
1333 assert((Size == 1 || Size == 2) &&
1334 "Unsupported size for EmitAtomicCmpSwapPartial.");
1336 MachineFunction *MF = BB->getParent();
1337 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1338 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1339 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1340 DebugLoc dl = MI->getDebugLoc();
1341 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1342 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1344 unsigned Dest = MI->getOperand(0).getReg();
1345 unsigned Ptr = MI->getOperand(1).getReg();
1346 unsigned CmpVal = MI->getOperand(2).getReg();
1347 unsigned NewVal = MI->getOperand(3).getReg();
1349 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1350 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1351 unsigned Mask = RegInfo.createVirtualRegister(RC);
1352 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1353 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1354 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1355 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1356 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1357 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1358 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1359 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1360 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1361 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1362 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1363 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1364 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1365 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1366 unsigned Success = RegInfo.createVirtualRegister(RC);
1368 // insert new blocks after the current block
1369 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1370 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1371 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1372 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1373 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1374 MachineFunction::iterator It = BB;
1376 MF->insert(It, loop1MBB);
1377 MF->insert(It, loop2MBB);
1378 MF->insert(It, sinkMBB);
1379 MF->insert(It, exitMBB);
1381 // Transfer the remainder of BB and its successor edges to exitMBB.
1382 exitMBB->splice(exitMBB->begin(), BB,
1383 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1384 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1386 BB->addSuccessor(loop1MBB);
1387 loop1MBB->addSuccessor(sinkMBB);
1388 loop1MBB->addSuccessor(loop2MBB);
1389 loop2MBB->addSuccessor(loop1MBB);
1390 loop2MBB->addSuccessor(sinkMBB);
1391 sinkMBB->addSuccessor(exitMBB);
1393 // FIXME: computation of newval2 can be moved to loop2MBB.
1395 // addiu masklsb2,$0,-4 # 0xfffffffc
1396 // and alignedaddr,ptr,masklsb2
1397 // andi ptrlsb2,ptr,3
1398 // sll shiftamt,ptrlsb2,3
1399 // ori maskupper,$0,255 # 0xff
1400 // sll mask,maskupper,shiftamt
1401 // nor mask2,$0,mask
1402 // andi maskedcmpval,cmpval,255
1403 // sll shiftedcmpval,maskedcmpval,shiftamt
1404 // andi maskednewval,newval,255
1405 // sll shiftednewval,maskednewval,shiftamt
1406 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1407 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1408 .addReg(Mips::ZERO).addImm(-4);
1409 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1410 .addReg(Ptr).addReg(MaskLSB2);
1411 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1412 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1413 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1414 .addReg(Mips::ZERO).addImm(MaskImm);
1415 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1416 .addReg(ShiftAmt).addReg(MaskUpper);
1417 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1418 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1419 .addReg(CmpVal).addImm(MaskImm);
1420 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1421 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1422 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1423 .addReg(NewVal).addImm(MaskImm);
1424 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1425 .addReg(ShiftAmt).addReg(MaskedNewVal);
1428 // ll oldval,0(alginedaddr)
1429 // and maskedoldval0,oldval,mask
1430 // bne maskedoldval0,shiftedcmpval,sinkMBB
1432 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1433 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1434 .addReg(OldVal).addReg(Mask);
1435 BuildMI(BB, dl, TII->get(Mips::BNE))
1436 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1439 // and maskedoldval1,oldval,mask2
1440 // or storeval,maskedoldval1,shiftednewval
1441 // sc success,storeval,0(alignedaddr)
1442 // beq success,$0,loop1MBB
1444 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1445 .addReg(OldVal).addReg(Mask2);
1446 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1447 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1448 BuildMI(BB, dl, TII->get(SC), Success)
1449 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1450 BuildMI(BB, dl, TII->get(Mips::BEQ))
1451 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1454 // srl srlres,maskedoldval0,shiftamt
1455 // sll sllres,srlres,24
1456 // sra dest,sllres,24
1458 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1460 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1461 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1462 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1463 .addReg(SrlRes).addImm(ShiftImm);
1464 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1465 .addReg(SllRes).addImm(ShiftImm);
1467 MI->eraseFromParent(); // The instruction is gone now.
1472 //===----------------------------------------------------------------------===//
1473 // Misc Lower Operation implementation
1474 //===----------------------------------------------------------------------===//
1475 SDValue MipsTargetLowering::
1476 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1478 MachineFunction &MF = DAG.getMachineFunction();
1479 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1480 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1482 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1483 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1484 "Cannot lower if the alignment of the allocated space is larger than \
1485 that of the stack.");
1487 SDValue Chain = Op.getOperand(0);
1488 SDValue Size = Op.getOperand(1);
1489 DebugLoc dl = Op.getDebugLoc();
1491 // Get a reference from Mips stack pointer
1492 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1494 // Subtract the dynamic size from the actual stack size to
1495 // obtain the new stack size.
1496 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1498 // The Sub result contains the new stack start address, so it
1499 // must be placed in the stack pointer register.
1500 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1502 // This node always has two return values: a new stack pointer
1503 // value and a chain
1504 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1505 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1506 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1508 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1511 SDValue MipsTargetLowering::
1512 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1514 // The first operand is the chain, the second is the condition, the third is
1515 // the block to branch to if the condition is true.
1516 SDValue Chain = Op.getOperand(0);
1517 SDValue Dest = Op.getOperand(2);
1518 DebugLoc dl = Op.getDebugLoc();
1520 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1522 // Return if flag is not set by a floating point comparison.
1523 if (CondRes.getOpcode() != MipsISD::FPCmp)
1526 SDValue CCNode = CondRes.getOperand(2);
1528 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1529 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1531 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1535 SDValue MipsTargetLowering::
1536 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1538 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1540 // Return if flag is not set by a floating point comparison.
1541 if (Cond.getOpcode() != MipsISD::FPCmp)
1544 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1548 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1549 SDValue Cond = CreateFPCmp(DAG, Op);
1551 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1552 "Floating point operand expected.");
1554 SDValue True = DAG.getConstant(1, MVT::i32);
1555 SDValue False = DAG.getConstant(0, MVT::i32);
1557 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1560 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1561 SelectionDAG &DAG) const {
1562 // FIXME there isn't actually debug info here
1563 DebugLoc dl = Op.getDebugLoc();
1564 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1566 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1567 SDVTList VTs = DAG.getVTList(MVT::i32);
1569 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1571 // %gp_rel relocation
1572 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1573 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1575 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1576 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1577 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1579 // %hi/%lo relocation
1580 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1582 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1584 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1585 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1586 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1589 EVT ValTy = Op.getValueType();
1590 bool HasGotOfst = (GV->hasInternalLinkage() ||
1591 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1592 unsigned GotFlag = HasMips64 ?
1593 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1594 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1595 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1596 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1597 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1598 MachinePointerInfo(), false, false, false, 0);
1599 // On functions and global targets not internal linked only
1600 // a load from got/GP is necessary for PIC to work.
1603 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1604 HasMips64 ? MipsII::MO_GOT_OFST :
1606 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1607 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1610 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1611 SelectionDAG &DAG) const {
1612 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1613 // FIXME there isn't actually debug info here
1614 DebugLoc dl = Op.getDebugLoc();
1616 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1617 // %hi/%lo relocation
1618 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1619 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1620 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1621 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1622 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1625 EVT ValTy = Op.getValueType();
1626 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1627 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1628 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1629 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1630 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1631 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1632 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1633 MachinePointerInfo(), false, false, false, 0);
1634 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1635 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1638 SDValue MipsTargetLowering::
1639 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1641 // If the relocation model is PIC, use the General Dynamic TLS Model or
1642 // Local Dynamic TLS model, otherwise use the Initial Exec or
1643 // Local Exec TLS Model.
1645 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1646 DebugLoc dl = GA->getDebugLoc();
1647 const GlobalValue *GV = GA->getGlobal();
1648 EVT PtrVT = getPointerTy();
1650 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1652 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1653 // General Dynamic and Local Dynamic TLS Model.
1654 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1657 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1658 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1659 GetGlobalReg(DAG, PtrVT), TGA);
1660 unsigned PtrSize = PtrVT.getSizeInBits();
1661 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1663 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1667 Entry.Node = Argument;
1669 Args.push_back(Entry);
1671 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1672 false, false, false, false, 0, CallingConv::C,
1673 /*isTailCall=*/false, /*doesNotRet=*/false,
1674 /*isReturnValueUsed=*/true,
1675 TlsGetAddr, Args, DAG, dl);
1676 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1678 SDValue Ret = CallResult.first;
1680 if (model != TLSModel::LocalDynamic)
1683 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1684 MipsII::MO_DTPREL_HI);
1685 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1686 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1687 MipsII::MO_DTPREL_LO);
1688 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1689 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1690 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1694 if (model == TLSModel::InitialExec) {
1695 // Initial Exec TLS Model
1696 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1697 MipsII::MO_GOTTPREL);
1698 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1700 Offset = DAG.getLoad(PtrVT, dl,
1701 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1702 false, false, false, 0);
1704 // Local Exec TLS Model
1705 assert(model == TLSModel::LocalExec);
1706 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1707 MipsII::MO_TPREL_HI);
1708 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1709 MipsII::MO_TPREL_LO);
1710 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1711 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1712 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1715 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1716 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1719 SDValue MipsTargetLowering::
1720 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1722 SDValue HiPart, JTI, JTILo;
1723 // FIXME there isn't actually debug info here
1724 DebugLoc dl = Op.getDebugLoc();
1725 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1726 EVT PtrVT = Op.getValueType();
1727 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1729 if (!IsPIC && !IsN64) {
1730 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1731 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1732 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1733 } else {// Emit Load from Global Pointer
1734 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1735 unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1736 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1737 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1739 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1740 MachinePointerInfo(), false, false, false, 0);
1741 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1744 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1745 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1748 SDValue MipsTargetLowering::
1749 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1752 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1753 const Constant *C = N->getConstVal();
1754 // FIXME there isn't actually debug info here
1755 DebugLoc dl = Op.getDebugLoc();
1757 // gp_rel relocation
1758 // FIXME: we should reference the constant pool using small data sections,
1759 // but the asm printer currently doesn't support this feature without
1760 // hacking it. This feature should come soon so we can uncomment the
1762 //if (IsInSmallSection(C->getType())) {
1763 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1764 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1765 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1767 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1768 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1769 N->getOffset(), MipsII::MO_ABS_HI);
1770 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1771 N->getOffset(), MipsII::MO_ABS_LO);
1772 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1773 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1774 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1776 EVT ValTy = Op.getValueType();
1777 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1778 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1779 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1780 N->getOffset(), GOTFlag);
1781 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1782 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1783 MachinePointerInfo::getConstantPool(), false,
1785 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1786 N->getOffset(), OFSTFlag);
1787 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1788 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1794 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1795 MachineFunction &MF = DAG.getMachineFunction();
1796 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1798 DebugLoc dl = Op.getDebugLoc();
1799 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1802 // vastart just stores the address of the VarArgsFrameIndex slot into the
1803 // memory location argument.
1804 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1805 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1806 MachinePointerInfo(SV), false, false, 0);
1809 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1810 EVT TyX = Op.getOperand(0).getValueType();
1811 EVT TyY = Op.getOperand(1).getValueType();
1812 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1813 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1814 DebugLoc DL = Op.getDebugLoc();
1817 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1819 SDValue X = (TyX == MVT::f32) ?
1820 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1821 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1823 SDValue Y = (TyY == MVT::f32) ?
1824 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1825 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1829 // ext E, Y, 31, 1 ; extract bit31 of Y
1830 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1831 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1832 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1835 // srl SrlX, SllX, 1
1837 // sll SllY, SrlX, 31
1838 // or Or, SrlX, SllY
1839 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1840 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1841 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1842 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1843 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1846 if (TyX == MVT::f32)
1847 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1849 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1850 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1851 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1854 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1855 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1856 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1857 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1858 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1859 DebugLoc DL = Op.getDebugLoc();
1861 // Bitcast to integer nodes.
1862 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1863 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1866 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1867 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1868 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1869 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1871 if (WidthX > WidthY)
1872 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1873 else if (WidthY > WidthX)
1874 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1876 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1877 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1878 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1881 // (d)sll SllX, X, 1
1882 // (d)srl SrlX, SllX, 1
1883 // (d)srl SrlY, Y, width(Y)-1
1884 // (d)sll SllY, SrlX, width(Y)-1
1885 // or Or, SrlX, SllY
1886 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1887 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1888 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1889 DAG.getConstant(WidthY - 1, MVT::i32));
1891 if (WidthX > WidthY)
1892 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1893 else if (WidthY > WidthX)
1894 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1896 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1897 DAG.getConstant(WidthX - 1, MVT::i32));
1898 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1899 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1903 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1904 if (Subtarget->hasMips64())
1905 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1907 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1910 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1911 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1912 DebugLoc DL = Op.getDebugLoc();
1914 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1916 SDValue X = (Op.getValueType() == MVT::f32) ?
1917 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1918 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1923 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1924 DAG.getRegister(Mips::ZERO, MVT::i32),
1925 DAG.getConstant(31, MVT::i32), Const1, X);
1927 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1928 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1931 if (Op.getValueType() == MVT::f32)
1932 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1934 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1935 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1936 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1939 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1940 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1941 DebugLoc DL = Op.getDebugLoc();
1943 // Bitcast to integer node.
1944 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1948 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1949 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1950 DAG.getConstant(63, MVT::i32), Const1, X);
1952 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1953 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1956 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1960 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
1961 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1962 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1964 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1967 SDValue MipsTargetLowering::
1968 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1970 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1971 "Frame address can only be determined for current frame.");
1973 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1974 MFI->setFrameAddressIsTaken(true);
1975 EVT VT = Op.getValueType();
1976 DebugLoc dl = Op.getDebugLoc();
1977 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
1978 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1982 // TODO: set SType according to the desired memory barrier behavior.
1984 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG& DAG) const {
1986 DebugLoc dl = Op.getDebugLoc();
1987 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1988 DAG.getConstant(SType, MVT::i32));
1991 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
1992 SelectionDAG& DAG) const {
1993 // FIXME: Need pseudo-fence for 'singlethread' fences
1994 // FIXME: Set SType for weaker fences where supported/appropriate.
1996 DebugLoc dl = Op.getDebugLoc();
1997 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
1998 DAG.getConstant(SType, MVT::i32));
2001 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2002 SelectionDAG& DAG) const {
2003 DebugLoc DL = Op.getDebugLoc();
2004 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2005 SDValue Shamt = Op.getOperand(2);
2008 // lo = (shl lo, shamt)
2009 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2012 // hi = (shl lo, shamt[4:0])
2013 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2014 DAG.getConstant(-1, MVT::i32));
2015 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2016 DAG.getConstant(1, MVT::i32));
2017 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2019 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2020 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2021 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2022 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2023 DAG.getConstant(0x20, MVT::i32));
2024 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, DAG.getConstant(0, MVT::i32),
2026 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2028 SDValue Ops[2] = {Lo, Hi};
2029 return DAG.getMergeValues(Ops, 2, DL);
2032 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG& DAG,
2034 DebugLoc DL = Op.getDebugLoc();
2035 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2036 SDValue Shamt = Op.getOperand(2);
2039 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2041 // hi = (sra hi, shamt)
2043 // hi = (srl hi, shamt)
2046 // lo = (sra hi, shamt[4:0])
2047 // hi = (sra hi, 31)
2049 // lo = (srl hi, shamt[4:0])
2051 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2052 DAG.getConstant(-1, MVT::i32));
2053 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2054 DAG.getConstant(1, MVT::i32));
2055 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2056 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2057 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2058 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2060 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2061 DAG.getConstant(0x20, MVT::i32));
2062 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2063 DAG.getConstant(31, MVT::i32));
2064 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2065 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2066 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2069 SDValue Ops[2] = {Lo, Hi};
2070 return DAG.getMergeValues(Ops, 2, DL);
2073 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2074 SDValue Chain, SDValue Src, unsigned Offset) {
2075 SDValue Ptr = LD->getBasePtr();
2076 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2077 EVT BasePtrVT = Ptr.getValueType();
2078 DebugLoc DL = LD->getDebugLoc();
2079 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2082 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2083 DAG.getConstant(Offset, BasePtrVT));
2085 SDValue Ops[] = { Chain, Ptr, Src };
2086 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2087 LD->getMemOperand());
2090 // Expand an unaligned 32 or 64-bit integer load node.
2091 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2092 LoadSDNode *LD = cast<LoadSDNode>(Op);
2093 EVT MemVT = LD->getMemoryVT();
2095 // Return if load is aligned or if MemVT is neither i32 nor i64.
2096 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2097 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2100 bool IsLittle = Subtarget->isLittle();
2101 EVT VT = Op.getValueType();
2102 ISD::LoadExtType ExtType = LD->getExtensionType();
2103 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2105 assert((VT == MVT::i32) || (VT == MVT::i64));
2108 // (set dst, (i64 (load baseptr)))
2110 // (set tmp, (ldl (add baseptr, 7), undef))
2111 // (set dst, (ldr baseptr, tmp))
2112 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2113 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2115 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2119 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2121 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2125 // (set dst, (i32 (load baseptr))) or
2126 // (set dst, (i64 (sextload baseptr))) or
2127 // (set dst, (i64 (extload baseptr)))
2129 // (set tmp, (lwl (add baseptr, 3), undef))
2130 // (set dst, (lwr baseptr, tmp))
2131 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2132 (ExtType == ISD::EXTLOAD))
2135 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2138 // (set dst, (i64 (zextload baseptr)))
2140 // (set tmp0, (lwl (add baseptr, 3), undef))
2141 // (set tmp1, (lwr baseptr, tmp0))
2142 // (set tmp2, (shl tmp1, 32))
2143 // (set dst, (srl tmp2, 32))
2144 DebugLoc DL = LD->getDebugLoc();
2145 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2146 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2147 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2148 SDValue Ops[] = { SRL, LWR.getValue(1) };
2149 return DAG.getMergeValues(Ops, 2, DL);
2152 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2153 SDValue Chain, unsigned Offset) {
2154 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2155 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2156 DebugLoc DL = SD->getDebugLoc();
2157 SDVTList VTList = DAG.getVTList(MVT::Other);
2160 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2161 DAG.getConstant(Offset, BasePtrVT));
2163 SDValue Ops[] = { Chain, Value, Ptr };
2164 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2165 SD->getMemOperand());
2168 // Expand an unaligned 32 or 64-bit integer store node.
2169 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2170 StoreSDNode *SD = cast<StoreSDNode>(Op);
2171 EVT MemVT = SD->getMemoryVT();
2173 // Return if store is aligned or if MemVT is neither i32 nor i64.
2174 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2175 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2178 bool IsLittle = Subtarget->isLittle();
2179 SDValue Value = SD->getValue(), Chain = SD->getChain();
2180 EVT VT = Value.getValueType();
2183 // (store val, baseptr) or
2184 // (truncstore val, baseptr)
2186 // (swl val, (add baseptr, 3))
2187 // (swr val, baseptr)
2188 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2189 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2191 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2194 assert(VT == MVT::i64);
2197 // (store val, baseptr)
2199 // (sdl val, (add baseptr, 7))
2200 // (sdr val, baseptr)
2201 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2202 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2205 //===----------------------------------------------------------------------===//
2206 // Calling Convention Implementation
2207 //===----------------------------------------------------------------------===//
2209 //===----------------------------------------------------------------------===//
2210 // TODO: Implement a generic logic using tblgen that can support this.
2211 // Mips O32 ABI rules:
2213 // i32 - Passed in A0, A1, A2, A3 and stack
2214 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2215 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2216 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2217 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2218 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2221 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2222 //===----------------------------------------------------------------------===//
2224 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2225 MVT LocVT, CCValAssign::LocInfo LocInfo,
2226 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2228 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2230 static const uint16_t IntRegs[] = {
2231 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2233 static const uint16_t F32Regs[] = {
2234 Mips::F12, Mips::F14
2236 static const uint16_t F64Regs[] = {
2241 if (ArgFlags.isByVal()) {
2242 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
2243 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
2244 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
2245 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
2246 r < std::min(IntRegsSize, NextReg); ++r)
2247 State.AllocateReg(IntRegs[r]);
2251 // Promote i8 and i16
2252 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2254 if (ArgFlags.isSExt())
2255 LocInfo = CCValAssign::SExt;
2256 else if (ArgFlags.isZExt())
2257 LocInfo = CCValAssign::ZExt;
2259 LocInfo = CCValAssign::AExt;
2264 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2265 // is true: function is vararg, argument is 3rd or higher, there is previous
2266 // argument which is not f32 or f64.
2267 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2268 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2269 unsigned OrigAlign = ArgFlags.getOrigAlign();
2270 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2272 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2273 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2274 // If this is the first part of an i64 arg,
2275 // the allocated register must be either A0 or A2.
2276 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2277 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2279 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2280 // Allocate int register and shadow next int register. If first
2281 // available register is Mips::A1 or Mips::A3, shadow it too.
2282 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2283 if (Reg == Mips::A1 || Reg == Mips::A3)
2284 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2285 State.AllocateReg(IntRegs, IntRegsSize);
2287 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2288 // we are guaranteed to find an available float register
2289 if (ValVT == MVT::f32) {
2290 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2291 // Shadow int register
2292 State.AllocateReg(IntRegs, IntRegsSize);
2294 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2295 // Shadow int registers
2296 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2297 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2298 State.AllocateReg(IntRegs, IntRegsSize);
2299 State.AllocateReg(IntRegs, IntRegsSize);
2302 llvm_unreachable("Cannot handle this ValVT.");
2304 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
2305 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
2308 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2310 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2312 return false; // CC must always match
2315 static const uint16_t Mips64IntRegs[8] =
2316 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
2317 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
2318 static const uint16_t Mips64DPRegs[8] =
2319 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
2320 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
2322 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
2323 CCValAssign::LocInfo LocInfo,
2324 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2325 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
2326 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
2327 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
2329 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
2331 // If byval is 16-byte aligned, the first arg register must be even.
2332 if ((Align == 16) && (FirstIdx % 2)) {
2333 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
2337 // Mark the registers allocated.
2338 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
2339 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
2341 // Allocate space on caller's stack.
2342 unsigned Offset = State.AllocateStack(Size, Align);
2345 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
2348 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2353 #include "MipsGenCallingConv.inc"
2356 AnalyzeMips64CallOperands(CCState &CCInfo,
2357 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2358 unsigned NumOps = Outs.size();
2359 for (unsigned i = 0; i != NumOps; ++i) {
2360 MVT ArgVT = Outs[i].VT;
2361 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2364 if (Outs[i].IsFixed)
2365 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2367 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2371 dbgs() << "Call operand #" << i << " has unhandled type "
2372 << EVT(ArgVT).getEVTString();
2374 llvm_unreachable(0);
2379 //===----------------------------------------------------------------------===//
2380 // Call Calling Convention Implementation
2381 //===----------------------------------------------------------------------===//
2383 static const unsigned O32IntRegsSize = 4;
2385 static const uint16_t O32IntRegs[] = {
2386 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2389 // Return next O32 integer argument register.
2390 static unsigned getNextIntArgReg(unsigned Reg) {
2391 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2392 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2395 // Write ByVal Arg to arg registers and stack.
2397 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2398 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2399 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2400 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2401 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2402 MVT PtrType, bool isLittle) {
2403 unsigned LocMemOffset = VA.getLocMemOffset();
2404 unsigned Offset = 0;
2405 uint32_t RemainingSize = Flags.getByValSize();
2406 unsigned ByValAlign = Flags.getByValAlign();
2408 // Copy the first 4 words of byval arg to registers A0 - A3.
2409 // FIXME: Use a stricter alignment if it enables better optimization in passes
2411 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2412 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2413 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2414 DAG.getConstant(Offset, MVT::i32));
2415 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2416 MachinePointerInfo(), false, false, false,
2417 std::min(ByValAlign, (unsigned )4));
2418 MemOpChains.push_back(LoadVal.getValue(1));
2419 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2420 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2423 if (RemainingSize == 0)
2426 // If there still is a register available for argument passing, write the
2427 // remaining part of the structure to it using subword loads and shifts.
2428 if (LocMemOffset < 4 * 4) {
2429 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2430 "There must be one to three bytes remaining.");
2431 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2432 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2433 DAG.getConstant(Offset, MVT::i32));
2434 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2435 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2436 LoadPtr, MachinePointerInfo(),
2437 MVT::getIntegerVT(LoadSize * 8), false,
2439 MemOpChains.push_back(LoadVal.getValue(1));
2441 // If target is big endian, shift it to the most significant half-word or
2444 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2445 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2448 RemainingSize -= LoadSize;
2450 // Read second subword if necessary.
2451 if (RemainingSize != 0) {
2452 assert(RemainingSize == 1 && "There must be one byte remaining.");
2453 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2454 DAG.getConstant(Offset, MVT::i32));
2455 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2456 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2457 LoadPtr, MachinePointerInfo(),
2458 MVT::i8, false, false, Alignment);
2459 MemOpChains.push_back(Subword.getValue(1));
2460 // Insert the loaded byte to LoadVal.
2461 // FIXME: Use INS if supported by target.
2462 unsigned ShiftAmt = isLittle ? 16 : 8;
2463 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2464 DAG.getConstant(ShiftAmt, MVT::i32));
2465 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2468 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2469 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2473 // Create a fixed object on stack at offset LocMemOffset and copy
2474 // remaining part of byval arg to it using memcpy.
2475 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2476 DAG.getConstant(Offset, MVT::i32));
2477 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2478 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2479 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2480 DAG.getConstant(RemainingSize, MVT::i32),
2481 std::min(ByValAlign, (unsigned)4),
2482 /*isVolatile=*/false, /*AlwaysInline=*/false,
2483 MachinePointerInfo(0), MachinePointerInfo(0));
2486 // Copy Mips64 byVal arg to registers and stack.
2488 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2489 SmallVector<std::pair<unsigned, SDValue>, 16>& RegsToPass,
2490 SmallVector<SDValue, 8>& MemOpChains, int& LastFI,
2491 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2492 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2493 EVT PtrTy, bool isLittle) {
2494 unsigned ByValSize = Flags.getByValSize();
2495 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2496 bool IsRegLoc = VA.isRegLoc();
2497 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2498 unsigned LocMemOffset = 0;
2499 unsigned MemCpySize = ByValSize;
2502 LocMemOffset = VA.getLocMemOffset();
2504 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2506 const uint16_t *RegEnd = Mips64IntRegs + 8;
2508 // Copy double words to registers.
2509 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2510 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2511 DAG.getConstant(Offset, PtrTy));
2512 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2513 MachinePointerInfo(), false, false, false,
2515 MemOpChains.push_back(LoadVal.getValue(1));
2516 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2519 // Return if the struct has been fully copied.
2520 if (!(MemCpySize = ByValSize - Offset))
2523 // If there is an argument register available, copy the remainder of the
2524 // byval argument with sub-doubleword loads and shifts.
2525 if (Reg != RegEnd) {
2526 assert((ByValSize < Offset + 8) &&
2527 "Size of the remainder should be smaller than 8-byte.");
2529 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2530 unsigned RemSize = ByValSize - Offset;
2532 if (RemSize < LoadSize)
2535 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2536 DAG.getConstant(Offset, PtrTy));
2538 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2539 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2540 false, false, Alignment);
2541 MemOpChains.push_back(LoadVal.getValue(1));
2543 // Offset in number of bits from double word boundary.
2544 unsigned OffsetDW = (Offset % 8) * 8;
2545 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2546 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2547 DAG.getConstant(Shamt, MVT::i32));
2549 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2552 Alignment = std::min(Alignment, LoadSize);
2555 RegsToPass.push_back(std::make_pair(*Reg, Val));
2560 assert(MemCpySize && "MemCpySize must not be zero.");
2562 // Create a fixed object on stack at offset LocMemOffset and copy
2563 // remainder of byval arg to it with memcpy.
2564 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2565 DAG.getConstant(Offset, PtrTy));
2566 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2567 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2568 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2569 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2570 /*isVolatile=*/false, /*AlwaysInline=*/false,
2571 MachinePointerInfo(0), MachinePointerInfo(0));
2574 /// LowerCall - functions arguments are copied from virtual regs to
2575 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2576 /// TODO: isTailCall.
2578 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2579 SmallVectorImpl<SDValue> &InVals) const {
2580 SelectionDAG &DAG = CLI.DAG;
2581 DebugLoc &dl = CLI.DL;
2582 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2583 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2584 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2585 SDValue InChain = CLI.Chain;
2586 SDValue Callee = CLI.Callee;
2587 bool &isTailCall = CLI.IsTailCall;
2588 CallingConv::ID CallConv = CLI.CallConv;
2589 bool isVarArg = CLI.IsVarArg;
2591 // MIPs target does not yet support tail call optimization.
2594 MachineFunction &MF = DAG.getMachineFunction();
2595 MachineFrameInfo *MFI = MF.getFrameInfo();
2596 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2597 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2598 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2600 // Analyze operands of the call, assigning locations to each operand.
2601 SmallVector<CCValAssign, 16> ArgLocs;
2602 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2603 getTargetMachine(), ArgLocs, *DAG.getContext());
2605 if (CallConv == CallingConv::Fast)
2606 CCInfo.AnalyzeCallOperands(Outs, CC_Mips_FastCC);
2608 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2610 AnalyzeMips64CallOperands(CCInfo, Outs);
2612 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2614 // Get a count of how many bytes are to be pushed on the stack.
2615 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2617 // Chain is the output chain of the last Load/Store or CopyToReg node.
2618 // ByValChain is the output chain of the last Memcpy node created for copying
2619 // byval arguments to the stack.
2620 SDValue Chain, CallSeqStart, ByValChain;
2621 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2622 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2623 ByValChain = InChain;
2625 // Get the frame index of the stack frame object that points to the location
2626 // of dynamically allocated area on the stack.
2627 int DynAllocFI = MipsFI->getDynAllocFI();
2629 // Update size of the maximum argument space.
2630 // For O32, a minimum of four words (16 bytes) of argument space is
2632 if (IsO32 && (CallConv != CallingConv::Fast))
2633 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2635 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2637 if (MaxCallFrameSize < NextStackOffset) {
2638 MipsFI->setMaxCallFrameSize(NextStackOffset);
2640 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2641 // allocated stack space. These offsets must be aligned to a boundary
2642 // determined by the stack alignment of the ABI.
2643 unsigned StackAlignment = TFL->getStackAlignment();
2644 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2645 StackAlignment * StackAlignment;
2647 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2650 // With EABI is it possible to have 16 args on registers.
2651 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2652 SmallVector<SDValue, 8> MemOpChains;
2654 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2656 // Walk the register/memloc assignments, inserting copies/loads.
2657 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2658 SDValue Arg = OutVals[i];
2659 CCValAssign &VA = ArgLocs[i];
2660 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2661 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2664 if (Flags.isByVal()) {
2665 assert(Flags.getByValSize() &&
2666 "ByVal args of size 0 should have been ignored by front-end.");
2668 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2669 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2670 Subtarget->isLittle());
2672 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2673 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2674 Subtarget->isLittle());
2678 // Promote the value if needed.
2679 switch (VA.getLocInfo()) {
2680 default: llvm_unreachable("Unknown loc info!");
2681 case CCValAssign::Full:
2682 if (VA.isRegLoc()) {
2683 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2684 (ValVT == MVT::f64 && LocVT == MVT::i64))
2685 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2686 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2687 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2688 Arg, DAG.getConstant(0, MVT::i32));
2689 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2690 Arg, DAG.getConstant(1, MVT::i32));
2691 if (!Subtarget->isLittle())
2693 unsigned LocRegLo = VA.getLocReg();
2694 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2695 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2696 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2701 case CCValAssign::SExt:
2702 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2704 case CCValAssign::ZExt:
2705 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2707 case CCValAssign::AExt:
2708 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2712 // Arguments that can be passed on register must be kept at
2713 // RegsToPass vector
2714 if (VA.isRegLoc()) {
2715 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2719 // Register can't get to this point...
2720 assert(VA.isMemLoc());
2722 // Create the frame index object for this incoming parameter
2723 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2724 VA.getLocMemOffset(), true);
2725 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2727 // emit ISD::STORE whichs stores the
2728 // parameter value to a stack Location
2729 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2730 MachinePointerInfo(), false, false, 0));
2733 // Extend range of indices of frame objects for outgoing arguments that were
2734 // created during this function call. Skip this step if no such objects were
2737 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2739 // If a memcpy has been created to copy a byval arg to a stack, replace the
2740 // chain input of CallSeqStart with ByValChain.
2741 if (InChain != ByValChain)
2742 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2743 NextStackOffsetVal);
2745 // Transform all store nodes into one single node because all store
2746 // nodes are independent of each other.
2747 if (!MemOpChains.empty())
2748 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2749 &MemOpChains[0], MemOpChains.size());
2751 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2752 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2753 // node so that legalize doesn't hack it.
2754 unsigned char OpFlag;
2755 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2756 bool GlobalOrExternal = false;
2759 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2760 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2761 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2762 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2763 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2765 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2768 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2769 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2770 getPointerTy(), 0, OpFlag);
2773 GlobalOrExternal = true;
2775 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2776 if (IsN64 || (!IsO32 && IsPIC))
2777 OpFlag = MipsII::MO_GOT_DISP;
2778 else if (!IsPIC) // !N64 && static
2779 OpFlag = MipsII::MO_NO_FLAG;
2781 OpFlag = MipsII::MO_GOT_CALL;
2782 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2784 GlobalOrExternal = true;
2789 // Create nodes that load address of callee and copy it to T9
2791 if (GlobalOrExternal) {
2792 // Load callee address
2793 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2794 GetGlobalReg(DAG, getPointerTy()), Callee);
2795 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2796 Callee, MachinePointerInfo::getGOT(),
2797 false, false, false, 0);
2799 // Use GOT+LO if callee has internal linkage.
2800 if (CalleeLo.getNode()) {
2801 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2802 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2808 // T9 should contain the address of the callee function if
2809 // -reloction-model=pic or it is an indirect call.
2810 if (IsPICCall || !GlobalOrExternal) {
2812 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2813 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2814 InFlag = Chain.getValue(1);
2815 Callee = DAG.getRegister(T9Reg, getPointerTy());
2818 // Insert node "GP copy globalreg" before call to function.
2819 // Lazy-binding stubs require GP to point to the GOT.
2821 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2822 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2823 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2826 // Build a sequence of copy-to-reg nodes chained together with token
2827 // chain and flag operands which copy the outgoing args into registers.
2828 // The InFlag in necessary since all emitted instructions must be
2830 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2831 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2832 RegsToPass[i].second, InFlag);
2833 InFlag = Chain.getValue(1);
2836 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2837 // = Chain, Callee, Reg#1, Reg#2, ...
2839 // Returns a chain & a flag for retval copy to use.
2840 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2841 SmallVector<SDValue, 8> Ops;
2842 Ops.push_back(Chain);
2843 Ops.push_back(Callee);
2845 // Add argument registers to the end of the list so that they are
2846 // known live into the call.
2847 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2848 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2849 RegsToPass[i].second.getValueType()));
2851 // Add a register mask operand representing the call-preserved registers.
2852 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2853 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2854 assert(Mask && "Missing call preserved mask for calling convention");
2855 Ops.push_back(DAG.getRegisterMask(Mask));
2857 if (InFlag.getNode())
2858 Ops.push_back(InFlag);
2860 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2861 InFlag = Chain.getValue(1);
2863 // Create the CALLSEQ_END node.
2864 Chain = DAG.getCALLSEQ_END(Chain,
2865 DAG.getIntPtrConstant(NextStackOffset, true),
2866 DAG.getIntPtrConstant(0, true), InFlag);
2867 InFlag = Chain.getValue(1);
2869 // Handle result values, copying them out of physregs into vregs that we
2871 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2872 Ins, dl, DAG, InVals);
2875 /// LowerCallResult - Lower the result values of a call into the
2876 /// appropriate copies out of appropriate physical registers.
2878 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2879 CallingConv::ID CallConv, bool isVarArg,
2880 const SmallVectorImpl<ISD::InputArg> &Ins,
2881 DebugLoc dl, SelectionDAG &DAG,
2882 SmallVectorImpl<SDValue> &InVals) const {
2883 // Assign locations to each value returned by this call.
2884 SmallVector<CCValAssign, 16> RVLocs;
2885 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2886 getTargetMachine(), RVLocs, *DAG.getContext());
2888 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2890 // Copy all of the result registers out of their specified physreg.
2891 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2892 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2893 RVLocs[i].getValVT(), InFlag).getValue(1);
2894 InFlag = Chain.getValue(2);
2895 InVals.push_back(Chain.getValue(0));
2901 //===----------------------------------------------------------------------===//
2902 // Formal Arguments Calling Convention Implementation
2903 //===----------------------------------------------------------------------===//
2904 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2905 std::vector<SDValue>& OutChains,
2906 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2907 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2908 const Argument *FuncArg) {
2909 unsigned LocMem = VA.getLocMemOffset();
2910 unsigned FirstWord = LocMem / 4;
2912 // copy register A0 - A3 to frame object
2913 for (unsigned i = 0; i < NumWords; ++i) {
2914 unsigned CurWord = FirstWord + i;
2915 if (CurWord >= O32IntRegsSize)
2918 unsigned SrcReg = O32IntRegs[CurWord];
2919 unsigned Reg = AddLiveIn(MF, SrcReg, &Mips::CPURegsRegClass);
2920 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2921 DAG.getConstant(i * 4, MVT::i32));
2922 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2923 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2925 OutChains.push_back(Store);
2929 // Create frame object on stack and copy registers used for byval passing to it.
2931 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2932 std::vector<SDValue>& OutChains, SelectionDAG &DAG,
2933 const CCValAssign &VA, const ISD::ArgFlagsTy& Flags,
2934 MachineFrameInfo *MFI, bool IsRegLoc,
2935 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
2936 EVT PtrTy, const Argument *FuncArg) {
2937 const uint16_t *Reg = Mips64IntRegs + 8;
2938 int FOOffset; // Frame object offset from virtual frame pointer.
2941 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
2942 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
2945 FOOffset = VA.getLocMemOffset();
2947 // Create frame object.
2948 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
2949 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
2950 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
2951 InVals.push_back(FIN);
2953 // Copy arg registers.
2954 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
2956 unsigned VReg = AddLiveIn(MF, *Reg, &Mips::CPU64RegsRegClass);
2957 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
2958 DAG.getConstant(I * 8, PtrTy));
2959 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
2960 StorePtr, MachinePointerInfo(FuncArg, I * 8),
2962 OutChains.push_back(Store);
2968 /// LowerFormalArguments - transform physical registers into virtual registers
2969 /// and generate load operations for arguments places on the stack.
2971 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2972 CallingConv::ID CallConv,
2974 const SmallVectorImpl<ISD::InputArg> &Ins,
2975 DebugLoc dl, SelectionDAG &DAG,
2976 SmallVectorImpl<SDValue> &InVals)
2978 MachineFunction &MF = DAG.getMachineFunction();
2979 MachineFrameInfo *MFI = MF.getFrameInfo();
2980 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2982 MipsFI->setVarArgsFrameIndex(0);
2984 // Used with vargs to acumulate store chains.
2985 std::vector<SDValue> OutChains;
2987 // Assign locations to all of the incoming arguments.
2988 SmallVector<CCValAssign, 16> ArgLocs;
2989 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2990 getTargetMachine(), ArgLocs, *DAG.getContext());
2992 if (CallConv == CallingConv::Fast)
2993 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FastCC);
2995 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
2997 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
2999 Function::const_arg_iterator FuncArg =
3000 DAG.getMachineFunction().getFunction()->arg_begin();
3001 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
3003 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
3004 CCValAssign &VA = ArgLocs[i];
3005 EVT ValVT = VA.getValVT();
3006 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3007 bool IsRegLoc = VA.isRegLoc();
3009 if (Flags.isByVal()) {
3010 assert(Flags.getByValSize() &&
3011 "ByVal args of size 0 should have been ignored by front-end.");
3013 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
3014 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
3016 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3017 InVals.push_back(FIN);
3018 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
3021 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
3022 MFI, IsRegLoc, InVals, MipsFI,
3023 getPointerTy(), &*FuncArg);
3027 // Arguments stored on registers
3029 EVT RegVT = VA.getLocVT();
3030 unsigned ArgReg = VA.getLocReg();
3031 const TargetRegisterClass *RC;
3033 if (RegVT == MVT::i32)
3034 RC = &Mips::CPURegsRegClass;
3035 else if (RegVT == MVT::i64)
3036 RC = &Mips::CPU64RegsRegClass;
3037 else if (RegVT == MVT::f32)
3038 RC = &Mips::FGR32RegClass;
3039 else if (RegVT == MVT::f64)
3040 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3042 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3044 // Transform the arguments stored on
3045 // physical registers into virtual ones
3046 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3047 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3049 // If this is an 8 or 16-bit value, it has been passed promoted
3050 // to 32 bits. Insert an assert[sz]ext to capture this, then
3051 // truncate to the right size.
3052 if (VA.getLocInfo() != CCValAssign::Full) {
3053 unsigned Opcode = 0;
3054 if (VA.getLocInfo() == CCValAssign::SExt)
3055 Opcode = ISD::AssertSext;
3056 else if (VA.getLocInfo() == CCValAssign::ZExt)
3057 Opcode = ISD::AssertZext;
3059 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3060 DAG.getValueType(ValVT));
3061 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3064 // Handle floating point arguments passed in integer registers.
3065 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3066 (RegVT == MVT::i64 && ValVT == MVT::f64))
3067 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3068 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3069 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3070 getNextIntArgReg(ArgReg), RC);
3071 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3072 if (!Subtarget->isLittle())
3073 std::swap(ArgValue, ArgValue2);
3074 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3075 ArgValue, ArgValue2);
3078 InVals.push_back(ArgValue);
3079 } else { // VA.isRegLoc()
3082 assert(VA.isMemLoc());
3084 // The stack pointer offset is relative to the caller stack frame.
3085 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3086 VA.getLocMemOffset(), true);
3088 // Create load nodes to retrieve arguments from the stack
3089 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3090 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3091 MachinePointerInfo::getFixedStack(LastFI),
3092 false, false, false, 0));
3096 // The mips ABIs for returning structs by value requires that we copy
3097 // the sret argument into $v0 for the return. Save the argument into
3098 // a virtual register so that we can access it from the return points.
3099 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3100 unsigned Reg = MipsFI->getSRetReturnReg();
3102 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
3103 MipsFI->setSRetReturnReg(Reg);
3105 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3106 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3110 unsigned NumOfRegs = IsO32 ? 4 : 8;
3111 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
3112 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
3113 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
3114 const TargetRegisterClass *RC = IsO32 ?
3115 (const TargetRegisterClass*)&Mips::CPURegsRegClass :
3116 (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
3117 unsigned RegSize = RC->getSize();
3118 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
3120 // Offset of the first variable argument from stack pointer.
3121 int FirstVaArgOffset;
3123 if (IsO32 || (Idx == NumOfRegs)) {
3125 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
3127 FirstVaArgOffset = RegSlotOffset;
3129 // Record the frame index of the first variable argument
3130 // which is a value necessary to VASTART.
3131 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
3132 MipsFI->setVarArgsFrameIndex(LastFI);
3134 // Copy the integer registers that have not been used for argument passing
3135 // to the argument register save area. For O32, the save area is allocated
3136 // in the caller's stack frame, while for N32/64, it is allocated in the
3137 // callee's stack frame.
3138 for (int StackOffset = RegSlotOffset;
3139 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
3140 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
3141 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3142 MVT::getIntegerVT(RegSize * 8));
3143 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
3144 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
3145 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
3146 MachinePointerInfo(), false, false, 0));
3150 MipsFI->setLastInArgFI(LastFI);
3152 // All stores are grouped in one node to allow the matching between
3153 // the size of Ins and InVals. This only happens when on varg functions
3154 if (!OutChains.empty()) {
3155 OutChains.push_back(Chain);
3156 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3157 &OutChains[0], OutChains.size());
3163 //===----------------------------------------------------------------------===//
3164 // Return Value Calling Convention Implementation
3165 //===----------------------------------------------------------------------===//
3168 MipsTargetLowering::LowerReturn(SDValue Chain,
3169 CallingConv::ID CallConv, bool isVarArg,
3170 const SmallVectorImpl<ISD::OutputArg> &Outs,
3171 const SmallVectorImpl<SDValue> &OutVals,
3172 DebugLoc dl, SelectionDAG &DAG) const {
3174 // CCValAssign - represent the assignment of
3175 // the return value to a location
3176 SmallVector<CCValAssign, 16> RVLocs;
3178 // CCState - Info about the registers and stack slot.
3179 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3180 getTargetMachine(), RVLocs, *DAG.getContext());
3182 // Analize return values.
3183 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3185 // If this is the first return lowered for this function, add
3186 // the regs to the liveout set for the function.
3187 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3188 for (unsigned i = 0; i != RVLocs.size(); ++i)
3189 if (RVLocs[i].isRegLoc())
3190 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3195 // Copy the result values into the output registers.
3196 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3197 CCValAssign &VA = RVLocs[i];
3198 assert(VA.isRegLoc() && "Can only return in registers!");
3200 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3202 // guarantee that all emitted copies are
3203 // stuck together, avoiding something bad
3204 Flag = Chain.getValue(1);
3207 // The mips ABIs for returning structs by value requires that we copy
3208 // the sret argument into $v0 for the return. We saved the argument into
3209 // a virtual register in the entry block, so now we copy the value out
3211 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3212 MachineFunction &MF = DAG.getMachineFunction();
3213 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3214 unsigned Reg = MipsFI->getSRetReturnReg();
3217 llvm_unreachable("sret virtual register not created in the entry block");
3218 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3220 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
3221 Flag = Chain.getValue(1);
3224 // Return on Mips is always a "jr $ra"
3226 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3227 Chain, DAG.getRegister(Mips::RA, MVT::i32), Flag);
3229 return DAG.getNode(MipsISD::Ret, dl, MVT::Other,
3230 Chain, DAG.getRegister(Mips::RA, MVT::i32));
3233 //===----------------------------------------------------------------------===//
3234 // Mips Inline Assembly Support
3235 //===----------------------------------------------------------------------===//
3237 /// getConstraintType - Given a constraint letter, return the type of
3238 /// constraint it is for this target.
3239 MipsTargetLowering::ConstraintType MipsTargetLowering::
3240 getConstraintType(const std::string &Constraint) const
3242 // Mips specific constrainy
3243 // GCC config/mips/constraints.md
3245 // 'd' : An address register. Equivalent to r
3246 // unless generating MIPS16 code.
3247 // 'y' : Equivalent to r; retained for
3248 // backwards compatibility.
3249 // 'c' : A register suitable for use in an indirect
3250 // jump. This will always be $25 for -mabicalls.
3251 // 'l' : The lo register. 1 word storage.
3252 // 'x' : The hilo register pair. Double word storage.
3253 if (Constraint.size() == 1) {
3254 switch (Constraint[0]) {
3262 return C_RegisterClass;
3265 return TargetLowering::getConstraintType(Constraint);
3268 /// Examine constraint type and operand type and determine a weight value.
3269 /// This object must already have been set up with the operand type
3270 /// and the current alternative constraint selected.
3271 TargetLowering::ConstraintWeight
3272 MipsTargetLowering::getSingleConstraintMatchWeight(
3273 AsmOperandInfo &info, const char *constraint) const {
3274 ConstraintWeight weight = CW_Invalid;
3275 Value *CallOperandVal = info.CallOperandVal;
3276 // If we don't have a value, we can't do a match,
3277 // but allow it at the lowest weight.
3278 if (CallOperandVal == NULL)
3280 Type *type = CallOperandVal->getType();
3281 // Look at the constraint type.
3282 switch (*constraint) {
3284 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3288 if (type->isIntegerTy())
3289 weight = CW_Register;
3292 if (type->isFloatTy())
3293 weight = CW_Register;
3295 case 'c': // $25 for indirect jumps
3296 case 'l': // lo register
3297 case 'x': // hilo register pair
3298 if (type->isIntegerTy())
3299 weight = CW_SpecificReg;
3301 case 'I': // signed 16 bit immediate
3302 case 'J': // integer zero
3303 case 'K': // unsigned 16 bit immediate
3304 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3305 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3306 case 'O': // signed 15 bit immediate (+- 16383)
3307 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3308 if (isa<ConstantInt>(CallOperandVal))
3309 weight = CW_Constant;
3315 /// Given a register class constraint, like 'r', if this corresponds directly
3316 /// to an LLVM register class, return a register of 0 and the register class
3318 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3319 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3321 if (Constraint.size() == 1) {
3322 switch (Constraint[0]) {
3323 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3324 case 'y': // Same as 'r'. Exists for compatibility.
3326 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
3327 return std::make_pair(0U, &Mips::CPURegsRegClass);
3328 if (VT == MVT::i64 && HasMips64)
3329 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3330 // This will generate an error message
3331 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3334 return std::make_pair(0U, &Mips::FGR32RegClass);
3335 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3336 if (Subtarget->isFP64bit())
3337 return std::make_pair(0U, &Mips::FGR64RegClass);
3338 return std::make_pair(0U, &Mips::AFGR64RegClass);
3341 case 'c': // register suitable for indirect jump
3343 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3344 assert(VT == MVT::i64 && "Unexpected type.");
3345 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3346 case 'l': // register suitable for indirect jump
3348 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3349 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3350 case 'x': // register suitable for indirect jump
3351 // Fixme: Not triggering the use of both hi and low
3352 // This will generate an error message
3353 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3356 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3359 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3360 /// vector. If it is invalid, don't add anything to Ops.
3361 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3362 std::string &Constraint,
3363 std::vector<SDValue>&Ops,
3364 SelectionDAG &DAG) const {
3365 SDValue Result(0, 0);
3367 // Only support length 1 constraints for now.
3368 if (Constraint.length() > 1) return;
3370 char ConstraintLetter = Constraint[0];
3371 switch (ConstraintLetter) {
3372 default: break; // This will fall through to the generic implementation
3373 case 'I': // Signed 16 bit constant
3374 // If this fails, the parent routine will give an error
3375 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3376 EVT Type = Op.getValueType();
3377 int64_t Val = C->getSExtValue();
3378 if (isInt<16>(Val)) {
3379 Result = DAG.getTargetConstant(Val, Type);
3384 case 'J': // integer zero
3385 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3386 EVT Type = Op.getValueType();
3387 int64_t Val = C->getZExtValue();
3389 Result = DAG.getTargetConstant(0, Type);
3394 case 'K': // unsigned 16 bit immediate
3395 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3396 EVT Type = Op.getValueType();
3397 uint64_t Val = (uint64_t)C->getZExtValue();
3398 if (isUInt<16>(Val)) {
3399 Result = DAG.getTargetConstant(Val, Type);
3404 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3405 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3406 EVT Type = Op.getValueType();
3407 int64_t Val = C->getSExtValue();
3408 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3409 Result = DAG.getTargetConstant(Val, Type);
3414 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3415 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3416 EVT Type = Op.getValueType();
3417 int64_t Val = C->getSExtValue();
3418 if ((Val >= -65535) && (Val <= -1)) {
3419 Result = DAG.getTargetConstant(Val, Type);
3424 case 'O': // signed 15 bit immediate
3425 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3426 EVT Type = Op.getValueType();
3427 int64_t Val = C->getSExtValue();
3428 if ((isInt<15>(Val))) {
3429 Result = DAG.getTargetConstant(Val, Type);
3434 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3435 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3436 EVT Type = Op.getValueType();
3437 int64_t Val = C->getSExtValue();
3438 if ((Val <= 65535) && (Val >= 1)) {
3439 Result = DAG.getTargetConstant(Val, Type);
3446 if (Result.getNode()) {
3447 Ops.push_back(Result);
3451 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3455 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3456 // The Mips target isn't yet aware of offsets.
3460 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3461 unsigned SrcAlign, bool IsZeroVal,
3463 MachineFunction &MF) const {
3464 if (Subtarget->hasMips64())
3470 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3471 if (VT != MVT::f32 && VT != MVT::f64)
3473 if (Imm.isNegZero())
3475 return Imm.isZero();
3478 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3480 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3482 return TargetLowering::getJumpTableEncoding();