1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
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"
18 #include "MipsSubtarget.h"
19 #include "MipsInstrInfo.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsMachineFunction.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstr.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Target/TargetMachine.h"
33 #include "llvm/Target/TargetOptions.h"
34 #include "llvm/Support/Mangler.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/MathExtras.h"
44 STATISTIC(EmittedInsts, "Number of machine instrs printed");
47 struct VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
49 const MipsSubtarget *Subtarget;
51 MipsAsmPrinter(std::ostream &O, MipsTargetMachine &TM,
52 const TargetAsmInfo *T):
53 AsmPrinter(O, TM, T) {
54 Subtarget = &TM.getSubtarget<MipsSubtarget>();
57 virtual const char *getPassName() const {
58 return "Mips Assembly Printer";
61 void printOperand(const MachineInstr *MI, int opNum);
62 void printMemOperand(const MachineInstr *MI, int opNum,
63 const char *Modifier = 0);
64 void printFCCOperand(const MachineInstr *MI, int opNum,
65 const char *Modifier = 0);
67 unsigned int getSavedRegsBitmask(bool isFloat, MachineFunction &MF);
68 void printHex32(unsigned int Value);
70 const char *emitCurrentABIString(void);
71 void emitFunctionStart(MachineFunction &MF);
72 void emitFunctionEnd(MachineFunction &MF);
73 void emitFrameDirective(MachineFunction &MF);
74 void emitMaskDirective(MachineFunction &MF);
75 void emitFMaskDirective(MachineFunction &MF);
77 bool printInstruction(const MachineInstr *MI); // autogenerated.
78 bool runOnMachineFunction(MachineFunction &F);
79 bool doInitialization(Module &M);
80 bool doFinalization(Module &M);
82 } // end of anonymous namespace
84 #include "MipsGenAsmWriter.inc"
86 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
87 /// assembly code for a MachineFunction to the given output stream,
88 /// using the given target machine description. This should work
89 /// regardless of whether the function is in SSA form.
90 FunctionPass *llvm::createMipsCodePrinterPass(std::ostream &o,
91 MipsTargetMachine &tm)
93 return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo());
96 //===----------------------------------------------------------------------===//
98 // Mips Asm Directives
100 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
101 // Describe the stack frame.
103 // -- Mask directives "(f)mask bitmask, offset"
104 // Tells the assembler which registers are saved and where.
105 // bitmask - contain a little endian bitset indicating which registers are
106 // saved on function prologue (e.g. with a 0x80000000 mask, the
107 // assembler knows the register 31 (RA) is saved at prologue.
108 // offset - the position before stack pointer subtraction indicating where
109 // the first saved register on prologue is located. (e.g. with a
111 // Consider the following function prologue:
114 // .mask 0xc0000000,-8
115 // addiu $sp, $sp, -48
119 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
120 // 30 (FP) are saved at prologue. As the save order on prologue is from
121 // left to right, RA is saved first. A -8 offset means that after the
122 // stack pointer subtration, the first register in the mask (RA) will be
123 // saved at address 48-8=40.
125 //===----------------------------------------------------------------------===//
127 //===----------------------------------------------------------------------===//
129 //===----------------------------------------------------------------------===//
131 /// Mask directive for GPR
132 void MipsAsmPrinter::
133 emitMaskDirective(MachineFunction &MF)
135 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
137 int StackSize = MF.getFrameInfo()->getStackSize();
138 int Offset = (!MipsFI->getTopSavedRegOffset()) ? 0 :
139 (-(StackSize-MipsFI->getTopSavedRegOffset()));
142 DOUT << "--> emitMaskDirective" << "\n";
143 DOUT << "StackSize : " << StackSize << "\n";
144 DOUT << "getTopSavedReg : " << MipsFI->getTopSavedRegOffset() << "\n";
145 DOUT << "Offset : " << Offset << "\n\n";
148 unsigned int Bitmask = getSavedRegsBitmask(false, MF);
151 O << "," << Offset << "\n";
154 /// TODO: Mask Directive for Floating Point
155 void MipsAsmPrinter::
156 emitFMaskDirective(MachineFunction &MF)
158 unsigned int Bitmask = getSavedRegsBitmask(true, MF);
165 // Create a bitmask with all callee saved registers for CPU
166 // or Floating Point registers. For CPU registers consider RA,
167 // GP and FP for saving if necessary.
168 unsigned int MipsAsmPrinter::
169 getSavedRegsBitmask(bool isFloat, MachineFunction &MF)
171 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
173 // Floating Point Registers, TODO
178 unsigned int Bitmask = 0;
180 MachineFrameInfo *MFI = MF.getFrameInfo();
181 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
182 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
183 Bitmask |= (1 << MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg()));
186 Bitmask |= (1 << MipsRegisterInfo::
187 getRegisterNumbering(RI.getFrameRegister(MF)));
189 if (MF.getFrameInfo()->hasCalls())
190 Bitmask |= (1 << MipsRegisterInfo::
191 getRegisterNumbering(RI.getRARegister()));
196 // Print a 32 bit hex number with all numbers.
197 void MipsAsmPrinter::
198 printHex32(unsigned int Value)
200 O << "0x" << std::hex;
201 for (int i = 7; i >= 0; i--)
202 O << std::hex << ( (Value & (0xF << (i*4))) >> (i*4) );
206 //===----------------------------------------------------------------------===//
207 // Frame and Set directives
208 //===----------------------------------------------------------------------===//
211 void MipsAsmPrinter::
212 emitFrameDirective(MachineFunction &MF)
214 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
216 unsigned stackReg = RI.getFrameRegister(MF);
217 unsigned returnReg = RI.getRARegister();
218 unsigned stackSize = MF.getFrameInfo()->getStackSize();
221 O << "\t.frame\t" << "$" << LowercaseString(RI.get(stackReg).AsmName)
222 << "," << stackSize << ","
223 << "$" << LowercaseString(RI.get(returnReg).AsmName)
227 /// Emit Set directives.
228 const char * MipsAsmPrinter::
229 emitCurrentABIString(void)
231 switch(Subtarget->getTargetABI()) {
232 case MipsSubtarget::O32: return "abi32";
233 case MipsSubtarget::O64: return "abiO64";
234 case MipsSubtarget::N32: return "abiN32";
235 case MipsSubtarget::N64: return "abi64";
236 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
240 assert(0 && "Unknown Mips ABI");
244 /// Emit the directives used by GAS on the start of functions
245 void MipsAsmPrinter::
246 emitFunctionStart(MachineFunction &MF)
248 // Print out the label for the function.
249 const Function *F = MF.getFunction();
250 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
255 O << "\t.globl\t" << CurrentFnName << "\n";
256 O << "\t.ent\t" << CurrentFnName << "\n";
258 if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
259 O << "\t.type\t" << CurrentFnName << ", @function\n";
261 O << CurrentFnName << ":\n";
263 emitFrameDirective(MF);
264 emitMaskDirective(MF);
265 emitFMaskDirective(MF);
270 /// Emit the directives used by GAS on the end of functions
271 void MipsAsmPrinter::
272 emitFunctionEnd(MachineFunction &MF)
274 // There are instruction for this macros, but they must
275 // always be at the function end, and we can't emit and
276 // break with BB logic.
277 O << "\t.set\tmacro\n";
278 O << "\t.set\treorder\n";
280 O << "\t.end\t" << CurrentFnName << "\n";
281 if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
282 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << "\n";
285 /// runOnMachineFunction - This uses the printMachineInstruction()
286 /// method to print assembly for each instruction.
287 bool MipsAsmPrinter::
288 runOnMachineFunction(MachineFunction &MF)
290 SetupMachineFunction(MF);
292 // Print out constants referenced by the function
293 EmitConstantPool(MF.getConstantPool());
295 // Print out jump tables referenced by the function
296 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
300 // What's my mangled name?
301 CurrentFnName = Mang->getValueName(MF.getFunction());
303 // Emit the function start directives
304 emitFunctionStart(MF);
306 // Print out code for the function.
307 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
310 // Print a label for the basic block.
311 if (I != MF.begin()) {
312 printBasicBlockLabel(I, true, true);
316 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
318 // Print the assembly for the instruction.
319 printInstruction(II);
323 // Each Basic Block is separated by a newline
327 // Emit function end directives
330 // We didn't modify anything.
334 void MipsAsmPrinter::
335 printOperand(const MachineInstr *MI, int opNum)
337 const MachineOperand &MO = MI->getOperand(opNum);
338 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
340 bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
341 bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
343 // %hi and %lo used on mips gas to load global addresses on
344 // static code. %got is used to load global addresses when
345 // using PIC_. %call16 is used to load direct call targets
346 // on PIC_ and small code size. %call_lo and %call_hi load
347 // direct call targets on PIC_ and large code size.
348 if (MI->getOpcode() == Mips::LUi && !MO.isRegister()
349 && !MO.isImmediate()) {
350 if ((isPIC) && (isCodeLarge))
355 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isRegister()
356 && !MO.isImmediate()) {
359 } else if ((isPIC) && (MI->getOpcode() == Mips::LW)
360 && (!MO.isRegister()) && (!MO.isImmediate())) {
361 const MachineOperand &firstMO = MI->getOperand(opNum-1);
362 const MachineOperand &lastMO = MI->getOperand(opNum+1);
363 if ((firstMO.isRegister()) && (lastMO.isRegister())) {
364 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
367 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
369 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
376 switch (MO.getType())
378 case MachineOperand::MO_Register:
379 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
380 O << "$" << LowercaseString (RI.get(MO.getReg()).AsmName);
382 O << "$" << MO.getReg();
385 case MachineOperand::MO_Immediate:
386 if ((MI->getOpcode() == Mips::SLTiu) || (MI->getOpcode() == Mips::ORi) ||
387 (MI->getOpcode() == Mips::LUi) || (MI->getOpcode() == Mips::ANDi))
388 O << (unsigned short int)MO.getImm();
390 O << (short int)MO.getImm();
393 case MachineOperand::MO_MachineBasicBlock:
394 printBasicBlockLabel(MO.getMBB());
397 case MachineOperand::MO_GlobalAddress:
398 O << Mang->getValueName(MO.getGlobal());
401 case MachineOperand::MO_ExternalSymbol:
402 O << MO.getSymbolName();
405 case MachineOperand::MO_JumpTableIndex:
406 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
407 << '_' << MO.getIndex();
410 // FIXME: Verify correct
411 case MachineOperand::MO_ConstantPoolIndex:
412 O << TAI->getPrivateGlobalPrefix() << "CPI"
413 << getFunctionNumber() << "_" << MO.getIndex();
417 O << "<unknown operand type>"; abort (); break;
420 if (closeP) O << ")";
423 void MipsAsmPrinter::
424 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier)
426 // when using stack locations for not load/store instructions
427 // print the same way as all normal 3 operand instructions.
428 if (Modifier && !strcmp(Modifier, "stackloc")) {
429 printOperand(MI, opNum+1);
431 printOperand(MI, opNum);
435 // Load/Store memory operands -- imm($reg)
436 // If PIC target the target is loaded as the
437 // pattern lw $25,%call16($28)
438 printOperand(MI, opNum);
440 printOperand(MI, opNum+1);
444 void MipsAsmPrinter::
445 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier)
447 const MachineOperand& MO = MI->getOperand(opNum);
448 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
451 bool MipsAsmPrinter::
452 doInitialization(Module &M)
454 Mang = new Mangler(M);
456 // Tell the assembler which ABI we are using
457 O << "\t.section .mdebug." << emitCurrentABIString() << "\n";
459 // TODO: handle O64 ABI
460 if (Subtarget->isABI_EABI())
461 O << "\t.section .gcc_compiled_long" <<
462 (Subtarget->isGP32bit() ? "32" : "64") << "\n";
464 // return to previous section
465 O << "\t.previous" << "\n";
467 return false; // success
470 bool MipsAsmPrinter::
471 doFinalization(Module &M)
473 const TargetData *TD = TM.getTargetData();
475 // Print out module-level global variables here.
476 for (Module::const_global_iterator I = M.global_begin(),
477 E = M.global_end(); I != E; ++I)
479 // External global require no code
480 if (I->hasInitializer()) {
482 // Check to see if this is a special global
483 // used by LLVM, if so, emit it.
484 if (EmitSpecialLLVMGlobal(I))
488 std::string name = Mang->getValueName(I);
489 Constant *C = I->getInitializer();
490 unsigned Size = TD->getABITypeSize(C->getType());
491 unsigned Align = TD->getPreferredAlignmentLog(I);
494 if (C->isNullValue() && (I->hasLinkOnceLinkage() ||
495 I->hasInternalLinkage() || I->hasWeakLinkage() ||
496 I->hasCommonLinkage()))
498 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
500 if (!NoZerosInBSS && TAI->getBSSSection())
501 SwitchToDataSection(TAI->getBSSSection(), I);
503 SwitchToDataSection(TAI->getDataSection(), I);
505 if (I->hasInternalLinkage()) {
506 if (TAI->getLCOMMDirective())
507 O << TAI->getLCOMMDirective() << name << "," << Size;
509 O << "\t.local\t" << name << "\n";
511 O << TAI->getCOMMDirective() << name << "," << Size;
512 // The .comm alignment in bytes.
513 if (TAI->getCOMMDirectiveTakesAlignment())
514 O << "," << (1 << Align);
519 switch (I->getLinkage())
521 case GlobalValue::LinkOnceLinkage:
522 case GlobalValue::CommonLinkage:
523 case GlobalValue::WeakLinkage:
524 // FIXME: Verify correct for weak.
525 // Nonnull linkonce -> weak
526 O << "\t.weak " << name << "\n";
527 SwitchToDataSection("", I);
528 O << "\t.section\t\".llvm.linkonce.d." << name
529 << "\",\"aw\",@progbits\n";
531 case GlobalValue::AppendingLinkage:
532 // FIXME: appending linkage variables
533 // should go into a section of their name or
534 // something. For now, just emit them as external.
535 case GlobalValue::ExternalLinkage:
536 // If external or appending, declare as a global symbol
537 O << TAI->getGlobalDirective() << name << "\n";
539 case GlobalValue::InternalLinkage:
540 // FIXME: special handling for ".ctors" & ".dtors" sections
541 if (I->hasSection() && (I->getSection() == ".ctors" ||
542 I->getSection() == ".dtors")) {
543 std::string SectionName = ".section " + I->getSection();
544 SectionName += ",\"aw\",%progbits";
545 SwitchToDataSection(SectionName.c_str());
547 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
548 SwitchToDataSection(TAI->getBSSSection(), I);
549 else if (!I->isConstant())
550 SwitchToDataSection(TAI->getDataSection(), I);
553 if (TAI->getReadOnlySection())
554 SwitchToDataSection(TAI->getReadOnlySection(), I);
556 SwitchToDataSection(TAI->getDataSection(), I);
560 case GlobalValue::GhostLinkage:
561 cerr << "Should not have any unmaterialized functions!\n";
563 case GlobalValue::DLLImportLinkage:
564 cerr << "DLLImport linkage is not supported by this target!\n";
566 case GlobalValue::DLLExportLinkage:
567 cerr << "DLLExport linkage is not supported by this target!\n";
570 assert(0 && "Unknown linkage type!");
573 O << "\t.align " << Align << "\n";
575 if (TAI->hasDotTypeDotSizeDirective()) {
576 O << "\t.type " << name << ",@object\n";
577 O << "\t.size " << name << "," << Size << "\n";
580 EmitGlobalConstant(C);
586 return AsmPrinter::doFinalization(M);