print all the newlines at the end of instructions with
[oota-llvm.git] / lib / Target / PIC16 / AsmPrinter / 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 "PIC16ABINames.h"
16 #include "PIC16AsmPrinter.h"
17 #include "PIC16Section.h"
18 #include "PIC16MCAsmInfo.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/DwarfWriter.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/MC/MCStreamer.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Target/TargetRegistry.h"
29 #include "llvm/Target/TargetLoweringObjectFile.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include <cstring>
33 using namespace llvm;
34
35 #include "PIC16GenAsmWriter.inc"
36
37 PIC16AsmPrinter::PIC16AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
38                                  MCContext &Ctx, MCStreamer &Streamer,
39                                  const MCAsmInfo *T)
40 : AsmPrinter(O, TM, Ctx, Streamer, T), DbgInfo(O, T) {
41   PTLI = static_cast<PIC16TargetLowering*>(TM.getTargetLowering());
42   PMAI = static_cast<const PIC16MCAsmInfo*>(T);
43   PTOF = (PIC16TargetObjectFile *)&PTLI->getObjFileLowering();
44 }
45
46 void PIC16AsmPrinter::EmitInstruction(const MachineInstr *MI) {
47   printInstruction(MI);
48   OutStreamer.AddBlankLine();
49 }
50
51 static int getFunctionColor(const Function *F) {
52   if (F->hasSection()) {
53     std::string Sectn = F->getSection();
54     std::string StrToFind = "Overlay=";
55     std::string::size_type Pos = Sectn.find(StrToFind);
56
57     // Retreive the color number if the key is found.
58     if (Pos != std::string::npos) {
59       Pos += StrToFind.length();
60       std::string Color = "";
61       char c = Sectn.at(Pos);
62       // A Color can only consist of digits.
63       while (c >= '0' && c<= '9') {
64         Color.append(1,c);
65         Pos++;
66         if (Pos >= Sectn.length())
67           break;
68         c = Sectn.at(Pos);
69       }
70       return atoi(Color.c_str());
71     }
72   }
73
74   // Color was not set for function, so return -1.
75   return -1;
76 }
77
78 // Color the Auto section of the given function. 
79 void PIC16AsmPrinter::ColorAutoSection(const Function *F) {
80   std::string SectionName = PAN::getAutosSectionName(CurrentFnSym->getName());
81   PIC16Section* Section = PTOF->findPIC16Section(SectionName);
82   if (Section != NULL) {
83     int Color = getFunctionColor(F);
84     if (Color >= 0)
85       Section->setColor(Color);
86   }
87 }
88
89
90 /// runOnMachineFunction - This emits the frame section, autos section and 
91 /// assembly for each instruction. Also takes care of function begin debug
92 /// directive and file begin debug directive (if required) for the function.
93 ///
94 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
95   // This calls the base class function required to be called at beginning
96   // of runOnMachineFunction.
97   SetupMachineFunction(MF);
98
99   // Put the color information from function to its auto section.
100   const Function *F = MF.getFunction();
101   ColorAutoSection(F);
102
103   // Emit the function frame (args and temps).
104   EmitFunctionFrame(MF);
105
106   DbgInfo.BeginFunction(MF);
107
108   // Now emit the instructions of function in its code section.
109   const MCSection *fCodeSection 
110     = getObjFileLowering().SectionForCode(CurrentFnSym->getName());
111
112   // Start the Code Section.
113   O <<  "\n";
114   OutStreamer.SwitchSection(fCodeSection);
115
116   // Emit the frame address of the function at the beginning of code.
117   O << "\tretlw  low(" << PAN::getFrameLabel(CurrentFnSym->getName()) << ")\n";
118   O << "\tretlw  high(" << PAN::getFrameLabel(CurrentFnSym->getName()) << ")\n";
119
120   // Emit function start label.
121   O << *CurrentFnSym << ":\n";
122
123   DebugLoc CurDL;
124   O << "\n"; 
125   // Print out code for the function.
126   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
127        I != E; ++I) {
128
129     // Print a label for the basic block.
130     if (I != MF.begin()) {
131       EmitBasicBlockStart(I);
132     }
133     
134     // Print a basic block.
135     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
136          II != E; ++II) {
137
138       // Emit the line directive if source line changed.
139       const DebugLoc DL = II->getDebugLoc();
140       if (!DL.isUnknown() && DL != CurDL) {
141         DbgInfo.ChangeDebugLoc(MF, DL);
142         CurDL = DL;
143       }
144         
145       // Print the assembly for the instruction.
146       EmitInstruction(II);
147     }
148   }
149   
150   // Emit function end debug directives.
151   DbgInfo.EndFunction(MF);
152
153   return false;  // we didn't modify anything.
154 }
155
156
157 // printOperand - print operand of insn.
158 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
159   const MachineOperand &MO = MI->getOperand(opNum);
160
161   switch (MO.getType()) {
162     case MachineOperand::MO_Register:
163       {
164         // For indirect load/store insns, the fsr name is printed as INDF.
165         std::string RegName = getRegisterName(MO.getReg());
166         if ((MI->getOpcode() == PIC16::load_indirect) ||
167             (MI->getOpcode() == PIC16::store_indirect))
168         {
169           RegName.replace (0, 3, "INDF");
170         }
171         O << RegName;
172       }
173       return;
174
175     case MachineOperand::MO_Immediate:
176       O << (int)MO.getImm();
177       return;
178
179     case MachineOperand::MO_GlobalAddress: {
180       MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
181       // FIXME: currently we do not have a memcpy def coming in the module
182       // by any chance, as we do not link in those as .bc lib. So these calls
183       // are always external and it is safe to emit an extern.
184       if (PAN::isMemIntrinsic(Sym->getName()))
185         LibcallDecls.push_back(createESName(Sym->getName()));
186
187       O << *Sym;
188       break;
189     }
190     case MachineOperand::MO_ExternalSymbol: {
191        const char *Sname = MO.getSymbolName();
192
193       // If its a libcall name, record it to decls section.
194       if (PAN::getSymbolTag(Sname) == PAN::LIBCALL)
195         LibcallDecls.push_back(Sname);
196
197       // Record a call to intrinsic to print the extern declaration for it.
198       std::string Sym = Sname;  
199       if (PAN::isMemIntrinsic(Sym)) {
200         Sym = PAN::addPrefix(Sym);
201         LibcallDecls.push_back(createESName(Sym));
202       }
203
204       O << Sym;
205       break;
206     }
207     case MachineOperand::MO_MachineBasicBlock:
208       O << *MO.getMBB()->getSymbol(OutContext);
209       return;
210
211     default:
212       llvm_unreachable(" Operand type not supported.");
213   }
214 }
215
216 /// printCCOperand - Print the cond code operand.
217 ///
218 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
219   int CC = (int)MI->getOperand(opNum).getImm();
220   O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
221 }
222
223 // This function is used to sort the decls list.
224 // should return true if s1 should come before s2.
225 static bool is_before(const char *s1, const char *s2) {
226   return strcmp(s1, s2) <= 0;
227 }
228
229 // This is used by list::unique below. 
230 // unique will filter out duplicates if it knows them.
231 static bool is_duplicate(const char *s1, const char *s2) {
232   return !strcmp(s1, s2);
233 }
234
235 /// printLibcallDecls - print the extern declarations for compiler 
236 /// intrinsics.
237 ///
238 void PIC16AsmPrinter::printLibcallDecls() {
239   // If no libcalls used, return.
240   if (LibcallDecls.empty()) return;
241
242   O << MAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
243   // Remove duplicate entries.
244   LibcallDecls.sort(is_before);
245   LibcallDecls.unique(is_duplicate);
246
247   for (std::list<const char*>::const_iterator I = LibcallDecls.begin(); 
248        I != LibcallDecls.end(); I++) {
249     O << MAI->getExternDirective() << *I << "\n";
250     O << MAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
251     O << MAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
252   }
253   O << MAI->getCommentString() << "External decls for libcalls - END." <<"\n";
254 }
255
256 /// doInitialization - Perform Module level initializations here.
257 /// One task that we do here is to sectionize all global variables.
258 /// The MemSelOptimizer pass depends on the sectionizing.
259 ///
260 bool PIC16AsmPrinter::doInitialization(Module &M) {
261   bool Result = AsmPrinter::doInitialization(M);
262
263   // Every asmbly contains these std headers. 
264   O << "\n#include p16f1xxx.inc";
265   O << "\n#include stdmacros.inc";
266
267   // Set the section names for all globals.
268   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
269        I != E; ++I) {
270
271     // Record External Var Decls.
272     if (I->isDeclaration()) {
273       ExternalVarDecls.push_back(I);
274       continue;
275     }
276
277     // Record Exteranl Var Defs.
278     if (I->hasExternalLinkage() || I->hasCommonLinkage()) {
279       ExternalVarDefs.push_back(I);
280     }
281
282     // Sectionify actual data.
283     if (!I->hasAvailableExternallyLinkage()) {
284       const MCSection *S = getObjFileLowering().SectionForGlobal(I, Mang, TM);
285       
286       I->setSection(((const PIC16Section *)S)->getName());
287     }
288   }
289
290   DbgInfo.BeginModule(M);
291   EmitFunctionDecls(M);
292   EmitUndefinedVars(M);
293   EmitDefinedVars(M);
294   EmitIData(M);
295   EmitUData(M);
296   EmitRomData(M);
297   EmitSharedUdata(M);
298   EmitUserSections(M);
299   return Result;
300 }
301
302 /// Emit extern decls for functions imported from other modules, and emit
303 /// global declarations for function defined in this module and which are
304 /// available to other modules.
305 ///
306 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
307  // Emit declarations for external functions.
308   O <<"\n"<<MAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
309   for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
310     if (I->isIntrinsic() || I->getName() == "@abort")
311       continue;
312     
313     if (!I->isDeclaration() && !I->hasExternalLinkage())
314       continue;
315
316     MCSymbol *Sym = GetGlobalValueSymbol(I);
317     
318     // Do not emit memcpy, memset, and memmove here.
319     // Calls to these routines can be generated in two ways,
320     // 1. User calling the standard lib function
321     // 2. Codegen generating these calls for llvm intrinsics.
322     // In the first case a prototype is alread availale, while in
323     // second case the call is via and externalsym and the prototype is missing.
324     // So declarations for these are currently always getting printing by
325     // tracking both kind of references in printInstrunction.
326     if (I->isDeclaration() && PAN::isMemIntrinsic(Sym->getName())) continue;
327
328     const char *directive = I->isDeclaration() ? MAI->getExternDirective() :
329                                                  MAI->getGlobalDirective();
330       
331     O << directive << Sym->getName() << "\n";
332     O << directive << PAN::getRetvalLabel(Sym->getName()) << "\n";
333     O << directive << PAN::getArgsLabel(Sym->getName()) << "\n";
334   }
335
336   O << MAI->getCommentString() << "Function Declarations - END." <<"\n";
337 }
338
339 // Emit variables imported from other Modules.
340 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
341   std::vector<const GlobalVariable*> Items = ExternalVarDecls;
342   if (!Items.size()) return;
343
344   O << "\n" << MAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
345   for (unsigned j = 0; j < Items.size(); j++)
346     O << MAI->getExternDirective() << *GetGlobalValueSymbol(Items[j]) << "\n";
347   O << MAI->getCommentString() << "Imported Variables - END" << "\n";
348 }
349
350 // Emit variables defined in this module and are available to other modules.
351 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
352   std::vector<const GlobalVariable*> Items = ExternalVarDefs;
353   if (!Items.size()) return;
354
355   O << "\n" << MAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
356   for (unsigned j = 0; j < Items.size(); j++)
357     O << MAI->getGlobalDirective() << *GetGlobalValueSymbol(Items[j]) << "\n";
358   O <<  MAI->getCommentString() << "Exported Variables - END" << "\n";
359 }
360
361 // Emit initialized data placed in ROM.
362 void PIC16AsmPrinter::EmitRomData(Module &M) {
363   EmitSingleSection(PTOF->ROMDATASection());
364 }
365
366 // Emit Shared section udata.
367 void PIC16AsmPrinter::EmitSharedUdata(Module &M) {
368   EmitSingleSection(PTOF->SHAREDUDATASection());
369 }
370
371 bool PIC16AsmPrinter::doFinalization(Module &M) {
372   EmitAllAutos(M);
373   printLibcallDecls();
374   DbgInfo.EndModule(M);
375   O << "\n\t" << "END\n";
376   return AsmPrinter::doFinalization(M);
377 }
378
379 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
380   const Function *F = MF.getFunction();
381   const TargetData *TD = TM.getTargetData();
382   // Emit the data section name.
383   O << "\n"; 
384   
385   PIC16Section *fPDataSection =
386     const_cast<PIC16Section *>(getObjFileLowering().
387                                 SectionForFrame(CurrentFnSym->getName()));
388  
389   fPDataSection->setColor(getFunctionColor(F)); 
390   OutStreamer.SwitchSection(fPDataSection);
391   
392   // Emit function frame label
393   O << PAN::getFrameLabel(CurrentFnSym->getName()) << ":\n";
394
395   const Type *RetType = F->getReturnType();
396   unsigned RetSize = 0; 
397   if (RetType->getTypeID() != Type::VoidTyID) 
398     RetSize = TD->getTypeAllocSize(RetType);
399   
400   //Emit function return value space
401   // FIXME: Do not emit RetvalLable when retsize is zero. To do this
402   // we will need to avoid printing a global directive for Retval label
403   // in emitExternandGloblas.
404   if(RetSize > 0)
405      O << PAN::getRetvalLabel(CurrentFnSym->getName())
406        << " RES " << RetSize << "\n";
407   else
408      O << PAN::getRetvalLabel(CurrentFnSym->getName()) << ": \n";
409    
410   // Emit variable to hold the space for function arguments 
411   unsigned ArgSize = 0;
412   for (Function::const_arg_iterator argi = F->arg_begin(),
413            arge = F->arg_end(); argi != arge ; ++argi) {
414     const Type *Ty = argi->getType();
415     ArgSize += TD->getTypeAllocSize(Ty);
416    }
417
418   O << PAN::getArgsLabel(CurrentFnSym->getName()) << " RES " << ArgSize << "\n";
419
420   // Emit temporary space
421   int TempSize = PTLI->GetTmpSize();
422   if (TempSize > 0)
423     O << PAN::getTempdataLabel(CurrentFnSym->getName()) << " RES  "
424       << TempSize << '\n';
425 }
426
427
428 void PIC16AsmPrinter::EmitInitializedDataSection(const PIC16Section *S) {
429   /// Emit Section header.
430   OutStreamer.SwitchSection(S);
431
432     std::vector<const GlobalVariable*> Items = S->Items;
433     for (unsigned j = 0; j < Items.size(); j++) {
434       Constant *C = Items[j]->getInitializer();
435       int AddrSpace = Items[j]->getType()->getAddressSpace();
436       O << *GetGlobalValueSymbol(Items[j]);
437       EmitGlobalConstant(C, AddrSpace);
438    }
439 }
440
441 // Print all IDATA sections.
442 void PIC16AsmPrinter::EmitIData(Module &M) {
443   EmitSectionList (M, PTOF->IDATASections());
444 }
445
446 void PIC16AsmPrinter::
447 EmitUninitializedDataSection(const PIC16Section *S) {
448     const TargetData *TD = TM.getTargetData();
449     OutStreamer.SwitchSection(S);
450     std::vector<const GlobalVariable*> Items = S->Items;
451     for (unsigned j = 0; j < Items.size(); j++) {
452       Constant *C = Items[j]->getInitializer();
453       const Type *Ty = C->getType();
454       unsigned Size = TD->getTypeAllocSize(Ty);
455       O << *GetGlobalValueSymbol(Items[j]) << " RES " << Size << "\n";
456     }
457 }
458
459 // Print all UDATA sections.
460 void PIC16AsmPrinter::EmitUData(Module &M) {
461   EmitSectionList (M, PTOF->UDATASections());
462 }
463
464 // Print all USER sections.
465 void PIC16AsmPrinter::EmitUserSections(Module &M) {
466   EmitSectionList (M, PTOF->USERSections());
467 }
468
469 // Print all AUTO sections.
470 void PIC16AsmPrinter::EmitAllAutos(Module &M) {
471   EmitSectionList (M, PTOF->AUTOSections());
472 }
473
474 extern "C" void LLVMInitializePIC16AsmPrinter() { 
475   RegisterAsmPrinter<PIC16AsmPrinter> X(ThePIC16Target);
476 }
477
478 // Emit one data section using correct section emitter based on section type.
479 void PIC16AsmPrinter::EmitSingleSection(const PIC16Section *S) {
480   if (S == NULL) return;
481
482   switch (S->getType()) {
483     default: llvm_unreachable ("unknow user section type");
484     case UDATA:
485     case UDATA_SHR:
486     case UDATA_OVR:
487       EmitUninitializedDataSection(S);
488       break;
489     case IDATA:
490     case ROMDATA:
491       EmitInitializedDataSection(S);
492       break;
493   }
494 }
495
496 // Emit a list of sections.
497 void PIC16AsmPrinter::
498 EmitSectionList(Module &M, const std::vector<PIC16Section *> &SList) {
499   for (unsigned i = 0; i < SList.size(); i++) {
500     // Exclude llvm specific metadata sections.
501     if (SList[i]->getName().find("llvm.") != std::string::npos)
502       continue;
503     O << "\n";
504     EmitSingleSection(SList[i]);
505   }
506 }
507