Simplify code and avoid allocations.
[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/CodeGen/DwarfWriter.h"
23 #include "llvm/CodeGen/MachineModuleInfo.h"
24 #include "llvm/MC/MCSection.h"
25 #include "llvm/Target/TargetRegistry.h"
26 #include "llvm/Target/TargetLoweringObjectFile.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/FormattedStream.h"
29 #include "llvm/Support/Mangler.h"
30 #include <cstring>
31 using namespace llvm;
32
33 #include "PIC16GenAsmWriter.inc"
34
35 PIC16AsmPrinter::PIC16AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
36                                  const TargetAsmInfo *T, bool V)
37 : AsmPrinter(O, TM, T, V), DbgInfo(O, T) {
38   PTLI = static_cast<const PIC16TargetLowering*>(TM.getTargetLowering());
39   PTAI = static_cast<const PIC16TargetAsmInfo*>(T);
40   PTOF = (PIC16TargetObjectFile*)&PTLI->getObjFileLowering();
41 }
42
43 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
44   printInstruction(MI);
45   return true;
46 }
47
48 /// runOnMachineFunction - This emits the frame section, autos section and 
49 /// assembly for each instruction. Also takes care of function begin debug
50 /// directive and file begin debug directive (if required) for the function.
51 ///
52 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
53   this->MF = &MF;
54
55   // This calls the base class function required to be called at beginning
56   // of runOnMachineFunction.
57   SetupMachineFunction(MF);
58
59   // Get the mangled name.
60   const Function *F = MF.getFunction();
61   CurrentFnName = Mang->getMangledName(F);
62
63   // Emit the function frame (args and temps).
64   EmitFunctionFrame(MF);
65
66   DbgInfo.BeginFunction(MF);
67
68   // Emit the autos section of function.
69   EmitAutos(CurrentFnName);
70
71   // Now emit the instructions of function in its code section.
72   const MCSection *fCodeSection = 
73     getObjFileLowering().getSectionForFunction(CurrentFnName);
74   // Start the Code Section.
75   O <<  "\n";
76   SwitchToSection(fCodeSection);
77
78   // Emit the frame address of the function at the beginning of code.
79   O << "\tretlw  low(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
80   O << "\tretlw  high(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
81
82   // Emit function start label.
83   O << CurrentFnName << ":\n";
84
85   DebugLoc CurDL;
86   O << "\n"; 
87   // Print out code for the function.
88   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
89        I != E; ++I) {
90
91     // Print a label for the basic block.
92     if (I != MF.begin()) {
93       printBasicBlockLabel(I, true);
94       O << '\n';
95     }
96     
97     // Print a basic block.
98     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
99          II != E; ++II) {
100
101       // Emit the line directive if source line changed.
102       const DebugLoc DL = II->getDebugLoc();
103       if (!DL.isUnknown() && DL != CurDL) {
104         DbgInfo.ChangeDebugLoc(MF, DL);
105         CurDL = DL;
106       }
107         
108       // Print the assembly for the instruction.
109       printMachineInstruction(II);
110     }
111   }
112   
113   // Emit function end debug directives.
114   DbgInfo.EndFunction(MF);
115
116   return false;  // we didn't modify anything.
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         llvm_unreachable("not implemented");
130       return;
131
132     case MachineOperand::MO_Immediate:
133       O << (int)MO.getImm();
134       return;
135
136     case MachineOperand::MO_GlobalAddress: {
137       std::string Sname = Mang->getMangledName(MO.getGlobal());
138       // FIXME: currently we do not have a memcpy def coming in the module
139       // by any chance, as we do not link in those as .bc lib. So these calls
140       // are always external and it is safe to emit an extern.
141       if (PAN::isMemIntrinsic(Sname)) {
142         LibcallDecls.push_back(createESName(Sname));
143       }
144
145       O << Sname;
146       break;
147     }
148     case MachineOperand::MO_ExternalSymbol: {
149        const char *Sname = MO.getSymbolName();
150
151       // If its a libcall name, record it to decls section.
152       if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
153         LibcallDecls.push_back(Sname);
154       }
155
156       // Record a call to intrinsic to print the extern declaration for it.
157       std::string Sym = Sname;  
158       if (PAN::isMemIntrinsic(Sym)) {
159         Sym = PAN::addPrefix(Sym);
160         LibcallDecls.push_back(createESName(Sym));
161       }
162
163       O  << Sym;
164       break;
165     }
166     case MachineOperand::MO_MachineBasicBlock:
167       printBasicBlockLabel(MO.getMBB());
168       return;
169
170     default:
171       llvm_unreachable(" Operand type not supported.");
172   }
173 }
174
175 /// printCCOperand - Print the cond code operand.
176 ///
177 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
178   int CC = (int)MI->getOperand(opNum).getImm();
179   O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
180 }
181
182 // This function is used to sort the decls list.
183 // should return true if s1 should come before s2.
184 static bool is_before(const char *s1, const char *s2) {
185   return strcmp(s1, s2) <= 0;
186 }
187
188 // This is used by list::unique below. 
189 // unique will filter out duplicates if it knows them.
190 static bool is_duplicate(const char *s1, const char *s2) {
191   return !strcmp(s1, s2);
192 }
193
194 /// printLibcallDecls - print the extern declarations for compiler 
195 /// intrinsics.
196 ///
197 void PIC16AsmPrinter::printLibcallDecls(void) {
198   // If no libcalls used, return.
199   if (LibcallDecls.empty()) return;
200
201   O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
202   // Remove duplicate entries.
203   LibcallDecls.sort(is_before);
204   LibcallDecls.unique(is_duplicate);
205
206   for (std::list<const char*>::const_iterator I = LibcallDecls.begin(); 
207        I != LibcallDecls.end(); I++) {
208     O << TAI->getExternDirective() << *I << "\n";
209     O << TAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
210     O << TAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
211   }
212   O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
213 }
214
215 /// doInitialization - Perfrom Module level initializations here.
216 /// One task that we do here is to sectionize all global variables.
217 /// The MemSelOptimizer pass depends on the sectionizing.
218 ///
219 bool PIC16AsmPrinter::doInitialization(Module &M) {
220   bool Result = AsmPrinter::doInitialization(M);
221
222   // FIXME:: This is temporary solution to generate the include file.
223   // The processor should be passed to llc as in input and the header file
224   // should be generated accordingly.
225   O << "\n\t#include P16F1937.INC\n";
226
227   // Set the section names for all globals.
228   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
229        I != E; ++I)
230     if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
231       I->setSection(getObjFileLowering().
232                     SectionForGlobal(I, Mang,TM)->getName());
233
234   DbgInfo.BeginModule(M);
235   EmitFunctionDecls(M);
236   EmitUndefinedVars(M);
237   EmitDefinedVars(M);
238   EmitIData(M);
239   EmitUData(M);
240   EmitRomData(M);
241   return Result;
242 }
243
244 /// Emit extern decls for functions imported from other modules, and emit
245 /// global declarations for function defined in this module and which are
246 /// available to other modules.
247 ///
248 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
249  // Emit declarations for external functions.
250   O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
251   for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
252     if (I->isIntrinsic())
253       continue;
254
255     std::string Name = Mang->getMangledName(I);
256     if (Name.compare("@abort") == 0)
257       continue;
258     
259     if (!I->isDeclaration() && !I->hasExternalLinkage())
260       continue;
261
262     // Do not emit memcpy, memset, and memmove here.
263     // Calls to these routines can be generated in two ways,
264     // 1. User calling the standard lib function
265     // 2. Codegen generating these calls for llvm intrinsics.
266     // In the first case a prototype is alread availale, while in
267     // second case the call is via and externalsym and the prototype is missing.
268     // So declarations for these are currently always getting printing by
269     // tracking both kind of references in printInstrunction.
270     if (I->isDeclaration() && PAN::isMemIntrinsic(Name)) continue;
271
272     const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
273                                                  TAI->getGlobalDirective();
274       
275     O << directive << Name << "\n";
276     O << directive << PAN::getRetvalLabel(Name) << "\n";
277     O << directive << PAN::getArgsLabel(Name) << "\n";
278   }
279
280   O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
281 }
282
283 // Emit variables imported from other Modules.
284 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
285   std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDecls->Items;
286   if (!Items.size()) return;
287
288   O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
289   for (unsigned j = 0; j < Items.size(); j++) {
290     O << TAI->getExternDirective() << Mang->getMangledName(Items[j]) << "\n";
291   }
292   O << TAI->getCommentString() << "Imported Variables - END" << "\n";
293 }
294
295 // Emit variables defined in this module and are available to other modules.
296 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
297   std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDefs->Items;
298   if (!Items.size()) return;
299
300   O << "\n" << TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
301   for (unsigned j = 0; j < Items.size(); j++) {
302     O << TAI->getGlobalDirective() << Mang->getMangledName(Items[j]) << "\n";
303   }
304   O <<  TAI->getCommentString() << "Exported Variables - END" << "\n";
305 }
306
307 // Emit initialized data placed in ROM.
308 void PIC16AsmPrinter::EmitRomData(Module &M) {
309   // Print ROM Data section.
310   const std::vector<PIC16Section*> &ROSections = PTOF->ROSections;
311   for (unsigned i = 0; i < ROSections.size(); i++) {
312     const std::vector<const GlobalVariable*> &Items = ROSections[i]->Items;
313     if (!Items.size()) continue;
314     O << "\n";
315     SwitchToSection(PTOF->ROSections[i]->S_);
316     for (unsigned j = 0; j < Items.size(); j++) {
317       O << Mang->getMangledName(Items[j]);
318       Constant *C = Items[j]->getInitializer();
319       int AddrSpace = Items[j]->getType()->getAddressSpace();
320       EmitGlobalConstant(C, AddrSpace);
321     }
322   }
323 }
324
325 bool PIC16AsmPrinter::doFinalization(Module &M) {
326   printLibcallDecls();
327   EmitRemainingAutos();
328   DbgInfo.EndModule(M);
329   O << "\n\t" << "END\n";
330   return AsmPrinter::doFinalization(M);
331 }
332
333 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
334   const Function *F = MF.getFunction();
335   std::string FuncName = Mang->getMangledName(F);
336   const TargetData *TD = TM.getTargetData();
337   // Emit the data section name.
338   O << "\n"; 
339   
340   const MCSection *fPDataSection =
341     getObjFileLowering().getSectionForFunctionFrame(CurrentFnName);
342   SwitchToSection(fPDataSection);
343   
344   // Emit function frame label
345   O << PAN::getFrameLabel(CurrentFnName) << ":\n";
346
347   const Type *RetType = F->getReturnType();
348   unsigned RetSize = 0; 
349   if (RetType->getTypeID() != Type::VoidTyID) 
350     RetSize = TD->getTypeAllocSize(RetType);
351   
352   //Emit function return value space
353   // FIXME: Do not emit RetvalLable when retsize is zero. To do this
354   // we will need to avoid printing a global directive for Retval label
355   // in emitExternandGloblas.
356   if(RetSize > 0)
357      O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
358   else
359      O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
360    
361   // Emit variable to hold the space for function arguments 
362   unsigned ArgSize = 0;
363   for (Function::const_arg_iterator argi = F->arg_begin(),
364            arge = F->arg_end(); argi != arge ; ++argi) {
365     const Type *Ty = argi->getType();
366     ArgSize += TD->getTypeAllocSize(Ty);
367    }
368
369   O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
370
371   // Emit temporary space
372   int TempSize = PTLI->GetTmpSize();
373   if (TempSize > 0)
374     O << PAN::getTempdataLabel(CurrentFnName) << " RES  " << TempSize << '\n';
375 }
376
377 void PIC16AsmPrinter::EmitIData(Module &M) {
378
379   // Print all IDATA sections.
380   const std::vector<PIC16Section*> &IDATASections = PTOF->IDATASections;
381   for (unsigned i = 0; i < IDATASections.size(); i++) {
382     O << "\n";
383     if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
384       continue;
385     SwitchToSection(IDATASections[i]->S_);
386     std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
387     for (unsigned j = 0; j < Items.size(); j++) {
388       std::string Name = Mang->getMangledName(Items[j]);
389       Constant *C = Items[j]->getInitializer();
390       int AddrSpace = Items[j]->getType()->getAddressSpace();
391       O << Name;
392       EmitGlobalConstant(C, AddrSpace);
393     }
394   }
395 }
396
397 void PIC16AsmPrinter::EmitUData(Module &M) {
398   const TargetData *TD = TM.getTargetData();
399
400   // Print all BSS sections.
401   const std::vector<PIC16Section*> &BSSSections = PTOF->BSSSections;
402   for (unsigned i = 0; i < BSSSections.size(); i++) {
403     O << "\n";
404     SwitchToSection(BSSSections[i]->S_);
405     std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
406     for (unsigned j = 0; j < Items.size(); j++) {
407       std::string Name = Mang->getMangledName(Items[j]);
408       Constant *C = Items[j]->getInitializer();
409       const Type *Ty = C->getType();
410       unsigned Size = TD->getTypeAllocSize(Ty);
411
412       O << Name << " RES " << Size << "\n";
413     }
414   }
415 }
416
417 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
418   // Section names for all globals are already set.
419   const TargetData *TD = TM.getTargetData();
420
421   // Now print Autos section for this function.
422   std::string SectionName = PAN::getAutosSectionName(FunctName);
423   const std::vector<PIC16Section*> &AutosSections = PTOF->AutosSections;
424   for (unsigned i = 0; i < AutosSections.size(); i++) {
425     O << "\n";
426     if (AutosSections[i]->S_->getName() == SectionName) { 
427       // Set the printing status to true
428       AutosSections[i]->setPrintedStatus(true);
429       SwitchToSection(AutosSections[i]->S_);
430       const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
431       for (unsigned j = 0; j < Items.size(); j++) {
432         std::string VarName = Mang->getMangledName(Items[j]);
433         Constant *C = Items[j]->getInitializer();
434         const Type *Ty = C->getType();
435         unsigned Size = TD->getTypeAllocSize(Ty);
436         // Emit memory reserve directive.
437         O << VarName << "  RES  " << Size << "\n";
438       }
439       break;
440     }
441   }
442 }
443
444 // Print autos that were not printed during the code printing of functions.
445 // As the functions might themselves would have got deleted by the optimizer.
446 void PIC16AsmPrinter::EmitRemainingAutos() {
447   const TargetData *TD = TM.getTargetData();
448
449   // Now print Autos section for this function.
450   std::vector <PIC16Section *>AutosSections = PTOF->AutosSections;
451   for (unsigned i = 0; i < AutosSections.size(); i++) {
452     
453     // if the section is already printed then don't print again
454     if (AutosSections[i]->isPrinted()) 
455       continue;
456
457     // Set status as printed
458     AutosSections[i]->setPrintedStatus(true);
459
460     O << "\n";
461     SwitchToSection(AutosSections[i]->S_);
462     const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
463     for (unsigned j = 0; j < Items.size(); j++) {
464       std::string VarName = Mang->getMangledName(Items[j]);
465       Constant *C = Items[j]->getInitializer();
466       const Type *Ty = C->getType();
467       unsigned Size = TD->getTypeAllocSize(Ty);
468       // Emit memory reserve directive.
469       O << VarName << "  RES  " << Size << "\n";
470     }
471   }
472 }
473
474
475 extern "C" void LLVMInitializePIC16Target() { 
476   // Register the targets
477   RegisterTargetMachine<PIC16TargetMachine> A(ThePIC16Target);  
478   RegisterTargetMachine<CooperTargetMachine> B(TheCooperTarget);
479   RegisterAsmPrinter<PIC16AsmPrinter> C(ThePIC16Target);
480   RegisterAsmPrinter<PIC16AsmPrinter> D(TheCooperTarget);
481 }