1 //===-- PIC16AsmPrinter.cpp - PIC16 LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PIC16 assembly language.
13 //===----------------------------------------------------------------------===//
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"
35 #include "PIC16GenAsmWriter.inc"
37 PIC16AsmPrinter::PIC16AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
38 const MCAsmInfo *T, bool V)
39 : AsmPrinter(O, TM, T, V), DbgInfo(O, T) {
40 PTLI = static_cast<PIC16TargetLowering*>(TM.getTargetLowering());
41 PMAI = static_cast<const PIC16MCAsmInfo*>(T);
42 PTOF = (PIC16TargetObjectFile *)&PTLI->getObjFileLowering();
45 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
46 processDebugLoc(MI, true);
51 processDebugLoc(MI, false);
55 static int getFunctionColor(const Function *F) {
56 if (F->hasSection()) {
57 std::string Sectn = F->getSection();
58 std::string StrToFind = "Overlay=";
59 std::string::size_type Pos = Sectn.find(StrToFind);
61 // Retreive the color number if the key is found.
62 if (Pos != std::string::npos) {
63 Pos += StrToFind.length();
64 std::string Color = "";
65 char c = Sectn.at(Pos);
66 // A Color can only consist of digits.
67 while (c >= '0' && c<= '9') {
70 if (Pos >= Sectn.length())
74 return atoi(Color.c_str());
78 // Color was not set for function, so return -1.
82 // Color the Auto section of the given function.
83 void PIC16AsmPrinter::ColorAutoSection(const Function *F) {
84 std::string SectionName = PAN::getAutosSectionName(CurrentFnSym->getName());
85 PIC16Section* Section = PTOF->findPIC16Section(SectionName);
86 if (Section != NULL) {
87 int Color = getFunctionColor(F);
89 Section->setColor(Color);
94 /// runOnMachineFunction - This emits the frame section, autos section and
95 /// assembly for each instruction. Also takes care of function begin debug
96 /// directive and file begin debug directive (if required) for the function.
98 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
99 // This calls the base class function required to be called at beginning
100 // of runOnMachineFunction.
101 SetupMachineFunction(MF);
103 // Put the color information from function to its auto section.
104 const Function *F = MF.getFunction();
107 // Emit the function frame (args and temps).
108 EmitFunctionFrame(MF);
110 DbgInfo.BeginFunction(MF);
112 // Now emit the instructions of function in its code section.
113 const MCSection *fCodeSection
114 = getObjFileLowering().SectionForCode(CurrentFnSym->getName());
116 // Start the Code Section.
118 OutStreamer.SwitchSection(fCodeSection);
120 // Emit the frame address of the function at the beginning of code.
121 O << "\tretlw low(" << PAN::getFrameLabel(CurrentFnSym->getName()) << ")\n";
122 O << "\tretlw high(" << PAN::getFrameLabel(CurrentFnSym->getName()) << ")\n";
124 // Emit function start label.
125 O << *CurrentFnSym << ":\n";
129 // Print out code for the function.
130 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
133 // Print a label for the basic block.
134 if (I != MF.begin()) {
135 EmitBasicBlockStart(I);
138 // Print a basic block.
139 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
142 // Emit the line directive if source line changed.
143 const DebugLoc DL = II->getDebugLoc();
144 if (!DL.isUnknown() && DL != CurDL) {
145 DbgInfo.ChangeDebugLoc(MF, DL);
149 // Print the assembly for the instruction.
150 printMachineInstruction(II);
154 // Emit function end debug directives.
155 DbgInfo.EndFunction(MF);
157 return false; // we didn't modify anything.
161 // printOperand - print operand of insn.
162 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
163 const MachineOperand &MO = MI->getOperand(opNum);
165 switch (MO.getType()) {
166 case MachineOperand::MO_Register:
168 // For indirect load/store insns, the fsr name is printed as INDF.
169 std::string RegName = getRegisterName(MO.getReg());
170 if ((MI->getOpcode() == PIC16::load_indirect) ||
171 (MI->getOpcode() == PIC16::store_indirect))
173 RegName.replace (0, 3, "INDF");
179 case MachineOperand::MO_Immediate:
180 O << (int)MO.getImm();
183 case MachineOperand::MO_GlobalAddress: {
184 MCSymbol *Sym = GetGlobalValueSymbol(MO.getGlobal());
185 // FIXME: currently we do not have a memcpy def coming in the module
186 // by any chance, as we do not link in those as .bc lib. So these calls
187 // are always external and it is safe to emit an extern.
188 if (PAN::isMemIntrinsic(Sym->getName()))
189 LibcallDecls.push_back(createESName(Sym->getName()));
194 case MachineOperand::MO_ExternalSymbol: {
195 const char *Sname = MO.getSymbolName();
197 // If its a libcall name, record it to decls section.
198 if (PAN::getSymbolTag(Sname) == PAN::LIBCALL)
199 LibcallDecls.push_back(Sname);
201 // Record a call to intrinsic to print the extern declaration for it.
202 std::string Sym = Sname;
203 if (PAN::isMemIntrinsic(Sym)) {
204 Sym = PAN::addPrefix(Sym);
205 LibcallDecls.push_back(createESName(Sym));
211 case MachineOperand::MO_MachineBasicBlock:
212 O << *GetMBBSymbol(MO.getMBB()->getNumber());
216 llvm_unreachable(" Operand type not supported.");
220 /// printCCOperand - Print the cond code operand.
222 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
223 int CC = (int)MI->getOperand(opNum).getImm();
224 O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
227 // This function is used to sort the decls list.
228 // should return true if s1 should come before s2.
229 static bool is_before(const char *s1, const char *s2) {
230 return strcmp(s1, s2) <= 0;
233 // This is used by list::unique below.
234 // unique will filter out duplicates if it knows them.
235 static bool is_duplicate(const char *s1, const char *s2) {
236 return !strcmp(s1, s2);
239 /// printLibcallDecls - print the extern declarations for compiler
242 void PIC16AsmPrinter::printLibcallDecls() {
243 // If no libcalls used, return.
244 if (LibcallDecls.empty()) return;
246 O << MAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
247 // Remove duplicate entries.
248 LibcallDecls.sort(is_before);
249 LibcallDecls.unique(is_duplicate);
251 for (std::list<const char*>::const_iterator I = LibcallDecls.begin();
252 I != LibcallDecls.end(); I++) {
253 O << MAI->getExternDirective() << *I << "\n";
254 O << MAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
255 O << MAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
257 O << MAI->getCommentString() << "External decls for libcalls - END." <<"\n";
260 /// doInitialization - Perform Module level initializations here.
261 /// One task that we do here is to sectionize all global variables.
262 /// The MemSelOptimizer pass depends on the sectionizing.
264 bool PIC16AsmPrinter::doInitialization(Module &M) {
265 bool Result = AsmPrinter::doInitialization(M);
267 // Every asmbly contains these std headers.
268 O << "\n#include p16f1xxx.inc";
269 O << "\n#include stdmacros.inc";
271 // Set the section names for all globals.
272 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
275 // Record External Var Decls.
276 if (I->isDeclaration()) {
277 ExternalVarDecls.push_back(I);
281 // Record Exteranl Var Defs.
282 if (I->hasExternalLinkage() || I->hasCommonLinkage()) {
283 ExternalVarDefs.push_back(I);
286 // Sectionify actual data.
287 if (!I->hasAvailableExternallyLinkage()) {
288 const MCSection *S = getObjFileLowering().SectionForGlobal(I, Mang, TM);
290 I->setSection(((const PIC16Section *)S)->getName());
294 DbgInfo.BeginModule(M);
295 EmitFunctionDecls(M);
296 EmitUndefinedVars(M);
306 /// Emit extern decls for functions imported from other modules, and emit
307 /// global declarations for function defined in this module and which are
308 /// available to other modules.
310 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
311 // Emit declarations for external functions.
312 O <<"\n"<<MAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
313 for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
314 if (I->isIntrinsic() || I->getName() == "@abort")
317 if (!I->isDeclaration() && !I->hasExternalLinkage())
320 MCSymbol *Sym = GetGlobalValueSymbol(I);
322 // Do not emit memcpy, memset, and memmove here.
323 // Calls to these routines can be generated in two ways,
324 // 1. User calling the standard lib function
325 // 2. Codegen generating these calls for llvm intrinsics.
326 // In the first case a prototype is alread availale, while in
327 // second case the call is via and externalsym and the prototype is missing.
328 // So declarations for these are currently always getting printing by
329 // tracking both kind of references in printInstrunction.
330 if (I->isDeclaration() && PAN::isMemIntrinsic(Sym->getName())) continue;
332 const char *directive = I->isDeclaration() ? MAI->getExternDirective() :
333 MAI->getGlobalDirective();
335 O << directive << Sym->getName() << "\n";
336 O << directive << PAN::getRetvalLabel(Sym->getName()) << "\n";
337 O << directive << PAN::getArgsLabel(Sym->getName()) << "\n";
340 O << MAI->getCommentString() << "Function Declarations - END." <<"\n";
343 // Emit variables imported from other Modules.
344 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
345 std::vector<const GlobalVariable*> Items = ExternalVarDecls;
346 if (!Items.size()) return;
348 O << "\n" << MAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
349 for (unsigned j = 0; j < Items.size(); j++)
350 O << MAI->getExternDirective() << *GetGlobalValueSymbol(Items[j]) << "\n";
351 O << MAI->getCommentString() << "Imported Variables - END" << "\n";
354 // Emit variables defined in this module and are available to other modules.
355 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
356 std::vector<const GlobalVariable*> Items = ExternalVarDefs;
357 if (!Items.size()) return;
359 O << "\n" << MAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
360 for (unsigned j = 0; j < Items.size(); j++)
361 O << MAI->getGlobalDirective() << *GetGlobalValueSymbol(Items[j]) << "\n";
362 O << MAI->getCommentString() << "Exported Variables - END" << "\n";
365 // Emit initialized data placed in ROM.
366 void PIC16AsmPrinter::EmitRomData(Module &M) {
367 EmitSingleSection(PTOF->ROMDATASection());
370 // Emit Shared section udata.
371 void PIC16AsmPrinter::EmitSharedUdata(Module &M) {
372 EmitSingleSection(PTOF->SHAREDUDATASection());
375 bool PIC16AsmPrinter::doFinalization(Module &M) {
378 DbgInfo.EndModule(M);
379 O << "\n\t" << "END\n";
380 return AsmPrinter::doFinalization(M);
383 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
384 const Function *F = MF.getFunction();
385 const TargetData *TD = TM.getTargetData();
386 // Emit the data section name.
389 PIC16Section *fPDataSection =
390 const_cast<PIC16Section *>(getObjFileLowering().
391 SectionForFrame(CurrentFnSym->getName()));
393 fPDataSection->setColor(getFunctionColor(F));
394 OutStreamer.SwitchSection(fPDataSection);
396 // Emit function frame label
397 O << PAN::getFrameLabel(CurrentFnSym->getName()) << ":\n";
399 const Type *RetType = F->getReturnType();
400 unsigned RetSize = 0;
401 if (RetType->getTypeID() != Type::VoidTyID)
402 RetSize = TD->getTypeAllocSize(RetType);
404 //Emit function return value space
405 // FIXME: Do not emit RetvalLable when retsize is zero. To do this
406 // we will need to avoid printing a global directive for Retval label
407 // in emitExternandGloblas.
409 O << PAN::getRetvalLabel(CurrentFnSym->getName())
410 << " RES " << RetSize << "\n";
412 O << PAN::getRetvalLabel(CurrentFnSym->getName()) << ": \n";
414 // Emit variable to hold the space for function arguments
415 unsigned ArgSize = 0;
416 for (Function::const_arg_iterator argi = F->arg_begin(),
417 arge = F->arg_end(); argi != arge ; ++argi) {
418 const Type *Ty = argi->getType();
419 ArgSize += TD->getTypeAllocSize(Ty);
422 O << PAN::getArgsLabel(CurrentFnSym->getName()) << " RES " << ArgSize << "\n";
424 // Emit temporary space
425 int TempSize = PTLI->GetTmpSize();
427 O << PAN::getTempdataLabel(CurrentFnSym->getName()) << " RES "
432 void PIC16AsmPrinter::EmitInitializedDataSection(const PIC16Section *S) {
433 /// Emit Section header.
434 OutStreamer.SwitchSection(S);
436 std::vector<const GlobalVariable*> Items = S->Items;
437 for (unsigned j = 0; j < Items.size(); j++) {
438 Constant *C = Items[j]->getInitializer();
439 int AddrSpace = Items[j]->getType()->getAddressSpace();
440 O << *GetGlobalValueSymbol(Items[j]);
441 EmitGlobalConstant(C, AddrSpace);
445 // Print all IDATA sections.
446 void PIC16AsmPrinter::EmitIData(Module &M) {
447 EmitSectionList (M, PTOF->IDATASections());
450 void PIC16AsmPrinter::
451 EmitUninitializedDataSection(const PIC16Section *S) {
452 const TargetData *TD = TM.getTargetData();
453 OutStreamer.SwitchSection(S);
454 std::vector<const GlobalVariable*> Items = S->Items;
455 for (unsigned j = 0; j < Items.size(); j++) {
456 Constant *C = Items[j]->getInitializer();
457 const Type *Ty = C->getType();
458 unsigned Size = TD->getTypeAllocSize(Ty);
459 O << *GetGlobalValueSymbol(Items[j]) << " RES " << Size << "\n";
463 // Print all UDATA sections.
464 void PIC16AsmPrinter::EmitUData(Module &M) {
465 EmitSectionList (M, PTOF->UDATASections());
468 // Print all USER sections.
469 void PIC16AsmPrinter::EmitUserSections(Module &M) {
470 EmitSectionList (M, PTOF->USERSections());
473 // Print all AUTO sections.
474 void PIC16AsmPrinter::EmitAllAutos(Module &M) {
475 EmitSectionList (M, PTOF->AUTOSections());
478 extern "C" void LLVMInitializePIC16AsmPrinter() {
479 RegisterAsmPrinter<PIC16AsmPrinter> X(ThePIC16Target);
482 // Emit one data section using correct section emitter based on section type.
483 void PIC16AsmPrinter::EmitSingleSection(const PIC16Section *S) {
484 if (S == NULL) return;
486 switch (S->getType()) {
487 default: llvm_unreachable ("unknow user section type");
491 EmitUninitializedDataSection(S);
495 EmitInitializedDataSection(S);
500 // Emit a list of sections.
501 void PIC16AsmPrinter::
502 EmitSectionList(Module &M, const std::vector<PIC16Section *> &SList) {
503 for (unsigned i = 0; i < SList.size(); i++) {
504 // Exclude llvm specific metadata sections.
505 if (SList[i]->getName().find("llvm.") != std::string::npos)
508 EmitSingleSection(SList[i]);