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/MDNode.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/DwarfWriter.h"
28 #include "llvm/CodeGen/MachineFunctionPass.h"
29 #include "llvm/CodeGen/MachineConstantPool.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetData.h"
34 #include "llvm/Target/TargetMachine.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/raw_ostream.h"
48 STATISTIC(EmittedInsts, "Number of machine instrs printed");
51 class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
52 const MipsSubtarget *Subtarget;
54 explicit MipsAsmPrinter(raw_ostream &O, MipsTargetMachine &TM,
55 const TargetAsmInfo *T, bool V)
56 : AsmPrinter(O, TM, T, V) {
57 Subtarget = &TM.getSubtarget<MipsSubtarget>();
60 virtual const char *getPassName() const {
61 return "Mips Assembly Printer";
64 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
65 unsigned AsmVariant, const char *ExtraCode);
66 void printOperand(const MachineInstr *MI, int opNum);
67 void printUnsignedImm(const MachineInstr *MI, int opNum);
68 void printMemOperand(const MachineInstr *MI, int opNum,
69 const char *Modifier = 0);
70 void printFCCOperand(const MachineInstr *MI, int opNum,
71 const char *Modifier = 0);
72 void printModuleLevelGV(const GlobalVariable* GVar);
73 void printSavedRegsBitmask(MachineFunction &MF);
74 void printHex32(unsigned int Value);
76 const char *emitCurrentABIString(void);
77 void emitFunctionStart(MachineFunction &MF);
78 void emitFunctionEnd(MachineFunction &MF);
79 void emitFrameDirective(MachineFunction &MF);
81 bool printInstruction(const MachineInstr *MI); // autogenerated.
82 bool runOnMachineFunction(MachineFunction &F);
83 bool doInitialization(Module &M);
84 bool doFinalization(Module &M);
86 } // end of anonymous namespace
88 #include "MipsGenAsmWriter.inc"
90 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
91 /// assembly code for a MachineFunction to the given output stream,
92 /// using the given target machine description. This should work
93 /// regardless of whether the function is in SSA form.
94 FunctionPass *llvm::createMipsCodePrinterPass(raw_ostream &o,
95 MipsTargetMachine &tm,
97 return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
100 //===----------------------------------------------------------------------===//
102 // Mips Asm Directives
104 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
105 // Describe the stack frame.
107 // -- Mask directives "(f)mask bitmask, offset"
108 // Tells the assembler which registers are saved and where.
109 // bitmask - contain a little endian bitset indicating which registers are
110 // saved on function prologue (e.g. with a 0x80000000 mask, the
111 // assembler knows the register 31 (RA) is saved at prologue.
112 // offset - the position before stack pointer subtraction indicating where
113 // the first saved register on prologue is located. (e.g. with a
115 // Consider the following function prologue:
118 // .mask 0xc0000000,-8
119 // addiu $sp, $sp, -48
123 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
124 // 30 (FP) are saved at prologue. As the save order on prologue is from
125 // left to right, RA is saved first. A -8 offset means that after the
126 // stack pointer subtration, the first register in the mask (RA) will be
127 // saved at address 48-8=40.
129 //===----------------------------------------------------------------------===//
131 //===----------------------------------------------------------------------===//
133 //===----------------------------------------------------------------------===//
135 // Create a bitmask with all callee saved registers for CPU or Floating Point
136 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
137 void MipsAsmPrinter::
138 printSavedRegsBitmask(MachineFunction &MF)
140 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
141 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
143 // CPU and FPU Saved Registers Bitmasks
144 unsigned int CPUBitmask = 0;
145 unsigned int FPUBitmask = 0;
147 // Set the CPU and FPU Bitmasks
148 MachineFrameInfo *MFI = MF.getFrameInfo();
149 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
150 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
151 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
152 if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
153 CPUBitmask |= (1 << RegNum);
155 FPUBitmask |= (1 << RegNum);
158 // Return Address and Frame registers must also be set in CPUBitmask.
160 CPUBitmask |= (1 << MipsRegisterInfo::
161 getRegisterNumbering(RI.getFrameRegister(MF)));
163 if (MF.getFrameInfo()->hasCalls())
164 CPUBitmask |= (1 << MipsRegisterInfo::
165 getRegisterNumbering(RI.getRARegister()));
168 O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
169 << MipsFI->getCPUTopSavedRegOff() << '\n';
172 O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
173 << MipsFI->getFPUTopSavedRegOff() << '\n';
176 // Print a 32 bit hex number with all numbers.
177 void MipsAsmPrinter::
178 printHex32(unsigned int Value)
181 for (int i = 7; i >= 0; i--)
182 O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
185 //===----------------------------------------------------------------------===//
186 // Frame and Set directives
187 //===----------------------------------------------------------------------===//
190 void MipsAsmPrinter::
191 emitFrameDirective(MachineFunction &MF)
193 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
195 unsigned stackReg = RI.getFrameRegister(MF);
196 unsigned returnReg = RI.getRARegister();
197 unsigned stackSize = MF.getFrameInfo()->getStackSize();
200 O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
201 << ',' << stackSize << ','
202 << '$' << LowercaseString(RI.get(returnReg).AsmName)
206 /// Emit Set directives.
207 const char * MipsAsmPrinter::
208 emitCurrentABIString(void)
210 switch(Subtarget->getTargetABI()) {
211 case MipsSubtarget::O32: return "abi32";
212 case MipsSubtarget::O64: return "abiO64";
213 case MipsSubtarget::N32: return "abiN32";
214 case MipsSubtarget::N64: return "abi64";
215 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
219 assert(0 && "Unknown Mips ABI");
223 /// Emit the directives used by GAS on the start of functions
224 void MipsAsmPrinter::
225 emitFunctionStart(MachineFunction &MF)
227 // Print out the label for the function.
228 const Function *F = MF.getFunction();
229 SwitchToSection(TAI->SectionForGlobal(F));
232 EmitAlignment(MF.getAlignment(), F);
234 O << "\t.globl\t" << CurrentFnName << '\n';
235 O << "\t.ent\t" << CurrentFnName << '\n';
237 printVisibility(CurrentFnName, F->getVisibility());
239 if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
240 O << "\t.type\t" << CurrentFnName << ", @function\n";
242 O << CurrentFnName << ":\n";
244 emitFrameDirective(MF);
245 printSavedRegsBitmask(MF);
250 /// Emit the directives used by GAS on the end of functions
251 void MipsAsmPrinter::
252 emitFunctionEnd(MachineFunction &MF)
254 // There are instruction for this macros, but they must
255 // always be at the function end, and we can't emit and
256 // break with BB logic.
257 O << "\t.set\tmacro\n";
258 O << "\t.set\treorder\n";
260 O << "\t.end\t" << CurrentFnName << '\n';
261 if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
262 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
265 /// runOnMachineFunction - This uses the printMachineInstruction()
266 /// method to print assembly for each instruction.
267 bool MipsAsmPrinter::
268 runOnMachineFunction(MachineFunction &MF)
272 SetupMachineFunction(MF);
274 // Print out constants referenced by the function
275 EmitConstantPool(MF.getConstantPool());
277 // Print out jump tables referenced by the function
278 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
282 // Emit the function start directives
283 emitFunctionStart(MF);
285 // Print out code for the function.
286 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
289 // Print a label for the basic block.
290 if (I != MF.begin()) {
291 printBasicBlockLabel(I, true, true);
295 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
297 // Print the assembly for the instruction.
298 printInstruction(II);
302 // Each Basic Block is separated by a newline
306 // Emit function end directives
309 // We didn't modify anything.
313 // Print out an operand for an inline asm expression.
314 bool MipsAsmPrinter::
315 PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
316 unsigned AsmVariant, const char *ExtraCode)
318 // Does this asm operand have a single letter operand modifier?
319 if (ExtraCode && ExtraCode[0])
320 return true; // Unknown modifier.
322 printOperand(MI, OpNo);
326 void MipsAsmPrinter::
327 printOperand(const MachineInstr *MI, int opNum)
329 const MachineOperand &MO = MI->getOperand(opNum);
330 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
332 bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
333 bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
335 // %hi and %lo used on mips gas to load global addresses on
336 // static code. %got is used to load global addresses when
337 // using PIC_. %call16 is used to load direct call targets
338 // on PIC_ and small code size. %call_lo and %call_hi load
339 // direct call targets on PIC_ and large code size.
340 if (MI->getOpcode() == Mips::LUi && !MO.isReg() && !MO.isImm()) {
341 if ((isPIC) && (isCodeLarge))
346 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isReg() && !MO.isImm()) {
347 const MachineOperand &firstMO = MI->getOperand(opNum-1);
348 if (firstMO.getReg() == Mips::GP)
353 } else if ((isPIC) && (MI->getOpcode() == Mips::LW) &&
354 (!MO.isReg()) && (!MO.isImm())) {
355 const MachineOperand &firstMO = MI->getOperand(opNum-1);
356 const MachineOperand &lastMO = MI->getOperand(opNum+1);
357 if ((firstMO.isReg()) && (lastMO.isReg())) {
358 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
361 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
363 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
370 switch (MO.getType())
372 case MachineOperand::MO_Register:
373 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
374 O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
376 O << '$' << MO.getReg();
379 case MachineOperand::MO_Immediate:
380 O << (short int)MO.getImm();
383 case MachineOperand::MO_MachineBasicBlock:
384 printBasicBlockLabel(MO.getMBB());
387 case MachineOperand::MO_GlobalAddress:
389 const GlobalValue *GV = MO.getGlobal();
390 O << Mang->getValueName(GV);
394 case MachineOperand::MO_ExternalSymbol:
395 O << MO.getSymbolName();
398 case MachineOperand::MO_JumpTableIndex:
399 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
400 << '_' << MO.getIndex();
403 case MachineOperand::MO_ConstantPoolIndex:
404 O << TAI->getPrivateGlobalPrefix() << "CPI"
405 << getFunctionNumber() << "_" << MO.getIndex();
409 LLVM_UNREACHABLE("<unknown operand type>");
412 if (closeP) O << ")";
415 void MipsAsmPrinter::
416 printUnsignedImm(const MachineInstr *MI, int opNum)
418 const MachineOperand &MO = MI->getOperand(opNum);
419 if (MO.getType() == MachineOperand::MO_Immediate)
420 O << (unsigned short int)MO.getImm();
422 printOperand(MI, opNum);
425 void MipsAsmPrinter::
426 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier)
428 // when using stack locations for not load/store instructions
429 // print the same way as all normal 3 operand instructions.
430 if (Modifier && !strcmp(Modifier, "stackloc")) {
431 printOperand(MI, opNum+1);
433 printOperand(MI, opNum);
437 // Load/Store memory operands -- imm($reg)
438 // If PIC target the target is loaded as the
439 // pattern lw $25,%call16($28)
440 printOperand(MI, opNum);
442 printOperand(MI, opNum+1);
446 void MipsAsmPrinter::
447 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier)
449 const MachineOperand& MO = MI->getOperand(opNum);
450 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
453 bool MipsAsmPrinter::
454 doInitialization(Module &M)
456 Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
458 // Tell the assembler which ABI we are using
459 O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
461 // TODO: handle O64 ABI
462 if (Subtarget->isABI_EABI())
463 O << "\t.section .gcc_compiled_long" <<
464 (Subtarget->isGP32bit() ? "32" : "64") << '\n';
466 // return to previous section
467 O << "\t.previous" << '\n';
469 return false; // success
472 void MipsAsmPrinter::
473 printModuleLevelGV(const GlobalVariable* GVar) {
474 const TargetData *TD = TM.getTargetData();
476 if (!GVar->hasInitializer())
477 return; // External global require no code
479 // Check to see if this is a special global used by LLVM, if so, emit it.
480 if (EmitSpecialLLVMGlobal(GVar))
484 std::string name = Mang->getValueName(GVar);
485 Constant *C = GVar->getInitializer();
486 if (isa<MDNode>(C) || isa<MDString>(C))
488 const Type *CTy = C->getType();
489 unsigned Size = TD->getTypeAllocSize(CTy);
490 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
491 bool printSizeAndType = true;
493 // A data structure or array is aligned in memory to the largest
494 // alignment boundary required by any data type inside it (this matches
495 // the Preferred Type Alignment). For integral types, the alignment is
498 if (CTy->getTypeID() == Type::IntegerTyID ||
499 CTy->getTypeID() == Type::VoidTyID) {
500 assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
501 Align = Log2_32(Size);
503 Align = TD->getPreferredTypeAlignmentShift(CTy);
505 printVisibility(name, GVar->getVisibility());
507 SwitchToSection(TAI->SectionForGlobal(GVar));
509 if (C->isNullValue() && !GVar->hasSection()) {
510 if (!GVar->isThreadLocal() &&
511 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
512 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
514 if (GVar->hasLocalLinkage())
515 O << "\t.local\t" << name << '\n';
517 O << TAI->getCOMMDirective() << name << ',' << Size;
518 if (TAI->getCOMMDirectiveTakesAlignment())
519 O << ',' << (1 << Align);
525 switch (GVar->getLinkage()) {
526 case GlobalValue::LinkOnceAnyLinkage:
527 case GlobalValue::LinkOnceODRLinkage:
528 case GlobalValue::CommonLinkage:
529 case GlobalValue::WeakAnyLinkage:
530 case GlobalValue::WeakODRLinkage:
531 // FIXME: Verify correct for weak.
532 // Nonnull linkonce -> weak
533 O << "\t.weak " << name << '\n';
535 case GlobalValue::AppendingLinkage:
536 // FIXME: appending linkage variables should go into a section of their name
537 // or something. For now, just emit them as external.
538 case GlobalValue::ExternalLinkage:
539 // If external or appending, declare as a global symbol
540 O << TAI->getGlobalDirective() << name << '\n';
542 case GlobalValue::PrivateLinkage:
543 case GlobalValue::InternalLinkage:
544 if (CVA && CVA->isCString())
545 printSizeAndType = false;
547 case GlobalValue::GhostLinkage:
548 LLVM_UNREACHABLE("Should not have any unmaterialized functions!");
549 case GlobalValue::DLLImportLinkage:
550 LLVM_UNREACHABLE("DLLImport linkage is not supported by this target!");
551 case GlobalValue::DLLExportLinkage:
552 LLVM_UNREACHABLE("DLLExport linkage is not supported by this target!");
554 LLVM_UNREACHABLE("Unknown linkage type!");
557 EmitAlignment(Align, GVar);
559 if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
560 O << "\t.type " << name << ",@object\n";
561 O << "\t.size " << name << ',' << Size << '\n';
565 EmitGlobalConstant(C);
568 bool MipsAsmPrinter::
569 doFinalization(Module &M)
571 // Print out module-level global variables here.
572 for (Module::const_global_iterator I = M.global_begin(),
573 E = M.global_end(); I != E; ++I)
574 printModuleLevelGV(I);
578 return AsmPrinter::doFinalization(M);
582 static struct Register {
584 MipsTargetMachine::registerAsmPrinter(createMipsCodePrinterPass);
589 // Force static initialization.
590 extern "C" void LLVMInitializeMipsAsmPrinter() { }