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/Target/TargetRegistry.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/Mangler.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/StringExtras.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/MathExtras.h"
49 STATISTIC(EmittedInsts, "Number of machine instrs printed");
52 class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
53 const MipsSubtarget *Subtarget;
55 explicit MipsAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
56 const TargetAsmInfo *T, bool V)
57 : AsmPrinter(O, TM, T, V) {
58 Subtarget = &TM.getSubtarget<MipsSubtarget>();
61 virtual const char *getPassName() const {
62 return "Mips Assembly Printer";
65 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
66 unsigned AsmVariant, const char *ExtraCode);
67 void printOperand(const MachineInstr *MI, int opNum);
68 void printUnsignedImm(const MachineInstr *MI, int opNum);
69 void printMemOperand(const MachineInstr *MI, int opNum,
70 const char *Modifier = 0);
71 void printFCCOperand(const MachineInstr *MI, int opNum,
72 const char *Modifier = 0);
73 void printModuleLevelGV(const GlobalVariable* GVar);
74 void printSavedRegsBitmask(MachineFunction &MF);
75 void printHex32(unsigned int Value);
77 const char *emitCurrentABIString(void);
78 void emitFunctionStart(MachineFunction &MF);
79 void emitFunctionEnd(MachineFunction &MF);
80 void emitFrameDirective(MachineFunction &MF);
82 bool printInstruction(const MachineInstr *MI); // autogenerated.
83 bool runOnMachineFunction(MachineFunction &F);
84 bool doInitialization(Module &M);
85 bool doFinalization(Module &M);
87 } // end of anonymous namespace
89 #include "MipsGenAsmWriter.inc"
91 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
92 /// assembly code for a MachineFunction to the given output stream,
93 /// using the given target machine description. This should work
94 /// regardless of whether the function is in SSA form.
95 FunctionPass *llvm::createMipsCodePrinterPass(formatted_raw_ostream &o,
98 return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
101 //===----------------------------------------------------------------------===//
103 // Mips Asm Directives
105 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
106 // Describe the stack frame.
108 // -- Mask directives "(f)mask bitmask, offset"
109 // Tells the assembler which registers are saved and where.
110 // bitmask - contain a little endian bitset indicating which registers are
111 // saved on function prologue (e.g. with a 0x80000000 mask, the
112 // assembler knows the register 31 (RA) is saved at prologue.
113 // offset - the position before stack pointer subtraction indicating where
114 // the first saved register on prologue is located. (e.g. with a
116 // Consider the following function prologue:
119 // .mask 0xc0000000,-8
120 // addiu $sp, $sp, -48
124 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
125 // 30 (FP) are saved at prologue. As the save order on prologue is from
126 // left to right, RA is saved first. A -8 offset means that after the
127 // stack pointer subtration, the first register in the mask (RA) will be
128 // saved at address 48-8=40.
130 //===----------------------------------------------------------------------===//
132 //===----------------------------------------------------------------------===//
134 //===----------------------------------------------------------------------===//
136 // Create a bitmask with all callee saved registers for CPU or Floating Point
137 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
138 void MipsAsmPrinter::
139 printSavedRegsBitmask(MachineFunction &MF)
141 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
142 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
144 // CPU and FPU Saved Registers Bitmasks
145 unsigned int CPUBitmask = 0;
146 unsigned int FPUBitmask = 0;
148 // Set the CPU and FPU Bitmasks
149 MachineFrameInfo *MFI = MF.getFrameInfo();
150 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
151 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
152 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
153 if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
154 CPUBitmask |= (1 << RegNum);
156 FPUBitmask |= (1 << RegNum);
159 // Return Address and Frame registers must also be set in CPUBitmask.
161 CPUBitmask |= (1 << MipsRegisterInfo::
162 getRegisterNumbering(RI.getFrameRegister(MF)));
164 if (MF.getFrameInfo()->hasCalls())
165 CPUBitmask |= (1 << MipsRegisterInfo::
166 getRegisterNumbering(RI.getRARegister()));
169 O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
170 << MipsFI->getCPUTopSavedRegOff() << '\n';
173 O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
174 << MipsFI->getFPUTopSavedRegOff() << '\n';
177 // Print a 32 bit hex number with all numbers.
178 void MipsAsmPrinter::
179 printHex32(unsigned int Value)
182 for (int i = 7; i >= 0; i--)
183 O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
186 //===----------------------------------------------------------------------===//
187 // Frame and Set directives
188 //===----------------------------------------------------------------------===//
191 void MipsAsmPrinter::
192 emitFrameDirective(MachineFunction &MF)
194 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
196 unsigned stackReg = RI.getFrameRegister(MF);
197 unsigned returnReg = RI.getRARegister();
198 unsigned stackSize = MF.getFrameInfo()->getStackSize();
201 O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
202 << ',' << stackSize << ','
203 << '$' << LowercaseString(RI.get(returnReg).AsmName)
207 /// Emit Set directives.
208 const char * MipsAsmPrinter::
209 emitCurrentABIString(void)
211 switch(Subtarget->getTargetABI()) {
212 case MipsSubtarget::O32: return "abi32";
213 case MipsSubtarget::O64: return "abiO64";
214 case MipsSubtarget::N32: return "abiN32";
215 case MipsSubtarget::N64: return "abi64";
216 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
220 llvm_unreachable("Unknown Mips ABI");
224 /// Emit the directives used by GAS on the start of functions
225 void MipsAsmPrinter::
226 emitFunctionStart(MachineFunction &MF)
228 // Print out the label for the function.
229 const Function *F = MF.getFunction();
230 SwitchToSection(TAI->SectionForGlobal(F));
233 EmitAlignment(MF.getAlignment(), F);
235 O << "\t.globl\t" << CurrentFnName << '\n';
236 O << "\t.ent\t" << CurrentFnName << '\n';
238 printVisibility(CurrentFnName, F->getVisibility());
240 if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
241 O << "\t.type\t" << CurrentFnName << ", @function\n";
243 O << CurrentFnName << ":\n";
245 emitFrameDirective(MF);
246 printSavedRegsBitmask(MF);
251 /// Emit the directives used by GAS on the end of functions
252 void MipsAsmPrinter::
253 emitFunctionEnd(MachineFunction &MF)
255 // There are instruction for this macros, but they must
256 // always be at the function end, and we can't emit and
257 // break with BB logic.
258 O << "\t.set\tmacro\n";
259 O << "\t.set\treorder\n";
261 O << "\t.end\t" << CurrentFnName << '\n';
262 if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
263 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
266 /// runOnMachineFunction - This uses the printMachineInstruction()
267 /// method to print assembly for each instruction.
268 bool MipsAsmPrinter::
269 runOnMachineFunction(MachineFunction &MF)
273 SetupMachineFunction(MF);
275 // Print out constants referenced by the function
276 EmitConstantPool(MF.getConstantPool());
278 // Print out jump tables referenced by the function
279 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
283 // Emit the function start directives
284 emitFunctionStart(MF);
286 // Print out code for the function.
287 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
290 // Print a label for the basic block.
291 if (I != MF.begin()) {
292 printBasicBlockLabel(I, true, true);
296 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
298 // Print the assembly for the instruction.
299 printInstruction(II);
303 // Each Basic Block is separated by a newline
307 // Emit function end directives
310 // We didn't modify anything.
314 // Print out an operand for an inline asm expression.
315 bool MipsAsmPrinter::
316 PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
317 unsigned AsmVariant, const char *ExtraCode)
319 // Does this asm operand have a single letter operand modifier?
320 if (ExtraCode && ExtraCode[0])
321 return true; // Unknown modifier.
323 printOperand(MI, OpNo);
327 void MipsAsmPrinter::
328 printOperand(const MachineInstr *MI, int opNum)
330 const MachineOperand &MO = MI->getOperand(opNum);
331 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
333 bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
334 bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
336 // %hi and %lo used on mips gas to load global addresses on
337 // static code. %got is used to load global addresses when
338 // using PIC_. %call16 is used to load direct call targets
339 // on PIC_ and small code size. %call_lo and %call_hi load
340 // direct call targets on PIC_ and large code size.
341 if (MI->getOpcode() == Mips::LUi && !MO.isReg() && !MO.isImm()) {
342 if ((isPIC) && (isCodeLarge))
347 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isReg() && !MO.isImm()) {
348 const MachineOperand &firstMO = MI->getOperand(opNum-1);
349 if (firstMO.getReg() == Mips::GP)
354 } else if ((isPIC) && (MI->getOpcode() == Mips::LW) &&
355 (!MO.isReg()) && (!MO.isImm())) {
356 const MachineOperand &firstMO = MI->getOperand(opNum-1);
357 const MachineOperand &lastMO = MI->getOperand(opNum+1);
358 if ((firstMO.isReg()) && (lastMO.isReg())) {
359 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
362 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
364 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
371 switch (MO.getType())
373 case MachineOperand::MO_Register:
374 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
375 O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
377 O << '$' << MO.getReg();
380 case MachineOperand::MO_Immediate:
381 O << (short int)MO.getImm();
384 case MachineOperand::MO_MachineBasicBlock:
385 printBasicBlockLabel(MO.getMBB());
388 case MachineOperand::MO_GlobalAddress:
389 O << Mang->getMangledName(MO.getGlobal());
392 case MachineOperand::MO_ExternalSymbol:
393 O << MO.getSymbolName();
396 case MachineOperand::MO_JumpTableIndex:
397 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
398 << '_' << MO.getIndex();
401 case MachineOperand::MO_ConstantPoolIndex:
402 O << TAI->getPrivateGlobalPrefix() << "CPI"
403 << getFunctionNumber() << "_" << MO.getIndex();
407 llvm_unreachable("<unknown operand type>");
410 if (closeP) O << ")";
413 void MipsAsmPrinter::
414 printUnsignedImm(const MachineInstr *MI, int opNum)
416 const MachineOperand &MO = MI->getOperand(opNum);
417 if (MO.getType() == MachineOperand::MO_Immediate)
418 O << (unsigned short int)MO.getImm();
420 printOperand(MI, opNum);
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, "", TAI->getPrivateGlobalPrefix(),
455 TAI->getLinkerPrivateGlobalPrefix());
457 // Tell the assembler which ABI we are using
458 O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
460 // TODO: handle O64 ABI
461 if (Subtarget->isABI_EABI())
462 O << "\t.section .gcc_compiled_long" <<
463 (Subtarget->isGP32bit() ? "32" : "64") << '\n';
465 // return to previous section
466 O << "\t.previous" << '\n';
468 return false; // success
471 void MipsAsmPrinter::
472 printModuleLevelGV(const GlobalVariable* GVar) {
473 const TargetData *TD = TM.getTargetData();
475 if (!GVar->hasInitializer())
476 return; // External global require no code
478 // Check to see if this is a special global used by LLVM, if so, emit it.
479 if (EmitSpecialLLVMGlobal(GVar))
483 std::string name = Mang->getMangledName(GVar);
484 Constant *C = GVar->getInitializer();
485 if (isa<MDNode>(C) || isa<MDString>(C))
487 const Type *CTy = C->getType();
488 unsigned Size = TD->getTypeAllocSize(CTy);
489 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
490 bool printSizeAndType = true;
492 // A data structure or array is aligned in memory to the largest
493 // alignment boundary required by any data type inside it (this matches
494 // the Preferred Type Alignment). For integral types, the alignment is
497 if (CTy->getTypeID() == Type::IntegerTyID ||
498 CTy->getTypeID() == Type::VoidTyID) {
499 assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
500 Align = Log2_32(Size);
502 Align = TD->getPreferredTypeAlignmentShift(CTy);
504 printVisibility(name, GVar->getVisibility());
506 SwitchToSection(TAI->SectionForGlobal(GVar));
508 if (C->isNullValue() && !GVar->hasSection()) {
509 if (!GVar->isThreadLocal() &&
510 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
511 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
513 if (GVar->hasLocalLinkage())
514 O << "\t.local\t" << name << '\n';
516 O << TAI->getCOMMDirective() << name << ',' << Size;
517 if (TAI->getCOMMDirectiveTakesAlignment())
518 O << ',' << (1 << Align);
524 switch (GVar->getLinkage()) {
525 case GlobalValue::LinkOnceAnyLinkage:
526 case GlobalValue::LinkOnceODRLinkage:
527 case GlobalValue::CommonLinkage:
528 case GlobalValue::WeakAnyLinkage:
529 case GlobalValue::WeakODRLinkage:
530 // FIXME: Verify correct for weak.
531 // Nonnull linkonce -> weak
532 O << "\t.weak " << name << '\n';
534 case GlobalValue::AppendingLinkage:
535 // FIXME: appending linkage variables should go into a section of their name
536 // or something. For now, just emit them as external.
537 case GlobalValue::ExternalLinkage:
538 // If external or appending, declare as a global symbol
539 O << TAI->getGlobalDirective() << name << '\n';
541 case GlobalValue::PrivateLinkage:
542 case GlobalValue::LinkerPrivateLinkage:
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);
581 // Force static initialization.
582 extern "C" void LLVMInitializeMipsAsmPrinter() {
583 TargetRegistry::RegisterAsmPrinter(TheMipsTarget, createMipsCodePrinterPass);
585 TargetRegistry::RegisterAsmPrinter(TheMipselTarget,
586 createMipsCodePrinterPass);