1 //===-- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer -------------------===//
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 contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-asm-printer"
16 #include "MipsAsmPrinter.h"
18 #include "MipsInstrInfo.h"
19 #include "InstPrinter/MipsInstPrinter.h"
20 #include "MCTargetDesc/MipsBaseInfo.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/Twine.h"
24 #include "llvm/BasicBlock.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineMemOperand.h"
30 #include "llvm/InlineAsm.h"
31 #include "llvm/Instructions.h"
32 #include "llvm/MC/MCAsmInfo.h"
33 #include "llvm/MC/MCInst.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/MCSymbol.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Support/TargetRegistry.h"
38 #include "llvm/Target/Mangler.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetOptions.h"
45 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
46 MipsFI = MF.getInfo<MipsFunctionInfo>();
47 AsmPrinter::runOnMachineFunction(MF);
51 void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
52 if (MI->isDebugValue()) {
54 raw_svector_ostream OS(Str);
56 PrintDebugValueComment(MI, OS);
60 MachineBasicBlock::const_instr_iterator I = MI;
61 MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
65 MCInstLowering.Lower(I++, TmpInst0);
66 OutStreamer.EmitInstruction(TmpInst0);
67 } while ((I != E) && I->isInsideBundle());
70 //===----------------------------------------------------------------------===//
72 // Mips Asm Directives
74 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
75 // Describe the stack frame.
77 // -- Mask directives "(f)mask bitmask, offset"
78 // Tells the assembler which registers are saved and where.
79 // bitmask - contain a little endian bitset indicating which registers are
80 // saved on function prologue (e.g. with a 0x80000000 mask, the
81 // assembler knows the register 31 (RA) is saved at prologue.
82 // offset - the position before stack pointer subtraction indicating where
83 // the first saved register on prologue is located. (e.g. with a
85 // Consider the following function prologue:
88 // .mask 0xc0000000,-8
89 // addiu $sp, $sp, -48
93 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
94 // 30 (FP) are saved at prologue. As the save order on prologue is from
95 // left to right, RA is saved first. A -8 offset means that after the
96 // stack pointer subtration, the first register in the mask (RA) will be
97 // saved at address 48-8=40.
99 //===----------------------------------------------------------------------===//
101 //===----------------------------------------------------------------------===//
103 //===----------------------------------------------------------------------===//
105 // Create a bitmask with all callee saved registers for CPU or Floating Point
106 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
107 void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
108 // CPU and FPU Saved Registers Bitmasks
109 unsigned CPUBitmask = 0, FPUBitmask = 0;
110 int CPUTopSavedRegOff, FPUTopSavedRegOff;
112 // Set the CPU and FPU Bitmasks
113 const MachineFrameInfo *MFI = MF->getFrameInfo();
114 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
115 // size of stack area to which FP callee-saved regs are saved.
116 unsigned CPURegSize = Mips::CPURegsRegClass.getSize();
117 unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
118 unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
119 bool HasAFGR64Reg = false;
120 unsigned CSFPRegsSize = 0;
121 unsigned i, e = CSI.size();
124 for (i = 0; i != e; ++i) {
125 unsigned Reg = CSI[i].getReg();
126 if (Mips::CPURegsRegClass.contains(Reg))
129 unsigned RegNum = getMipsRegisterNumbering(Reg);
130 if (Mips::AFGR64RegClass.contains(Reg)) {
131 FPUBitmask |= (3 << RegNum);
132 CSFPRegsSize += AFGR64RegSize;
137 FPUBitmask |= (1 << RegNum);
138 CSFPRegsSize += FGR32RegSize;
142 for (; i != e; ++i) {
143 unsigned Reg = CSI[i].getReg();
144 unsigned RegNum = getMipsRegisterNumbering(Reg);
145 CPUBitmask |= (1 << RegNum);
148 // FP Regs are saved right below where the virtual frame pointer points to.
149 FPUTopSavedRegOff = FPUBitmask ?
150 (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
152 // CPU Regs are saved below FP Regs.
153 CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
156 O << "\t.mask \t"; printHex32(CPUBitmask, O);
157 O << ',' << CPUTopSavedRegOff << '\n';
160 O << "\t.fmask\t"; printHex32(FPUBitmask, O);
161 O << "," << FPUTopSavedRegOff << '\n';
164 // Print a 32 bit hex number with all numbers.
165 void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
167 for (int i = 7; i >= 0; i--)
168 O.write_hex((Value & (0xF << (i*4))) >> (i*4));
171 //===----------------------------------------------------------------------===//
172 // Frame and Set directives
173 //===----------------------------------------------------------------------===//
176 void MipsAsmPrinter::emitFrameDirective() {
177 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
179 unsigned stackReg = RI.getFrameRegister(*MF);
180 unsigned returnReg = RI.getRARegister();
181 unsigned stackSize = MF->getFrameInfo()->getStackSize();
183 if (OutStreamer.hasRawTextSupport())
184 OutStreamer.EmitRawText("\t.frame\t$" +
185 StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
186 "," + Twine(stackSize) + ",$" +
187 StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
190 /// Emit Set directives.
191 const char *MipsAsmPrinter::getCurrentABIString() const {
192 switch (Subtarget->getTargetABI()) {
193 case MipsSubtarget::O32: return "abi32";
194 case MipsSubtarget::N32: return "abiN32";
195 case MipsSubtarget::N64: return "abi64";
196 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
197 default: llvm_unreachable("Unknown Mips ABI");;
201 void MipsAsmPrinter::EmitFunctionEntryLabel() {
202 if (OutStreamer.hasRawTextSupport()) {
203 if (Subtarget->inMips16Mode())
204 OutStreamer.EmitRawText(StringRef("\t.set\tmips16"));
206 OutStreamer.EmitRawText(StringRef("\t.set\tnomips16"));
207 // leave out until FSF available gas has micromips changes
208 // OutStreamer.EmitRawText(StringRef("\t.set\tnomicromips"));
209 OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
211 OutStreamer.EmitLabel(CurrentFnSym);
214 /// EmitFunctionBodyStart - Targets can override this to emit stuff before
215 /// the first basic block in the function.
216 void MipsAsmPrinter::EmitFunctionBodyStart() {
217 MCInstLowering.Initialize(Mang, &MF->getContext());
219 emitFrameDirective();
221 if (OutStreamer.hasRawTextSupport()) {
222 SmallString<128> Str;
223 raw_svector_ostream OS(Str);
224 printSavedRegsBitmask(OS);
225 OutStreamer.EmitRawText(OS.str());
227 OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
228 OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
229 if (MipsFI->getEmitNOAT())
230 OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
234 /// EmitFunctionBodyEnd - Targets can override this to emit stuff after
235 /// the last basic block in the function.
236 void MipsAsmPrinter::EmitFunctionBodyEnd() {
237 // There are instruction for this macros, but they must
238 // always be at the function end, and we can't emit and
239 // break with BB logic.
240 if (OutStreamer.hasRawTextSupport()) {
241 if (MipsFI->getEmitNOAT())
242 OutStreamer.EmitRawText(StringRef("\t.set\tat"));
244 OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
245 OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
246 OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
250 /// isBlockOnlyReachableByFallthough - Return true if the basic block has
251 /// exactly one predecessor and the control transfer mechanism between
252 /// the predecessor and this block is a fall-through.
253 bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
255 // The predecessor has to be immediately before this block.
256 const MachineBasicBlock *Pred = *MBB->pred_begin();
258 // If the predecessor is a switch statement, assume a jump table
259 // implementation, so it is not a fall through.
260 if (const BasicBlock *bb = Pred->getBasicBlock())
261 if (isa<SwitchInst>(bb->getTerminator()))
264 // If this is a landing pad, it isn't a fall through. If it has no preds,
265 // then nothing falls through to it.
266 if (MBB->isLandingPad() || MBB->pred_empty())
269 // If there isn't exactly one predecessor, it can't be a fall through.
270 MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
273 if (PI2 != MBB->pred_end())
276 // The predecessor has to be immediately before this block.
277 if (!Pred->isLayoutSuccessor(MBB))
280 // If the block is completely empty, then it definitely does fall through.
284 // Otherwise, check the last instruction.
285 // Check if the last terminator is an unconditional branch.
286 MachineBasicBlock::const_iterator I = Pred->end();
287 while (I != Pred->begin() && !(--I)->isTerminator()) ;
289 return !I->isBarrier();
292 // Print out an operand for an inline asm expression.
293 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
294 unsigned AsmVariant,const char *ExtraCode,
296 // Does this asm operand have a single letter operand modifier?
297 if (ExtraCode && ExtraCode[0]) {
298 if (ExtraCode[1] != 0) return true; // Unknown modifier.
300 const MachineOperand &MO = MI->getOperand(OpNum);
301 switch (ExtraCode[0]) {
303 // See if this is a generic print operand
304 return AsmPrinter::PrintAsmOperand(MI,OpNum,AsmVariant,ExtraCode,O);
305 case 'X': // hex const int
306 if ((MO.getType()) != MachineOperand::MO_Immediate)
308 O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
310 case 'x': // hex const int (low 16 bits)
311 if ((MO.getType()) != MachineOperand::MO_Immediate)
313 O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
315 case 'd': // decimal const int
316 if ((MO.getType()) != MachineOperand::MO_Immediate)
320 case 'm': // decimal const int minus 1
321 if ((MO.getType()) != MachineOperand::MO_Immediate)
323 O << MO.getImm() - 1;
326 // $0 if zero, regular printing otherwise
327 if (MO.getType() != MachineOperand::MO_Immediate)
329 int64_t Val = MO.getImm();
336 // This will be shared with other cases in succeeding checkins
338 // Second part of a double word register operand
341 const MachineOperand &FlagsOP = MI->getOperand(OpNum - 1);
342 if (!FlagsOP.isImm())
344 unsigned Flags = FlagsOP.getImm();
345 unsigned NumVals = InlineAsm::getNumOperandRegisters(Flags);
347 if (!Subtarget->isGP32bit() && NumVals == 1 && MO.isReg()) {
348 // In 64 bit mode long longs are always just a single reg
349 unsigned Reg = MO.getReg();
350 O << '$' << MipsInstPrinter::getRegisterName(Reg);
356 switch(ExtraCode[0]) {
357 // This will have other cases in succeeding checkins
359 RegOp = (!Subtarget->isGP32bit()) ? OpNum : OpNum + 1;
362 if (RegOp >= MI->getNumOperands())
364 const MachineOperand &MO = MI->getOperand(RegOp);
367 unsigned Reg = MO.getReg();
368 O << '$' << MipsInstPrinter::getRegisterName(Reg);
374 printOperand(MI, OpNum, O);
378 bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
379 unsigned OpNum, unsigned AsmVariant,
380 const char *ExtraCode,
382 if (ExtraCode && ExtraCode[0])
383 return true; // Unknown modifier.
385 const MachineOperand &MO = MI->getOperand(OpNum);
386 assert(MO.isReg() && "unexpected inline asm memory operand");
387 O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
392 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
394 const MachineOperand &MO = MI->getOperand(opNum);
397 if (MO.getTargetFlags())
400 switch(MO.getTargetFlags()) {
401 case MipsII::MO_GPREL: O << "%gp_rel("; break;
402 case MipsII::MO_GOT_CALL: O << "%call16("; break;
403 case MipsII::MO_GOT: O << "%got("; break;
404 case MipsII::MO_ABS_HI: O << "%hi("; break;
405 case MipsII::MO_ABS_LO: O << "%lo("; break;
406 case MipsII::MO_TLSGD: O << "%tlsgd("; break;
407 case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
408 case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
409 case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
410 case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
411 case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
412 case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
413 case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
414 case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
417 switch (MO.getType()) {
418 case MachineOperand::MO_Register:
420 << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
423 case MachineOperand::MO_Immediate:
427 case MachineOperand::MO_MachineBasicBlock:
428 O << *MO.getMBB()->getSymbol();
431 case MachineOperand::MO_GlobalAddress:
432 O << *Mang->getSymbol(MO.getGlobal());
435 case MachineOperand::MO_BlockAddress: {
436 MCSymbol *BA = GetBlockAddressSymbol(MO.getBlockAddress());
441 case MachineOperand::MO_ExternalSymbol:
442 O << *GetExternalSymbolSymbol(MO.getSymbolName());
445 case MachineOperand::MO_JumpTableIndex:
446 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
447 << '_' << MO.getIndex();
450 case MachineOperand::MO_ConstantPoolIndex:
451 O << MAI->getPrivateGlobalPrefix() << "CPI"
452 << getFunctionNumber() << "_" << MO.getIndex();
454 O << "+" << MO.getOffset();
458 llvm_unreachable("<unknown operand type>");
461 if (closeP) O << ")";
464 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
466 const MachineOperand &MO = MI->getOperand(opNum);
468 O << (unsigned short int)MO.getImm();
470 printOperand(MI, opNum, O);
473 void MipsAsmPrinter::
474 printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
475 // Load/Store memory operands -- imm($reg)
476 // If PIC target the target is loaded as the
477 // pattern lw $25,%call16($28)
478 printOperand(MI, opNum+1, O);
480 printOperand(MI, opNum, O);
484 void MipsAsmPrinter::
485 printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
486 // when using stack locations for not load/store instructions
487 // print the same way as all normal 3 operand instructions.
488 printOperand(MI, opNum, O);
490 printOperand(MI, opNum+1, O);
494 void MipsAsmPrinter::
495 printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
496 const char *Modifier) {
497 const MachineOperand &MO = MI->getOperand(opNum);
498 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
501 void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
502 // FIXME: Use SwitchSection.
504 // Tell the assembler which ABI we are using
505 if (OutStreamer.hasRawTextSupport())
506 OutStreamer.EmitRawText("\t.section .mdebug." +
507 Twine(getCurrentABIString()));
509 // TODO: handle O64 ABI
510 if (OutStreamer.hasRawTextSupport()) {
511 if (Subtarget->isABI_EABI()) {
512 if (Subtarget->isGP32bit())
513 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
515 OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
519 // return to previous section
520 if (OutStreamer.hasRawTextSupport())
521 OutStreamer.EmitRawText(StringRef("\t.previous"));
525 MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
526 // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
527 assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
528 assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
529 "Unexpected MachineOperand types");
530 return MachineLocation(MI->getOperand(0).getReg(),
531 MI->getOperand(1).getImm());
534 void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
539 // Force static initialization.
540 extern "C" void LLVMInitializeMipsAsmPrinter() {
541 RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
542 RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
543 RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
544 RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);