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/DwarfWriter.h"
27 #include "llvm/CodeGen/MachineFunctionPass.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
46 STATISTIC(EmittedInsts, "Number of machine instrs printed");
49 struct VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
51 const MipsSubtarget *Subtarget;
53 MipsAsmPrinter(raw_ostream &O, MipsTargetMachine &TM,
54 const TargetAsmInfo *T):
55 AsmPrinter(O, TM, T) {
56 Subtarget = &TM.getSubtarget<MipsSubtarget>();
59 virtual const char *getPassName() const {
60 return "Mips Assembly Printer";
63 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
64 unsigned AsmVariant, const char *ExtraCode);
65 void printOperand(const MachineInstr *MI, int opNum);
66 void printUnsignedImm(const MachineInstr *MI, int opNum);
67 void printMemOperand(const MachineInstr *MI, int opNum,
68 const char *Modifier = 0);
69 void printFCCOperand(const MachineInstr *MI, int opNum,
70 const char *Modifier = 0);
71 void printModuleLevelGV(const GlobalVariable* GVar);
72 void printSavedRegsBitmask(MachineFunction &MF);
73 void printHex32(unsigned int Value);
75 const char *emitCurrentABIString(void);
76 void emitFunctionStart(MachineFunction &MF);
77 void emitFunctionEnd(MachineFunction &MF);
78 void emitFrameDirective(MachineFunction &MF);
80 bool printInstruction(const MachineInstr *MI); // autogenerated.
81 bool runOnMachineFunction(MachineFunction &F);
82 bool doInitialization(Module &M);
83 bool doFinalization(Module &M);
85 } // end of anonymous namespace
87 #include "MipsGenAsmWriter.inc"
89 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
90 /// assembly code for a MachineFunction to the given output stream,
91 /// using the given target machine description. This should work
92 /// regardless of whether the function is in SSA form.
93 FunctionPass *llvm::createMipsCodePrinterPass(raw_ostream &o,
94 MipsTargetMachine &tm)
96 return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo());
99 //===----------------------------------------------------------------------===//
101 // Mips Asm Directives
103 // -- Frame directive "frame Stackpointer, Stacksize, RARegister"
104 // Describe the stack frame.
106 // -- Mask directives "(f)mask bitmask, offset"
107 // Tells the assembler which registers are saved and where.
108 // bitmask - contain a little endian bitset indicating which registers are
109 // saved on function prologue (e.g. with a 0x80000000 mask, the
110 // assembler knows the register 31 (RA) is saved at prologue.
111 // offset - the position before stack pointer subtraction indicating where
112 // the first saved register on prologue is located. (e.g. with a
114 // Consider the following function prologue:
117 // .mask 0xc0000000,-8
118 // addiu $sp, $sp, -48
122 // With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
123 // 30 (FP) are saved at prologue. As the save order on prologue is from
124 // left to right, RA is saved first. A -8 offset means that after the
125 // stack pointer subtration, the first register in the mask (RA) will be
126 // saved at address 48-8=40.
128 //===----------------------------------------------------------------------===//
130 //===----------------------------------------------------------------------===//
132 //===----------------------------------------------------------------------===//
134 // Create a bitmask with all callee saved registers for CPU or Floating Point
135 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
136 void MipsAsmPrinter::
137 printSavedRegsBitmask(MachineFunction &MF)
139 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
140 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
142 // CPU and FPU Saved Registers Bitmasks
143 unsigned int CPUBitmask = 0;
144 unsigned int FPUBitmask = 0;
146 // Set the CPU and FPU Bitmasks
147 MachineFrameInfo *MFI = MF.getFrameInfo();
148 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
149 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
150 unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
151 if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
152 CPUBitmask |= (1 << RegNum);
154 FPUBitmask |= (1 << RegNum);
157 // Return Address and Frame registers must also be set in CPUBitmask.
159 CPUBitmask |= (1 << MipsRegisterInfo::
160 getRegisterNumbering(RI.getFrameRegister(MF)));
162 if (MF.getFrameInfo()->hasCalls())
163 CPUBitmask |= (1 << MipsRegisterInfo::
164 getRegisterNumbering(RI.getRARegister()));
167 O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
168 << MipsFI->getCPUTopSavedRegOff() << '\n';
171 O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
172 << MipsFI->getFPUTopSavedRegOff() << '\n';
175 // Print a 32 bit hex number with all numbers.
176 void MipsAsmPrinter::
177 printHex32(unsigned int Value)
180 for (int i = 7; i >= 0; i--)
181 O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
184 //===----------------------------------------------------------------------===//
185 // Frame and Set directives
186 //===----------------------------------------------------------------------===//
189 void MipsAsmPrinter::
190 emitFrameDirective(MachineFunction &MF)
192 const TargetRegisterInfo &RI = *TM.getRegisterInfo();
194 unsigned stackReg = RI.getFrameRegister(MF);
195 unsigned returnReg = RI.getRARegister();
196 unsigned stackSize = MF.getFrameInfo()->getStackSize();
199 O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
200 << ',' << stackSize << ','
201 << '$' << LowercaseString(RI.get(returnReg).AsmName)
205 /// Emit Set directives.
206 const char * MipsAsmPrinter::
207 emitCurrentABIString(void)
209 switch(Subtarget->getTargetABI()) {
210 case MipsSubtarget::O32: return "abi32";
211 case MipsSubtarget::O64: return "abiO64";
212 case MipsSubtarget::N32: return "abiN32";
213 case MipsSubtarget::N64: return "abi64";
214 case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
218 assert(0 && "Unknown Mips ABI");
222 /// Emit the directives used by GAS on the start of functions
223 void MipsAsmPrinter::
224 emitFunctionStart(MachineFunction &MF)
226 // Print out the label for the function.
227 const Function *F = MF.getFunction();
228 SwitchToSection(TAI->SectionForGlobal(F));
233 O << "\t.globl\t" << CurrentFnName << '\n';
234 O << "\t.ent\t" << CurrentFnName << '\n';
236 printVisibility(CurrentFnName, F->getVisibility());
238 if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
239 O << "\t.type\t" << CurrentFnName << ", @function\n";
241 O << CurrentFnName << ":\n";
243 emitFrameDirective(MF);
244 printSavedRegsBitmask(MF);
249 /// Emit the directives used by GAS on the end of functions
250 void MipsAsmPrinter::
251 emitFunctionEnd(MachineFunction &MF)
253 // There are instruction for this macros, but they must
254 // always be at the function end, and we can't emit and
255 // break with BB logic.
256 O << "\t.set\tmacro\n";
257 O << "\t.set\treorder\n";
259 O << "\t.end\t" << CurrentFnName << '\n';
260 if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
261 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
264 /// runOnMachineFunction - This uses the printMachineInstruction()
265 /// method to print assembly for each instruction.
266 bool MipsAsmPrinter::
267 runOnMachineFunction(MachineFunction &MF)
269 SetupMachineFunction(MF);
271 // Print out constants referenced by the function
272 EmitConstantPool(MF.getConstantPool());
274 // Print out jump tables referenced by the function
275 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
279 // Emit the function start directives
280 emitFunctionStart(MF);
282 // Print out code for the function.
283 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
286 // Print a label for the basic block.
287 if (I != MF.begin()) {
288 printBasicBlockLabel(I, true, true);
292 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
294 // Print the assembly for the instruction.
295 printInstruction(II);
299 // Each Basic Block is separated by a newline
303 // Emit function end directives
306 // We didn't modify anything.
310 // Print out an operand for an inline asm expression.
311 bool MipsAsmPrinter::
312 PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
313 unsigned AsmVariant, const char *ExtraCode)
315 // Does this asm operand have a single letter operand modifier?
316 if (ExtraCode && ExtraCode[0])
317 return true; // Unknown modifier.
319 printOperand(MI, OpNo);
323 void MipsAsmPrinter::
324 printOperand(const MachineInstr *MI, int opNum)
326 const MachineOperand &MO = MI->getOperand(opNum);
327 const TargetRegisterInfo &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.isReg() && !MO.isImm()) {
338 if ((isPIC) && (isCodeLarge))
343 } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isReg() && !MO.isImm()) {
344 const MachineOperand &firstMO = MI->getOperand(opNum-1);
345 if (firstMO.getReg() == Mips::GP)
350 } else if ((isPIC) && (MI->getOpcode() == Mips::LW) &&
351 (!MO.isReg()) && (!MO.isImm())) {
352 const MachineOperand &firstMO = MI->getOperand(opNum-1);
353 const MachineOperand &lastMO = MI->getOperand(opNum+1);
354 if ((firstMO.isReg()) && (lastMO.isReg())) {
355 if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
358 else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
360 else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
367 switch (MO.getType())
369 case MachineOperand::MO_Register:
370 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
371 O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
373 O << '$' << MO.getReg();
376 case MachineOperand::MO_Immediate:
377 O << (short int)MO.getImm();
380 case MachineOperand::MO_MachineBasicBlock:
381 printBasicBlockLabel(MO.getMBB());
384 case MachineOperand::MO_GlobalAddress:
386 const GlobalValue *GV = MO.getGlobal();
387 O << Mang->getValueName(GV);
391 case MachineOperand::MO_ExternalSymbol:
392 O << MO.getSymbolName();
395 case MachineOperand::MO_JumpTableIndex:
396 O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
397 << '_' << MO.getIndex();
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 printUnsignedImm(const MachineInstr *MI, int opNum)
415 const MachineOperand &MO = MI->getOperand(opNum);
416 if (MO.getType() == MachineOperand::MO_Immediate)
417 O << (unsigned short int)MO.getImm();
419 printOperand(MI, opNum);
422 void MipsAsmPrinter::
423 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier)
425 // when using stack locations for not load/store instructions
426 // print the same way as all normal 3 operand instructions.
427 if (Modifier && !strcmp(Modifier, "stackloc")) {
428 printOperand(MI, opNum+1);
430 printOperand(MI, opNum);
434 // Load/Store memory operands -- imm($reg)
435 // If PIC target the target is loaded as the
436 // pattern lw $25,%call16($28)
437 printOperand(MI, opNum);
439 printOperand(MI, opNum+1);
443 void MipsAsmPrinter::
444 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier)
446 const MachineOperand& MO = MI->getOperand(opNum);
447 O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
450 bool MipsAsmPrinter::
451 doInitialization(Module &M)
453 Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
455 // Tell the assembler which ABI we are using
456 O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
458 // TODO: handle O64 ABI
459 if (Subtarget->isABI_EABI())
460 O << "\t.section .gcc_compiled_long" <<
461 (Subtarget->isGP32bit() ? "32" : "64") << '\n';
463 // return to previous section
464 O << "\t.previous" << '\n';
466 return false; // success
469 void MipsAsmPrinter::
470 printModuleLevelGV(const GlobalVariable* GVar) {
471 const TargetData *TD = TM.getTargetData();
473 if (!GVar->hasInitializer())
474 return; // External global require no code
476 // Check to see if this is a special global used by LLVM, if so, emit it.
477 if (EmitSpecialLLVMGlobal(GVar))
481 std::string name = Mang->getValueName(GVar);
482 Constant *C = GVar->getInitializer();
483 const Type *CTy = C->getType();
484 unsigned Size = TD->getTypePaddedSize(CTy);
485 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
486 bool printSizeAndType = true;
488 // A data structure or array is aligned in memory to the largest
489 // alignment boundary required by any data type inside it (this matches
490 // the Preferred Type Alignment). For integral types, the alignment is
493 if (CTy->getTypeID() == Type::IntegerTyID ||
494 CTy->getTypeID() == Type::VoidTyID) {
495 assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
496 Align = Log2_32(Size);
498 Align = TD->getPreferredTypeAlignmentShift(CTy);
500 printVisibility(name, GVar->getVisibility());
502 SwitchToSection(TAI->SectionForGlobal(GVar));
504 if (C->isNullValue() && !GVar->hasSection()) {
505 if (!GVar->isThreadLocal() &&
506 (GVar->hasLocalLinkage() || GVar->mayBeOverridden())) {
507 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
509 if (GVar->hasLocalLinkage())
510 O << "\t.local\t" << name << '\n';
512 O << TAI->getCOMMDirective() << name << ',' << Size;
513 if (TAI->getCOMMDirectiveTakesAlignment())
514 O << ',' << (1 << Align);
520 switch (GVar->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';
528 case GlobalValue::AppendingLinkage:
529 // FIXME: appending linkage variables should go into a section of their name
530 // or something. For now, just emit them as external.
531 case GlobalValue::ExternalLinkage:
532 // If external or appending, declare as a global symbol
533 O << TAI->getGlobalDirective() << name << '\n';
535 case GlobalValue::PrivateLinkage:
536 case GlobalValue::InternalLinkage:
537 if (CVA && CVA->isCString())
538 printSizeAndType = false;
540 case GlobalValue::GhostLinkage:
541 cerr << "Should not have any unmaterialized functions!\n";
543 case GlobalValue::DLLImportLinkage:
544 cerr << "DLLImport linkage is not supported by this target!\n";
546 case GlobalValue::DLLExportLinkage:
547 cerr << "DLLExport linkage is not supported by this target!\n";
550 assert(0 && "Unknown linkage type!");
553 EmitAlignment(Align, GVar);
555 if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
556 O << "\t.type " << name << ",@object\n";
557 O << "\t.size " << name << ',' << Size << '\n';
561 EmitGlobalConstant(C);
564 bool MipsAsmPrinter::
565 doFinalization(Module &M)
567 // Print out module-level global variables here.
568 for (Module::const_global_iterator I = M.global_begin(),
569 E = M.global_end(); I != E; ++I)
570 printModuleLevelGV(I);
574 return AsmPrinter::doFinalization(M);