Add XCore backend.
[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   struct VISIBILITY_HIDDEN XCoreAsmPrinter : public AsmPrinter {
57     XCoreAsmPrinter(raw_ostream &O, XCoreTargetMachine &TM,
58                     const TargetAsmInfo *T)
59       : AsmPrinter(O, TM, T), DW(O, this, T),
60         Subtarget(*TM.getSubtargetImpl()) { }
61
62     DwarfWriter DW;
63     const XCoreSubtarget &Subtarget;
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     }
95   };
96 } // end of anonymous namespace
97
98 #include "XCoreGenAsmWriter.inc"
99
100 /// createXCoreCodePrinterPass - Returns a pass that prints the XCore
101 /// assembly code for a MachineFunction to the given output stream,
102 /// using the given target machine description.  This should work
103 /// regardless of whether the function is in SSA form.
104 ///
105 FunctionPass *llvm::createXCoreCodePrinterPass(raw_ostream &o,
106                                                XCoreTargetMachine &tm) {
107   return new XCoreAsmPrinter(o, tm, tm.getTargetAsmInfo());
108 }
109
110 // PrintEscapedString - Print each character of the specified string, escaping
111 // it if it is not printable or if it is an escape char.
112 static void PrintEscapedString(const std::string &Str, raw_ostream &Out) {
113   for (unsigned i = 0, e = Str.size(); i != e; ++i) {
114     unsigned char C = Str[i];
115     if (isprint(C) && C != '"' && C != '\\') {
116       Out << C;
117     } else {
118       Out << '\\'
119           << (char) ((C/16  < 10) ? ( C/16 +'0') : ( C/16 -10+'A'))
120           << (char)(((C&15) < 10) ? ((C&15)+'0') : ((C&15)-10+'A'));
121     }
122   }
123 }
124
125 void XCoreAsmPrinter::
126 emitFileDirective(const std::string &name)
127 {
128   O << "\t.file\t\"";
129   PrintEscapedString(name, O);
130   O << "\"\n";
131 }
132
133 void XCoreAsmPrinter::
134 emitGlobalDirective(const std::string &name)
135 {
136   O << TAI->getGlobalDirective() << name;
137   O << "\n";
138 }
139
140 void XCoreAsmPrinter::
141 emitExternDirective(const std::string &name)
142 {
143   O << "\t.extern\t" << name;
144   O << '\n';
145 }
146
147 void XCoreAsmPrinter::
148 emitArrayBound(const std::string &name, const GlobalVariable *GV)
149 {
150   assert((GV->hasExternalLinkage() ||
151     GV->hasWeakLinkage()) ||
152     GV->hasLinkOnceLinkage() && "Unexpected linkage");
153   if (const ArrayType *ATy = dyn_cast<ArrayType>(
154     cast<PointerType>(GV->getType())->getElementType()))
155   {
156     O << TAI->getGlobalDirective() << name << ".globound" << "\n";
157     O << TAI->getSetDirective() << name << ".globound" << ","
158       << ATy->getNumElements() << "\n";
159     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
160       // TODO Use COMDAT groups for LinkOnceLinkage
161       O << TAI->getWeakDefDirective() << name << ".globound" << "\n";
162     }
163   }
164 }
165
166 void XCoreAsmPrinter::
167 emitGlobal(const GlobalVariable *GV)
168 {
169   const TargetData *TD = TM.getTargetData();
170
171   if (GV->hasInitializer()) {
172     // Check to see if this is a special global used by LLVM, if so, emit it.
173     if (EmitSpecialLLVMGlobal(GV))
174       return;
175
176     SwitchToSection(TAI->SectionForGlobal(GV));
177     
178     std::string name = Mang->getValueName(GV);
179     Constant *C = GV->getInitializer();
180     unsigned Align = (unsigned)TD->getPreferredTypeAlignmentShift(C->getType());
181     
182     // Mark the start of the global
183     O << "\t.cc_top " << name << ".data," << name << "\n";
184
185     switch (GV->getLinkage()) {
186     case GlobalValue::AppendingLinkage:
187       cerr << "AppendingLinkage is not supported by this target!\n";
188       abort();
189     case GlobalValue::LinkOnceLinkage:
190     case GlobalValue::WeakLinkage:
191     case GlobalValue::ExternalLinkage:
192       emitArrayBound(name, GV);
193       emitGlobalDirective(name);
194       // TODO Use COMDAT groups for LinkOnceLinkage
195       if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
196         O << TAI->getWeakDefDirective() << name << "\n";
197       }
198       // FALL THROUGH
199     case GlobalValue::InternalLinkage:
200       break;
201     case GlobalValue::GhostLinkage:
202       cerr << "Should not have any unmaterialized functions!\n";
203       abort();
204     case GlobalValue::DLLImportLinkage:
205       cerr << "DLLImport linkage is not supported by this target!\n";
206       abort();
207     case GlobalValue::DLLExportLinkage:
208       cerr << "DLLExport linkage is not supported by this target!\n";
209       abort();
210     default:
211       assert(0 && "Unknown linkage type!");
212     }
213
214     EmitAlignment(Align, GV, 2);
215     
216     unsigned Size = TD->getABITypeSize(C->getType());
217     if (GV->isThreadLocal()) {
218       Size *= MaxThreads;
219     }
220     if (TAI->hasDotTypeDotSizeDirective()) {
221       O << "\t.type " << name << ",@object\n";
222       O << "\t.size " << name << "," << Size << "\n";
223     }
224     O << name << ":\n";
225     
226     EmitGlobalConstant(C);
227     if (GV->isThreadLocal()) {
228       for (unsigned i = 1; i < MaxThreads; ++i) {
229         EmitGlobalConstant(C);
230       }
231     }
232     if (Size < 4) {
233       // The ABI requires that unsigned scalar types smaller than 32 bits
234       // are are padded to 32 bits.
235       EmitZeros(4 - Size);
236     }
237     
238     // Mark the end of the global
239     O << "\t.cc_bottom " << name << ".data\n";
240   } else {
241     if (GV->hasExternalWeakLinkage())
242       ExtWeakSymbols.insert(GV);
243   }
244 }
245
246 /// Emit the directives on the start of functions
247 void XCoreAsmPrinter::
248 emitFunctionStart(MachineFunction &MF)
249 {
250   // Print out the label for the function.
251   const Function *F = MF.getFunction();
252
253   SwitchToSection(TAI->SectionForGlobal(F));
254   
255   // Mark the start of the function
256   O << "\t.cc_top " << CurrentFnName << ".function," << CurrentFnName << "\n";
257
258   switch (F->getLinkage()) {
259   default: assert(0 && "Unknown linkage type!");
260   case Function::InternalLinkage:  // Symbols default to internal.
261     break;
262   case Function::ExternalLinkage:
263     emitGlobalDirective(CurrentFnName);
264     break;
265   case Function::LinkOnceLinkage:
266   case Function::WeakLinkage:
267     // TODO Use COMDAT groups for LinkOnceLinkage
268     O << TAI->getGlobalDirective() << CurrentFnName << "\n";
269     O << TAI->getWeakDefDirective() << CurrentFnName << "\n";
270     break;
271   }
272   // (1 << 1) byte aligned
273   EmitAlignment(1, F, 1);
274   if (TAI->hasDotTypeDotSizeDirective()) {
275     O << "\t.type " << CurrentFnName << ",@function\n";
276   }
277   O << CurrentFnName << ":\n";
278 }
279
280 /// Emit the directives on the end of functions
281 void XCoreAsmPrinter::
282 emitFunctionEnd(MachineFunction &MF) 
283 {
284   // Mark the end of the function
285   O << "\t.cc_bottom " << CurrentFnName << ".function\n";
286 }
287
288 /// runOnMachineFunction - This uses the printMachineInstruction()
289 /// method to print assembly for each instruction.
290 ///
291 bool XCoreAsmPrinter::runOnMachineFunction(MachineFunction &MF)
292 {
293   SetupMachineFunction(MF);
294
295   // Print out constants referenced by the function
296   EmitConstantPool(MF.getConstantPool());
297
298   // Print out jump tables referenced by the function
299   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
300
301   // What's my mangled name?
302   CurrentFnName = Mang->getValueName(MF.getFunction());
303
304   // Emit the function start directives
305   emitFunctionStart(MF);
306   
307   // Emit pre-function debug information.
308   DW.BeginFunction(&MF);
309
310   // Print out code for the function.
311   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
312        I != E; ++I) {
313
314     // Print a label for the basic block.
315     if (I != MF.begin()) {
316       printBasicBlockLabel(I, true , true);
317       O << '\n';
318     }
319
320     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
321          II != E; ++II) {
322       // Print the assembly for the instruction.
323       O << "\t";
324       printMachineInstruction(II);
325     }
326
327     // Each Basic Block is separated by a newline
328     O << '\n';
329   }
330
331   // Emit function end directives
332   emitFunctionEnd(MF);
333   
334   // Emit post-function debug information.
335   DW.EndFunction(&MF);
336
337   // We didn't modify anything.
338   return false;
339 }
340
341 void XCoreAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum)
342 {
343   printOperand(MI, opNum);
344   
345   if (MI->getOperand(opNum+1).isImm()
346     && MI->getOperand(opNum+1).getImm() == 0)
347     return;
348   
349   O << "+";
350   printOperand(MI, opNum+1);
351 }
352
353 void XCoreAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
354   const MachineOperand &MO = MI->getOperand(opNum);
355   switch (MO.getType()) {
356   case MachineOperand::MO_Register:
357     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
358       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
359     else
360       assert(0 && "not implemented");
361     break;
362   case MachineOperand::MO_Immediate:
363     O << MO.getImm();
364     break;
365   case MachineOperand::MO_MachineBasicBlock:
366     printBasicBlockLabel(MO.getMBB());
367     break;
368   case MachineOperand::MO_GlobalAddress:
369     O << Mang->getValueName(MO.getGlobal());
370     if (MO.getGlobal()->hasExternalWeakLinkage())
371       ExtWeakSymbols.insert(MO.getGlobal());
372     break;
373   case MachineOperand::MO_ExternalSymbol:
374     O << MO.getSymbolName();
375     break;
376   case MachineOperand::MO_ConstantPoolIndex:
377     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
378       << '_' << MO.getIndex();
379     break;
380   case MachineOperand::MO_JumpTableIndex:
381     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
382       << '_' << MO.getIndex();
383     break;
384   default:
385     assert(0 && "not implemented");
386   }
387 }
388
389 /// PrintAsmOperand - Print out an operand for an inline asm expression.
390 ///
391 bool XCoreAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
392                                       unsigned AsmVariant, 
393                                       const char *ExtraCode) {
394   printOperand(MI, OpNo);
395   return false;
396 }
397
398 void XCoreAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
399   ++EmittedInsts;
400
401   // Check for mov mnemonic
402   unsigned src, dst;
403   if (TM.getInstrInfo()->isMoveInstr(*MI, src, dst)) {
404     O << "\tmov ";
405     O << TM.getRegisterInfo()->get(dst).AsmName;
406     O << ", ";
407     O << TM.getRegisterInfo()->get(src).AsmName;
408     O << "\n";
409     return;
410   }
411   if (printInstruction(MI)) {
412     return;
413   }
414   assert(0 && "Unhandled instruction in asm writer!");
415 }
416
417 bool XCoreAsmPrinter::doInitialization(Module &M) {
418   bool Result = AsmPrinter::doInitialization(M);
419   
420   if (!FileDirective.empty()) {
421     emitFileDirective(FileDirective);
422   }
423   
424   // Print out type strings for external functions here
425   for (Module::const_iterator I = M.begin(), E = M.end();
426        I != E; ++I) {
427     if (I->isDeclaration() && !I->isIntrinsic()) {
428       switch (I->getLinkage()) {
429       default:
430         assert(0 && "Unexpected linkage");
431       case Function::ExternalWeakLinkage:
432         ExtWeakSymbols.insert(I);
433         // fallthrough
434       case Function::ExternalLinkage:
435         break;
436       }
437     }
438   }
439
440   // Emit initial debug information.
441   DW.BeginModule(&M);
442
443   DW.SetModuleInfo(getAnalysisToUpdate<MachineModuleInfo>());
444   return Result;
445 }
446
447 bool XCoreAsmPrinter::doFinalization(Module &M) {
448
449   // Print out module-level global variables.
450   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
451        I != E; ++I) {
452     emitGlobal(I);
453   }
454   
455   // Emit final debug information.
456   DW.EndModule();
457
458   return AsmPrinter::doFinalization(M);
459 }