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/Support/FormattedStream.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/CodeGen/DwarfWriter.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/Target/TargetRegistry.h"
28 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "PIC16GenAsmWriter.inc"
34 PIC16AsmPrinter::PIC16AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
35 const TargetAsmInfo *T, bool V)
36 : AsmPrinter(O, TM, T, V), DbgInfo(O, T) {
37 PTLI = static_cast<const PIC16TargetLowering*>(TM.getTargetLowering());
38 PTAI = static_cast<const PIC16TargetAsmInfo*>(T);
39 PTOF = (PIC16TargetObjectFile*)&PTLI->getObjFileLowering();
42 bool PIC16AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
47 /// runOnMachineFunction - This emits the frame section, autos section and
48 /// assembly for each instruction. Also takes care of function begin debug
49 /// directive and file begin debug directive (if required) for the function.
51 bool PIC16AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
54 // This calls the base class function required to be called at beginning
55 // of runOnMachineFunction.
56 SetupMachineFunction(MF);
58 // Get the mangled name.
59 const Function *F = MF.getFunction();
60 CurrentFnName = Mang->getMangledName(F);
62 // Emit the function frame (args and temps).
63 EmitFunctionFrame(MF);
65 DbgInfo.BeginFunction(MF);
67 // Emit the autos section of function.
68 EmitAutos(CurrentFnName);
70 // Now emit the instructions of function in its code section.
71 std::string T = PAN::getCodeSectionName(CurrentFnName);
72 const char *codeSection = T.c_str();
74 const Section *fCodeSection =
75 getObjFileLowering().getOrCreateSection(codeSection, false,
77 // Start the Code Section.
79 SwitchToSection(fCodeSection);
81 // Emit the frame address of the function at the beginning of code.
82 O << "\tretlw low(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
83 O << "\tretlw high(" << PAN::getFrameLabel(CurrentFnName) << ")\n";
85 // Emit function start label.
86 O << CurrentFnName << ":\n";
90 // Print out code for the function.
91 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
94 // Print a label for the basic block.
95 if (I != MF.begin()) {
96 printBasicBlockLabel(I, true);
100 // Print a basic block.
101 for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
104 // Emit the line directive if source line changed.
105 const DebugLoc DL = II->getDebugLoc();
106 if (!DL.isUnknown() && DL != CurDL) {
107 DbgInfo.ChangeDebugLoc(MF, DL);
111 // Print the assembly for the instruction.
112 printMachineInstruction(II);
116 // Emit function end debug directives.
117 DbgInfo.EndFunction(MF);
119 return false; // we didn't modify anything.
123 // printOperand - print operand of insn.
124 void PIC16AsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
125 const MachineOperand &MO = MI->getOperand(opNum);
127 switch (MO.getType()) {
128 case MachineOperand::MO_Register:
129 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
130 O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
132 llvm_unreachable("not implemented");
135 case MachineOperand::MO_Immediate:
136 O << (int)MO.getImm();
139 case MachineOperand::MO_GlobalAddress: {
140 std::string Sname = Mang->getMangledName(MO.getGlobal());
141 // FIXME: currently we do not have a memcpy def coming in the module
142 // by any chance, as we do not link in those as .bc lib. So these calls
143 // are always external and it is safe to emit an extern.
144 if (PAN::isMemIntrinsic(Sname)) {
145 LibcallDecls.push_back(createESName(Sname));
151 case MachineOperand::MO_ExternalSymbol: {
152 const char *Sname = MO.getSymbolName();
154 // If its a libcall name, record it to decls section.
155 if (PAN::getSymbolTag(Sname) == PAN::LIBCALL) {
156 LibcallDecls.push_back(Sname);
159 // Record a call to intrinsic to print the extern declaration for it.
160 std::string Sym = Sname;
161 if (PAN::isMemIntrinsic(Sym)) {
162 Sym = PAN::addPrefix(Sym);
163 LibcallDecls.push_back(createESName(Sym));
169 case MachineOperand::MO_MachineBasicBlock:
170 printBasicBlockLabel(MO.getMBB());
174 llvm_unreachable(" Operand type not supported.");
178 /// printCCOperand - Print the cond code operand.
180 void PIC16AsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
181 int CC = (int)MI->getOperand(opNum).getImm();
182 O << PIC16CondCodeToString((PIC16CC::CondCodes)CC);
185 // This function is used to sort the decls list.
186 // should return true if s1 should come before s2.
187 static bool is_before(const char *s1, const char *s2) {
188 std::string str1 = s1;
189 std::string str2 = s2;
190 int i = str1.compare(str2);
191 // Return true if s1 is smaller or equal.
192 if (i <= 0) return true;
193 // false if s1 should come after s2.
197 // This is used by list::unique below.
198 // unique will filter out duplicates if it knows them.
199 static bool is_duplicate(const char *s1, const char *s2) {
200 std::string str1 = s1;
201 std::string str2 = s2;
205 /// printLibcallDecls - print the extern declarations for compiler
208 void PIC16AsmPrinter::printLibcallDecls(void) {
209 // If no libcalls used, return.
210 if (LibcallDecls.empty()) return;
212 O << TAI->getCommentString() << "External decls for libcalls - BEGIN." <<"\n";
213 // Remove duplicate entries.
214 LibcallDecls.sort(is_before);
215 LibcallDecls.unique(is_duplicate);
217 for (std::list<const char*>::const_iterator I = LibcallDecls.begin();
218 I != LibcallDecls.end(); I++) {
219 O << TAI->getExternDirective() << *I << "\n";
220 O << TAI->getExternDirective() << PAN::getArgsLabel(*I) << "\n";
221 O << TAI->getExternDirective() << PAN::getRetvalLabel(*I) << "\n";
223 O << TAI->getCommentString() << "External decls for libcalls - END." <<"\n";
226 /// doInitialization - Perfrom Module level initializations here.
227 /// One task that we do here is to sectionize all global variables.
228 /// The MemSelOptimizer pass depends on the sectionizing.
230 bool PIC16AsmPrinter::doInitialization(Module &M) {
231 bool Result = AsmPrinter::doInitialization(M);
233 // FIXME:: This is temporary solution to generate the include file.
234 // The processor should be passed to llc as in input and the header file
235 // should be generated accordingly.
236 O << "\n\t#include P16F1937.INC\n";
238 // Set the section names for all globals.
239 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
241 I->setSection(getObjFileLowering().SectionForGlobal(I, Mang,TM)->getName());
243 DbgInfo.BeginModule(M);
244 EmitFunctionDecls(M);
245 EmitUndefinedVars(M);
253 /// Emit extern decls for functions imported from other modules, and emit
254 /// global declarations for function defined in this module and which are
255 /// available to other modules.
257 void PIC16AsmPrinter::EmitFunctionDecls(Module &M) {
258 // Emit declarations for external functions.
259 O <<"\n"<<TAI->getCommentString() << "Function Declarations - BEGIN." <<"\n";
260 for (Module::iterator I = M.begin(), E = M.end(); I != E; I++) {
261 if (I->isIntrinsic())
264 std::string Name = Mang->getMangledName(I);
265 if (Name.compare("@abort") == 0)
268 if (!I->isDeclaration() && !I->hasExternalLinkage())
271 // Do not emit memcpy, memset, and memmove here.
272 // Calls to these routines can be generated in two ways,
273 // 1. User calling the standard lib function
274 // 2. Codegen generating these calls for llvm intrinsics.
275 // In the first case a prototype is alread availale, while in
276 // second case the call is via and externalsym and the prototype is missing.
277 // So declarations for these are currently always getting printing by
278 // tracking both kind of references in printInstrunction.
279 if (I->isDeclaration() && PAN::isMemIntrinsic(Name)) continue;
281 const char *directive = I->isDeclaration() ? TAI->getExternDirective() :
282 TAI->getGlobalDirective();
284 O << directive << Name << "\n";
285 O << directive << PAN::getRetvalLabel(Name) << "\n";
286 O << directive << PAN::getArgsLabel(Name) << "\n";
289 O << TAI->getCommentString() << "Function Declarations - END." <<"\n";
292 // Emit variables imported from other Modules.
293 void PIC16AsmPrinter::EmitUndefinedVars(Module &M) {
294 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDecls->Items;
295 if (!Items.size()) return;
297 O << "\n" << TAI->getCommentString() << "Imported Variables - BEGIN" << "\n";
298 for (unsigned j = 0; j < Items.size(); j++) {
299 O << TAI->getExternDirective() << Mang->getMangledName(Items[j]) << "\n";
301 O << TAI->getCommentString() << "Imported Variables - END" << "\n";
304 // Emit variables defined in this module and are available to other modules.
305 void PIC16AsmPrinter::EmitDefinedVars(Module &M) {
306 std::vector<const GlobalVariable*> Items = PTOF->ExternalVarDefs->Items;
307 if (!Items.size()) return;
309 O << "\n" << TAI->getCommentString() << "Exported Variables - BEGIN" << "\n";
310 for (unsigned j = 0; j < Items.size(); j++) {
311 O << TAI->getGlobalDirective() << Mang->getMangledName(Items[j]) << "\n";
313 O << TAI->getCommentString() << "Exported Variables - END" << "\n";
316 // Emit initialized data placed in ROM.
317 void PIC16AsmPrinter::EmitRomData(Module &M) {
318 // Print ROM Data section.
319 const std::vector<PIC16Section*> &ROSections = PTOF->ROSections;
320 for (unsigned i = 0; i < ROSections.size(); i++) {
321 const std::vector<const GlobalVariable*> &Items = ROSections[i]->Items;
322 if (!Items.size()) continue;
324 SwitchToSection(PTOF->ROSections[i]->S_);
325 for (unsigned j = 0; j < Items.size(); j++) {
326 O << Mang->getMangledName(Items[j]);
327 Constant *C = Items[j]->getInitializer();
328 int AddrSpace = Items[j]->getType()->getAddressSpace();
329 EmitGlobalConstant(C, AddrSpace);
334 bool PIC16AsmPrinter::doFinalization(Module &M) {
336 EmitRemainingAutos();
337 DbgInfo.EndModule(M);
338 O << "\n\t" << "END\n";
339 return AsmPrinter::doFinalization(M);
342 void PIC16AsmPrinter::EmitFunctionFrame(MachineFunction &MF) {
343 const Function *F = MF.getFunction();
344 std::string FuncName = Mang->getMangledName(F);
345 const TargetData *TD = TM.getTargetData();
346 // Emit the data section name.
348 std::string T = PAN::getFrameSectionName(CurrentFnName);
349 const char *SectionName = T.c_str();
351 const Section *fPDataSection =
352 getObjFileLowering().getOrCreateSection(SectionName, false,
353 SectionKind::DataRel);
354 SwitchToSection(fPDataSection);
356 // Emit function frame label
357 O << PAN::getFrameLabel(CurrentFnName) << ":\n";
359 const Type *RetType = F->getReturnType();
360 unsigned RetSize = 0;
361 if (RetType->getTypeID() != Type::VoidTyID)
362 RetSize = TD->getTypeAllocSize(RetType);
364 //Emit function return value space
365 // FIXME: Do not emit RetvalLable when retsize is zero. To do this
366 // we will need to avoid printing a global directive for Retval label
367 // in emitExternandGloblas.
369 O << PAN::getRetvalLabel(CurrentFnName) << " RES " << RetSize << "\n";
371 O << PAN::getRetvalLabel(CurrentFnName) << ": \n";
373 // Emit variable to hold the space for function arguments
374 unsigned ArgSize = 0;
375 for (Function::const_arg_iterator argi = F->arg_begin(),
376 arge = F->arg_end(); argi != arge ; ++argi) {
377 const Type *Ty = argi->getType();
378 ArgSize += TD->getTypeAllocSize(Ty);
381 O << PAN::getArgsLabel(CurrentFnName) << " RES " << ArgSize << "\n";
383 // Emit temporary space
384 int TempSize = PTLI->GetTmpSize();
386 O << PAN::getTempdataLabel(CurrentFnName) << " RES " << TempSize << '\n';
389 void PIC16AsmPrinter::EmitIData(Module &M) {
391 // Print all IDATA sections.
392 const std::vector<PIC16Section*> &IDATASections = PTOF->IDATASections;
393 for (unsigned i = 0; i < IDATASections.size(); i++) {
395 if (IDATASections[i]->S_->getName().find("llvm.") != std::string::npos)
397 SwitchToSection(IDATASections[i]->S_);
398 std::vector<const GlobalVariable*> Items = IDATASections[i]->Items;
399 for (unsigned j = 0; j < Items.size(); j++) {
400 std::string Name = Mang->getMangledName(Items[j]);
401 Constant *C = Items[j]->getInitializer();
402 int AddrSpace = Items[j]->getType()->getAddressSpace();
404 EmitGlobalConstant(C, AddrSpace);
409 void PIC16AsmPrinter::EmitUData(Module &M) {
410 const TargetData *TD = TM.getTargetData();
412 // Print all BSS sections.
413 const std::vector<PIC16Section*> &BSSSections = PTOF->BSSSections;
414 for (unsigned i = 0; i < BSSSections.size(); i++) {
416 SwitchToSection(BSSSections[i]->S_);
417 std::vector<const GlobalVariable*> Items = BSSSections[i]->Items;
418 for (unsigned j = 0; j < Items.size(); j++) {
419 std::string Name = Mang->getMangledName(Items[j]);
420 Constant *C = Items[j]->getInitializer();
421 const Type *Ty = C->getType();
422 unsigned Size = TD->getTypeAllocSize(Ty);
424 O << Name << " RES " << Size << "\n";
429 void PIC16AsmPrinter::EmitAutos(std::string FunctName) {
430 // Section names for all globals are already set.
431 const TargetData *TD = TM.getTargetData();
433 // Now print Autos section for this function.
434 std::string SectionName = PAN::getAutosSectionName(FunctName);
435 const std::vector<PIC16Section*> &AutosSections = PTOF->AutosSections;
436 for (unsigned i = 0; i < AutosSections.size(); i++) {
438 if (AutosSections[i]->S_->getName() == SectionName) {
439 // Set the printing status to true
440 AutosSections[i]->setPrintedStatus(true);
441 SwitchToSection(AutosSections[i]->S_);
442 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
443 for (unsigned j = 0; j < Items.size(); j++) {
444 std::string VarName = Mang->getMangledName(Items[j]);
445 Constant *C = Items[j]->getInitializer();
446 const Type *Ty = C->getType();
447 unsigned Size = TD->getTypeAllocSize(Ty);
448 // Emit memory reserve directive.
449 O << VarName << " RES " << Size << "\n";
456 // Print autos that were not printed during the code printing of functions.
457 // As the functions might themselves would have got deleted by the optimizer.
458 void PIC16AsmPrinter::EmitRemainingAutos() {
459 const TargetData *TD = TM.getTargetData();
461 // Now print Autos section for this function.
462 std::vector <PIC16Section *>AutosSections = PTOF->AutosSections;
463 for (unsigned i = 0; i < AutosSections.size(); i++) {
465 // if the section is already printed then don't print again
466 if (AutosSections[i]->isPrinted())
469 // Set status as printed
470 AutosSections[i]->setPrintedStatus(true);
473 SwitchToSection(AutosSections[i]->S_);
474 const std::vector<const GlobalVariable*> &Items = AutosSections[i]->Items;
475 for (unsigned j = 0; j < Items.size(); j++) {
476 std::string VarName = Mang->getMangledName(Items[j]);
477 Constant *C = Items[j]->getInitializer();
478 const Type *Ty = C->getType();
479 unsigned Size = TD->getTypeAllocSize(Ty);
480 // Emit memory reserve directive.
481 O << VarName << " RES " << Size << "\n";
487 extern "C" void LLVMInitializePIC16Target() {
488 // Register the targets
489 RegisterTargetMachine<PIC16TargetMachine> A(ThePIC16Target);
490 RegisterTargetMachine<CooperTargetMachine> B(TheCooperTarget);
491 RegisterAsmPrinter<PIC16AsmPrinter> C(ThePIC16Target);
492 RegisterAsmPrinter<PIC16AsmPrinter> D(TheCooperTarget);