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