1 //===-- MipsISelDAGToDAG.cpp - A Dag to Dag Inst Selector for Mips --------===//
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 an instruction selector for the MIPS target.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "mips-isel"
16 #include "MipsAnalyzeImmediate.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsRegisterInfo.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MCTargetDesc/MipsBaseInfo.h"
22 #include "llvm/GlobalValue.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Intrinsics.h"
25 #include "llvm/Support/CFG.h"
26 #include "llvm/Type.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/SelectionDAGISel.h"
33 #include "llvm/CodeGen/SelectionDAGNodes.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
40 //===----------------------------------------------------------------------===//
41 // Instruction Selector Implementation
42 //===----------------------------------------------------------------------===//
44 //===----------------------------------------------------------------------===//
45 // MipsDAGToDAGISel - MIPS specific code to select MIPS machine
46 // instructions for SelectionDAG operations.
47 //===----------------------------------------------------------------------===//
50 class MipsDAGToDAGISel : public SelectionDAGISel {
52 /// TM - Keep a reference to MipsTargetMachine.
53 MipsTargetMachine &TM;
55 /// Subtarget - Keep a pointer to the MipsSubtarget around so that we can
56 /// make the right decision when generating code for different targets.
57 const MipsSubtarget &Subtarget;
60 explicit MipsDAGToDAGISel(MipsTargetMachine &tm) :
62 TM(tm), Subtarget(tm.getSubtarget<MipsSubtarget>()) {}
65 virtual const char *getPassName() const {
66 return "MIPS DAG->DAG Pattern Instruction Selection";
69 virtual bool runOnMachineFunction(MachineFunction &MF);
72 // Include the pieces autogenerated from the target description.
73 #include "MipsGenDAGISel.inc"
75 /// getTargetMachine - Return a reference to the TargetMachine, casted
76 /// to the target-specific type.
77 const MipsTargetMachine &getTargetMachine() {
78 return static_cast<const MipsTargetMachine &>(TM);
81 /// getInstrInfo - Return a reference to the TargetInstrInfo, casted
82 /// to the target-specific type.
83 const MipsInstrInfo *getInstrInfo() {
84 return getTargetMachine().getInstrInfo();
87 SDNode *getGlobalBaseReg();
89 std::pair<SDNode*, SDNode*> SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl,
90 EVT Ty, bool HasLo, bool HasHi);
92 SDNode *Select(SDNode *N);
95 bool SelectAddr(SDNode *Parent, SDValue N, SDValue &Base, SDValue &Offset);
97 // getImm - Return a target constant with the specified value.
98 inline SDValue getImm(const SDNode *Node, unsigned Imm) {
99 return CurDAG->getTargetConstant(Imm, Node->getValueType(0));
102 void ProcessFunctionAfterISel(MachineFunction &MF);
103 bool ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI, const MachineInstr&);
104 void InitGlobalBaseReg(MachineFunction &MF);
106 virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
108 std::vector<SDValue> &OutOps);
113 // Insert instructions to initialize the global base register in the
114 // first MBB of the function. When the ABI is O32 and the relocation model is
115 // PIC, the necessary instructions are emitted later to prevent optimization
116 // passes from moving them.
117 void MipsDAGToDAGISel::InitGlobalBaseReg(MachineFunction &MF) {
118 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
120 if (((MF.getTarget().getRelocationModel() == Reloc::Static) ||
121 Subtarget.inMips16Mode()) && !MipsFI->globalBaseRegSet())
124 MachineBasicBlock &MBB = MF.front();
125 MachineBasicBlock::iterator I = MBB.begin();
126 MachineRegisterInfo &RegInfo = MF.getRegInfo();
127 const MipsRegisterInfo *TargetRegInfo = TM.getRegisterInfo();
128 const MipsInstrInfo *MII = TM.getInstrInfo();
129 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
130 DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
131 unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
134 if (!Subtarget.inMips16Mode())
135 FI= MipsFI->initGlobalRegFI();
137 const TargetRegisterClass *RC = Subtarget.isABI_N64() ?
138 (const TargetRegisterClass*)&Mips::CPU64RegsRegClass :
139 (const TargetRegisterClass*)&Mips::CPURegsRegClass;
141 V0 = RegInfo.createVirtualRegister(RC);
142 V1 = RegInfo.createVirtualRegister(RC);
144 if (Subtarget.isABI_N64()) {
145 MF.getRegInfo().addLiveIn(Mips::T9_64);
146 MBB.addLiveIn(Mips::T9_64);
148 // lui $v0, %hi(%neg(%gp_rel(fname)))
149 // daddu $v1, $v0, $t9
150 // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
151 const GlobalValue *FName = MF.getFunction();
152 BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
153 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
154 BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0)
155 .addReg(Mips::T9_64);
156 BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
157 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
158 MII->storeRegToStackSlot(MBB, I, GlobalBaseReg, false, FI, RC,
163 if (MF.getTarget().getRelocationModel() == Reloc::Static) {
164 // Set global register to __gnu_local_gp.
166 // lui $v0, %hi(__gnu_local_gp)
167 // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
168 BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
169 .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
170 BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
171 .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
172 MII->storeRegToStackSlot(MBB, I, GlobalBaseReg, false, FI, RC,
177 MF.getRegInfo().addLiveIn(Mips::T9);
178 MBB.addLiveIn(Mips::T9);
180 if (Subtarget.isABI_N32()) {
181 // lui $v0, %hi(%neg(%gp_rel(fname)))
182 // addu $v1, $v0, $t9
183 // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
184 const GlobalValue *FName = MF.getFunction();
185 BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
186 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
187 BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
188 BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
189 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
190 MII->storeRegToStackSlot(MBB, I, GlobalBaseReg, false, FI, RC,
195 assert(Subtarget.isABI_O32());
197 if (Subtarget.inMips16Mode())
198 return; // no need to load GP. It can be calculated anywhere
201 // For O32 ABI, the following instruction sequence is emitted to initialize
202 // the global base register:
204 // 0. lui $2, %hi(_gp_disp)
205 // 1. addiu $2, $2, %lo(_gp_disp)
206 // 2. addu $globalbasereg, $2, $t9
208 // We emit only the last instruction here.
210 // GNU linker requires that the first two instructions appear at the beginning
211 // of a function and no instructions be inserted before or between them.
212 // The two instructions are emitted during lowering to MC layer in order to
213 // avoid any reordering.
215 // Register $2 (Mips::V0) is added to the list of live-in registers to ensure
216 // the value instruction 1 (addiu) defines is valid when instruction 2 (addu)
218 MF.getRegInfo().addLiveIn(Mips::V0);
219 MBB.addLiveIn(Mips::V0);
220 BuildMI(MBB, I, DL, TII.get(Mips::ADDu), GlobalBaseReg)
221 .addReg(Mips::V0).addReg(Mips::T9);
222 MII->storeRegToStackSlot(MBB, I, GlobalBaseReg, false, FI, RC, TargetRegInfo);
225 bool MipsDAGToDAGISel::ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI,
226 const MachineInstr& MI) {
227 unsigned DstReg = 0, ZeroReg = 0;
229 // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
230 if ((MI.getOpcode() == Mips::ADDiu) &&
231 (MI.getOperand(1).getReg() == Mips::ZERO) &&
232 (MI.getOperand(2).getImm() == 0)) {
233 DstReg = MI.getOperand(0).getReg();
234 ZeroReg = Mips::ZERO;
235 } else if ((MI.getOpcode() == Mips::DADDiu) &&
236 (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
237 (MI.getOperand(2).getImm() == 0)) {
238 DstReg = MI.getOperand(0).getReg();
239 ZeroReg = Mips::ZERO_64;
245 // Replace uses with ZeroReg.
246 for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
247 E = MRI->use_end(); U != E; ++U) {
248 MachineOperand &MO = U.getOperand();
249 MachineInstr *MI = MO.getParent();
251 // Do not replace if it is a phi's operand or is tied to def operand.
252 if (MI->isPHI() || MI->isRegTiedToDefOperand(U.getOperandNo()) ||
262 void MipsDAGToDAGISel::ProcessFunctionAfterISel(MachineFunction &MF) {
263 InitGlobalBaseReg(MF);
265 MachineRegisterInfo *MRI = &MF.getRegInfo();
267 for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
269 for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I)
270 ReplaceUsesWithZeroReg(MRI, *I);
273 bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
274 bool Ret = SelectionDAGISel::runOnMachineFunction(MF);
276 ProcessFunctionAfterISel(MF);
281 /// getGlobalBaseReg - Output the instructions required to put the
282 /// GOT address into a register.
283 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
284 unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
285 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
288 /// ComplexPattern used on MipsInstrInfo
289 /// Used on Mips Load/Store instructions
290 bool MipsDAGToDAGISel::
291 SelectAddr(SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset) {
292 EVT ValTy = Addr.getValueType();
294 // If Parent is an unaligned f32 load or store, select a (base + index)
295 // floating point load/store instruction (luxc1 or suxc1).
296 const LSBaseSDNode *LS = 0;
298 if (Parent && (LS = dyn_cast<LSBaseSDNode>(Parent))) {
299 EVT VT = LS->getMemoryVT();
301 if (VT.getSizeInBits() / 8 > LS->getAlignment()) {
302 assert(TLI.allowsUnalignedMemoryAccesses(VT) &&
303 "Unaligned loads/stores not supported for this type.");
309 // if Address is FI, get the TargetFrameIndex.
310 if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
311 Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
312 Offset = CurDAG->getTargetConstant(0, ValTy);
316 // on PIC code Load GA
317 if (Addr.getOpcode() == MipsISD::Wrapper) {
318 Base = Addr.getOperand(0);
319 Offset = Addr.getOperand(1);
323 if (TM.getRelocationModel() != Reloc::PIC_) {
324 if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
325 Addr.getOpcode() == ISD::TargetGlobalAddress))
329 // Addresses of the form FI+const or FI|const
330 if (CurDAG->isBaseWithConstantOffset(Addr)) {
331 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
332 if (isInt<16>(CN->getSExtValue())) {
334 // If the first operand is a FI, get the TargetFI Node
335 if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
336 (Addr.getOperand(0)))
337 Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
339 Base = Addr.getOperand(0);
341 Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
346 // Operand is a result from an ADD.
347 if (Addr.getOpcode() == ISD::ADD) {
348 // When loading from constant pools, load the lower address part in
349 // the instruction itself. Example, instead of:
350 // lui $2, %hi($CPI1_0)
351 // addiu $2, $2, %lo($CPI1_0)
354 // lui $2, %hi($CPI1_0)
355 // lwc1 $f0, %lo($CPI1_0)($2)
356 if (Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
357 SDValue LoVal = Addr.getOperand(1), Opnd0 = LoVal.getOperand(0);
358 if (isa<ConstantPoolSDNode>(Opnd0) || isa<GlobalAddressSDNode>(Opnd0) ||
359 isa<JumpTableSDNode>(Opnd0)) {
360 Base = Addr.getOperand(0);
366 // If an indexed floating point load/store can be emitted, return false.
368 (LS->getMemoryVT() == MVT::f32 || LS->getMemoryVT() == MVT::f64) &&
369 Subtarget.hasMips32r2Or64())
374 Offset = CurDAG->getTargetConstant(0, ValTy);
378 /// Select multiply instructions.
379 std::pair<SDNode*, SDNode*>
380 MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty,
381 bool HasLo, bool HasHi) {
382 SDNode *Lo = 0, *Hi = 0;
383 SDNode *Mul = CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand(0),
385 SDValue InFlag = SDValue(Mul, 0);
388 Lo = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64, dl,
389 Ty, MVT::Glue, InFlag);
390 InFlag = SDValue(Lo, 1);
393 Hi = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64, dl,
396 return std::make_pair(Lo, Hi);
400 /// Select instructions not customized! Used for
401 /// expanded, promoted and normal instructions
402 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
403 unsigned Opcode = Node->getOpcode();
404 DebugLoc dl = Node->getDebugLoc();
406 // Dump information about the Node being selected
407 DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
409 // If we have a custom node, we already have selected!
410 if (Node->isMachineOpcode()) {
411 DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
416 // Instruction Selection not handled by the auto-generated
417 // tablegen selection should be handled here.
419 EVT NodeTy = Node->getValueType(0);
427 SDValue InFlag = Node->getOperand(2), CmpLHS;
428 unsigned Opc = InFlag.getOpcode(); (void)Opc;
429 assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
430 (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
431 "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
434 if (Opcode == ISD::ADDE) {
435 CmpLHS = InFlag.getValue(0);
438 CmpLHS = InFlag.getOperand(0);
442 SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
444 SDValue LHS = Node->getOperand(0);
445 SDValue RHS = Node->getOperand(1);
447 EVT VT = LHS.getValueType();
448 SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
449 SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
450 SDValue(Carry,0), RHS);
452 return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
453 LHS, SDValue(AddCarry,0));
456 /// Mul with two results
458 case ISD::UMUL_LOHI: {
459 if (NodeTy == MVT::i32)
460 MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
462 MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
464 std::pair<SDNode*, SDNode*> LoHi = SelectMULT(Node, MultOpc, dl, NodeTy,
467 if (!SDValue(Node, 0).use_empty())
468 ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
470 if (!SDValue(Node, 1).use_empty())
471 ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
478 // Mips32 has a 32-bit three operand mul instruction.
479 if (Subtarget.hasMips32() && NodeTy == MVT::i32)
481 return SelectMULT(Node, NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT,
482 dl, NodeTy, true, false).first;
486 if (NodeTy == MVT::i32)
487 MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
489 MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
491 return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
494 // Get target GOT address.
495 case ISD::GLOBAL_OFFSET_TABLE:
496 return getGlobalBaseReg();
498 case ISD::ConstantFP: {
499 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
500 if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
501 if (Subtarget.hasMips64()) {
502 SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
503 Mips::ZERO_64, MVT::i64);
504 return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
507 SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
508 Mips::ZERO, MVT::i32);
509 return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
515 case ISD::Constant: {
516 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
517 unsigned Size = CN->getValueSizeInBits(0);
522 MipsAnalyzeImmediate AnalyzeImm;
523 int64_t Imm = CN->getSExtValue();
525 const MipsAnalyzeImmediate::InstSeq &Seq =
526 AnalyzeImm.Analyze(Imm, Size, false);
528 MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
529 DebugLoc DL = CN->getDebugLoc();
531 SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
534 // The first instruction can be a LUi which is different from other
535 // instructions (ADDiu, ORI and SLL) in that it does not have a register
537 if (Inst->Opc == Mips::LUi64)
538 RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
541 CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
542 CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
545 // The remaining instructions in the sequence are handled here.
546 for (++Inst; Inst != Seq.end(); ++Inst) {
547 ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
549 RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
550 SDValue(RegOpnd, 0), ImmOpnd);
556 case MipsISD::ThreadPointer: {
557 EVT PtrVT = TLI.getPointerTy();
558 unsigned RdhwrOpc, SrcReg, DestReg;
560 if (PtrVT == MVT::i32) {
561 RdhwrOpc = Mips::RDHWR;
562 SrcReg = Mips::HWR29;
565 RdhwrOpc = Mips::RDHWR64;
566 SrcReg = Mips::HWR29_64;
567 DestReg = Mips::V1_64;
571 CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
572 Node->getValueType(0),
573 CurDAG->getRegister(SrcReg, PtrVT));
574 SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
576 SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
577 ReplaceUses(SDValue(Node, 0), ResNode);
578 return ResNode.getNode();
582 // Select the default instruction
583 SDNode *ResNode = SelectCode(Node);
585 DEBUG(errs() << "=> ");
586 if (ResNode == NULL || ResNode == Node)
587 DEBUG(Node->dump(CurDAG));
589 DEBUG(ResNode->dump(CurDAG));
590 DEBUG(errs() << "\n");
594 bool MipsDAGToDAGISel::
595 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
596 std::vector<SDValue> &OutOps) {
597 assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
598 OutOps.push_back(Op);
602 /// createMipsISelDag - This pass converts a legalized DAG into a
603 /// MIPS-specific DAG, ready for instruction scheduling.
604 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
605 return new MipsDAGToDAGISel(TM);