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 "MipsInstrInfo.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsMachineFunction.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Module.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Mangler.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/SetVector.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 {
48 MipsAsmPrinter(std::ostream &O, MipsTargetMachine &TM,
49 const TargetAsmInfo *T):
50 AsmPrinter(O, TM, T) {}
52 virtual const char *getPassName() const {
53 return "Mips Assembly Printer";
56 enum SetDirectiveFlags {
57 REORDER, // enables instruction reordering.
58 NOREORDER, // disables instruction reordering.
59 MACRO, // enables GAS macros.
60 NOMACRO // disables GAS macros.
63 void printOperand(const MachineInstr *MI, int opNum);
64 void printMemOperand(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 void emitFunctionStart(MachineFunction &MF);
71 void emitFunctionEnd(MachineFunction &MF);
72 void emitFrameDirective(MachineFunction &MF);
73 void emitMaskDirective(MachineFunction &MF);
74 void emitFMaskDirective(MachineFunction &MF);
75 void emitSetDirective(SetDirectiveFlags Flag);
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 /// Mask directive for GPR
128 void MipsAsmPrinter::
129 emitMaskDirective(MachineFunction &MF)
131 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
133 int StackSize = MF.getFrameInfo()->getStackSize();
134 int Offset = (!MipsFI->getTopSavedRegOffset()) ? 0 :
135 (-(StackSize-MipsFI->getTopSavedRegOffset()));
138 DOUT << "--> emitMaskDirective" << "\n";
139 DOUT << "StackSize : " << StackSize << "\n";
140 DOUT << "getTopSavedReg : " << MipsFI->getTopSavedRegOffset() << "\n";
141 DOUT << "Offset : " << Offset << "\n\n";
144 unsigned int Bitmask = getSavedRegsBitmask(false, MF);
147 O << "," << Offset << "\n";
150 /// TODO: Mask Directive for Float Point
151 void MipsAsmPrinter::
152 emitFMaskDirective(MachineFunction &MF)
154 unsigned int Bitmask = getSavedRegsBitmask(true, MF);
162 void MipsAsmPrinter::
163 emitFrameDirective(MachineFunction &MF)
165 const MRegisterInfo &RI = *TM.getRegisterInfo();
167 unsigned stackReg = RI.getFrameRegister(MF);
168 unsigned returnReg = RI.getRARegister();
169 unsigned stackSize = MF.getFrameInfo()->getStackSize();
172 O << "\t.frame\t" << "$" << LowercaseString(RI.get(stackReg).Name)
173 << "," << stackSize << ","
174 << "$" << LowercaseString(RI.get(returnReg).Name)
178 /// Emit Set directives.
179 void MipsAsmPrinter::
180 emitSetDirective(SetDirectiveFlags Flag)
184 case REORDER: O << "reorder" << "\n"; break;
185 case NOREORDER: O << "noreorder" << "\n"; break;
186 case MACRO: O << "macro" << "\n"; break;
187 case NOMACRO: O << "nomacro" << "\n"; break;
192 // Create a bitmask with all callee saved registers for CPU
193 // or Float Point registers. For CPU registers consider RA,
194 // GP and FP for saving if necessary.
195 unsigned int MipsAsmPrinter::
196 getSavedRegsBitmask(bool isFloat, MachineFunction &MF)
198 const MRegisterInfo &RI = *TM.getRegisterInfo();
200 // Float Point Registers, TODO
205 unsigned int Bitmask = 0;
207 MachineFrameInfo *MFI = MF.getFrameInfo();
208 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
209 for (unsigned i = 0, e = CSI.size(); i != e; ++i)
210 Bitmask |= (1 << MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg()));
213 Bitmask |= (1 << MipsRegisterInfo::
214 getRegisterNumbering(RI.getFrameRegister(MF)));
216 if (MF.getFrameInfo()->hasCalls())
217 Bitmask |= (1 << MipsRegisterInfo::
218 getRegisterNumbering(RI.getRARegister()));
223 // Print a 32 bit hex number with all numbers.
224 void MipsAsmPrinter::
225 printHex32(unsigned int Value)
227 O << "0x" << std::hex;
228 for (int i = 7; i >= 0; i--)
229 O << std::hex << ( (Value & (0xF << (i*4))) >> (i*4) );
233 /// Emit the directives used by GAS on the start of functions
234 void MipsAsmPrinter::
235 emitFunctionStart(MachineFunction &MF)
237 // Print out the label for the function.
238 const Function *F = MF.getFunction();
239 SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
244 O << "\t.globl\t" << CurrentFnName << "\n";
245 O << "\t.ent\t" << CurrentFnName << "\n";
246 O << "\t.type\t" << CurrentFnName << ", @function\n";
247 O << CurrentFnName << ":\n";
249 emitFrameDirective(MF);
250 emitMaskDirective(MF);
251 emitFMaskDirective(MF);
253 if (TM.getRelocationModel() == Reloc::Static) {
254 emitSetDirective(NOREORDER);
255 emitSetDirective(NOMACRO);
261 /// Emit the directives used by GAS on the end of functions
262 void MipsAsmPrinter::
263 emitFunctionEnd(MachineFunction &MF)
265 if (TM.getRelocationModel() == Reloc::Static) {
266 emitSetDirective(MACRO);
267 emitSetDirective(REORDER);
270 O << "\t.end\t" << CurrentFnName << "\n";
273 /// runOnMachineFunction - This uses the printMachineInstruction()
274 /// method to print assembly for each instruction.
275 bool MipsAsmPrinter::
276 runOnMachineFunction(MachineFunction &MF)
278 SetupMachineFunction(MF);
280 // Print out constants referenced by the function
281 EmitConstantPool(MF.getConstantPool());
283 // Print out jump tables referenced by the function
284 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
288 // What's my mangled name?
289 CurrentFnName = Mang->getValueName(MF.getFunction());
291 // Emit the function start directives
292 emitFunctionStart(MF);
294 // Print out code for the function.
295 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
298 // Print a label for the basic block.
299 if (I != MF.begin()) {
300 printBasicBlockLabel(I, true);
304 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
306 // Print the assembly for the instruction.
308 printInstruction(II);
312 // Each Basic Block is separated by a newline
316 // Emit function end directives
319 // We didn't modify anything.
323 void MipsAsmPrinter::
324 printOperand(const MachineInstr *MI, int opNum)
326 const MachineOperand &MO = MI->getOperand(opNum);
327 const MRegisterInfo &RI = *TM.getRegisterInfo();
329 bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
330 bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
332 // %hi and %lo used on mips gas to load global addresses on
333 // static code. %got is used to load global addresses when
334 // using PIC_. %call16 is used to load direct call targets
335 // on PIC_ and small code size. %call_lo and %call_hi load
336 // direct call targets on PIC_ and large code size.
337 if (MI->getOpcode() == Mips::LUi && !MO.isRegister()
338 && !MO.isImmediate()) {
339 if ((isPIC) && (isCodeLarge))
344 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isRegister()
345 && !MO.isImmediate()) {
348 } else if ((isPIC) && (MI->getOpcode() == Mips::LW)
349 && (!MO.isRegister()) && (!MO.isImmediate())) {
350 const MachineOperand &firstMO = MI->getOperand(opNum-1);
351 const MachineOperand &lastMO = MI->getOperand(opNum+1);
352 if ((firstMO.isRegister()) && (lastMO.isRegister())) {
353 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
356 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
358 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
365 switch (MO.getType())
367 case MachineOperand::MO_Register:
368 if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
369 O << "$" << LowercaseString (RI.get(MO.getReg()).Name);
371 O << "$" << MO.getReg();
374 case MachineOperand::MO_Immediate:
375 if ((MI->getOpcode() == Mips::SLTiu) || (MI->getOpcode() == Mips::ORi) ||
376 (MI->getOpcode() == Mips::LUi) || (MI->getOpcode() == Mips::ANDi))
377 O << (unsigned short int)MO.getImm();
379 O << (short int)MO.getImm();
382 case MachineOperand::MO_MachineBasicBlock:
383 printBasicBlockLabel(MO.getMBB());
386 case MachineOperand::MO_GlobalAddress:
387 O << Mang->getValueName(MO.getGlobal());
390 case MachineOperand::MO_ExternalSymbol:
391 O << MO.getSymbolName();
394 case MachineOperand::MO_JumpTableIndex:
395 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
396 << '_' << MO.getIndex();
399 // FIXME: Verify correct
400 case MachineOperand::MO_ConstantPoolIndex:
401 O << TAI->getPrivateGlobalPrefix() << "CPI"
402 << getFunctionNumber() << "_" << MO.getIndex();
406 O << "<unknown operand type>"; abort (); break;
409 if (closeP) O << ")";
412 void MipsAsmPrinter::
413 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier)
415 // when using stack locations for not load/store instructions
416 // print the same way as all normal 3 operand instructions.
417 if (Modifier && !strcmp(Modifier, "stackloc")) {
418 printOperand(MI, opNum+1);
420 printOperand(MI, opNum);
424 // Load/Store memory operands -- imm($reg)
425 // If PIC target the target is loaded as the
426 // pattern lw $25,%call16($28)
427 printOperand(MI, opNum);
429 printOperand(MI, opNum+1);
433 bool MipsAsmPrinter::
434 doInitialization(Module &M)
436 Mang = new Mangler(M);
437 return false; // success
440 bool MipsAsmPrinter::
441 doFinalization(Module &M)
443 const TargetData *TD = TM.getTargetData();
445 // Print out module-level global variables here.
446 for (Module::const_global_iterator I = M.global_begin(),
447 E = M.global_end(); I != E; ++I)
449 // External global require no code
450 if (I->hasInitializer()) {
452 // Check to see if this is a special global
453 // used by LLVM, if so, emit it.
454 if (EmitSpecialLLVMGlobal(I))
458 std::string name = Mang->getValueName(I);
459 Constant *C = I->getInitializer();
460 unsigned Size = TD->getABITypeSize(C->getType());
461 unsigned Align = TD->getPreferredAlignmentLog(I);
464 if (C->isNullValue() && (I->hasLinkOnceLinkage() ||
465 I->hasInternalLinkage() || I->hasWeakLinkage()))
467 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
469 if (!NoZerosInBSS && TAI->getBSSSection())
470 SwitchToDataSection(TAI->getBSSSection(), I);
472 SwitchToDataSection(TAI->getDataSection(), I);
474 if (I->hasInternalLinkage()) {
475 if (TAI->getLCOMMDirective())
476 O << TAI->getLCOMMDirective() << name << "," << Size;
478 O << "\t.local\t" << name << "\n";
480 O << TAI->getCOMMDirective() << name << "," << Size;
481 // The .comm alignment in bytes.
482 if (TAI->getCOMMDirectiveTakesAlignment())
483 O << "," << (1 << Align);
488 switch (I->getLinkage())
490 case GlobalValue::LinkOnceLinkage:
491 case GlobalValue::WeakLinkage:
492 // FIXME: Verify correct for weak.
493 // Nonnull linkonce -> weak
494 O << "\t.weak " << name << "\n";
495 SwitchToDataSection("", I);
496 O << "\t.section\t\".llvm.linkonce.d." << name
497 << "\",\"aw\",@progbits\n";
499 case GlobalValue::AppendingLinkage:
500 // FIXME: appending linkage variables
501 // should go into a section of their name or
502 // something. For now, just emit them as external.
503 case GlobalValue::ExternalLinkage:
504 // If external or appending, declare as a global symbol
505 O << TAI->getGlobalDirective() << name << "\n";
507 case GlobalValue::InternalLinkage:
508 // FIXME: special handling for ".ctors" & ".dtors" sections
509 if (I->hasSection() && (I->getSection() == ".ctors" ||
510 I->getSection() == ".dtors")) {
511 std::string SectionName = ".section " + I->getSection();
512 SectionName += ",\"aw\",%progbits";
513 SwitchToDataSection(SectionName.c_str());
515 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
516 SwitchToDataSection(TAI->getBSSSection(), I);
517 else if (!I->isConstant())
518 SwitchToDataSection(TAI->getDataSection(), I);
521 if (TAI->getReadOnlySection())
522 SwitchToDataSection(TAI->getReadOnlySection(), I);
524 SwitchToDataSection(TAI->getDataSection(), I);
528 case GlobalValue::GhostLinkage:
529 cerr << "Should not have any unmaterialized functions!\n";
531 case GlobalValue::DLLImportLinkage:
532 cerr << "DLLImport linkage is not supported by this target!\n";
534 case GlobalValue::DLLExportLinkage:
535 cerr << "DLLExport linkage is not supported by this target!\n";
538 assert(0 && "Unknown linkage type!");
541 O << "\t.align " << Align << "\n";
542 O << "\t.type " << name << ",@object\n";
543 O << "\t.size " << name << "," << Size << "\n";
545 EmitGlobalConstant(C);
549 return AsmPrinter::doFinalization(M);