Do not call getMangledName on Intrinsics.
[oota-llvm.git] / lib / Target / PIC16 / PIC16AsmPrinter.cpp
1 //===-- PIC16AsmPrinter.cpp - PIC16 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 PIC16 assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PIC16AsmPrinter.h"
16 #include "PIC16TargetAsmInfo.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Module.h"
20 #include "llvm/CodeGen/DwarfWriter.h"
21 #include "llvm/Support/FormattedStream.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27
28 using namespace llvm;
29
30 #include "PIC16GenAsmWriter.inc"
31
32 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
33   printInstruction(MI);
34   return true;
35 }
36
37 /// runOnMachineFunction - This emits the frame section, autos section and 
38 /// assembly for each instruction. Also takes care of function begin debug
39 /// directive and file begin debug directive (if required) for the function.
40 ///
41 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
42   this->MF = &MF;
43
44   // This calls the base class function required to be called at beginning
45   // of runOnMachineFunction.
46   SetupMachineFunction(MF);
47
48   // Get the mangled name.
49   const Function *F = MF.getFunction();
50   CurrentFnName = Mang->getMangledName(F);
51
52   // Emit the function frame (args and temps).
53   EmitFunctionFrame(MF);
54
55   DbgInfo.BeginFunction(MF);
56
57   // Emit the autos section of function.
58   EmitAutos(CurrentFnName);
59
60   // Now emit the instructions of function in its code section.
61   const char *codeSection = PAN::getCodeSectionName(CurrentFnName).c_str();
62  
63   const Section *fCodeSection = TAI->getNamedSection(codeSection,
64                                                      SectionFlags::Code);
65   // Start the Code Section.
66   O <<  "\n";
67   SwitchToSection(fCodeSection);
68
69   // Emit the frame address of the function at the beginning of code.
70   O << "\tretlw  low(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
71   O << "\tretlw  high(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
72
73   // Emit function start label.
74   O << CurrentFnName << ":\n";
75
76   DebugLoc CurDL;
77   O << "\n"; 
78   // Print out code for the function.
79   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
80        I != E; ++I) {
81
82     // Print a label for the basic block.
83     if (I != MF.begin()) {
84       printBasicBlockLabel(I, true);
85       O << '\n';
86     }
87     
88     // Print a basic block.
89     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
90          II != E; ++II) {
91
92       // Emit the line directive if source line changed.
93       const DebugLoc DL = II->getDebugLoc();
94       if (!DL.isUnknown() && DL != CurDL) {
95         DbgInfo.ChangeDebugLoc(MF, DL);
96         CurDL = DL;
97       }
98         
99       // Print the assembly for the instruction.
100       printMachineInstruction(II);
101     }
102   }
103   
104   // Emit function end debug directives.
105   DbgInfo.EndFunction(MF);
106
107   return false;  // we didn't modify anything.
108 }
109
110 /// createPIC16CodePrinterPass - Returns a pass that prints the PIC16
111 /// assembly code for a MachineFunction to the given output stream,
112 /// using the given target machine description.  This should work
113 /// regardless of whether the function is in SSA form.
114 ///
115 FunctionPass *llvm::createPIC16CodePrinterPass(formatted_raw_ostream &o,
116                                                TargetMachine &tm,
117                                                bool verbose) {
118   return new PIC16AsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
119 }
120
121
122 // printOperand - print operand of insn.
123 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
124   const MachineOperand &MO = MI->getOperand(opNum);
125
126   switch (MO.getType()) {
127     case MachineOperand::MO_Register:
128       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
129         O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
130       else
131         llvm_unreachable("not implemented");
132       return;
133
134     case MachineOperand::MO_Immediate:
135       O << (int)MO.getImm();
136       return;
137
138     case MachineOperand::MO_GlobalAddress: {
139       O << Mang->getMangledName(MO.getGlobal());
140       break;
141     }
142     case MachineOperand::MO_ExternalSymbol: {
143        const char *Sname = MO.getSymbolName();
144
145       // If its a libcall name, record it to decls section.
146       if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
147         LibcallDecls.push_back(Sname);
148       }
149
150       O  << Sname;
151       break;
152     }
153     case MachineOperand::MO_MachineBasicBlock:
154       printBasicBlockLabel(MO.getMBB());
155       return;
156
157     default:
158       llvm_unreachable(" Operand type not supported.");
159   }
160 }
161
162 /// printCCOperand - Print the cond code operand.
163 ///
164 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
165   int CC = (int)MI->getOperand(opNum).getImm();
166   O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
167 }
168
169 /// printLibcallDecls - print the extern declarations for compiler 
170 /// intrinsics.
171 ///
172 void PIC16AsmPrinter::printLibcallDecls(void) {
173   // If no libcalls used, return.
174   if (LibcallDecls.empty()) return;
175
176   O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
177   // Remove duplicate entries.
178   LibcallDecls.sort();
179   LibcallDecls.unique();
180   for (std::list<const char*>::const_iterator I = LibcallDecls.begin(); 
181        I != LibcallDecls.end(); I++) {
182     O << TAI->getExternDirective() << *I << "\n";
183     O << TAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
184     O << TAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
185   }
186   O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
187 }
188
189 /// doInitialization - Perfrom Module level initializations here.
190 /// One task that we do here is to sectionize all global variables.
191 /// The MemSelOptimizer pass depends on the sectionizing.
192 ///
193 bool PIC16AsmPrinter::doInitialization(Module &M) {
194   bool Result = AsmPrinter::doInitialization(M);
195
196   // FIXME:: This is temporary solution to generate the include file.
197   // The processor should be passed to llc as in input and the header file
198   // should be generated accordingly.
199   O << "\n\t#include P16F1937.INC\n";
200
201   // Set the section names for all globals.
202   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
203        I != E; ++I) {
204     I->setSection(TAI->SectionForGlobal(I)->getName());
205   }
206
207   DbgInfo.BeginModule(M);
208   EmitFunctionDecls(M);
209   EmitUndefinedVars(M);
210   EmitDefinedVars(M);
211   EmitIData(M);
212   EmitUData(M);
213   EmitRomData(M);
214   return Result;
215 }
216
217 /// Emit extern decls for functions imported from other modules, and emit
218 /// global declarations for function defined in this module and which are
219 /// available to other modules.
220 ///
221 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
222  // Emit declarations for external functions.
223   O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
224   for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
225     if (I->isIntrinsic())
226       continue;
227
228     std::string Name = Mang->getMangledName(I);
229     if (Name.compare("@abort") == 0)
230       continue;
231     
232     if (!I->isDeclaration() && !I->hasExternalLinkage())
233       continue;
234
235     const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
236                                                  TAI->getGlobalDirective();
237       
238     O << directive << Name << "\n";
239     O << directive << PAN::getRetvalLabel(Name) << "\n";
240     O << directive << PAN::getArgsLabel(Name) << "\n";
241   }
242
243   O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
244 }
245
246 // Emit variables imported from other Modules.
247 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
248   std::vector<const GlobalVariable*> Items = PTAI->ExternalVarDecls->Items;
249   if (!Items.size()) return;
250
251   O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
252   for (unsigned j = 0; j < Items.size(); j++) {
253     O << TAI->getExternDirective() << Mang->getMangledName(Items[j]) << "\n";
254   }
255   O << TAI->getCommentString() << "Imported Variables - END" << "\n";
256 }
257
258 // Emit variables defined in this module and are available to other modules.
259 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
260   std::vector<const GlobalVariable*> Items = PTAI->ExternalVarDefs->Items;
261   if (!Items.size()) return;
262
263   O << "\n" << TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
264   for (unsigned j = 0; j < Items.size(); j++) {
265     O << TAI->getGlobalDirective() << Mang->getMangledName(Items[j]) << "\n";
266   }
267   O <<  TAI->getCommentString() << "Exported Variables - END" << "\n";
268 }
269
270 // Emit initialized data placed in ROM.
271 void PIC16AsmPrinter::EmitRomData(Module &M) {
272   // Print ROM Data section.
273   const std::vector<PIC16Section*> &ROSections = PTAI->ROSections;
274   for (unsigned i = 0; i < ROSections.size(); i++) {
275     const std::vector<const GlobalVariable*> &Items = ROSections[i]->Items;
276     if (!Items.size()) continue;
277     O << "\n";
278     SwitchToSection(PTAI->ROSections[i]->S_);
279     for (unsigned j = 0; j < Items.size(); j++) {
280       O << Mang->getMangledName(Items[j]);
281       Constant *C = Items[j]->getInitializer();
282       int AddrSpace = Items[j]->getType()->getAddressSpace();
283       EmitGlobalConstant(C, AddrSpace);
284     }
285   }
286 }
287
288 bool PIC16AsmPrinter::doFinalization(Module &M) {
289   printLibcallDecls();
290   EmitRemainingAutos();
291   DbgInfo.EndModule(M);
292   O << "\n\t" << "END\n";
293   return AsmPrinter::doFinalization(M);
294 }
295
296 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
297   const Function *F = MF.getFunction();
298   std::string FuncName = Mang->getMangledName(F);
299   const TargetData *TD = TM.getTargetData();
300   // Emit the data section name.
301   O << "\n"; 
302   const char *SectionName = PAN::getFrameSectionName(CurrentFnName).c_str();
303
304   const Section *fPDataSection = TAI->getNamedSection(SectionName,
305                                                       SectionFlags::Writeable);
306   SwitchToSection(fPDataSection);
307   
308   // Emit function frame label
309   O << PAN::getFrameLabel(CurrentFnName) << ":\n";
310
311   const Type *RetType = F->getReturnType();
312   unsigned RetSize = 0; 
313   if (RetType->getTypeID() != Type::VoidTyID) 
314     RetSize = TD->getTypeAllocSize(RetType);
315   
316   //Emit function return value space
317   // FIXME: Do not emit RetvalLable when retsize is zero. To do this
318   // we will need to avoid printing a global directive for Retval label
319   // in emitExternandGloblas.
320   if(RetSize > 0)
321      O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
322   else
323      O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
324    
325   // Emit variable to hold the space for function arguments 
326   unsigned ArgSize = 0;
327   for (Function::const_arg_iterator argi = F->arg_begin(),
328            arge = F->arg_end(); argi != arge ; ++argi) {
329     const Type *Ty = argi->getType();
330     ArgSize += TD->getTypeAllocSize(Ty);
331    }
332
333   O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
334
335   // Emit temporary space
336   int TempSize = PTLI->GetTmpSize();
337   if (TempSize > 0)
338     O << PAN::getTempdataLabel(CurrentFnName) << " RES  " << TempSize << '\n';
339 }
340
341 void PIC16AsmPrinter::EmitIData(Module &M) {
342
343   // Print all IDATA sections.
344   const std::vector<PIC16Section*> &IDATASections = PTAI->IDATASections;
345   for (unsigned i = 0; i < IDATASections.size(); i++) {
346     O << "\n";
347     if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
348       continue;
349     SwitchToSection(IDATASections[i]->S_);
350     std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
351     for (unsigned j = 0; j < Items.size(); j++) {
352       std::string Name = Mang->getMangledName(Items[j]);
353       Constant *C = Items[j]->getInitializer();
354       int AddrSpace = Items[j]->getType()->getAddressSpace();
355       O << Name;
356       EmitGlobalConstant(C, AddrSpace);
357     }
358   }
359 }
360
361 void PIC16AsmPrinter::EmitUData(Module &M) {
362   const TargetData *TD = TM.getTargetData();
363
364   // Print all BSS sections.
365   const std::vector<PIC16Section*> &BSSSections = PTAI->BSSSections;
366   for (unsigned i = 0; i < BSSSections.size(); i++) {
367     O << "\n";
368     SwitchToSection(BSSSections[i]->S_);
369     std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
370     for (unsigned j = 0; j < Items.size(); j++) {
371       std::string Name = Mang->getMangledName(Items[j]);
372       Constant *C = Items[j]->getInitializer();
373       const Type *Ty = C->getType();
374       unsigned Size = TD->getTypeAllocSize(Ty);
375
376       O << Name << " RES " << Size << "\n";
377     }
378   }
379 }
380
381 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
382   // Section names for all globals are already set.
383   const TargetData *TD = TM.getTargetData();
384
385   // Now print Autos section for this function.
386   std::string SectionName = PAN::getAutosSectionName(FunctName);
387   const std::vector<PIC16Section*> &AutosSections = PTAI->AutosSections;
388   for (unsigned i = 0; i < AutosSections.size(); i++) {
389     O << "\n";
390     if (AutosSections[i]->S_->getName() == SectionName) { 
391       // Set the printing status to true
392       AutosSections[i]->setPrintedStatus(true);
393       SwitchToSection(AutosSections[i]->S_);
394       const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
395       for (unsigned j = 0; j < Items.size(); j++) {
396         std::string VarName = Mang->getMangledName(Items[j]);
397         Constant *C = Items[j]->getInitializer();
398         const Type *Ty = C->getType();
399         unsigned Size = TD->getTypeAllocSize(Ty);
400         // Emit memory reserve directive.
401         O << VarName << "  RES  " << Size << "\n";
402       }
403       break;
404     }
405   }
406 }
407
408 // Print autos that were not printed during the code printing of functions.
409 // As the functions might themselves would have got deleted by the optimizer.
410 void PIC16AsmPrinter::EmitRemainingAutos() {
411   const TargetData *TD = TM.getTargetData();
412
413   // Now print Autos section for this function.
414   std::vector <PIC16Section *>AutosSections = PTAI->AutosSections;
415   for (unsigned i = 0; i < AutosSections.size(); i++) {
416     
417     // if the section is already printed then don't print again
418     if (AutosSections[i]->isPrinted()) 
419       continue;
420
421     // Set status as printed
422     AutosSections[i]->setPrintedStatus(true);
423
424     O << "\n";
425     SwitchToSection(AutosSections[i]->S_);
426     const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
427     for (unsigned j = 0; j < Items.size(); j++) {
428       std::string VarName = Mang->getMangledName(Items[j]);
429       Constant *C = Items[j]->getInitializer();
430       const Type *Ty = C->getType();
431       unsigned Size = TD->getTypeAllocSize(Ty);
432       // Emit memory reserve directive.
433       O << VarName << "  RES  " << Size << "\n";
434     }
435   }
436 }
437