cb23f6212ca4b36c85e803b437914ba5a69364f5
[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/Support/Mangler.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/MathExtras.h"
35 #include <cctype>
36 #include <cstring>
37 #include <map>
38 using namespace llvm;
39
40 STATISTIC(EmittedInsts, "Number of machine instrs printed");
41
42 namespace {
43   class VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {
44     /// We name each basic block in a Function with a unique number, so
45     /// that we can consistently refer to them later. This is cleared
46     /// at the beginning of each call to runOnMachineFunction().
47     ///
48     typedef std::map<const Value *, unsigned> ValueMapTy;
49     ValueMapTy NumberForBB;
50     unsigned BBNumber;
51   public:
52     explicit SparcAsmPrinter(raw_ostream &O, TargetMachine &TM,
53                              const TargetAsmInfo *T, CodeGenOpt::Level OL,
54                              bool V)
55       : AsmPrinter(O, TM, T, OL, V), BBNumber(0) {}
56
57     virtual const char *getPassName() const {
58       return "Sparc Assembly Printer";
59     }
60
61     void printModuleLevelGV(const GlobalVariable* GVar);
62     void printOperand(const MachineInstr *MI, int opNum);
63     void printMemOperand(const MachineInstr *MI, int opNum,
64                          const char *Modifier = 0);
65     void printCCOperand(const MachineInstr *MI, int opNum);
66
67     bool printInstruction(const MachineInstr *MI);  // autogenerated.
68     bool runOnMachineFunction(MachineFunction &F);
69     bool doInitialization(Module &M);
70     bool doFinalization(Module &M);
71     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
72                        unsigned AsmVariant, const char *ExtraCode);
73     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
74                              unsigned AsmVariant, const char *ExtraCode);
75   };
76 } // end of anonymous namespace
77
78 #include "SparcGenAsmWriter.inc"
79
80 /// createSparcCodePrinterPass - Returns a pass that prints the SPARC
81 /// assembly code for a MachineFunction to the given output stream,
82 /// using the given target machine description.  This should work
83 /// regardless of whether the function is in SSA form.
84 ///
85 FunctionPass *llvm::createSparcCodePrinterPass(raw_ostream &o,
86                                                TargetMachine &tm,
87                                                CodeGenOpt::Level OptLevel,
88                                                bool verbose) {
89   return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo(), OptLevel, 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(4, 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     {
177       const GlobalValue *GV = MO.getGlobal();
178       O << Mang->getValueName(GV);
179     }
180     break;
181   case MachineOperand::MO_ExternalSymbol:
182     O << MO.getSymbolName();
183     break;
184   case MachineOperand::MO_ConstantPoolIndex:
185     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
186       << MO.getIndex();
187     break;
188   default:
189     O << "<unknown operand type>"; abort (); break;
190   }
191   if (CloseParen) O << ")";
192 }
193
194 void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
195                                       const char *Modifier) {
196   printOperand(MI, opNum);
197
198   // If this is an ADD operand, emit it like normal operands.
199   if (Modifier && !strcmp(Modifier, "arith")) {
200     O << ", ";
201     printOperand(MI, opNum+1);
202     return;
203   }
204
205   if (MI->getOperand(opNum+1).isReg() &&
206       MI->getOperand(opNum+1).getReg() == SP::G0)
207     return;   // don't print "+%g0"
208   if (MI->getOperand(opNum+1).isImm() &&
209       MI->getOperand(opNum+1).getImm() == 0)
210     return;   // don't print "+0"
211
212   O << "+";
213   if (MI->getOperand(opNum+1).isGlobal() ||
214       MI->getOperand(opNum+1).isCPI()) {
215     O << "%lo(";
216     printOperand(MI, opNum+1);
217     O << ")";
218   } else {
219     printOperand(MI, opNum+1);
220   }
221 }
222
223 void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
224   int CC = (int)MI->getOperand(opNum).getImm();
225   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
226 }
227
228 bool SparcAsmPrinter::doInitialization(Module &M) {
229   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
230   return false; // success
231 }
232
233 bool SparcAsmPrinter::doFinalization(Module &M) {
234   // Print out module-level global variables here.
235   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
236        I != E; ++I)
237     printModuleLevelGV(I);
238
239   O << '\n';
240
241   return AsmPrinter::doFinalization(M);
242 }
243
244 void SparcAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
245   const TargetData *TD = TM.getTargetData();
246
247   if (!GVar->hasInitializer())
248     return;  // External global require no code
249
250   // Check to see if this is a special global used by LLVM, if so, emit it.
251   if (EmitSpecialLLVMGlobal(GVar))
252     return;
253
254   O << "\n\n";
255   std::string name = Mang->getValueName(GVar);
256   Constant *C = GVar->getInitializer();
257   if (isa<MDNode>(C) || isa<MDString>(C))
258     return;
259   unsigned Size = TD->getTypeAllocSize(C->getType());
260   unsigned Align = TD->getPreferredAlignment(GVar);
261
262   printVisibility(name, GVar->getVisibility());
263
264   SwitchToSection(TAI->SectionForGlobal(GVar));
265
266   if (C->isNullValue() && !GVar->hasSection()) {
267     if (!GVar->isThreadLocal() &&
268         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
269       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
270
271       if (GVar->hasLocalLinkage())
272         O << "\t.local " << name << '\n';
273
274       O << TAI->getCOMMDirective() << name << ',' << Size;
275       if (TAI->getCOMMDirectiveTakesAlignment())
276         O << ',' << (1 << Align);
277
278       O << '\n';
279       return;
280     }
281   }
282
283   switch (GVar->getLinkage()) {
284    case GlobalValue::CommonLinkage:
285    case GlobalValue::LinkOnceAnyLinkage:
286    case GlobalValue::LinkOnceODRLinkage:
287    case GlobalValue::WeakAnyLinkage: // FIXME: Verify correct for weak.
288    case GlobalValue::WeakODRLinkage: // FIXME: Verify correct for weak.
289     // Nonnull linkonce -> weak
290     O << "\t.weak " << name << '\n';
291     break;
292    case GlobalValue::AppendingLinkage:
293     // FIXME: appending linkage variables should go into a section of
294     // their name or something.  For now, just emit them as external.
295    case GlobalValue::ExternalLinkage:
296     // If external or appending, declare as a global symbol
297     O << TAI->getGlobalDirective() << name << '\n';
298     // FALL THROUGH
299    case GlobalValue::PrivateLinkage:
300    case GlobalValue::InternalLinkage:
301     break;
302    case GlobalValue::GhostLinkage:
303     cerr << "Should not have any unmaterialized functions!\n";
304     abort();
305    case GlobalValue::DLLImportLinkage:
306     cerr << "DLLImport linkage is not supported by this target!\n";
307     abort();
308    case GlobalValue::DLLExportLinkage:
309     cerr << "DLLExport linkage is not supported by this target!\n";
310     abort();
311    default:
312     assert(0 && "Unknown linkage type!");
313   }
314
315   EmitAlignment(Align, GVar);
316
317   if (TAI->hasDotTypeDotSizeDirective()) {
318     O << "\t.type " << name << ",#object\n";
319     O << "\t.size " << name << ',' << Size << '\n';
320   }
321
322   O << name << ":\n";
323   EmitGlobalConstant(C);
324 }
325
326 /// PrintAsmOperand - Print out an operand for an inline asm expression.
327 ///
328 bool SparcAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
329                                       unsigned AsmVariant,
330                                       const char *ExtraCode) {
331   if (ExtraCode && ExtraCode[0]) {
332     if (ExtraCode[1] != 0) return true; // Unknown modifier.
333
334     switch (ExtraCode[0]) {
335     default: return true;  // Unknown modifier.
336     case 'r':
337      break;
338     }
339   }
340
341   printOperand(MI, OpNo);
342
343   return false;
344 }
345
346 bool SparcAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
347                                             unsigned OpNo,
348                                             unsigned AsmVariant,
349                                             const char *ExtraCode) {
350   if (ExtraCode && ExtraCode[0])
351     return true;  // Unknown modifier
352
353   O << '[';
354   printMemOperand(MI, OpNo);
355   O << ']';
356
357   return false;
358 }
359
360 namespace {
361   static struct Register {
362     Register() {
363       SparcTargetMachine::registerAsmPrinter(createSparcCodePrinterPass);
364     }
365   } Registrator;
366 }
367
368 // Force static initialization.
369 extern "C" void LLVMInitializeSparcAsmPrinter() { }