Rip all of the global variable lowering logic out of TargetAsmInfo. Since
[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/TargetLoweringObjectFile.h" 
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/Mangler.h"
40 #include "llvm/ADT/Statistic.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/MathExtras.h"
46 #include <cctype>
47
48 using namespace llvm;
49
50 STATISTIC(EmittedInsts, "Number of machine instrs printed");
51
52 namespace {
53   class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
54     const MipsSubtarget *Subtarget;
55   public:
56     explicit MipsAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM, 
57                             const TargetAsmInfo *T, bool V)
58       : AsmPrinter(O, TM, T, V) {
59       Subtarget = &TM.getSubtarget<MipsSubtarget>();
60     }
61
62     virtual const char *getPassName() const {
63       return "Mips Assembly Printer";
64     }
65
66     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 
67                          unsigned AsmVariant, const char *ExtraCode);
68     void printOperand(const MachineInstr *MI, int opNum);
69     void printUnsignedImm(const MachineInstr *MI, int opNum);
70     void printMemOperand(const MachineInstr *MI, int opNum, 
71                          const char *Modifier = 0);
72     void printFCCOperand(const MachineInstr *MI, int opNum, 
73                          const char *Modifier = 0);
74     void PrintGlobalVariable(const GlobalVariable *GVar);
75     void printSavedRegsBitmask(MachineFunction &MF);
76     void printHex32(unsigned int Value);
77
78     const char *emitCurrentABIString(void);
79     void emitFunctionStart(MachineFunction &MF);
80     void emitFunctionEnd(MachineFunction &MF);
81     void emitFrameDirective(MachineFunction &MF);
82
83     bool printInstruction(const MachineInstr *MI);  // autogenerated.
84     bool runOnMachineFunction(MachineFunction &F);
85     bool doInitialization(Module &M);
86   };
87 } // end of anonymous namespace
88
89 #include "MipsGenAsmWriter.inc"
90
91 //===----------------------------------------------------------------------===//
92 //
93 //  Mips Asm Directives
94 //
95 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
96 //  Describe the stack frame.
97 //
98 //  -- Mask directives "(f)mask  bitmask, offset" 
99 //  Tells the assembler which registers are saved and where.
100 //  bitmask - contain a little endian bitset indicating which registers are 
101 //            saved on function prologue (e.g. with a 0x80000000 mask, the 
102 //            assembler knows the register 31 (RA) is saved at prologue.
103 //  offset  - the position before stack pointer subtraction indicating where 
104 //            the first saved register on prologue is located. (e.g. with a
105 //
106 //  Consider the following function prologue:
107 //
108 //    .frame  $fp,48,$ra
109 //    .mask   0xc0000000,-8
110 //       addiu $sp, $sp, -48
111 //       sw $ra, 40($sp)
112 //       sw $fp, 36($sp)
113 //
114 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and 
115 //    30 (FP) are saved at prologue. As the save order on prologue is from 
116 //    left to right, RA is saved first. A -8 offset means that after the 
117 //    stack pointer subtration, the first register in the mask (RA) will be
118 //    saved at address 48-8=40.
119 //
120 //===----------------------------------------------------------------------===//
121
122 //===----------------------------------------------------------------------===//
123 // Mask directives
124 //===----------------------------------------------------------------------===//
125
126 // Create a bitmask with all callee saved registers for CPU or Floating Point 
127 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
128 void MipsAsmPrinter::
129 printSavedRegsBitmask(MachineFunction &MF)
130 {
131   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
132   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
133              
134   // CPU and FPU Saved Registers Bitmasks
135   unsigned int CPUBitmask = 0;
136   unsigned int FPUBitmask = 0;
137
138   // Set the CPU and FPU Bitmasks
139   MachineFrameInfo *MFI = MF.getFrameInfo();
140   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
141   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
142     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
143     if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
144       CPUBitmask |= (1 << RegNum);
145     else
146       FPUBitmask |= (1 << RegNum);
147   }
148
149   // Return Address and Frame registers must also be set in CPUBitmask.
150   if (RI.hasFP(MF)) 
151     CPUBitmask |= (1 << MipsRegisterInfo::
152                 getRegisterNumbering(RI.getFrameRegister(MF)));
153   
154   if (MF.getFrameInfo()->hasCalls()) 
155     CPUBitmask |= (1 << MipsRegisterInfo::
156                 getRegisterNumbering(RI.getRARegister()));
157
158   // Print CPUBitmask
159   O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
160     << MipsFI->getCPUTopSavedRegOff() << '\n';
161
162   // Print FPUBitmask
163   O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
164     << MipsFI->getFPUTopSavedRegOff() << '\n';
165 }
166
167 // Print a 32 bit hex number with all numbers.
168 void MipsAsmPrinter::
169 printHex32(unsigned int Value) 
170 {
171   O << "0x";
172   for (int i = 7; i >= 0; i--) 
173     O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
174 }
175
176 //===----------------------------------------------------------------------===//
177 // Frame and Set directives
178 //===----------------------------------------------------------------------===//
179
180 /// Frame Directive
181 void MipsAsmPrinter::
182 emitFrameDirective(MachineFunction &MF)
183 {
184   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
185
186   unsigned stackReg  = RI.getFrameRegister(MF);
187   unsigned returnReg = RI.getRARegister();
188   unsigned stackSize = MF.getFrameInfo()->getStackSize();
189
190
191   O << "\t.frame\t" << '$' << LowercaseString(RI.get(stackReg).AsmName)
192                     << ',' << stackSize << ','
193                     << '$' << LowercaseString(RI.get(returnReg).AsmName)
194                     << '\n';
195 }
196
197 /// Emit Set directives.
198 const char * MipsAsmPrinter::
199 emitCurrentABIString(void) 
200 {  
201   switch(Subtarget->getTargetABI()) {
202     case MipsSubtarget::O32:  return "abi32";  
203     case MipsSubtarget::O64:  return "abiO64";
204     case MipsSubtarget::N32:  return "abiN32";
205     case MipsSubtarget::N64:  return "abi64";
206     case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
207     default: break;
208   }
209
210   llvm_unreachable("Unknown Mips ABI");
211   return NULL;
212 }  
213
214 /// Emit the directives used by GAS on the start of functions
215 void MipsAsmPrinter::emitFunctionStart(MachineFunction &MF) {
216   // Print out the label for the function.
217   const Function *F = MF.getFunction();
218   SwitchToSection(getObjFileLowering().SectionForGlobal(F, TM));
219
220   // 2 bits aligned
221   EmitAlignment(MF.getAlignment(), F);
222
223   O << "\t.globl\t"  << CurrentFnName << '\n';
224   O << "\t.ent\t"    << CurrentFnName << '\n';
225
226   printVisibility(CurrentFnName, F->getVisibility());
227
228   if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
229     O << "\t.type\t"   << CurrentFnName << ", @function\n";
230
231   O << CurrentFnName << ":\n";
232
233   emitFrameDirective(MF);
234   printSavedRegsBitmask(MF);
235
236   O << '\n';
237 }
238
239 /// Emit the directives used by GAS on the end of functions
240 void MipsAsmPrinter::
241 emitFunctionEnd(MachineFunction &MF) 
242 {
243   // There are instruction for this macros, but they must
244   // always be at the function end, and we can't emit and
245   // break with BB logic. 
246   O << "\t.set\tmacro\n"; 
247   O << "\t.set\treorder\n"; 
248
249   O << "\t.end\t" << CurrentFnName << '\n';
250   if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
251     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
252 }
253
254 /// runOnMachineFunction - This uses the printMachineInstruction()
255 /// method to print assembly for each instruction.
256 bool MipsAsmPrinter::
257 runOnMachineFunction(MachineFunction &MF) 
258 {
259   this->MF = &MF;
260
261   SetupMachineFunction(MF);
262
263   // Print out constants referenced by the function
264   EmitConstantPool(MF.getConstantPool());
265
266   // Print out jump tables referenced by the function
267   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
268
269   O << "\n\n";
270
271   // Emit the function start directives
272   emitFunctionStart(MF);
273
274   // Print out code for the function.
275   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
276        I != E; ++I) {
277
278     // Print a label for the basic block.
279     if (I != MF.begin()) {
280       printBasicBlockLabel(I, true, true);
281       O << '\n';
282     }
283
284     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
285          II != E; ++II) {
286       // Print the assembly for the instruction.
287       printInstruction(II);
288       ++EmittedInsts;
289     }
290
291     // Each Basic Block is separated by a newline
292     O << '\n';
293   }
294
295   // Emit function end directives
296   emitFunctionEnd(MF);
297
298   // We didn't modify anything.
299   return false;
300 }
301
302 // Print out an operand for an inline asm expression.
303 bool MipsAsmPrinter::
304 PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 
305                 unsigned AsmVariant, const char *ExtraCode) 
306 {
307   // Does this asm operand have a single letter operand modifier?
308   if (ExtraCode && ExtraCode[0]) 
309     return true; // Unknown modifier.
310
311   printOperand(MI, OpNo);
312   return false;
313 }
314
315 void MipsAsmPrinter::
316 printOperand(const MachineInstr *MI, int opNum) 
317 {
318   const MachineOperand &MO = MI->getOperand(opNum);
319   const TargetRegisterInfo  &RI = *TM.getRegisterInfo();
320   bool closeP = false;
321   bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
322   bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
323
324   // %hi and %lo used on mips gas to load global addresses on
325   // static code. %got is used to load global addresses when 
326   // using PIC_. %call16 is used to load direct call targets
327   // on PIC_ and small code size. %call_lo and %call_hi load 
328   // direct call targets on PIC_ and large code size.
329   if (MI->getOpcode() == Mips::LUi && !MO.isReg() && !MO.isImm()) {
330     if ((isPIC) && (isCodeLarge))
331       O << "%call_hi(";
332     else
333       O << "%hi(";
334     closeP = true;
335   } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isReg() && !MO.isImm()) {
336     const MachineOperand &firstMO = MI->getOperand(opNum-1);
337     if (firstMO.getReg() == Mips::GP)
338       O << "%gp_rel(";
339     else
340       O << "%lo(";
341     closeP = true;
342   } else if ((isPIC) && (MI->getOpcode() == Mips::LW) &&
343              (!MO.isReg()) && (!MO.isImm())) {
344     const MachineOperand &firstMO = MI->getOperand(opNum-1);
345     const MachineOperand &lastMO  = MI->getOperand(opNum+1);
346     if ((firstMO.isReg()) && (lastMO.isReg())) {
347       if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP) 
348           && (!isCodeLarge))
349         O << "%call16(";
350       else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
351         O << "%got(";
352       else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP) 
353                && (isCodeLarge))
354         O << "%call_lo(";
355       closeP = true;
356     }
357   }
358  
359   switch (MO.getType()) 
360   {
361     case MachineOperand::MO_Register:
362       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
363         O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
364       else
365         O << '$' << MO.getReg();
366       break;
367
368     case MachineOperand::MO_Immediate:
369       O << (short int)MO.getImm();
370       break;
371
372     case MachineOperand::MO_MachineBasicBlock:
373       printBasicBlockLabel(MO.getMBB());
374       return;
375
376     case MachineOperand::MO_GlobalAddress:
377       O << Mang->getMangledName(MO.getGlobal());
378       break;
379
380     case MachineOperand::MO_ExternalSymbol:
381       O << MO.getSymbolName();
382       break;
383
384     case MachineOperand::MO_JumpTableIndex:
385       O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
386       << '_' << MO.getIndex();
387       break;
388
389     case MachineOperand::MO_ConstantPoolIndex:
390       O << TAI->getPrivateGlobalPrefix() << "CPI"
391         << getFunctionNumber() << "_" << MO.getIndex();
392       break;
393   
394     default:
395       llvm_unreachable("<unknown operand type>");
396   }
397
398   if (closeP) O << ")";
399 }
400
401 void MipsAsmPrinter::
402 printUnsignedImm(const MachineInstr *MI, int opNum) {
403   const MachineOperand &MO = MI->getOperand(opNum);
404   if (MO.getType() == MachineOperand::MO_Immediate)
405     O << (unsigned short int)MO.getImm();
406   else 
407     printOperand(MI, opNum);
408 }
409
410 void MipsAsmPrinter::
411 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
412   // when using stack locations for not load/store instructions
413   // print the same way as all normal 3 operand instructions.
414   if (Modifier && !strcmp(Modifier, "stackloc")) {
415     printOperand(MI, opNum+1);
416     O << ", ";
417     printOperand(MI, opNum);
418     return;
419   }
420
421   // Load/Store memory operands -- imm($reg) 
422   // If PIC target the target is loaded as the 
423   // pattern lw $25,%call16($28)
424   printOperand(MI, opNum);
425   O << "(";
426   printOperand(MI, opNum+1);
427   O << ")";
428 }
429
430 void MipsAsmPrinter::
431 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
432   const MachineOperand& MO = MI->getOperand(opNum);
433   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm()); 
434 }
435
436 bool MipsAsmPrinter::doInitialization(Module &M) {
437   // FIXME: Use SwitchToDataSection.
438   
439   // Tell the assembler which ABI we are using
440   O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
441
442   // TODO: handle O64 ABI
443   if (Subtarget->isABI_EABI())
444     O << "\t.section .gcc_compiled_long" << 
445       (Subtarget->isGP32bit() ? "32" : "64") << '\n';
446
447   // return to previous section
448   O << "\t.previous" << '\n'; 
449
450   return AsmPrinter::doInitialization(M);
451 }
452
453 void MipsAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
454   const TargetData *TD = TM.getTargetData();
455
456   if (!GVar->hasInitializer())
457     return;   // External global require no code
458
459   // Check to see if this is a special global used by LLVM, if so, emit it.
460   if (EmitSpecialLLVMGlobal(GVar))
461     return;
462
463   O << "\n\n";
464   std::string name = Mang->getMangledName(GVar);
465   Constant *C = GVar->getInitializer();
466   if (isa<MDNode>(C) || isa<MDString>(C))
467     return;
468   const Type *CTy = C->getType();
469   unsigned Size = TD->getTypeAllocSize(CTy);
470   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
471   bool printSizeAndType = true;
472
473   // A data structure or array is aligned in memory to the largest
474   // alignment boundary required by any data type inside it (this matches
475   // the Preferred Type Alignment). For integral types, the alignment is
476   // the type size.
477   unsigned Align;
478   if (CTy->getTypeID() == Type::IntegerTyID ||
479       CTy->getTypeID() == Type::VoidTyID) {
480     assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
481     Align = Log2_32(Size);
482   } else
483     Align = TD->getPreferredTypeAlignmentShift(CTy);
484
485   printVisibility(name, GVar->getVisibility());
486
487   SwitchToSection(getObjFileLowering().SectionForGlobal(GVar, TM));
488
489   if (C->isNullValue() && !GVar->hasSection()) {
490     if (!GVar->isThreadLocal() &&
491         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
492       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
493
494       if (GVar->hasLocalLinkage())
495         O << "\t.local\t" << name << '\n';
496
497       O << TAI->getCOMMDirective() << name << ',' << Size;
498       if (TAI->getCOMMDirectiveTakesAlignment())
499         O << ',' << (1 << Align);
500
501       O << '\n';
502       return;
503     }
504   }
505   switch (GVar->getLinkage()) {
506    case GlobalValue::LinkOnceAnyLinkage:
507    case GlobalValue::LinkOnceODRLinkage:
508    case GlobalValue::CommonLinkage:
509    case GlobalValue::WeakAnyLinkage:
510    case GlobalValue::WeakODRLinkage:
511     // FIXME: Verify correct for weak.
512     // Nonnull linkonce -> weak
513     O << "\t.weak " << name << '\n';
514     break;
515    case GlobalValue::AppendingLinkage:
516     // FIXME: appending linkage variables should go into a section of their name
517     // or something.  For now, just emit them as external.
518    case GlobalValue::ExternalLinkage:
519     // If external or appending, declare as a global symbol
520     O << TAI->getGlobalDirective() << name << '\n';
521     // Fall Through
522    case GlobalValue::PrivateLinkage:
523    case GlobalValue::LinkerPrivateLinkage:
524    case GlobalValue::InternalLinkage:
525     if (CVA && CVA->isCString())
526       printSizeAndType = false;
527     break;
528    case GlobalValue::GhostLinkage:
529     llvm_unreachable("Should not have any unmaterialized functions!");
530    case GlobalValue::DLLImportLinkage:
531     llvm_unreachable("DLLImport linkage is not supported by this target!");
532    case GlobalValue::DLLExportLinkage:
533     llvm_unreachable("DLLExport linkage is not supported by this target!");
534    default:
535     llvm_unreachable("Unknown linkage type!");
536   }
537
538   EmitAlignment(Align, GVar);
539
540   if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
541     O << "\t.type " << name << ",@object\n";
542     O << "\t.size " << name << ',' << Size << '\n';
543   }
544
545   O << name << ":\n";
546   EmitGlobalConstant(C);
547 }
548
549
550 // Force static initialization.
551 extern "C" void LLVMInitializeMipsAsmPrinter() { 
552   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
553   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
554 }