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 "MCSectionPIC16.h"
17 #include "PIC16MCAsmInfo.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/MC/MCStreamer.h"
26 #include "llvm/Target/TargetRegistry.h"
27 #include "llvm/Target/TargetLoweringObjectFile.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Support/Mangler.h"
34 #include "PIC16GenAsmWriter.inc"
36 PIC16AsmPrinter::PIC16AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
37 const MCAsmInfo *T, bool V)
38 : AsmPrinter(O, TM, T, V), DbgInfo(O, T) {
39 PTLI = static_cast<PIC16TargetLowering*>(TM.getTargetLowering());
40 PTAI = static_cast<const PIC16MCAsmInfo*>(T);
41 PTOF = (PIC16TargetObjectFile*)&PTLI->getObjFileLowering();
44 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
49 /// runOnMachineFunction - This emits the frame section, autos section and
50 /// assembly for each instruction. Also takes care of function begin debug
51 /// directive and file begin debug directive (if required) for the function.
53 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
56 // This calls the base class function required to be called at beginning
57 // of runOnMachineFunction.
58 SetupMachineFunction(MF);
60 // Get the mangled name.
61 const Function *F = MF.getFunction();
62 CurrentFnName = Mang->getMangledName(F);
64 // Emit the function frame (args and temps).
65 EmitFunctionFrame(MF);
67 DbgInfo.BeginFunction(MF);
69 // Emit the autos section of function.
70 EmitAutos(CurrentFnName);
72 // Now emit the instructions of function in its code section.
73 const MCSection *fCodeSection =
74 getObjFileLowering().getSectionForFunction(CurrentFnName);
75 // Start the Code Section.
77 OutStreamer.SwitchSection(fCodeSection);
79 // Emit the frame address of the function at the beginning of code.
80 O << "\tretlw low(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
81 O << "\tretlw high(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
83 // Emit function start label.
84 O << CurrentFnName << ":\n";
88 // Print out code for the function.
89 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
92 // Print a label for the basic block.
93 if (I != MF.begin()) {
94 printBasicBlockLabel(I, true);
98 // Print a basic block.
99 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
102 // Emit the line directive if source line changed.
103 const DebugLoc DL = II->getDebugLoc();
104 if (!DL.isUnknown() && DL != CurDL) {
105 DbgInfo.ChangeDebugLoc(MF, DL);
109 // Print the assembly for the instruction.
110 printMachineInstruction(II);
114 // Emit function end debug directives.
115 DbgInfo.EndFunction(MF);
117 return false; // we didn't modify anything.
121 // printOperand - print operand of insn.
122 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
123 const MachineOperand &MO = MI->getOperand(opNum);
125 switch (MO.getType()) {
126 case MachineOperand::MO_Register:
127 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
128 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
130 llvm_unreachable("not implemented");
133 case MachineOperand::MO_Immediate:
134 O << (int)MO.getImm();
137 case MachineOperand::MO_GlobalAddress: {
138 std::string Sname = Mang->getMangledName(MO.getGlobal());
139 // FIXME: currently we do not have a memcpy def coming in the module
140 // by any chance, as we do not link in those as .bc lib. So these calls
141 // are always external and it is safe to emit an extern.
142 if (PAN::isMemIntrinsic(Sname)) {
143 LibcallDecls.push_back(createESName(Sname));
149 case MachineOperand::MO_ExternalSymbol: {
150 const char *Sname = MO.getSymbolName();
152 // If its a libcall name, record it to decls section.
153 if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
154 LibcallDecls.push_back(Sname);
157 // Record a call to intrinsic to print the extern declaration for it.
158 std::string Sym = Sname;
159 if (PAN::isMemIntrinsic(Sym)) {
160 Sym = PAN::addPrefix(Sym);
161 LibcallDecls.push_back(createESName(Sym));
167 case MachineOperand::MO_MachineBasicBlock:
168 printBasicBlockLabel(MO.getMBB());
172 llvm_unreachable(" Operand type not supported.");
176 /// printCCOperand - Print the cond code operand.
178 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
179 int CC = (int)MI->getOperand(opNum).getImm();
180 O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
183 // This function is used to sort the decls list.
184 // should return true if s1 should come before s2.
185 static bool is_before(const char *s1, const char *s2) {
186 return strcmp(s1, s2) <= 0;
189 // This is used by list::unique below.
190 // unique will filter out duplicates if it knows them.
191 static bool is_duplicate(const char *s1, const char *s2) {
192 return !strcmp(s1, s2);
195 /// printLibcallDecls - print the extern declarations for compiler
198 void PIC16AsmPrinter::printLibcallDecls() {
199 // If no libcalls used, return.
200 if (LibcallDecls.empty()) return;
202 O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
203 // Remove duplicate entries.
204 LibcallDecls.sort(is_before);
205 LibcallDecls.unique(is_duplicate);
207 for (std::list<const char*>::const_iterator I = LibcallDecls.begin();
208 I != LibcallDecls.end(); I++) {
209 O << TAI->getExternDirective() << *I << "\n";
210 O << TAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
211 O << TAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
213 O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
216 /// doInitialization - Perfrom Module level initializations here.
217 /// One task that we do here is to sectionize all global variables.
218 /// The MemSelOptimizer pass depends on the sectionizing.
220 bool PIC16AsmPrinter::doInitialization(Module &M) {
221 bool Result = AsmPrinter::doInitialization(M);
223 // FIXME:: This is temporary solution to generate the include file.
224 // The processor should be passed to llc as in input and the header file
225 // should be generated accordingly.
226 O << "\n\t#include P16F1937.INC\n";
228 // Set the section names for all globals.
229 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
231 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) {
232 const MCSection *S = getObjFileLowering().SectionForGlobal(I, Mang, TM);
234 I->setSection(((const MCSectionPIC16*)S)->getName());
237 DbgInfo.BeginModule(M);
238 EmitFunctionDecls(M);
239 EmitUndefinedVars(M);
247 /// Emit extern decls for functions imported from other modules, and emit
248 /// global declarations for function defined in this module and which are
249 /// available to other modules.
251 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
252 // Emit declarations for external functions.
253 O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
254 for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
255 if (I->isIntrinsic())
258 std::string Name = Mang->getMangledName(I);
259 if (Name.compare("@abort") == 0)
262 if (!I->isDeclaration() && !I->hasExternalLinkage())
265 // Do not emit memcpy, memset, and memmove here.
266 // Calls to these routines can be generated in two ways,
267 // 1. User calling the standard lib function
268 // 2. Codegen generating these calls for llvm intrinsics.
269 // In the first case a prototype is alread availale, while in
270 // second case the call is via and externalsym and the prototype is missing.
271 // So declarations for these are currently always getting printing by
272 // tracking both kind of references in printInstrunction.
273 if (I->isDeclaration() && PAN::isMemIntrinsic(Name)) continue;
275 const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
276 TAI->getGlobalDirective();
278 O << directive << Name << "\n";
279 O << directive << PAN::getRetvalLabel(Name) << "\n";
280 O << directive << PAN::getArgsLabel(Name) << "\n";
283 O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
286 // Emit variables imported from other Modules.
287 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
288 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDecls->Items;
289 if (!Items.size()) return;
291 O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
292 for (unsigned j = 0; j < Items.size(); j++) {
293 O << TAI->getExternDirective() << Mang->getMangledName(Items[j]) << "\n";
295 O << TAI->getCommentString() << "Imported Variables - END" << "\n";
298 // Emit variables defined in this module and are available to other modules.
299 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
300 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDefs->Items;
301 if (!Items.size()) return;
303 O << "\n" << TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
304 for (unsigned j = 0; j < Items.size(); j++) {
305 O << TAI->getGlobalDirective() << Mang->getMangledName(Items[j]) << "\n";
307 O << TAI->getCommentString() << "Exported Variables - END" << "\n";
310 // Emit initialized data placed in ROM.
311 void PIC16AsmPrinter::EmitRomData(Module &M) {
312 // Print ROM Data section.
313 const std::vector<PIC16Section*> &ROSections = PTOF->ROSections;
314 for (unsigned i = 0; i < ROSections.size(); i++) {
315 const std::vector<const GlobalVariable*> &Items = ROSections[i]->Items;
316 if (!Items.size()) continue;
318 OutStreamer.SwitchSection(PTOF->ROSections[i]->S_);
319 for (unsigned j = 0; j < Items.size(); j++) {
320 O << Mang->getMangledName(Items[j]);
321 Constant *C = Items[j]->getInitializer();
322 int AddrSpace = Items[j]->getType()->getAddressSpace();
323 EmitGlobalConstant(C, AddrSpace);
328 bool PIC16AsmPrinter::doFinalization(Module &M) {
330 EmitRemainingAutos();
331 DbgInfo.EndModule(M);
332 O << "\n\t" << "END\n";
333 return AsmPrinter::doFinalization(M);
336 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
337 const Function *F = MF.getFunction();
338 std::string FuncName = Mang->getMangledName(F);
339 const TargetData *TD = TM.getTargetData();
340 // Emit the data section name.
343 const MCSection *fPDataSection =
344 getObjFileLowering().getSectionForFunctionFrame(CurrentFnName);
345 OutStreamer.SwitchSection(fPDataSection);
347 // Emit function frame label
348 O << PAN::getFrameLabel(CurrentFnName) << ":\n";
350 const Type *RetType = F->getReturnType();
351 unsigned RetSize = 0;
352 if (RetType->getTypeID() != Type::VoidTyID)
353 RetSize = TD->getTypeAllocSize(RetType);
355 //Emit function return value space
356 // FIXME: Do not emit RetvalLable when retsize is zero. To do this
357 // we will need to avoid printing a global directive for Retval label
358 // in emitExternandGloblas.
360 O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
362 O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
364 // Emit variable to hold the space for function arguments
365 unsigned ArgSize = 0;
366 for (Function::const_arg_iterator argi = F->arg_begin(),
367 arge = F->arg_end(); argi != arge ; ++argi) {
368 const Type *Ty = argi->getType();
369 ArgSize += TD->getTypeAllocSize(Ty);
372 O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
374 // Emit temporary space
375 int TempSize = PTLI->GetTmpSize();
377 O << PAN::getTempdataLabel(CurrentFnName) << " RES " << TempSize << '\n';
380 void PIC16AsmPrinter::EmitIData(Module &M) {
382 // Print all IDATA sections.
383 const std::vector<PIC16Section*> &IDATASections = PTOF->IDATASections;
384 for (unsigned i = 0; i < IDATASections.size(); i++) {
386 if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
388 OutStreamer.SwitchSection(IDATASections[i]->S_);
389 std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
390 for (unsigned j = 0; j < Items.size(); j++) {
391 std::string Name = Mang->getMangledName(Items[j]);
392 Constant *C = Items[j]->getInitializer();
393 int AddrSpace = Items[j]->getType()->getAddressSpace();
395 EmitGlobalConstant(C, AddrSpace);
400 void PIC16AsmPrinter::EmitUData(Module &M) {
401 const TargetData *TD = TM.getTargetData();
403 // Print all BSS sections.
404 const std::vector<PIC16Section*> &BSSSections = PTOF->BSSSections;
405 for (unsigned i = 0; i < BSSSections.size(); i++) {
407 OutStreamer.SwitchSection(BSSSections[i]->S_);
408 std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
409 for (unsigned j = 0; j < Items.size(); j++) {
410 std::string Name = Mang->getMangledName(Items[j]);
411 Constant *C = Items[j]->getInitializer();
412 const Type *Ty = C->getType();
413 unsigned Size = TD->getTypeAllocSize(Ty);
415 O << Name << " RES " << Size << "\n";
420 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
421 // Section names for all globals are already set.
422 const TargetData *TD = TM.getTargetData();
424 // Now print Autos section for this function.
425 std::string SectionName = PAN::getAutosSectionName(FunctName);
426 const std::vector<PIC16Section*> &AutosSections = PTOF->AutosSections;
427 for (unsigned i = 0; i < AutosSections.size(); i++) {
429 if (AutosSections[i]->S_->getName() == SectionName) {
430 // Set the printing status to true
431 AutosSections[i]->setPrintedStatus(true);
432 OutStreamer.SwitchSection(AutosSections[i]->S_);
433 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
434 for (unsigned j = 0; j < Items.size(); j++) {
435 std::string VarName = Mang->getMangledName(Items[j]);
436 Constant *C = Items[j]->getInitializer();
437 const Type *Ty = C->getType();
438 unsigned Size = TD->getTypeAllocSize(Ty);
439 // Emit memory reserve directive.
440 O << VarName << " RES " << Size << "\n";
447 // Print autos that were not printed during the code printing of functions.
448 // As the functions might themselves would have got deleted by the optimizer.
449 void PIC16AsmPrinter::EmitRemainingAutos() {
450 const TargetData *TD = TM.getTargetData();
452 // Now print Autos section for this function.
453 std::vector <PIC16Section *>AutosSections = PTOF->AutosSections;
454 for (unsigned i = 0; i < AutosSections.size(); i++) {
456 // if the section is already printed then don't print again
457 if (AutosSections[i]->isPrinted())
460 // Set status as printed
461 AutosSections[i]->setPrintedStatus(true);
464 OutStreamer.SwitchSection(AutosSections[i]->S_);
465 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
466 for (unsigned j = 0; j < Items.size(); j++) {
467 std::string VarName = Mang->getMangledName(Items[j]);
468 Constant *C = Items[j]->getInitializer();
469 const Type *Ty = C->getType();
470 unsigned Size = TD->getTypeAllocSize(Ty);
471 // Emit memory reserve directive.
472 O << VarName << " RES " << Size << "\n";
478 extern "C" void LLVMInitializePIC16AsmPrinter() {
479 RegisterAsmPrinter<PIC16AsmPrinter> X(ThePIC16Target);