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 "PIC16Section.h"
17 #include "PIC16TargetAsmInfo.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Function.h"
20 #include "llvm/Module.h"
21 #include "llvm/CodeGen/DwarfWriter.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/CodeGen/MachineModuleInfo.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 const MCSection *S = getObjFileLowering().SectionForGlobal(I, Mang, TM);
233 I->setSection(((const MCSectionPIC16*)S)->getName());
236 DbgInfo.BeginModule(M);
237 EmitFunctionDecls(M);
238 EmitUndefinedVars(M);
246 /// Emit extern decls for functions imported from other modules, and emit
247 /// global declarations for function defined in this module and which are
248 /// available to other modules.
250 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
251 // Emit declarations for external functions.
252 O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
253 for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
254 if (I->isIntrinsic())
257 std::string Name = Mang->getMangledName(I);
258 if (Name.compare("@abort") == 0)
261 if (!I->isDeclaration() && !I->hasExternalLinkage())
264 // Do not emit memcpy, memset, and memmove here.
265 // Calls to these routines can be generated in two ways,
266 // 1. User calling the standard lib function
267 // 2. Codegen generating these calls for llvm intrinsics.
268 // In the first case a prototype is alread availale, while in
269 // second case the call is via and externalsym and the prototype is missing.
270 // So declarations for these are currently always getting printing by
271 // tracking both kind of references in printInstrunction.
272 if (I->isDeclaration() && PAN::isMemIntrinsic(Name)) continue;
274 const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
275 TAI->getGlobalDirective();
277 O << directive << Name << "\n";
278 O << directive << PAN::getRetvalLabel(Name) << "\n";
279 O << directive << PAN::getArgsLabel(Name) << "\n";
282 O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
285 // Emit variables imported from other Modules.
286 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
287 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDecls->Items;
288 if (!Items.size()) return;
290 O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
291 for (unsigned j = 0; j < Items.size(); j++) {
292 O << TAI->getExternDirective() << Mang->getMangledName(Items[j]) << "\n";
294 O << TAI->getCommentString() << "Imported Variables - END" << "\n";
297 // Emit variables defined in this module and are available to other modules.
298 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
299 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDefs->Items;
300 if (!Items.size()) return;
302 O << "\n" << TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
303 for (unsigned j = 0; j < Items.size(); j++) {
304 O << TAI->getGlobalDirective() << Mang->getMangledName(Items[j]) << "\n";
306 O << TAI->getCommentString() << "Exported Variables - END" << "\n";
309 // Emit initialized data placed in ROM.
310 void PIC16AsmPrinter::EmitRomData(Module &M) {
311 // Print ROM Data section.
312 const std::vector<PIC16Section*> &ROSections = PTOF->ROSections;
313 for (unsigned i = 0; i < ROSections.size(); i++) {
314 const std::vector<const GlobalVariable*> &Items = ROSections[i]->Items;
315 if (!Items.size()) continue;
317 SwitchToSection(PTOF->ROSections[i]->S_);
318 for (unsigned j = 0; j < Items.size(); j++) {
319 O << Mang->getMangledName(Items[j]);
320 Constant *C = Items[j]->getInitializer();
321 int AddrSpace = Items[j]->getType()->getAddressSpace();
322 EmitGlobalConstant(C, AddrSpace);
327 bool PIC16AsmPrinter::doFinalization(Module &M) {
329 EmitRemainingAutos();
330 DbgInfo.EndModule(M);
331 O << "\n\t" << "END\n";
332 return AsmPrinter::doFinalization(M);
335 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
336 const Function *F = MF.getFunction();
337 std::string FuncName = Mang->getMangledName(F);
338 const TargetData *TD = TM.getTargetData();
339 // Emit the data section name.
342 const MCSection *fPDataSection =
343 getObjFileLowering().getSectionForFunctionFrame(CurrentFnName);
344 SwitchToSection(fPDataSection);
346 // Emit function frame label
347 O << PAN::getFrameLabel(CurrentFnName) << ":\n";
349 const Type *RetType = F->getReturnType();
350 unsigned RetSize = 0;
351 if (RetType->getTypeID() != Type::VoidTyID)
352 RetSize = TD->getTypeAllocSize(RetType);
354 //Emit function return value space
355 // FIXME: Do not emit RetvalLable when retsize is zero. To do this
356 // we will need to avoid printing a global directive for Retval label
357 // in emitExternandGloblas.
359 O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
361 O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
363 // Emit variable to hold the space for function arguments
364 unsigned ArgSize = 0;
365 for (Function::const_arg_iterator argi = F->arg_begin(),
366 arge = F->arg_end(); argi != arge ; ++argi) {
367 const Type *Ty = argi->getType();
368 ArgSize += TD->getTypeAllocSize(Ty);
371 O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
373 // Emit temporary space
374 int TempSize = PTLI->GetTmpSize();
376 O << PAN::getTempdataLabel(CurrentFnName) << " RES " << TempSize << '\n';
379 void PIC16AsmPrinter::EmitIData(Module &M) {
381 // Print all IDATA sections.
382 const std::vector<PIC16Section*> &IDATASections = PTOF->IDATASections;
383 for (unsigned i = 0; i < IDATASections.size(); i++) {
385 if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
387 SwitchToSection(IDATASections[i]->S_);
388 std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
389 for (unsigned j = 0; j < Items.size(); j++) {
390 std::string Name = Mang->getMangledName(Items[j]);
391 Constant *C = Items[j]->getInitializer();
392 int AddrSpace = Items[j]->getType()->getAddressSpace();
394 EmitGlobalConstant(C, AddrSpace);
399 void PIC16AsmPrinter::EmitUData(Module &M) {
400 const TargetData *TD = TM.getTargetData();
402 // Print all BSS sections.
403 const std::vector<PIC16Section*> &BSSSections = PTOF->BSSSections;
404 for (unsigned i = 0; i < BSSSections.size(); i++) {
406 SwitchToSection(BSSSections[i]->S_);
407 std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
408 for (unsigned j = 0; j < Items.size(); j++) {
409 std::string Name = Mang->getMangledName(Items[j]);
410 Constant *C = Items[j]->getInitializer();
411 const Type *Ty = C->getType();
412 unsigned Size = TD->getTypeAllocSize(Ty);
414 O << Name << " RES " << Size << "\n";
419 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
420 // Section names for all globals are already set.
421 const TargetData *TD = TM.getTargetData();
423 // Now print Autos section for this function.
424 std::string SectionName = PAN::getAutosSectionName(FunctName);
425 const std::vector<PIC16Section*> &AutosSections = PTOF->AutosSections;
426 for (unsigned i = 0; i < AutosSections.size(); i++) {
428 if (AutosSections[i]->S_->getName() == SectionName) {
429 // Set the printing status to true
430 AutosSections[i]->setPrintedStatus(true);
431 SwitchToSection(AutosSections[i]->S_);
432 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
433 for (unsigned j = 0; j < Items.size(); j++) {
434 std::string VarName = Mang->getMangledName(Items[j]);
435 Constant *C = Items[j]->getInitializer();
436 const Type *Ty = C->getType();
437 unsigned Size = TD->getTypeAllocSize(Ty);
438 // Emit memory reserve directive.
439 O << VarName << " RES " << Size << "\n";
446 // Print autos that were not printed during the code printing of functions.
447 // As the functions might themselves would have got deleted by the optimizer.
448 void PIC16AsmPrinter::EmitRemainingAutos() {
449 const TargetData *TD = TM.getTargetData();
451 // Now print Autos section for this function.
452 std::vector <PIC16Section *>AutosSections = PTOF->AutosSections;
453 for (unsigned i = 0; i < AutosSections.size(); i++) {
455 // if the section is already printed then don't print again
456 if (AutosSections[i]->isPrinted())
459 // Set status as printed
460 AutosSections[i]->setPrintedStatus(true);
463 SwitchToSection(AutosSections[i]->S_);
464 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
465 for (unsigned j = 0; j < Items.size(); j++) {
466 std::string VarName = Mang->getMangledName(Items[j]);
467 Constant *C = Items[j]->getInitializer();
468 const Type *Ty = C->getType();
469 unsigned Size = TD->getTypeAllocSize(Ty);
470 // Emit memory reserve directive.
471 O << VarName << " RES " << Size << "\n";
477 extern "C" void LLVMInitializePIC16Target() {
478 // Register the targets
479 RegisterTargetMachine<PIC16TargetMachine> A(ThePIC16Target);
480 RegisterTargetMachine<CooperTargetMachine> B(TheCooperTarget);
481 RegisterAsmPrinter<PIC16AsmPrinter> C(ThePIC16Target);
482 RegisterAsmPrinter<PIC16AsmPrinter> D(TheCooperTarget);