Add plumbing for the `linker_private' linkage type. This type is meant for
[oota-llvm.git] / lib / Target / Sparc / AsmPrinter / SparcAsmPrinter.cpp
1 //===-- SparcAsmPrinter.cpp - Sparc 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 SPARC assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "Sparc.h"
17 #include "SparcInstrInfo.h"
18 #include "SparcTargetMachine.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/MDNode.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetRegistry.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/MathExtras.h"
37 #include <cctype>
38 #include <cstring>
39 #include <map>
40 using namespace llvm;
41
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43
44 namespace {
45   class VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {
46     /// We name each basic block in a Function with a unique number, so
47     /// that we can consistently refer to them later. This is cleared
48     /// at the beginning of each call to runOnMachineFunction().
49     ///
50     typedef std::map<const Value *, unsigned> ValueMapTy;
51     ValueMapTy NumberForBB;
52     unsigned BBNumber;
53   public:
54     explicit SparcAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
55                              const TargetAsmInfo *T, bool V)
56       : AsmPrinter(O, TM, T, V), BBNumber(0) {}
57
58     virtual const char *getPassName() const {
59       return "Sparc Assembly Printer";
60     }
61
62     void printModuleLevelGV(const GlobalVariable* GVar);
63     void printOperand(const MachineInstr *MI, int opNum);
64     void printMemOperand(const MachineInstr *MI, int opNum,
65                          const char *Modifier = 0);
66     void printCCOperand(const MachineInstr *MI, int opNum);
67
68     bool printInstruction(const MachineInstr *MI);  // autogenerated.
69     bool runOnMachineFunction(MachineFunction &F);
70     bool doInitialization(Module &M);
71     bool doFinalization(Module &M);
72     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
73                        unsigned AsmVariant, const char *ExtraCode);
74     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
75                              unsigned AsmVariant, const char *ExtraCode);
76   };
77 } // end of anonymous namespace
78
79 #include "SparcGenAsmWriter.inc"
80
81 /// createSparcCodePrinterPass - Returns a pass that prints the SPARC
82 /// assembly code for a MachineFunction to the given output stream,
83 /// using the given target machine description.  This should work
84 /// regardless of whether the function is in SSA form.
85 ///
86 FunctionPass *llvm::createSparcCodePrinterPass(formatted_raw_ostream &o,
87                                                TargetMachine &tm,
88                                                bool verbose) {
89   return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
90 }
91
92
93 /// runOnMachineFunction - This uses the printInstruction()
94 /// method to print assembly for each instruction.
95 ///
96 bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
97   this->MF = &MF;
98
99   SetupMachineFunction(MF);
100
101   // Print out constants referenced by the function
102   EmitConstantPool(MF.getConstantPool());
103
104   // BBNumber is used here so that a given Printer will never give two
105   // BBs the same name. (If you have a better way, please let me know!)
106
107   O << "\n\n";
108
109   // Print out the label for the function.
110   const Function *F = MF.getFunction();
111   SwitchToSection(TAI->SectionForGlobal(F));
112   EmitAlignment(MF.getAlignment(), F);
113   O << "\t.globl\t" << CurrentFnName << '\n';
114
115   printVisibility(CurrentFnName, F->getVisibility());
116
117   O << "\t.type\t" << CurrentFnName << ", #function\n";
118   O << CurrentFnName << ":\n";
119
120   // Number each basic block so that we can consistently refer to them
121   // in PC-relative references.
122   // FIXME: Why not use the MBB numbers?
123   NumberForBB.clear();
124   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
125        I != E; ++I) {
126     NumberForBB[I->getBasicBlock()] = BBNumber++;
127   }
128
129   // Print out code for the function.
130   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
131        I != E; ++I) {
132     // Print a label for the basic block.
133     if (I != MF.begin()) {
134       printBasicBlockLabel(I, true, true);
135       O << '\n';
136     }
137     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
138          II != E; ++II) {
139       // Print the assembly for the instruction.
140       printInstruction(II);
141       ++EmittedInsts;
142     }
143   }
144
145   // We didn't modify anything.
146   return false;
147 }
148
149 void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
150   const MachineOperand &MO = MI->getOperand (opNum);
151   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
152   bool CloseParen = false;
153   if (MI->getOpcode() == SP::SETHIi && !MO.isReg() && !MO.isImm()) {
154     O << "%hi(";
155     CloseParen = true;
156   } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri) &&
157              !MO.isReg() && !MO.isImm()) {
158     O << "%lo(";
159     CloseParen = true;
160   }
161   switch (MO.getType()) {
162   case MachineOperand::MO_Register:
163     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
164       O << "%" << LowercaseString (RI.get(MO.getReg()).AsmName);
165     else
166       O << "%reg" << MO.getReg();
167     break;
168
169   case MachineOperand::MO_Immediate:
170     O << (int)MO.getImm();
171     break;
172   case MachineOperand::MO_MachineBasicBlock:
173     printBasicBlockLabel(MO.getMBB());
174     return;
175   case MachineOperand::MO_GlobalAddress:
176     O << Mang->getMangledName(MO.getGlobal());
177     break;
178   case MachineOperand::MO_ExternalSymbol:
179     O << MO.getSymbolName();
180     break;
181   case MachineOperand::MO_ConstantPoolIndex:
182     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
183       << MO.getIndex();
184     break;
185   default:
186     llvm_unreachable("<unknown operand type>");
187   }
188   if (CloseParen) O << ")";
189 }
190
191 void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
192                                       const char *Modifier) {
193   printOperand(MI, opNum);
194
195   // If this is an ADD operand, emit it like normal operands.
196   if (Modifier && !strcmp(Modifier, "arith")) {
197     O << ", ";
198     printOperand(MI, opNum+1);
199     return;
200   }
201
202   if (MI->getOperand(opNum+1).isReg() &&
203       MI->getOperand(opNum+1).getReg() == SP::G0)
204     return;   // don't print "+%g0"
205   if (MI->getOperand(opNum+1).isImm() &&
206       MI->getOperand(opNum+1).getImm() == 0)
207     return;   // don't print "+0"
208
209   O << "+";
210   if (MI->getOperand(opNum+1).isGlobal() ||
211       MI->getOperand(opNum+1).isCPI()) {
212     O << "%lo(";
213     printOperand(MI, opNum+1);
214     O << ")";
215   } else {
216     printOperand(MI, opNum+1);
217   }
218 }
219
220 void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
221   int CC = (int)MI->getOperand(opNum).getImm();
222   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
223 }
224
225 bool SparcAsmPrinter::doInitialization(Module &M) {
226   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
227   return false; // success
228 }
229
230 bool SparcAsmPrinter::doFinalization(Module &M) {
231   // Print out module-level global variables here.
232   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
233        I != E; ++I)
234     printModuleLevelGV(I);
235
236   O << '\n';
237
238   return AsmPrinter::doFinalization(M);
239 }
240
241 void SparcAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
242   const TargetData *TD = TM.getTargetData();
243
244   if (!GVar->hasInitializer())
245     return;  // External global require no code
246
247   // Check to see if this is a special global used by LLVM, if so, emit it.
248   if (EmitSpecialLLVMGlobal(GVar))
249     return;
250
251   O << "\n\n";
252   std::string name = Mang->getMangledName(GVar);
253   Constant *C = GVar->getInitializer();
254   if (isa<MDNode>(C) || isa<MDString>(C))
255     return;
256   unsigned Size = TD->getTypeAllocSize(C->getType());
257   unsigned Align = TD->getPreferredAlignment(GVar);
258
259   printVisibility(name, GVar->getVisibility());
260
261   SwitchToSection(TAI->SectionForGlobal(GVar));
262
263   if (C->isNullValue() && !GVar->hasSection()) {
264     if (!GVar->isThreadLocal() &&
265         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
266       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
267
268       if (GVar->hasLocalLinkage())
269         O << "\t.local " << name << '\n';
270
271       O << TAI->getCOMMDirective() << name << ',' << Size;
272       if (TAI->getCOMMDirectiveTakesAlignment())
273         O << ',' << (1 << Align);
274
275       O << '\n';
276       return;
277     }
278   }
279
280   switch (GVar->getLinkage()) {
281    case GlobalValue::CommonLinkage:
282    case GlobalValue::LinkOnceAnyLinkage:
283    case GlobalValue::LinkOnceODRLinkage:
284    case GlobalValue::WeakAnyLinkage: // FIXME: Verify correct for weak.
285    case GlobalValue::WeakODRLinkage: // FIXME: Verify correct for weak.
286     // Nonnull linkonce -> weak
287     O << "\t.weak " << name << '\n';
288     break;
289    case GlobalValue::AppendingLinkage:
290     // FIXME: appending linkage variables should go into a section of
291     // their name or something.  For now, just emit them as external.
292    case GlobalValue::ExternalLinkage:
293     // If external or appending, declare as a global symbol
294     O << TAI->getGlobalDirective() << name << '\n';
295     // FALL THROUGH
296    case GlobalValue::PrivateLinkage:
297    case GlobalValue::LinkerPrivateLinkage:
298    case GlobalValue::InternalLinkage:
299     break;
300    case GlobalValue::GhostLinkage:
301     llvm_unreachable("Should not have any unmaterialized functions!");
302    case GlobalValue::DLLImportLinkage:
303     llvm_unreachable("DLLImport linkage is not supported by this target!");
304    case GlobalValue::DLLExportLinkage:
305     llvm_unreachable("DLLExport linkage is not supported by this target!");
306    default:
307     llvm_unreachable("Unknown linkage type!");
308   }
309
310   EmitAlignment(Align, GVar);
311
312   if (TAI->hasDotTypeDotSizeDirective()) {
313     O << "\t.type " << name << ",#object\n";
314     O << "\t.size " << name << ',' << Size << '\n';
315   }
316
317   O << name << ":\n";
318   EmitGlobalConstant(C);
319 }
320
321 /// PrintAsmOperand - Print out an operand for an inline asm expression.
322 ///
323 bool SparcAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
324                                       unsigned AsmVariant,
325                                       const char *ExtraCode) {
326   if (ExtraCode && ExtraCode[0]) {
327     if (ExtraCode[1] != 0) return true; // Unknown modifier.
328
329     switch (ExtraCode[0]) {
330     default: return true;  // Unknown modifier.
331     case 'r':
332      break;
333     }
334   }
335
336   printOperand(MI, OpNo);
337
338   return false;
339 }
340
341 bool SparcAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
342                                             unsigned OpNo,
343                                             unsigned AsmVariant,
344                                             const char *ExtraCode) {
345   if (ExtraCode && ExtraCode[0])
346     return true;  // Unknown modifier
347
348   O << '[';
349   printMemOperand(MI, OpNo);
350   O << ']';
351
352   return false;
353 }
354
355 // Force static initialization.
356 extern "C" void LLVMInitializeSparcAsmPrinter() { 
357   TargetRegistry::RegisterAsmPrinter(TheSparcTarget, 
358                                      createSparcCodePrinterPass);
359 }