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 "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"
33 #include "PIC16GenAsmWriter.inc"
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();
43 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
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.
52 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
55 // This calls the base class function required to be called at beginning
56 // of runOnMachineFunction.
57 SetupMachineFunction(MF);
59 // Get the mangled name.
60 const Function *F = MF.getFunction();
61 CurrentFnName = Mang->getMangledName(F);
63 // Emit the function frame (args and temps).
64 EmitFunctionFrame(MF);
66 DbgInfo.BeginFunction(MF);
68 // Emit the autos section of function.
69 EmitAutos(CurrentFnName);
71 // Now emit the instructions of function in its code section.
72 const MCSection *fCodeSection =
73 getObjFileLowering().getSectionForFunction(CurrentFnName);
74 // Start the Code Section.
76 SwitchToSection(fCodeSection);
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";
82 // Emit function start label.
83 O << CurrentFnName << ":\n";
87 // Print out code for the function.
88 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
91 // Print a label for the basic block.
92 if (I != MF.begin()) {
93 printBasicBlockLabel(I, true);
97 // Print a basic block.
98 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
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);
108 // Print the assembly for the instruction.
109 printMachineInstruction(II);
113 // Emit function end debug directives.
114 DbgInfo.EndFunction(MF);
116 return false; // we didn't modify anything.
120 // printOperand - print operand of insn.
121 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
122 const MachineOperand &MO = MI->getOperand(opNum);
124 switch (MO.getType()) {
125 case MachineOperand::MO_Register:
126 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
127 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
129 llvm_unreachable("not implemented");
132 case MachineOperand::MO_Immediate:
133 O << (int)MO.getImm();
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));
148 case MachineOperand::MO_ExternalSymbol: {
149 const char *Sname = MO.getSymbolName();
151 // If its a libcall name, record it to decls section.
152 if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
153 LibcallDecls.push_back(Sname);
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));
166 case MachineOperand::MO_MachineBasicBlock:
167 printBasicBlockLabel(MO.getMBB());
171 llvm_unreachable(" Operand type not supported.");
175 /// printCCOperand - Print the cond code operand.
177 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
178 int CC = (int)MI->getOperand(opNum).getImm();
179 O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
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;
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);
194 /// printLibcallDecls - print the extern declarations for compiler
197 void PIC16AsmPrinter::printLibcallDecls(void) {
198 // If no libcalls used, return.
199 if (LibcallDecls.empty()) return;
201 O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
202 // Remove duplicate entries.
203 LibcallDecls.sort(is_before);
204 LibcallDecls.unique(is_duplicate);
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";
212 O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
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.
219 bool PIC16AsmPrinter::doInitialization(Module &M) {
220 bool Result = AsmPrinter::doInitialization(M);
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";
227 // Set the section names for all globals.
228 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
230 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage())
231 I->setSection(getObjFileLowering().
232 SectionForGlobal(I, Mang,TM)->getName());
234 DbgInfo.BeginModule(M);
235 EmitFunctionDecls(M);
236 EmitUndefinedVars(M);
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.
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())
255 std::string Name = Mang->getMangledName(I);
256 if (Name.compare("@abort") == 0)
259 if (!I->isDeclaration() && !I->hasExternalLinkage())
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;
272 const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
273 TAI->getGlobalDirective();
275 O << directive << Name << "\n";
276 O << directive << PAN::getRetvalLabel(Name) << "\n";
277 O << directive << PAN::getArgsLabel(Name) << "\n";
280 O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
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;
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";
292 O << TAI->getCommentString() << "Imported Variables - END" << "\n";
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;
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";
304 O << TAI->getCommentString() << "Exported Variables - END" << "\n";
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;
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);
325 bool PIC16AsmPrinter::doFinalization(Module &M) {
327 EmitRemainingAutos();
328 DbgInfo.EndModule(M);
329 O << "\n\t" << "END\n";
330 return AsmPrinter::doFinalization(M);
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.
340 const MCSection *fPDataSection =
341 getObjFileLowering().getSectionForFunctionFrame(CurrentFnName);
342 SwitchToSection(fPDataSection);
344 // Emit function frame label
345 O << PAN::getFrameLabel(CurrentFnName) << ":\n";
347 const Type *RetType = F->getReturnType();
348 unsigned RetSize = 0;
349 if (RetType->getTypeID() != Type::VoidTyID)
350 RetSize = TD->getTypeAllocSize(RetType);
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.
357 O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
359 O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
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);
369 O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
371 // Emit temporary space
372 int TempSize = PTLI->GetTmpSize();
374 O << PAN::getTempdataLabel(CurrentFnName) << " RES " << TempSize << '\n';
377 void PIC16AsmPrinter::EmitIData(Module &M) {
379 // Print all IDATA sections.
380 const std::vector<PIC16Section*> &IDATASections = PTOF->IDATASections;
381 for (unsigned i = 0; i < IDATASections.size(); i++) {
383 if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
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();
392 EmitGlobalConstant(C, AddrSpace);
397 void PIC16AsmPrinter::EmitUData(Module &M) {
398 const TargetData *TD = TM.getTargetData();
400 // Print all BSS sections.
401 const std::vector<PIC16Section*> &BSSSections = PTOF->BSSSections;
402 for (unsigned i = 0; i < BSSSections.size(); i++) {
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);
412 O << Name << " RES " << Size << "\n";
417 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
418 // Section names for all globals are already set.
419 const TargetData *TD = TM.getTargetData();
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++) {
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";
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();
449 // Now print Autos section for this function.
450 std::vector <PIC16Section *>AutosSections = PTOF->AutosSections;
451 for (unsigned i = 0; i < AutosSections.size(); i++) {
453 // if the section is already printed then don't print again
454 if (AutosSections[i]->isPrinted())
457 // Set status as printed
458 AutosSections[i]->setPrintedStatus(true);
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";
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);