make AsmPrinter::doFinalization iterate over the global variables
[oota-llvm.git] / lib / Target / XCore / XCoreAsmPrinter.cpp
1 //===-- XCoreAsmPrinter.cpp - XCore 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 the XAS-format XCore assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "XCore.h"
17 #include "XCoreInstrInfo.h"
18 #include "XCoreSubtarget.h"
19 #include "XCoreTargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/Mangler.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/MathExtras.h"
38 #include <algorithm>
39 #include <cctype>
40 using namespace llvm;
41
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43
44 static cl::opt<unsigned> MaxThreads("xcore-max-threads", cl::Optional,
45   cl::desc("Maximum number of threads (for emulation thread-local storage)"),
46   cl::Hidden,
47   cl::value_desc("number"),
48   cl::init(8));
49
50 namespace {
51   class VISIBILITY_HIDDEN XCoreAsmPrinter : public AsmPrinter {
52     DwarfWriter *DW;
53     const XCoreSubtarget &Subtarget;
54   public:
55     explicit XCoreAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
56                              const TargetAsmInfo *T, bool V)
57       : AsmPrinter(O, TM, T, V), DW(0),
58       Subtarget(TM.getSubtarget<XCoreSubtarget>()) {}
59
60     virtual const char *getPassName() const {
61       return "XCore Assembly Printer";
62     }
63
64     void printMemOperand(const MachineInstr *MI, int opNum);
65     void printOperand(const MachineInstr *MI, int opNum);
66     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
67                         unsigned AsmVariant, const char *ExtraCode);
68
69     void emitGlobalDirective(const std::string &name);
70     void emitExternDirective(const std::string &name);
71     
72     void emitArrayBound(const std::string &name, const GlobalVariable *GV);
73     virtual void PrintGlobalVariable(const GlobalVariable *GV);
74
75     void emitFunctionStart(MachineFunction &MF);
76     void emitFunctionEnd(MachineFunction &MF);
77
78     bool printInstruction(const MachineInstr *MI);  // autogenerated.
79     void printMachineInstruction(const MachineInstr *MI);
80     bool runOnMachineFunction(MachineFunction &F);
81     bool doInitialization(Module &M);
82     
83     void getAnalysisUsage(AnalysisUsage &AU) const {
84       AsmPrinter::getAnalysisUsage(AU);
85       AU.setPreservesAll();
86       AU.addRequired<MachineModuleInfo>();
87       AU.addRequired<DwarfWriter>();
88     }
89   };
90 } // end of anonymous namespace
91
92 #include "XCoreGenAsmWriter.inc"
93
94 /// createXCoreCodePrinterPass - Returns a pass that prints the XCore
95 /// assembly code for a MachineFunction to the given output stream,
96 /// using the given target machine description.  This should work
97 /// regardless of whether the function is in SSA form.
98 ///
99 FunctionPass *llvm::createXCoreCodePrinterPass(formatted_raw_ostream &o,
100                                                TargetMachine &tm,
101                                                bool verbose) {
102   return new XCoreAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
103 }
104
105 void XCoreAsmPrinter::
106 emitGlobalDirective(const std::string &name)
107 {
108   O << TAI->getGlobalDirective() << name;
109   O << "\n";
110 }
111
112 void XCoreAsmPrinter::
113 emitExternDirective(const std::string &name)
114 {
115   O << "\t.extern\t" << name;
116   O << '\n';
117 }
118
119 void XCoreAsmPrinter::
120 emitArrayBound(const std::string &name, const GlobalVariable *GV)
121 {
122   assert(((GV->hasExternalLinkage() ||
123     GV->hasWeakLinkage()) ||
124     GV->hasLinkOnceLinkage()) && "Unexpected linkage");
125   if (const ArrayType *ATy = dyn_cast<ArrayType>(
126     cast<PointerType>(GV->getType())->getElementType()))
127   {
128     O << TAI->getGlobalDirective() << name << ".globound" << "\n";
129     O << TAI->getSetDirective() << name << ".globound" << ","
130       << ATy->getNumElements() << "\n";
131     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
132       // TODO Use COMDAT groups for LinkOnceLinkage
133       O << TAI->getWeakDefDirective() << name << ".globound" << "\n";
134     }
135   }
136 }
137
138 void XCoreAsmPrinter::PrintGlobalVariable(const GlobalVariable *GV) {
139   // Check to see if this is a special global used by LLVM, if so, emit it.
140   if (!GV->hasInitializer() ||
141       EmitSpecialLLVMGlobal(GV))
142     return;
143
144   const TargetData *TD = TM.getTargetData();
145   
146   SwitchToSection(TAI->SectionForGlobal(GV));
147   
148   std::string name = Mang->getMangledName(GV);
149   Constant *C = GV->getInitializer();
150   unsigned Align = (unsigned)TD->getPreferredTypeAlignmentShift(C->getType());
151   
152   // Mark the start of the global
153   O << "\t.cc_top " << name << ".data," << name << "\n";
154
155   switch (GV->getLinkage()) {
156   case GlobalValue::AppendingLinkage:
157     llvm_report_error("AppendingLinkage is not supported by this target!");
158   case GlobalValue::LinkOnceAnyLinkage:
159   case GlobalValue::LinkOnceODRLinkage:
160   case GlobalValue::WeakAnyLinkage:
161   case GlobalValue::WeakODRLinkage:
162   case GlobalValue::ExternalLinkage:
163     emitArrayBound(name, GV);
164     emitGlobalDirective(name);
165     // TODO Use COMDAT groups for LinkOnceLinkage
166     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
167       O << TAI->getWeakDefDirective() << name << "\n";
168     }
169     // FALL THROUGH
170   case GlobalValue::InternalLinkage:
171   case GlobalValue::PrivateLinkage:
172   case GlobalValue::LinkerPrivateLinkage:
173     break;
174   case GlobalValue::GhostLinkage:
175     llvm_unreachable("Should not have any unmaterialized functions!");
176   case GlobalValue::DLLImportLinkage:
177     llvm_unreachable("DLLImport linkage is not supported by this target!");
178   case GlobalValue::DLLExportLinkage:
179     llvm_unreachable("DLLExport linkage is not supported by this target!");
180   default:
181     llvm_unreachable("Unknown linkage type!");
182   }
183
184   EmitAlignment(Align, GV, 2);
185   
186   unsigned Size = TD->getTypeAllocSize(C->getType());
187   if (GV->isThreadLocal()) {
188     Size *= MaxThreads;
189   }
190   if (TAI->hasDotTypeDotSizeDirective()) {
191     O << "\t.type " << name << ",@object\n";
192     O << "\t.size " << name << "," << Size << "\n";
193   }
194   O << name << ":\n";
195   
196   EmitGlobalConstant(C);
197   if (GV->isThreadLocal()) {
198     for (unsigned i = 1; i < MaxThreads; ++i) {
199       EmitGlobalConstant(C);
200     }
201   }
202   if (Size < 4) {
203     // The ABI requires that unsigned scalar types smaller than 32 bits
204     // are are padded to 32 bits.
205     EmitZeros(4 - Size);
206   }
207   
208   // Mark the end of the global
209   O << "\t.cc_bottom " << name << ".data\n";
210 }
211
212 /// Emit the directives on the start of functions
213 void XCoreAsmPrinter::emitFunctionStart(MachineFunction &MF) {
214   // Print out the label for the function.
215   const Function *F = MF.getFunction();
216
217   SwitchToSection(TAI->SectionForGlobal(F));
218   
219   // Mark the start of the function
220   O << "\t.cc_top " << CurrentFnName << ".function," << CurrentFnName << "\n";
221
222   switch (F->getLinkage()) {
223   default: llvm_unreachable("Unknown linkage type!");
224   case Function::InternalLinkage:  // Symbols default to internal.
225   case Function::PrivateLinkage:
226   case Function::LinkerPrivateLinkage:
227     break;
228   case Function::ExternalLinkage:
229     emitGlobalDirective(CurrentFnName);
230     break;
231   case Function::LinkOnceAnyLinkage:
232   case Function::LinkOnceODRLinkage:
233   case Function::WeakAnyLinkage:
234   case Function::WeakODRLinkage:
235     // TODO Use COMDAT groups for LinkOnceLinkage
236     O << TAI->getGlobalDirective() << CurrentFnName << "\n";
237     O << TAI->getWeakDefDirective() << CurrentFnName << "\n";
238     break;
239   }
240   // (1 << 1) byte aligned
241   EmitAlignment(MF.getAlignment(), F, 1);
242   if (TAI->hasDotTypeDotSizeDirective()) {
243     O << "\t.type " << CurrentFnName << ",@function\n";
244   }
245   O << CurrentFnName << ":\n";
246 }
247
248 /// Emit the directives on the end of functions
249 void XCoreAsmPrinter::
250 emitFunctionEnd(MachineFunction &MF) 
251 {
252   // Mark the end of the function
253   O << "\t.cc_bottom " << CurrentFnName << ".function\n";
254 }
255
256 /// runOnMachineFunction - This uses the printMachineInstruction()
257 /// method to print assembly for each instruction.
258 ///
259 bool XCoreAsmPrinter::runOnMachineFunction(MachineFunction &MF)
260 {
261   this->MF = &MF;
262
263   SetupMachineFunction(MF);
264
265   // Print out constants referenced by the function
266   EmitConstantPool(MF.getConstantPool());
267
268   // Print out jump tables referenced by the function
269   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
270
271   // Emit the function start directives
272   emitFunctionStart(MF);
273   
274   // Emit pre-function debug information.
275   DW->BeginFunction(&MF);
276
277   // Print out code for the function.
278   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
279        I != E; ++I) {
280
281     // Print a label for the basic block.
282     if (I != MF.begin()) {
283       printBasicBlockLabel(I, true , true);
284       O << '\n';
285     }
286
287     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
288          II != E; ++II) {
289       // Print the assembly for the instruction.
290       O << "\t";
291       printMachineInstruction(II);
292     }
293
294     // Each Basic Block is separated by a newline
295     O << '\n';
296   }
297
298   // Emit function end directives
299   emitFunctionEnd(MF);
300   
301   // Emit post-function debug information.
302   DW->EndFunction(&MF);
303
304   // We didn't modify anything.
305   return false;
306 }
307
308 void XCoreAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum)
309 {
310   printOperand(MI, opNum);
311   
312   if (MI->getOperand(opNum+1).isImm()
313     && MI->getOperand(opNum+1).getImm() == 0)
314     return;
315   
316   O << "+";
317   printOperand(MI, opNum+1);
318 }
319
320 void XCoreAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
321   const MachineOperand &MO = MI->getOperand(opNum);
322   switch (MO.getType()) {
323   case MachineOperand::MO_Register:
324     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
325       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
326     else
327       llvm_unreachable("not implemented");
328     break;
329   case MachineOperand::MO_Immediate:
330     O << MO.getImm();
331     break;
332   case MachineOperand::MO_MachineBasicBlock:
333     printBasicBlockLabel(MO.getMBB());
334     break;
335   case MachineOperand::MO_GlobalAddress:
336     O << Mang->getMangledName(MO.getGlobal());
337     break;
338   case MachineOperand::MO_ExternalSymbol:
339     O << MO.getSymbolName();
340     break;
341   case MachineOperand::MO_ConstantPoolIndex:
342     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
343       << '_' << MO.getIndex();
344     break;
345   case MachineOperand::MO_JumpTableIndex:
346     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
347       << '_' << MO.getIndex();
348     break;
349   default:
350     llvm_unreachable("not implemented");
351   }
352 }
353
354 /// PrintAsmOperand - Print out an operand for an inline asm expression.
355 ///
356 bool XCoreAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
357                                       unsigned AsmVariant, 
358                                       const char *ExtraCode) {
359   printOperand(MI, OpNo);
360   return false;
361 }
362
363 void XCoreAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
364   ++EmittedInsts;
365
366   // Check for mov mnemonic
367   unsigned src, dst, srcSR, dstSR;
368   if (TM.getInstrInfo()->isMoveInstr(*MI, src, dst, srcSR, dstSR)) {
369     O << "\tmov ";
370     O << TM.getRegisterInfo()->get(dst).AsmName;
371     O << ", ";
372     O << TM.getRegisterInfo()->get(src).AsmName;
373     O << "\n";
374     return;
375   }
376   if (printInstruction(MI)) {
377     return;
378   }
379   llvm_unreachable("Unhandled instruction in asm writer!");
380 }
381
382 bool XCoreAsmPrinter::doInitialization(Module &M) {
383   bool Result = AsmPrinter::doInitialization(M);
384   DW = getAnalysisIfAvailable<DwarfWriter>();
385   
386   return Result;
387 }
388
389