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