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 (!MipsFI->globalBaseRegSet())
123 MachineBasicBlock &MBB = MF.front();
124 MachineBasicBlock::iterator I = MBB.begin();
125 MachineRegisterInfo &RegInfo = MF.getRegInfo();
126 const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo();
127 DebugLoc DL = I != MBB.end() ? I->getDebugLoc() : DebugLoc();
128 unsigned V0, V1, GlobalBaseReg = MipsFI->getGlobalBaseReg();
129 bool FixGlobalBaseReg = MipsFI->globalBaseRegFixed();
131 if (Subtarget.isABI_O32() && FixGlobalBaseReg)
132 // $gp is the global base register.
133 V0 = V1 = GlobalBaseReg;
135 const TargetRegisterClass *RC;
136 RC = Subtarget.isABI_N64() ?
137 Mips::CPU64RegsRegisterClass : Mips::CPURegsRegisterClass;
139 V0 = RegInfo.createVirtualRegister(RC);
140 V1 = RegInfo.createVirtualRegister(RC);
143 if (Subtarget.isABI_N64()) {
144 MF.getRegInfo().addLiveIn(Mips::T9_64);
146 // lui $v0, %hi(%neg(%gp_rel(fname)))
147 // daddu $v1, $v0, $t9
148 // daddiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
149 const GlobalValue *FName = MF.getFunction();
150 BuildMI(MBB, I, DL, TII.get(Mips::LUi64), V0)
151 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
152 BuildMI(MBB, I, DL, TII.get(Mips::DADDu), V1).addReg(V0).addReg(Mips::T9_64);
153 BuildMI(MBB, I, DL, TII.get(Mips::DADDiu), GlobalBaseReg).addReg(V1)
154 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
155 } else if (MF.getTarget().getRelocationModel() == Reloc::Static) {
156 // Set global register to __gnu_local_gp.
158 // lui $v0, %hi(__gnu_local_gp)
159 // addiu $globalbasereg, $v0, %lo(__gnu_local_gp)
160 BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
161 .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_HI);
162 BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V0)
163 .addExternalSymbol("__gnu_local_gp", MipsII::MO_ABS_LO);
165 MF.getRegInfo().addLiveIn(Mips::T9);
167 if (Subtarget.isABI_N32()) {
168 // lui $v0, %hi(%neg(%gp_rel(fname)))
169 // addu $v1, $v0, $t9
170 // addiu $globalbasereg, $v1, %lo(%neg(%gp_rel(fname)))
171 const GlobalValue *FName = MF.getFunction();
172 BuildMI(MBB, I, DL, TII.get(Mips::LUi), V0)
173 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_HI);
174 BuildMI(MBB, I, DL, TII.get(Mips::ADDu), V1).addReg(V0).addReg(Mips::T9);
175 BuildMI(MBB, I, DL, TII.get(Mips::ADDiu), GlobalBaseReg).addReg(V1)
176 .addGlobalAddress(FName, 0, MipsII::MO_GPOFF_LO);
177 } else if (!MipsFI->globalBaseRegFixed()) {
178 assert(Subtarget.isABI_O32());
180 BuildMI(MBB, I, DL, TII.get(Mips::SETGP2), GlobalBaseReg)
186 bool MipsDAGToDAGISel::ReplaceUsesWithZeroReg(MachineRegisterInfo *MRI,
187 const MachineInstr& MI) {
188 unsigned DstReg = 0, ZeroReg = 0;
190 // Check if MI is "addiu $dst, $zero, 0" or "daddiu $dst, $zero, 0".
191 if ((MI.getOpcode() == Mips::ADDiu) &&
192 (MI.getOperand(1).getReg() == Mips::ZERO) &&
193 (MI.getOperand(2).getImm() == 0)) {
194 DstReg = MI.getOperand(0).getReg();
195 ZeroReg = Mips::ZERO;
196 } else if ((MI.getOpcode() == Mips::DADDiu) &&
197 (MI.getOperand(1).getReg() == Mips::ZERO_64) &&
198 (MI.getOperand(2).getImm() == 0)) {
199 DstReg = MI.getOperand(0).getReg();
200 ZeroReg = Mips::ZERO_64;
206 // Replace uses with ZeroReg.
207 for (MachineRegisterInfo::use_iterator U = MRI->use_begin(DstReg),
208 E = MRI->use_end(); U != E; ++U) {
209 MachineOperand &MO = U.getOperand();
210 MachineInstr *MI = MO.getParent();
212 // Do not replace if it is a phi's operand or is tied to def operand.
213 if (MI->isPHI() || MI->isRegTiedToDefOperand(U.getOperandNo()))
222 void MipsDAGToDAGISel::ProcessFunctionAfterISel(MachineFunction &MF) {
223 InitGlobalBaseReg(MF);
225 MachineRegisterInfo *MRI = &MF.getRegInfo();
227 for (MachineFunction::iterator MFI = MF.begin(), MFE = MF.end(); MFI != MFE;
229 for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I)
230 ReplaceUsesWithZeroReg(MRI, *I);
233 bool MipsDAGToDAGISel::runOnMachineFunction(MachineFunction &MF) {
234 bool Ret = SelectionDAGISel::runOnMachineFunction(MF);
236 ProcessFunctionAfterISel(MF);
241 /// getGlobalBaseReg - Output the instructions required to put the
242 /// GOT address into a register.
243 SDNode *MipsDAGToDAGISel::getGlobalBaseReg() {
244 unsigned GlobalBaseReg = MF->getInfo<MipsFunctionInfo>()->getGlobalBaseReg();
245 return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode();
248 /// ComplexPattern used on MipsInstrInfo
249 /// Used on Mips Load/Store instructions
250 bool MipsDAGToDAGISel::
251 SelectAddr(SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset) {
252 EVT ValTy = Addr.getValueType();
254 // If Parent is an unaligned f32 load or store, select a (base + index)
255 // floating point load/store instruction (luxc1 or suxc1).
256 const LSBaseSDNode* LS = 0;
258 if (Parent && (LS = dyn_cast<LSBaseSDNode>(Parent))) {
259 EVT VT = LS->getMemoryVT();
261 if (VT.getSizeInBits() / 8 > LS->getAlignment()) {
262 assert(TLI.allowsUnalignedMemoryAccesses(VT) &&
263 "Unaligned loads/stores not supported for this type.");
269 // if Address is FI, get the TargetFrameIndex.
270 if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) {
271 Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
272 Offset = CurDAG->getTargetConstant(0, ValTy);
276 // on PIC code Load GA
277 if (Addr.getOpcode() == MipsISD::Wrapper) {
278 Base = Addr.getOperand(0);
279 Offset = Addr.getOperand(1);
283 if (TM.getRelocationModel() != Reloc::PIC_) {
284 if ((Addr.getOpcode() == ISD::TargetExternalSymbol ||
285 Addr.getOpcode() == ISD::TargetGlobalAddress))
289 // Addresses of the form FI+const or FI|const
290 if (CurDAG->isBaseWithConstantOffset(Addr)) {
291 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1));
292 if (isInt<16>(CN->getSExtValue())) {
294 // If the first operand is a FI, get the TargetFI Node
295 if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>
296 (Addr.getOperand(0)))
297 Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy);
299 Base = Addr.getOperand(0);
301 Offset = CurDAG->getTargetConstant(CN->getZExtValue(), ValTy);
306 // Operand is a result from an ADD.
307 if (Addr.getOpcode() == ISD::ADD) {
308 // When loading from constant pools, load the lower address part in
309 // the instruction itself. Example, instead of:
310 // lui $2, %hi($CPI1_0)
311 // addiu $2, $2, %lo($CPI1_0)
314 // lui $2, %hi($CPI1_0)
315 // lwc1 $f0, %lo($CPI1_0)($2)
316 if (Addr.getOperand(1).getOpcode() == MipsISD::Lo) {
317 SDValue LoVal = Addr.getOperand(1);
318 if (isa<ConstantPoolSDNode>(LoVal.getOperand(0)) ||
319 isa<GlobalAddressSDNode>(LoVal.getOperand(0))) {
320 Base = Addr.getOperand(0);
321 Offset = LoVal.getOperand(0);
326 // If an indexed floating point load/store can be emitted, return false.
327 if (LS && (LS->getMemoryVT() == MVT::f32 || LS->getMemoryVT() == MVT::f64) &&
328 Subtarget.hasMips32r2Or64())
333 Offset = CurDAG->getTargetConstant(0, ValTy);
337 /// Select multiply instructions.
338 std::pair<SDNode*, SDNode*>
339 MipsDAGToDAGISel::SelectMULT(SDNode *N, unsigned Opc, DebugLoc dl, EVT Ty,
340 bool HasLo, bool HasHi) {
341 SDNode *Lo = 0, *Hi = 0;
342 SDNode *Mul = CurDAG->getMachineNode(Opc, dl, MVT::Glue, N->getOperand(0),
344 SDValue InFlag = SDValue(Mul, 0);
347 Lo = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFLO : Mips::MFLO64, dl,
348 Ty, MVT::Glue, InFlag);
349 InFlag = SDValue(Lo, 1);
352 Hi = CurDAG->getMachineNode(Ty == MVT::i32 ? Mips::MFHI : Mips::MFHI64, dl,
355 return std::make_pair(Lo, Hi);
359 /// Select instructions not customized! Used for
360 /// expanded, promoted and normal instructions
361 SDNode* MipsDAGToDAGISel::Select(SDNode *Node) {
362 unsigned Opcode = Node->getOpcode();
363 DebugLoc dl = Node->getDebugLoc();
365 // Dump information about the Node being selected
366 DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n");
368 // If we have a custom node, we already have selected!
369 if (Node->isMachineOpcode()) {
370 DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n");
375 // Instruction Selection not handled by the auto-generated
376 // tablegen selection should be handled here.
378 EVT NodeTy = Node->getValueType(0);
386 SDValue InFlag = Node->getOperand(2), CmpLHS;
387 unsigned Opc = InFlag.getOpcode(); (void)Opc;
388 assert(((Opc == ISD::ADDC || Opc == ISD::ADDE) ||
389 (Opc == ISD::SUBC || Opc == ISD::SUBE)) &&
390 "(ADD|SUB)E flag operand must come from (ADD|SUB)C/E insn");
393 if (Opcode == ISD::ADDE) {
394 CmpLHS = InFlag.getValue(0);
397 CmpLHS = InFlag.getOperand(0);
401 SDValue Ops[] = { CmpLHS, InFlag.getOperand(1) };
403 SDValue LHS = Node->getOperand(0);
404 SDValue RHS = Node->getOperand(1);
406 EVT VT = LHS.getValueType();
407 SDNode *Carry = CurDAG->getMachineNode(Mips::SLTu, dl, VT, Ops, 2);
408 SDNode *AddCarry = CurDAG->getMachineNode(Mips::ADDu, dl, VT,
409 SDValue(Carry,0), RHS);
411 return CurDAG->SelectNodeTo(Node, MOp, VT, MVT::Glue,
412 LHS, SDValue(AddCarry,0));
415 /// Mul with two results
417 case ISD::UMUL_LOHI: {
418 if (NodeTy == MVT::i32)
419 MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::MULTu : Mips::MULT);
421 MultOpc = (Opcode == ISD::UMUL_LOHI ? Mips::DMULTu : Mips::DMULT);
423 std::pair<SDNode*, SDNode*> LoHi = SelectMULT(Node, MultOpc, dl, NodeTy,
426 if (!SDValue(Node, 0).use_empty())
427 ReplaceUses(SDValue(Node, 0), SDValue(LoHi.first, 0));
429 if (!SDValue(Node, 1).use_empty())
430 ReplaceUses(SDValue(Node, 1), SDValue(LoHi.second, 0));
437 // Mips32 has a 32-bit three operand mul instruction.
438 if (Subtarget.hasMips32() && NodeTy == MVT::i32)
440 return SelectMULT(Node, NodeTy == MVT::i32 ? Mips::MULT : Mips::DMULT,
441 dl, NodeTy, true, false).first;
445 if (NodeTy == MVT::i32)
446 MultOpc = (Opcode == ISD::MULHU ? Mips::MULTu : Mips::MULT);
448 MultOpc = (Opcode == ISD::MULHU ? Mips::DMULTu : Mips::DMULT);
450 return SelectMULT(Node, MultOpc, dl, NodeTy, false, true).second;
453 // Get target GOT address.
454 case ISD::GLOBAL_OFFSET_TABLE:
455 return getGlobalBaseReg();
457 case ISD::ConstantFP: {
458 ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(Node);
459 if (Node->getValueType(0) == MVT::f64 && CN->isExactlyValue(+0.0)) {
460 if (Subtarget.hasMips64()) {
461 SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
462 Mips::ZERO_64, MVT::i64);
463 return CurDAG->getMachineNode(Mips::DMTC1, dl, MVT::f64, Zero);
466 SDValue Zero = CurDAG->getCopyFromReg(CurDAG->getEntryNode(), dl,
467 Mips::ZERO, MVT::i32);
468 return CurDAG->getMachineNode(Mips::BuildPairF64, dl, MVT::f64, Zero,
474 case ISD::Constant: {
475 const ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node);
476 unsigned Size = CN->getValueSizeInBits(0);
481 MipsAnalyzeImmediate AnalyzeImm;
482 int64_t Imm = CN->getSExtValue();
484 const MipsAnalyzeImmediate::InstSeq &Seq =
485 AnalyzeImm.Analyze(Imm, Size, false);
487 MipsAnalyzeImmediate::InstSeq::const_iterator Inst = Seq.begin();
488 DebugLoc DL = CN->getDebugLoc();
490 SDValue ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
493 // The first instruction can be a LUi which is different from other
494 // instructions (ADDiu, ORI and SLL) in that it does not have a register
496 if (Inst->Opc == Mips::LUi64)
497 RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64, ImmOpnd);
500 CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
501 CurDAG->getRegister(Mips::ZERO_64, MVT::i64),
504 // The remaining instructions in the sequence are handled here.
505 for (++Inst; Inst != Seq.end(); ++Inst) {
506 ImmOpnd = CurDAG->getTargetConstant(SignExtend64<16>(Inst->ImmOpnd),
508 RegOpnd = CurDAG->getMachineNode(Inst->Opc, DL, MVT::i64,
509 SDValue(RegOpnd, 0), ImmOpnd);
515 case MipsISD::ThreadPointer: {
516 EVT PtrVT = TLI.getPointerTy();
517 unsigned RdhwrOpc, SrcReg, DestReg;
519 if (PtrVT == MVT::i32) {
520 RdhwrOpc = Mips::RDHWR;
521 SrcReg = Mips::HWR29;
524 RdhwrOpc = Mips::RDHWR64;
525 SrcReg = Mips::HWR29_64;
526 DestReg = Mips::V1_64;
530 CurDAG->getMachineNode(RdhwrOpc, Node->getDebugLoc(),
531 Node->getValueType(0),
532 CurDAG->getRegister(SrcReg, PtrVT));
533 SDValue Chain = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, DestReg,
535 SDValue ResNode = CurDAG->getCopyFromReg(Chain, dl, DestReg, PtrVT);
536 ReplaceUses(SDValue(Node, 0), ResNode);
537 return ResNode.getNode();
541 // Select the default instruction
542 SDNode *ResNode = SelectCode(Node);
544 DEBUG(errs() << "=> ");
545 if (ResNode == NULL || ResNode == Node)
546 DEBUG(Node->dump(CurDAG));
548 DEBUG(ResNode->dump(CurDAG));
549 DEBUG(errs() << "\n");
553 bool MipsDAGToDAGISel::
554 SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode,
555 std::vector<SDValue> &OutOps) {
556 assert(ConstraintCode == 'm' && "unexpected asm memory constraint");
557 OutOps.push_back(Op);
561 /// createMipsISelDag - This pass converts a legalized DAG into a
562 /// MIPS-specific DAG, ready for instruction scheduling.
563 FunctionPass *llvm::createMipsISelDag(MipsTargetMachine &TM) {
564 return new MipsDAGToDAGISel(TM);