Remove old style hacks to register AsmPrinter into TargetMachine.
[oota-llvm.git] / lib / Target / Mips / AsmPrinter / MipsAsmPrinter.cpp
1 //===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to GAS-format MIPS assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "mips-asm-printer"
16
17 #include "Mips.h"
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"
45 #include <cctype>
46
47 using namespace llvm;
48
49 STATISTIC(EmittedInsts, "Number of machine instrs printed");
50
51 namespace {
52   class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
53     const MipsSubtarget *Subtarget;
54   public:
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>();
59     }
60
61     virtual const char *getPassName() const {
62       return "Mips Assembly Printer";
63     }
64
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);
76
77     const char *emitCurrentABIString(void);
78     void emitFunctionStart(MachineFunction &MF);
79     void emitFunctionEnd(MachineFunction &MF);
80     void emitFrameDirective(MachineFunction &MF);
81
82     bool printInstruction(const MachineInstr *MI);  // autogenerated.
83     bool runOnMachineFunction(MachineFunction &F);
84     bool doInitialization(Module &M);
85     bool doFinalization(Module &M);
86   };
87 } // end of anonymous namespace
88
89 #include "MipsGenAsmWriter.inc"
90
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,
96                                               TargetMachine &tm,
97                                               bool verbose) {
98   return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
99 }
100
101 //===----------------------------------------------------------------------===//
102 //
103 //  Mips Asm Directives
104 //
105 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
106 //  Describe the stack frame.
107 //
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
115 //
116 //  Consider the following function prologue:
117 //
118 //    .frame  $fp,48,$ra
119 //    .mask   0xc0000000,-8
120 //       addiu $sp, $sp, -48
121 //       sw $ra, 40($sp)
122 //       sw $fp, 36($sp)
123 //
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.
129 //
130 //===----------------------------------------------------------------------===//
131
132 //===----------------------------------------------------------------------===//
133 // Mask directives
134 //===----------------------------------------------------------------------===//
135
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)
140 {
141   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
142   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
143              
144   // CPU and FPU Saved Registers Bitmasks
145   unsigned int CPUBitmask = 0;
146   unsigned int FPUBitmask = 0;
147
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);
155     else
156       FPUBitmask |= (1 << RegNum);
157   }
158
159   // Return Address and Frame registers must also be set in CPUBitmask.
160   if (RI.hasFP(MF)) 
161     CPUBitmask |= (1 << MipsRegisterInfo::
162                 getRegisterNumbering(RI.getFrameRegister(MF)));
163   
164   if (MF.getFrameInfo()->hasCalls()) 
165     CPUBitmask |= (1 << MipsRegisterInfo::
166                 getRegisterNumbering(RI.getRARegister()));
167
168   // Print CPUBitmask
169   O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
170     << MipsFI->getCPUTopSavedRegOff() << '\n';
171
172   // Print FPUBitmask
173   O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
174     << MipsFI->getFPUTopSavedRegOff() << '\n';
175 }
176
177 // Print a 32 bit hex number with all numbers.
178 void MipsAsmPrinter::
179 printHex32(unsigned int Value) 
180 {
181   O << "0x";
182   for (int i = 7; i >= 0; i--) 
183     O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
184 }
185
186 //===----------------------------------------------------------------------===//
187 // Frame and Set directives
188 //===----------------------------------------------------------------------===//
189
190 /// Frame Directive
191 void MipsAsmPrinter::
192 emitFrameDirective(MachineFunction &MF)
193 {
194   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
195
196   unsigned stackReg  = RI.getFrameRegister(MF);
197   unsigned returnReg = RI.getRARegister();
198   unsigned stackSize = MF.getFrameInfo()->getStackSize();
199
200
201   O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
202                     << ',' << stackSize << ','
203                     << '$' << LowercaseString(RI.get(returnReg).AsmName)
204                     << '\n';
205 }
206
207 /// Emit Set directives.
208 const char * MipsAsmPrinter::
209 emitCurrentABIString(void) 
210 {  
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
217     default: break;
218   }
219
220   llvm_unreachable("Unknown Mips ABI");
221   return NULL;
222 }  
223
224 /// Emit the directives used by GAS on the start of functions
225 void MipsAsmPrinter::
226 emitFunctionStart(MachineFunction &MF)
227 {
228   // Print out the label for the function.
229   const Function *F = MF.getFunction();
230   SwitchToSection(TAI->SectionForGlobal(F));
231
232   // 2 bits aligned
233   EmitAlignment(MF.getAlignment(), F);
234
235   O << "\t.globl\t"  << CurrentFnName << '\n';
236   O << "\t.ent\t"    << CurrentFnName << '\n';
237
238   printVisibility(CurrentFnName, F->getVisibility());
239
240   if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
241     O << "\t.type\t"   << CurrentFnName << ", @function\n";
242
243   O << CurrentFnName << ":\n";
244
245   emitFrameDirective(MF);
246   printSavedRegsBitmask(MF);
247
248   O << '\n';
249 }
250
251 /// Emit the directives used by GAS on the end of functions
252 void MipsAsmPrinter::
253 emitFunctionEnd(MachineFunction &MF) 
254 {
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"; 
260
261   O << "\t.end\t" << CurrentFnName << '\n';
262   if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
263     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
264 }
265
266 /// runOnMachineFunction - This uses the printMachineInstruction()
267 /// method to print assembly for each instruction.
268 bool MipsAsmPrinter::
269 runOnMachineFunction(MachineFunction &MF) 
270 {
271   this->MF = &MF;
272
273   SetupMachineFunction(MF);
274
275   // Print out constants referenced by the function
276   EmitConstantPool(MF.getConstantPool());
277
278   // Print out jump tables referenced by the function
279   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
280
281   O << "\n\n";
282
283   // Emit the function start directives
284   emitFunctionStart(MF);
285
286   // Print out code for the function.
287   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
288        I != E; ++I) {
289
290     // Print a label for the basic block.
291     if (I != MF.begin()) {
292       printBasicBlockLabel(I, true, true);
293       O << '\n';
294     }
295
296     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
297          II != E; ++II) {
298       // Print the assembly for the instruction.
299       printInstruction(II);
300       ++EmittedInsts;
301     }
302
303     // Each Basic Block is separated by a newline
304     O << '\n';
305   }
306
307   // Emit function end directives
308   emitFunctionEnd(MF);
309
310   // We didn't modify anything.
311   return false;
312 }
313
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) 
318 {
319   // Does this asm operand have a single letter operand modifier?
320   if (ExtraCode && ExtraCode[0]) 
321     return true; // Unknown modifier.
322
323   printOperand(MI, OpNo);
324   return false;
325 }
326
327 void MipsAsmPrinter::
328 printOperand(const MachineInstr *MI, int opNum) 
329 {
330   const MachineOperand &MO = MI->getOperand(opNum);
331   const TargetRegisterInfo  &RI = *TM.getRegisterInfo();
332   bool closeP = false;
333   bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
334   bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
335
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))
343       O << "%call_hi(";
344     else
345       O << "%hi(";
346     closeP = true;
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)
350       O << "%gp_rel(";
351     else
352       O << "%lo(";
353     closeP = true;
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) 
360           && (!isCodeLarge))
361         O << "%call16(";
362       else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
363         O << "%got(";
364       else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP) 
365                && (isCodeLarge))
366         O << "%call_lo(";
367       closeP = true;
368     }
369   }
370  
371   switch (MO.getType()) 
372   {
373     case MachineOperand::MO_Register:
374       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
375         O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
376       else
377         O << '$' << MO.getReg();
378       break;
379
380     case MachineOperand::MO_Immediate:
381       O << (short int)MO.getImm();
382       break;
383
384     case MachineOperand::MO_MachineBasicBlock:
385       printBasicBlockLabel(MO.getMBB());
386       return;
387
388     case MachineOperand::MO_GlobalAddress:
389       O << Mang->getMangledName(MO.getGlobal());
390       break;
391
392     case MachineOperand::MO_ExternalSymbol:
393       O << MO.getSymbolName();
394       break;
395
396     case MachineOperand::MO_JumpTableIndex:
397       O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
398       << '_' << MO.getIndex();
399       break;
400
401     case MachineOperand::MO_ConstantPoolIndex:
402       O << TAI->getPrivateGlobalPrefix() << "CPI"
403         << getFunctionNumber() << "_" << MO.getIndex();
404       break;
405   
406     default:
407       llvm_unreachable("<unknown operand type>");
408   }
409
410   if (closeP) O << ")";
411 }
412
413 void MipsAsmPrinter::
414 printUnsignedImm(const MachineInstr *MI, int opNum) 
415 {
416   const MachineOperand &MO = MI->getOperand(opNum);
417   if (MO.getType() == MachineOperand::MO_Immediate)
418     O << (unsigned short int)MO.getImm();
419   else 
420     printOperand(MI, opNum);
421 }
422
423 void MipsAsmPrinter::
424 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier) 
425 {
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);
430     O << ", ";
431     printOperand(MI, opNum);
432     return;
433   }
434
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);
439   O << "(";
440   printOperand(MI, opNum+1);
441   O << ")";
442 }
443
444 void MipsAsmPrinter::
445 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier) 
446 {
447   const MachineOperand& MO = MI->getOperand(opNum);
448   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm()); 
449 }
450
451 bool MipsAsmPrinter::
452 doInitialization(Module &M) 
453 {
454   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
455
456   // Tell the assembler which ABI we are using
457   O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
458
459   // TODO: handle O64 ABI
460   if (Subtarget->isABI_EABI())
461     O << "\t.section .gcc_compiled_long" << 
462       (Subtarget->isGP32bit() ? "32" : "64") << '\n';
463
464   // return to previous section
465   O << "\t.previous" << '\n'; 
466
467   return false; // success
468 }
469
470 void MipsAsmPrinter::
471 printModuleLevelGV(const GlobalVariable* GVar) {
472   const TargetData *TD = TM.getTargetData();
473
474   if (!GVar->hasInitializer())
475     return;   // External global require no code
476
477   // Check to see if this is a special global used by LLVM, if so, emit it.
478   if (EmitSpecialLLVMGlobal(GVar))
479     return;
480
481   O << "\n\n";
482   std::string name = Mang->getMangledName(GVar);
483   Constant *C = GVar->getInitializer();
484   if (isa<MDNode>(C) || isa<MDString>(C))
485     return;
486   const Type *CTy = C->getType();
487   unsigned Size = TD->getTypeAllocSize(CTy);
488   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
489   bool printSizeAndType = true;
490
491   // A data structure or array is aligned in memory to the largest
492   // alignment boundary required by any data type inside it (this matches
493   // the Preferred Type Alignment). For integral types, the alignment is
494   // the type size.
495   unsigned Align;
496   if (CTy->getTypeID() == Type::IntegerTyID ||
497       CTy->getTypeID() == Type::VoidTyID) {
498     assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
499     Align = Log2_32(Size);
500   } else
501     Align = TD->getPreferredTypeAlignmentShift(CTy);
502
503   printVisibility(name, GVar->getVisibility());
504
505   SwitchToSection(TAI->SectionForGlobal(GVar));
506
507   if (C->isNullValue() && !GVar->hasSection()) {
508     if (!GVar->isThreadLocal() &&
509         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
510       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
511
512       if (GVar->hasLocalLinkage())
513         O << "\t.local\t" << name << '\n';
514
515       O << TAI->getCOMMDirective() << name << ',' << Size;
516       if (TAI->getCOMMDirectiveTakesAlignment())
517         O << ',' << (1 << Align);
518
519       O << '\n';
520       return;
521     }
522   }
523   switch (GVar->getLinkage()) {
524    case GlobalValue::LinkOnceAnyLinkage:
525    case GlobalValue::LinkOnceODRLinkage:
526    case GlobalValue::CommonLinkage:
527    case GlobalValue::WeakAnyLinkage:
528    case GlobalValue::WeakODRLinkage:
529     // FIXME: Verify correct for weak.
530     // Nonnull linkonce -> weak
531     O << "\t.weak " << name << '\n';
532     break;
533    case GlobalValue::AppendingLinkage:
534     // FIXME: appending linkage variables should go into a section of their name
535     // or something.  For now, just emit them as external.
536    case GlobalValue::ExternalLinkage:
537     // If external or appending, declare as a global symbol
538     O << TAI->getGlobalDirective() << name << '\n';
539     // Fall Through
540    case GlobalValue::PrivateLinkage:
541    case GlobalValue::InternalLinkage:
542     if (CVA && CVA->isCString())
543       printSizeAndType = false;
544     break;
545    case GlobalValue::GhostLinkage:
546     llvm_unreachable("Should not have any unmaterialized functions!");
547    case GlobalValue::DLLImportLinkage:
548     llvm_unreachable("DLLImport linkage is not supported by this target!");
549    case GlobalValue::DLLExportLinkage:
550     llvm_unreachable("DLLExport linkage is not supported by this target!");
551    default:
552     llvm_unreachable("Unknown linkage type!");
553   }
554
555   EmitAlignment(Align, GVar);
556
557   if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
558     O << "\t.type " << name << ",@object\n";
559     O << "\t.size " << name << ',' << Size << '\n';
560   }
561
562   O << name << ":\n";
563   EmitGlobalConstant(C);
564 }
565
566 bool MipsAsmPrinter::
567 doFinalization(Module &M)
568 {
569   // Print out module-level global variables here.
570   for (Module::const_global_iterator I = M.global_begin(),
571          E = M.global_end(); I != E; ++I)
572     printModuleLevelGV(I);
573
574   O << '\n';
575
576   return AsmPrinter::doFinalization(M);
577 }
578
579 // Force static initialization.
580 extern "C" void LLVMInitializeMipsAsmPrinter() { 
581   extern Target TheMipsTarget;
582   TargetRegistry::RegisterAsmPrinter(TheMipsTarget, createMipsCodePrinterPass);
583
584   extern Target TheMipselTarget;
585   TargetRegistry::RegisterAsmPrinter(TheMipselTarget, 
586                                      createMipsCodePrinterPass);
587 }