Put code that generates debug labels into TableGen so that it can be used by
[oota-llvm.git] / lib / Target / Mips / 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/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"
42 #include <cctype>
43
44 using namespace llvm;
45
46 STATISTIC(EmittedInsts, "Number of machine instrs printed");
47
48 namespace {
49   struct VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
50
51     const MipsSubtarget *Subtarget;
52
53     MipsAsmPrinter(raw_ostream &O, MipsTargetMachine &TM, 
54                    const TargetAsmInfo *T): 
55                    AsmPrinter(O, TM, T) {
56       Subtarget = &TM.getSubtarget<MipsSubtarget>();
57     }
58
59     virtual const char *getPassName() const {
60       return "Mips Assembly Printer";
61     }
62
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);
74
75     const char *emitCurrentABIString(void);
76     void emitFunctionStart(MachineFunction &MF);
77     void emitFunctionEnd(MachineFunction &MF);
78     void emitFrameDirective(MachineFunction &MF);
79
80     bool printInstruction(const MachineInstr *MI);  // autogenerated.
81     bool runOnMachineFunction(MachineFunction &F);
82     bool doInitialization(Module &M);
83     bool doFinalization(Module &M);
84   };
85 } // end of anonymous namespace
86
87 #include "MipsGenAsmWriter.inc"
88
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) 
95 {
96   return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo());
97 }
98
99 //===----------------------------------------------------------------------===//
100 //
101 //  Mips Asm Directives
102 //
103 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
104 //  Describe the stack frame.
105 //
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
113 //
114 //  Consider the following function prologue:
115 //
116 //    .frame  $fp,48,$ra
117 //    .mask   0xc0000000,-8
118 //       addiu $sp, $sp, -48
119 //       sw $ra, 40($sp)
120 //       sw $fp, 36($sp)
121 //
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.
127 //
128 //===----------------------------------------------------------------------===//
129
130 //===----------------------------------------------------------------------===//
131 // Mask directives
132 //===----------------------------------------------------------------------===//
133
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)
138 {
139   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
140   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
141              
142   // CPU and FPU Saved Registers Bitmasks
143   unsigned int CPUBitmask = 0;
144   unsigned int FPUBitmask = 0;
145
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);
153     else
154       FPUBitmask |= (1 << RegNum);
155   }
156
157   // Return Address and Frame registers must also be set in CPUBitmask.
158   if (RI.hasFP(MF)) 
159     CPUBitmask |= (1 << MipsRegisterInfo::
160                 getRegisterNumbering(RI.getFrameRegister(MF)));
161   
162   if (MF.getFrameInfo()->hasCalls()) 
163     CPUBitmask |= (1 << MipsRegisterInfo::
164                 getRegisterNumbering(RI.getRARegister()));
165
166   // Print CPUBitmask
167   O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
168     << MipsFI->getCPUTopSavedRegOff() << '\n';
169
170   // Print FPUBitmask
171   O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
172     << MipsFI->getFPUTopSavedRegOff() << '\n';
173 }
174
175 // Print a 32 bit hex number with all numbers.
176 void MipsAsmPrinter::
177 printHex32(unsigned int Value) 
178 {
179   O << "0x";
180   for (int i = 7; i >= 0; i--) 
181     O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
182 }
183
184 //===----------------------------------------------------------------------===//
185 // Frame and Set directives
186 //===----------------------------------------------------------------------===//
187
188 /// Frame Directive
189 void MipsAsmPrinter::
190 emitFrameDirective(MachineFunction &MF)
191 {
192   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
193
194   unsigned stackReg  = RI.getFrameRegister(MF);
195   unsigned returnReg = RI.getRARegister();
196   unsigned stackSize = MF.getFrameInfo()->getStackSize();
197
198
199   O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
200                     << ',' << stackSize << ','
201                     << '$' << LowercaseString(RI.get(returnReg).AsmName)
202                     << '\n';
203 }
204
205 /// Emit Set directives.
206 const char * MipsAsmPrinter::
207 emitCurrentABIString(void) 
208 {  
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
215     default: break;
216   }
217
218   assert(0 && "Unknown Mips ABI");
219   return NULL;
220 }  
221
222 /// Emit the directives used by GAS on the start of functions
223 void MipsAsmPrinter::
224 emitFunctionStart(MachineFunction &MF)
225 {
226   // Print out the label for the function.
227   const Function *F = MF.getFunction();
228   SwitchToSection(TAI->SectionForGlobal(F));
229
230   // 2 bits aligned
231   EmitAlignment(2, F);
232
233   O << "\t.globl\t"  << CurrentFnName << '\n';
234   O << "\t.ent\t"    << CurrentFnName << '\n';
235
236   printVisibility(CurrentFnName, F->getVisibility());
237
238   if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
239     O << "\t.type\t"   << CurrentFnName << ", @function\n";
240
241   O << CurrentFnName << ":\n";
242
243   emitFrameDirective(MF);
244   printSavedRegsBitmask(MF);
245
246   O << '\n';
247 }
248
249 /// Emit the directives used by GAS on the end of functions
250 void MipsAsmPrinter::
251 emitFunctionEnd(MachineFunction &MF) 
252 {
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"; 
258
259   O << "\t.end\t" << CurrentFnName << '\n';
260   if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
261     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
262 }
263
264 /// runOnMachineFunction - This uses the printMachineInstruction()
265 /// method to print assembly for each instruction.
266 bool MipsAsmPrinter::
267 runOnMachineFunction(MachineFunction &MF) 
268 {
269   SetupMachineFunction(MF);
270
271   // Print out constants referenced by the function
272   EmitConstantPool(MF.getConstantPool());
273
274   // Print out jump tables referenced by the function
275   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
276
277   O << "\n\n";
278
279   // Emit the function start directives
280   emitFunctionStart(MF);
281
282   // Print out code for the function.
283   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
284        I != E; ++I) {
285
286     // Print a label for the basic block.
287     if (I != MF.begin()) {
288       printBasicBlockLabel(I, true, true);
289       O << '\n';
290     }
291
292     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
293          II != E; ++II) {
294       // Print the assembly for the instruction.
295       printInstruction(II);
296       ++EmittedInsts;
297     }
298
299     // Each Basic Block is separated by a newline
300     O << '\n';
301   }
302
303   // Emit function end directives
304   emitFunctionEnd(MF);
305
306   // We didn't modify anything.
307   return false;
308 }
309
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) 
314 {
315   // Does this asm operand have a single letter operand modifier?
316   if (ExtraCode && ExtraCode[0]) 
317     return true; // Unknown modifier.
318
319   printOperand(MI, OpNo);
320   return false;
321 }
322
323 void MipsAsmPrinter::
324 printOperand(const MachineInstr *MI, int opNum) 
325 {
326   const MachineOperand &MO = MI->getOperand(opNum);
327   const TargetRegisterInfo  &RI = *TM.getRegisterInfo();
328   bool closeP = false;
329   bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
330   bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
331
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))
339       O << "%call_hi(";
340     else
341       O << "%hi(";
342     closeP = true;
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)
346       O << "%gp_rel(";
347     else
348       O << "%lo(";
349     closeP = true;
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) 
356           && (!isCodeLarge))
357         O << "%call16(";
358       else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
359         O << "%got(";
360       else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP) 
361                && (isCodeLarge))
362         O << "%call_lo(";
363       closeP = true;
364     }
365   }
366  
367   switch (MO.getType()) 
368   {
369     case MachineOperand::MO_Register:
370       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
371         O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
372       else
373         O << '$' << MO.getReg();
374       break;
375
376     case MachineOperand::MO_Immediate:
377       O << (short int)MO.getImm();
378       break;
379
380     case MachineOperand::MO_MachineBasicBlock:
381       printBasicBlockLabel(MO.getMBB());
382       return;
383
384     case MachineOperand::MO_GlobalAddress:
385       {
386         const GlobalValue *GV = MO.getGlobal();
387         O << Mang->getValueName(GV);
388       }
389       break;
390
391     case MachineOperand::MO_ExternalSymbol:
392       O << MO.getSymbolName();
393       break;
394
395     case MachineOperand::MO_JumpTableIndex:
396       O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
397       << '_' << MO.getIndex();
398       break;
399
400     case MachineOperand::MO_ConstantPoolIndex:
401       O << TAI->getPrivateGlobalPrefix() << "CPI"
402         << getFunctionNumber() << "_" << MO.getIndex();
403       break;
404   
405     default:
406       O << "<unknown operand type>"; abort (); break;
407   }
408
409   if (closeP) O << ")";
410 }
411
412 void MipsAsmPrinter::
413 printUnsignedImm(const MachineInstr *MI, int opNum) 
414 {
415   const MachineOperand &MO = MI->getOperand(opNum);
416   if (MO.getType() == MachineOperand::MO_Immediate)
417     O << (unsigned short int)MO.getImm();
418   else 
419     printOperand(MI, opNum);
420 }
421
422 void MipsAsmPrinter::
423 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier) 
424 {
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);
429     O << ", ";
430     printOperand(MI, opNum);
431     return;
432   }
433
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);
438   O << "(";
439   printOperand(MI, opNum+1);
440   O << ")";
441 }
442
443 void MipsAsmPrinter::
444 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier) 
445 {
446   const MachineOperand& MO = MI->getOperand(opNum);
447   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm()); 
448 }
449
450 bool MipsAsmPrinter::
451 doInitialization(Module &M) 
452 {
453   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
454
455   // Tell the assembler which ABI we are using
456   O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
457
458   // TODO: handle O64 ABI
459   if (Subtarget->isABI_EABI())
460     O << "\t.section .gcc_compiled_long" << 
461       (Subtarget->isGP32bit() ? "32" : "64") << '\n';
462
463   // return to previous section
464   O << "\t.previous" << '\n'; 
465
466   return false; // success
467 }
468
469 void MipsAsmPrinter::
470 printModuleLevelGV(const GlobalVariable* GVar) {
471   const TargetData *TD = TM.getTargetData();
472
473   if (!GVar->hasInitializer())
474     return;   // External global require no code
475
476   // Check to see if this is a special global used by LLVM, if so, emit it.
477   if (EmitSpecialLLVMGlobal(GVar))
478     return;
479
480   O << "\n\n";
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;
487
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
491   // the type size.
492   unsigned Align;
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);
497   } else
498     Align = TD->getPreferredTypeAlignmentShift(CTy);
499
500   printVisibility(name, GVar->getVisibility());
501
502   SwitchToSection(TAI->SectionForGlobal(GVar));
503
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.
508
509       if (GVar->hasLocalLinkage())
510         O << "\t.local\t" << name << '\n';
511
512       O << TAI->getCOMMDirective() << name << ',' << Size;
513       if (TAI->getCOMMDirectiveTakesAlignment())
514         O << ',' << (1 << Align);
515
516       O << '\n';
517       return;
518     }
519   }
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';
527     break;
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';
534     // Fall Through
535    case GlobalValue::PrivateLinkage:
536    case GlobalValue::InternalLinkage:
537     if (CVA && CVA->isCString())
538       printSizeAndType = false;
539     break;
540    case GlobalValue::GhostLinkage:
541     cerr << "Should not have any unmaterialized functions!\n";
542     abort();
543    case GlobalValue::DLLImportLinkage:
544     cerr << "DLLImport linkage is not supported by this target!\n";
545     abort();
546    case GlobalValue::DLLExportLinkage:
547     cerr << "DLLExport linkage is not supported by this target!\n";
548     abort();
549    default:
550     assert(0 && "Unknown linkage type!");
551   }
552
553   EmitAlignment(Align, GVar);
554
555   if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
556     O << "\t.type " << name << ",@object\n";
557     O << "\t.size " << name << ',' << Size << '\n';
558   }
559
560   O << name << ":\n";
561   EmitGlobalConstant(C);
562 }
563
564 bool MipsAsmPrinter::
565 doFinalization(Module &M)
566 {
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);
571
572   O << '\n';
573
574   return AsmPrinter::doFinalization(M);
575 }