ff63542b703b6ed3281f57553281a8655b33f515
[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/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetRegistry.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/Mangler.h"
38 #include "llvm/Support/MathExtras.h"
39 #include <cctype>
40 #include <cstring>
41 #include <map>
42 using namespace llvm;
43
44 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45
46 namespace {
47   class VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {
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     unsigned BBNumber;
55   public:
56     explicit SparcAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
57                              const MCAsmInfo *T, bool V)
58       : AsmPrinter(O, TM, T, V), BBNumber(0) {}
59
60     virtual const char *getPassName() const {
61       return "Sparc Assembly Printer";
62     }
63
64     void PrintGlobalVariable(const GlobalVariable *GVar);
65     void printOperand(const MachineInstr *MI, int opNum);
66     void printMemOperand(const MachineInstr *MI, int opNum,
67                          const char *Modifier = 0);
68     void printCCOperand(const MachineInstr *MI, int opNum);
69
70     void printInstruction(const MachineInstr *MI);  // autogenerated.
71     bool runOnMachineFunction(MachineFunction &F);
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
82 /// runOnMachineFunction - This uses the printInstruction()
83 /// method to print assembly for each instruction.
84 ///
85 bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
86   this->MF = &MF;
87
88   SetupMachineFunction(MF);
89
90   // Print out constants referenced by the function
91   EmitConstantPool(MF.getConstantPool());
92
93   // BBNumber is used here so that a given Printer will never give two
94   // BBs the same name. (If you have a better way, please let me know!)
95
96   O << "\n\n";
97
98   // Print out the label for the function.
99   const Function *F = MF.getFunction();
100   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
101   EmitAlignment(MF.getAlignment(), F);
102   O << "\t.globl\t" << CurrentFnName << '\n';
103
104   printVisibility(CurrentFnName, F->getVisibility());
105
106   O << "\t.type\t" << CurrentFnName << ", #function\n";
107   O << CurrentFnName << ":\n";
108   // Emit pre-function debug information.
109   DW->BeginFunction(&MF);
110
111   // Number each basic block so that we can consistently refer to them
112   // in PC-relative references.
113   // FIXME: Why not use the MBB numbers?
114   NumberForBB.clear();
115   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
116        I != E; ++I) {
117     NumberForBB[I->getBasicBlock()] = BBNumber++;
118   }
119
120   // Print out code for the function.
121   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
122        I != E; ++I) {
123     // Print a label for the basic block.
124     if (I != MF.begin()) {
125       printBasicBlockLabel(I, true, true);
126       O << '\n';
127     }
128     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
129          II != E; ++II) {
130       // Print the assembly for the instruction.
131       processDebugLoc(II->getDebugLoc());
132       printInstruction(II);
133       
134       if (VerboseAsm && !II->getDebugLoc().isUnknown())
135         EmitComments(*II);
136       O << '\n';
137       
138       ++EmittedInsts;
139     }
140   }
141
142   // Emit post-function debug information.
143   DW->EndFunction(&MF);
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     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
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 << MAI->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 void SparcAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
226   const TargetData *TD = TM.getTargetData();
227
228   if (!GVar->hasInitializer())
229     return;  // External global require no code
230
231   // Check to see if this is a special global used by LLVM, if so, emit it.
232   if (EmitSpecialLLVMGlobal(GVar))
233     return;
234
235   O << "\n\n";
236   std::string name = Mang->getMangledName(GVar);
237   Constant *C = GVar->getInitializer();
238   unsigned Size = TD->getTypeAllocSize(C->getType());
239   unsigned Align = TD->getPreferredAlignment(GVar);
240
241   printVisibility(name, GVar->getVisibility());
242
243   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
244                                                                   TM));
245
246   if (C->isNullValue() && !GVar->hasSection()) {
247     if (!GVar->isThreadLocal() &&
248         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
249       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
250
251       if (GVar->hasLocalLinkage())
252         O << "\t.local " << name << '\n';
253
254       O << MAI->getCOMMDirective() << name << ',' << Size;
255       if (MAI->getCOMMDirectiveTakesAlignment())
256         O << ',' << (1 << Align);
257
258       O << '\n';
259       return;
260     }
261   }
262
263   switch (GVar->getLinkage()) {
264    case GlobalValue::CommonLinkage:
265    case GlobalValue::LinkOnceAnyLinkage:
266    case GlobalValue::LinkOnceODRLinkage:
267    case GlobalValue::WeakAnyLinkage: // FIXME: Verify correct for weak.
268    case GlobalValue::WeakODRLinkage: // FIXME: Verify correct for weak.
269     // Nonnull linkonce -> weak
270     O << "\t.weak " << name << '\n';
271     break;
272    case GlobalValue::AppendingLinkage:
273     // FIXME: appending linkage variables should go into a section of
274     // their name or something.  For now, just emit them as external.
275    case GlobalValue::ExternalLinkage:
276     // If external or appending, declare as a global symbol
277     O << MAI->getGlobalDirective() << name << '\n';
278     // FALL THROUGH
279    case GlobalValue::PrivateLinkage:
280    case GlobalValue::LinkerPrivateLinkage:
281    case GlobalValue::InternalLinkage:
282     break;
283    case GlobalValue::GhostLinkage:
284     llvm_unreachable("Should not have any unmaterialized functions!");
285    case GlobalValue::DLLImportLinkage:
286     llvm_unreachable("DLLImport linkage is not supported by this target!");
287    case GlobalValue::DLLExportLinkage:
288     llvm_unreachable("DLLExport linkage is not supported by this target!");
289    default:
290     llvm_unreachable("Unknown linkage type!");
291   }
292
293   EmitAlignment(Align, GVar);
294
295   if (MAI->hasDotTypeDotSizeDirective()) {
296     O << "\t.type " << name << ",#object\n";
297     O << "\t.size " << name << ',' << Size << '\n';
298   }
299
300   O << name << ":\n";
301   EmitGlobalConstant(C);
302 }
303
304 /// PrintAsmOperand - Print out an operand for an inline asm expression.
305 ///
306 bool SparcAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
307                                       unsigned AsmVariant,
308                                       const char *ExtraCode) {
309   if (ExtraCode && ExtraCode[0]) {
310     if (ExtraCode[1] != 0) return true; // Unknown modifier.
311
312     switch (ExtraCode[0]) {
313     default: return true;  // Unknown modifier.
314     case 'r':
315      break;
316     }
317   }
318
319   printOperand(MI, OpNo);
320
321   return false;
322 }
323
324 bool SparcAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
325                                             unsigned OpNo,
326                                             unsigned AsmVariant,
327                                             const char *ExtraCode) {
328   if (ExtraCode && ExtraCode[0])
329     return true;  // Unknown modifier
330
331   O << '[';
332   printMemOperand(MI, OpNo);
333   O << ']';
334
335   return false;
336 }
337
338 // Force static initialization.
339 extern "C" void LLVMInitializeSparcAsmPrinter() { 
340   RegisterAsmPrinter<SparcAsmPrinter> X(TheSparcTarget);
341 }