Overhaul my earlier submission due to feedback. It's a large patch, but most of
[oota-llvm.git] / lib / Target / XCore / XCoreAsmPrinter.cpp
1 //===-- XCoreAsmPrinter.cpp - XCore LLVM assembly writer ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to the XAS-format XCore assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "XCore.h"
17 #include "XCoreInstrInfo.h"
18 #include "XCoreSubtarget.h"
19 #include "XCoreTargetMachine.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/DwarfWriter.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/MathExtras.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include <algorithm>
38 #include <cctype>
39 using namespace llvm;
40
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
42
43 static cl::opt<std::string> FileDirective("xcore-file-directive", cl::Optional,
44   cl::desc("Output a file directive into the assembly file"),
45   cl::Hidden,
46   cl::value_desc("filename"),
47   cl::init(""));
48
49 static cl::opt<unsigned> MaxThreads("xcore-max-threads", cl::Optional,
50   cl::desc("Maximum number of threads (for emulation thread-local storage)"),
51   cl::Hidden,
52   cl::value_desc("number"),
53   cl::init(8));
54
55 namespace {
56   class VISIBILITY_HIDDEN XCoreAsmPrinter : public AsmPrinter {
57     DwarfWriter *DW;
58     const XCoreSubtarget &Subtarget;
59   public:
60     XCoreAsmPrinter(raw_ostream &O, XCoreTargetMachine &TM,
61                     const TargetAsmInfo *T, bool F)
62       : AsmPrinter(O, TM, T, F), DW(0),
63         Subtarget(*TM.getSubtargetImpl()) {}
64
65     virtual const char *getPassName() const {
66       return "XCore Assembly Printer";
67     }
68
69     void printMemOperand(const MachineInstr *MI, int opNum);
70     void printOperand(const MachineInstr *MI, int opNum);
71     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
72                         unsigned AsmVariant, const char *ExtraCode);
73     
74     void emitFileDirective(const std::string &filename);
75     void emitGlobalDirective(const std::string &name);
76     void emitExternDirective(const std::string &name);
77     
78     void emitArrayBound(const std::string &name, const GlobalVariable *GV);
79     void emitGlobal(const GlobalVariable *GV);
80
81     void emitFunctionStart(MachineFunction &MF);
82     void emitFunctionEnd(MachineFunction &MF);
83
84     bool printInstruction(const MachineInstr *MI);  // autogenerated.
85     void printMachineInstruction(const MachineInstr *MI);
86     bool runOnMachineFunction(MachineFunction &F);
87     bool doInitialization(Module &M);
88     bool doFinalization(Module &M);
89     
90     void getAnalysisUsage(AnalysisUsage &AU) const {
91       AsmPrinter::getAnalysisUsage(AU);
92       AU.setPreservesAll();
93       AU.addRequired<MachineModuleInfo>();
94       AU.addRequired<DwarfWriter>();
95     }
96   };
97 } // end of anonymous namespace
98
99 #include "XCoreGenAsmWriter.inc"
100
101 /// createXCoreCodePrinterPass - Returns a pass that prints the XCore
102 /// assembly code for a MachineFunction to the given output stream,
103 /// using the given target machine description.  This should work
104 /// regardless of whether the function is in SSA form.
105 ///
106 FunctionPass *llvm::createXCoreCodePrinterPass(raw_ostream &o,
107                                                XCoreTargetMachine &tm,
108                                                bool fast) {
109   return new XCoreAsmPrinter(o, tm, tm.getTargetAsmInfo(), fast);
110 }
111
112 // PrintEscapedString - Print each character of the specified string, escaping
113 // it if it is not printable or if it is an escape char.
114 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
115   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
116     unsigned char C = Str[i];
117     if (isprint(C) && C != '"' && C != '\\') {
118       Out << C;
119     } else {
120       Out << '\\'
121           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
122           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
123     }
124   }
125 }
126
127 void XCoreAsmPrinter::
128 emitFileDirective(const std::string &name)
129 {
130   O << "\t.file\t\"";
131   PrintEscapedString(name, O);
132   O << "\"\n";
133 }
134
135 void XCoreAsmPrinter::
136 emitGlobalDirective(const std::string &name)
137 {
138   O << TAI->getGlobalDirective() << name;
139   O << "\n";
140 }
141
142 void XCoreAsmPrinter::
143 emitExternDirective(const std::string &name)
144 {
145   O << "\t.extern\t" << name;
146   O << '\n';
147 }
148
149 void XCoreAsmPrinter::
150 emitArrayBound(const std::string &name, const GlobalVariable *GV)
151 {
152   assert(((GV->hasExternalLinkage() ||
153     GV->hasWeakLinkage()) ||
154     GV->hasLinkOnceLinkage()) && "Unexpected linkage");
155   if (const ArrayType *ATy = dyn_cast<ArrayType>(
156     cast<PointerType>(GV->getType())->getElementType()))
157   {
158     O << TAI->getGlobalDirective() << name << ".globound" << "\n";
159     O << TAI->getSetDirective() << name << ".globound" << ","
160       << ATy->getNumElements() << "\n";
161     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
162       // TODO Use COMDAT groups for LinkOnceLinkage
163       O << TAI->getWeakDefDirective() << name << ".globound" << "\n";
164     }
165   }
166 }
167
168 void XCoreAsmPrinter::
169 emitGlobal(const GlobalVariable *GV)
170 {
171   const TargetData *TD = TM.getTargetData();
172
173   if (GV->hasInitializer()) {
174     // Check to see if this is a special global used by LLVM, if so, emit it.
175     if (EmitSpecialLLVMGlobal(GV))
176       return;
177
178     SwitchToSection(TAI->SectionForGlobal(GV));
179     
180     std::string name = Mang->getValueName(GV);
181     Constant *C = GV->getInitializer();
182     unsigned Align = (unsigned)TD->getPreferredTypeAlignmentShift(C->getType());
183     
184     // Mark the start of the global
185     O << "\t.cc_top " << name << ".data," << name << "\n";
186
187     switch (GV->getLinkage()) {
188     case GlobalValue::AppendingLinkage:
189       cerr << "AppendingLinkage is not supported by this target!\n";
190       abort();
191     case GlobalValue::LinkOnceLinkage:
192     case GlobalValue::WeakLinkage:
193     case GlobalValue::ExternalLinkage:
194       emitArrayBound(name, GV);
195       emitGlobalDirective(name);
196       // TODO Use COMDAT groups for LinkOnceLinkage
197       if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
198         O << TAI->getWeakDefDirective() << name << "\n";
199       }
200       // FALL THROUGH
201     case GlobalValue::InternalLinkage:
202     case GlobalValue::PrivateLinkage:
203       break;
204     case GlobalValue::GhostLinkage:
205       cerr << "Should not have any unmaterialized functions!\n";
206       abort();
207     case GlobalValue::DLLImportLinkage:
208       cerr << "DLLImport linkage is not supported by this target!\n";
209       abort();
210     case GlobalValue::DLLExportLinkage:
211       cerr << "DLLExport linkage is not supported by this target!\n";
212       abort();
213     default:
214       assert(0 && "Unknown linkage type!");
215     }
216
217     EmitAlignment(Align, GV, 2);
218     
219     unsigned Size = TD->getTypePaddedSize(C->getType());
220     if (GV->isThreadLocal()) {
221       Size *= MaxThreads;
222     }
223     if (TAI->hasDotTypeDotSizeDirective()) {
224       O << "\t.type " << name << ",@object\n";
225       O << "\t.size " << name << "," << Size << "\n";
226     }
227     O << name << ":\n";
228     
229     EmitGlobalConstant(C);
230     if (GV->isThreadLocal()) {
231       for (unsigned i = 1; i < MaxThreads; ++i) {
232         EmitGlobalConstant(C);
233       }
234     }
235     if (Size < 4) {
236       // The ABI requires that unsigned scalar types smaller than 32 bits
237       // are are padded to 32 bits.
238       EmitZeros(4 - Size);
239     }
240     
241     // Mark the end of the global
242     O << "\t.cc_bottom " << name << ".data\n";
243   } else {
244     if (GV->hasExternalWeakLinkage())
245       ExtWeakSymbols.insert(GV);
246   }
247 }
248
249 /// Emit the directives on the start of functions
250 void XCoreAsmPrinter::
251 emitFunctionStart(MachineFunction &MF)
252 {
253   // Print out the label for the function.
254   const Function *F = MF.getFunction();
255
256   SwitchToSection(TAI->SectionForGlobal(F));
257   
258   // Mark the start of the function
259   O << "\t.cc_top " << CurrentFnName << ".function," << CurrentFnName << "\n";
260
261   switch (F->getLinkage()) {
262   default: assert(0 && "Unknown linkage type!");
263   case Function::InternalLinkage:  // Symbols default to internal.
264   case Function::PrivateLinkage:
265     break;
266   case Function::ExternalLinkage:
267     emitGlobalDirective(CurrentFnName);
268     break;
269   case Function::LinkOnceLinkage:
270   case Function::WeakLinkage:
271     // TODO Use COMDAT groups for LinkOnceLinkage
272     O << TAI->getGlobalDirective() << CurrentFnName << "\n";
273     O << TAI->getWeakDefDirective() << CurrentFnName << "\n";
274     break;
275   }
276   // (1 << 1) byte aligned
277   EmitAlignment(1, F, 1);
278   if (TAI->hasDotTypeDotSizeDirective()) {
279     O << "\t.type " << CurrentFnName << ",@function\n";
280   }
281   O << CurrentFnName << ":\n";
282 }
283
284 /// Emit the directives on the end of functions
285 void XCoreAsmPrinter::
286 emitFunctionEnd(MachineFunction &MF) 
287 {
288   // Mark the end of the function
289   O << "\t.cc_bottom " << CurrentFnName << ".function\n";
290 }
291
292 /// runOnMachineFunction - This uses the printMachineInstruction()
293 /// method to print assembly for each instruction.
294 ///
295 bool XCoreAsmPrinter::runOnMachineFunction(MachineFunction &MF)
296 {
297   this->MF = &MF;
298
299   SetupMachineFunction(MF);
300
301   // Print out constants referenced by the function
302   EmitConstantPool(MF.getConstantPool());
303
304   // Print out jump tables referenced by the function
305   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
306
307   // Emit the function start directives
308   emitFunctionStart(MF);
309   
310   // Emit pre-function debug information.
311   DW->BeginFunction(&MF);
312
313   // Print out code for the function.
314   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
315        I != E; ++I) {
316
317     // Print a label for the basic block.
318     if (I != MF.begin()) {
319       printBasicBlockLabel(I, true , true);
320       O << '\n';
321     }
322
323     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
324          II != E; ++II) {
325       // Print the assembly for the instruction.
326       O << "\t";
327       printMachineInstruction(II);
328     }
329
330     // Each Basic Block is separated by a newline
331     O << '\n';
332   }
333
334   // Emit function end directives
335   emitFunctionEnd(MF);
336   
337   // Emit post-function debug information.
338   DW->EndFunction(&MF);
339
340   // We didn't modify anything.
341   return false;
342 }
343
344 void XCoreAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum)
345 {
346   printOperand(MI, opNum);
347   
348   if (MI->getOperand(opNum+1).isImm()
349     && MI->getOperand(opNum+1).getImm() == 0)
350     return;
351   
352   O << "+";
353   printOperand(MI, opNum+1);
354 }
355
356 void XCoreAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
357   const MachineOperand &MO = MI->getOperand(opNum);
358   switch (MO.getType()) {
359   case MachineOperand::MO_Register:
360     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
361       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
362     else
363       assert(0 && "not implemented");
364     break;
365   case MachineOperand::MO_Immediate:
366     O << MO.getImm();
367     break;
368   case MachineOperand::MO_MachineBasicBlock:
369     printBasicBlockLabel(MO.getMBB());
370     break;
371   case MachineOperand::MO_GlobalAddress:
372     {
373       const GlobalValue *GV = MO.getGlobal();
374       O << Mang->getValueName(GV);
375       if (GV->hasExternalWeakLinkage())
376         ExtWeakSymbols.insert(GV);
377     }
378     break;
379   case MachineOperand::MO_ExternalSymbol:
380     O << MO.getSymbolName();
381     break;
382   case MachineOperand::MO_ConstantPoolIndex:
383     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
384       << '_' << MO.getIndex();
385     break;
386   case MachineOperand::MO_JumpTableIndex:
387     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
388       << '_' << MO.getIndex();
389     break;
390   default:
391     assert(0 && "not implemented");
392   }
393 }
394
395 /// PrintAsmOperand - Print out an operand for an inline asm expression.
396 ///
397 bool XCoreAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
398                                       unsigned AsmVariant, 
399                                       const char *ExtraCode) {
400   printOperand(MI, OpNo);
401   return false;
402 }
403
404 void XCoreAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
405   ++EmittedInsts;
406
407   // Check for mov mnemonic
408   unsigned src, dst, srcSR, dstSR;
409   if (TM.getInstrInfo()->isMoveInstr(*MI, src, dst, srcSR, dstSR)) {
410     O << "\tmov ";
411     O << TM.getRegisterInfo()->get(dst).AsmName;
412     O << ", ";
413     O << TM.getRegisterInfo()->get(src).AsmName;
414     O << "\n";
415     return;
416   }
417   if (printInstruction(MI)) {
418     return;
419   }
420   assert(0 && "Unhandled instruction in asm writer!");
421 }
422
423 bool XCoreAsmPrinter::doInitialization(Module &M) {
424   bool Result = AsmPrinter::doInitialization(M);
425   
426   if (!FileDirective.empty()) {
427     emitFileDirective(FileDirective);
428   }
429   
430   // Print out type strings for external functions here
431   for (Module::const_iterator I = M.begin(), E = M.end();
432        I != E; ++I) {
433     if (I->isDeclaration() && !I->isIntrinsic()) {
434       switch (I->getLinkage()) {
435       default:
436         assert(0 && "Unexpected linkage");
437       case Function::ExternalWeakLinkage:
438         ExtWeakSymbols.insert(I);
439         // fallthrough
440       case Function::ExternalLinkage:
441         break;
442       }
443     }
444   }
445
446   // Emit initial debug information.
447   DW = getAnalysisIfAvailable<DwarfWriter>();
448   assert(DW && "Dwarf Writer is not available");
449   DW->BeginModule(&M, getAnalysisIfAvailable<MachineModuleInfo>(),
450                   O, this, TAI);
451   return Result;
452 }
453
454 bool XCoreAsmPrinter::doFinalization(Module &M) {
455
456   // Print out module-level global variables.
457   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
458        I != E; ++I) {
459     emitGlobal(I);
460   }
461   
462   // Emit final debug information.
463   DW->EndModule();
464
465   return AsmPrinter::doFinalization(M);
466 }