reduce indentation by using an early exit.
[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/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <algorithm>
39 #include <cctype>
40 using namespace llvm;
41
42 STATISTIC(EmittedInsts, "Number of machine instrs printed");
43
44 static cl::opt<unsigned> MaxThreads("xcore-max-threads", cl::Optional,
45   cl::desc("Maximum number of threads (for emulation thread-local storage)"),
46   cl::Hidden,
47   cl::value_desc("number"),
48   cl::init(8));
49
50 namespace {
51   class VISIBILITY_HIDDEN XCoreAsmPrinter : public AsmPrinter {
52     DwarfWriter *DW;
53     const XCoreSubtarget &Subtarget;
54   public:
55     explicit XCoreAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
56                              const TargetAsmInfo *T, bool V)
57       : AsmPrinter(O, TM, T, V), DW(0),
58       Subtarget(TM.getSubtarget<XCoreSubtarget>()) {}
59
60     virtual const char *getPassName() const {
61       return "XCore Assembly Printer";
62     }
63
64     void printMemOperand(const MachineInstr *MI, int opNum);
65     void printOperand(const MachineInstr *MI, int opNum);
66     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
67                         unsigned AsmVariant, const char *ExtraCode);
68
69     void emitGlobalDirective(const std::string &name);
70     void emitExternDirective(const std::string &name);
71     
72     void emitArrayBound(const std::string &name, const GlobalVariable *GV);
73     void emitGlobal(const GlobalVariable *GV);
74
75     void emitFunctionStart(MachineFunction &MF);
76     void emitFunctionEnd(MachineFunction &MF);
77
78     bool printInstruction(const MachineInstr *MI);  // autogenerated.
79     void printMachineInstruction(const MachineInstr *MI);
80     bool runOnMachineFunction(MachineFunction &F);
81     bool doInitialization(Module &M);
82     bool doFinalization(Module &M);
83     
84     void getAnalysisUsage(AnalysisUsage &AU) const {
85       AsmPrinter::getAnalysisUsage(AU);
86       AU.setPreservesAll();
87       AU.addRequired<MachineModuleInfo>();
88       AU.addRequired<DwarfWriter>();
89     }
90   };
91 } // end of anonymous namespace
92
93 #include "XCoreGenAsmWriter.inc"
94
95 /// createXCoreCodePrinterPass - Returns a pass that prints the XCore
96 /// assembly code for a MachineFunction to the given output stream,
97 /// using the given target machine description.  This should work
98 /// regardless of whether the function is in SSA form.
99 ///
100 FunctionPass *llvm::createXCoreCodePrinterPass(formatted_raw_ostream &o,
101                                                TargetMachine &tm,
102                                                bool verbose) {
103   return new XCoreAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
104 }
105
106 void XCoreAsmPrinter::
107 emitGlobalDirective(const std::string &name)
108 {
109   O << TAI->getGlobalDirective() << name;
110   O << "\n";
111 }
112
113 void XCoreAsmPrinter::
114 emitExternDirective(const std::string &name)
115 {
116   O << "\t.extern\t" << name;
117   O << '\n';
118 }
119
120 void XCoreAsmPrinter::
121 emitArrayBound(const std::string &name, const GlobalVariable *GV)
122 {
123   assert(((GV->hasExternalLinkage() ||
124     GV->hasWeakLinkage()) ||
125     GV->hasLinkOnceLinkage()) && "Unexpected linkage");
126   if (const ArrayType *ATy = dyn_cast<ArrayType>(
127     cast<PointerType>(GV->getType())->getElementType()))
128   {
129     O << TAI->getGlobalDirective() << name << ".globound" << "\n";
130     O << TAI->getSetDirective() << name << ".globound" << ","
131       << ATy->getNumElements() << "\n";
132     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
133       // TODO Use COMDAT groups for LinkOnceLinkage
134       O << TAI->getWeakDefDirective() << name << ".globound" << "\n";
135     }
136   }
137 }
138
139 void XCoreAsmPrinter::emitGlobal(const GlobalVariable *GV) {
140   // Check to see if this is a special global used by LLVM, if so, emit it.
141   if (!GV->hasInitializer() ||
142       EmitSpecialLLVMGlobal(GV))
143     return;
144
145   const TargetData *TD = TM.getTargetData();
146   
147   SwitchToSection(TAI->SectionForGlobal(GV));
148   
149   std::string name = Mang->getMangledName(GV);
150   Constant *C = GV->getInitializer();
151   unsigned Align = (unsigned)TD->getPreferredTypeAlignmentShift(C->getType());
152   
153   // Mark the start of the global
154   O << "\t.cc_top " << name << ".data," << name << "\n";
155
156   switch (GV->getLinkage()) {
157   case GlobalValue::AppendingLinkage:
158     llvm_report_error("AppendingLinkage is not supported by this target!");
159   case GlobalValue::LinkOnceAnyLinkage:
160   case GlobalValue::LinkOnceODRLinkage:
161   case GlobalValue::WeakAnyLinkage:
162   case GlobalValue::WeakODRLinkage:
163   case GlobalValue::ExternalLinkage:
164     emitArrayBound(name, GV);
165     emitGlobalDirective(name);
166     // TODO Use COMDAT groups for LinkOnceLinkage
167     if (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage()) {
168       O << TAI->getWeakDefDirective() << name << "\n";
169     }
170     // FALL THROUGH
171   case GlobalValue::InternalLinkage:
172   case GlobalValue::PrivateLinkage:
173   case GlobalValue::LinkerPrivateLinkage:
174     break;
175   case GlobalValue::GhostLinkage:
176     llvm_unreachable("Should not have any unmaterialized functions!");
177   case GlobalValue::DLLImportLinkage:
178     llvm_unreachable("DLLImport linkage is not supported by this target!");
179   case GlobalValue::DLLExportLinkage:
180     llvm_unreachable("DLLExport linkage is not supported by this target!");
181   default:
182     llvm_unreachable("Unknown linkage type!");
183   }
184
185   EmitAlignment(Align, GV, 2);
186   
187   unsigned Size = TD->getTypeAllocSize(C->getType());
188   if (GV->isThreadLocal()) {
189     Size *= MaxThreads;
190   }
191   if (TAI->hasDotTypeDotSizeDirective()) {
192     O << "\t.type " << name << ",@object\n";
193     O << "\t.size " << name << "," << Size << "\n";
194   }
195   O << name << ":\n";
196   
197   EmitGlobalConstant(C);
198   if (GV->isThreadLocal()) {
199     for (unsigned i = 1; i < MaxThreads; ++i) {
200       EmitGlobalConstant(C);
201     }
202   }
203   if (Size < 4) {
204     // The ABI requires that unsigned scalar types smaller than 32 bits
205     // are are padded to 32 bits.
206     EmitZeros(4 - Size);
207   }
208   
209   // Mark the end of the global
210   O << "\t.cc_bottom " << name << ".data\n";
211 }
212
213 /// Emit the directives on the start of functions
214 void XCoreAsmPrinter::emitFunctionStart(MachineFunction &MF) {
215   // Print out the label for the function.
216   const Function *F = MF.getFunction();
217
218   SwitchToSection(TAI->SectionForGlobal(F));
219   
220   // Mark the start of the function
221   O << "\t.cc_top " << CurrentFnName << ".function," << CurrentFnName << "\n";
222
223   switch (F->getLinkage()) {
224   default: llvm_unreachable("Unknown linkage type!");
225   case Function::InternalLinkage:  // Symbols default to internal.
226   case Function::PrivateLinkage:
227   case Function::LinkerPrivateLinkage:
228     break;
229   case Function::ExternalLinkage:
230     emitGlobalDirective(CurrentFnName);
231     break;
232   case Function::LinkOnceAnyLinkage:
233   case Function::LinkOnceODRLinkage:
234   case Function::WeakAnyLinkage:
235   case Function::WeakODRLinkage:
236     // TODO Use COMDAT groups for LinkOnceLinkage
237     O << TAI->getGlobalDirective() << CurrentFnName << "\n";
238     O << TAI->getWeakDefDirective() << CurrentFnName << "\n";
239     break;
240   }
241   // (1 << 1) byte aligned
242   EmitAlignment(MF.getAlignment(), F, 1);
243   if (TAI->hasDotTypeDotSizeDirective()) {
244     O << "\t.type " << CurrentFnName << ",@function\n";
245   }
246   O << CurrentFnName << ":\n";
247 }
248
249 /// Emit the directives on the end of functions
250 void XCoreAsmPrinter::
251 emitFunctionEnd(MachineFunction &MF) 
252 {
253   // Mark the end of the function
254   O << "\t.cc_bottom " << CurrentFnName << ".function\n";
255 }
256
257 /// runOnMachineFunction - This uses the printMachineInstruction()
258 /// method to print assembly for each instruction.
259 ///
260 bool XCoreAsmPrinter::runOnMachineFunction(MachineFunction &MF)
261 {
262   this->MF = &MF;
263
264   SetupMachineFunction(MF);
265
266   // Print out constants referenced by the function
267   EmitConstantPool(MF.getConstantPool());
268
269   // Print out jump tables referenced by the function
270   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
271
272   // Emit the function start directives
273   emitFunctionStart(MF);
274   
275   // Emit pre-function debug information.
276   DW->BeginFunction(&MF);
277
278   // Print out code for the function.
279   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
280        I != E; ++I) {
281
282     // Print a label for the basic block.
283     if (I != MF.begin()) {
284       printBasicBlockLabel(I, true , true);
285       O << '\n';
286     }
287
288     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
289          II != E; ++II) {
290       // Print the assembly for the instruction.
291       O << "\t";
292       printMachineInstruction(II);
293     }
294
295     // Each Basic Block is separated by a newline
296     O << '\n';
297   }
298
299   // Emit function end directives
300   emitFunctionEnd(MF);
301   
302   // Emit post-function debug information.
303   DW->EndFunction(&MF);
304
305   // We didn't modify anything.
306   return false;
307 }
308
309 void XCoreAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum)
310 {
311   printOperand(MI, opNum);
312   
313   if (MI->getOperand(opNum+1).isImm()
314     && MI->getOperand(opNum+1).getImm() == 0)
315     return;
316   
317   O << "+";
318   printOperand(MI, opNum+1);
319 }
320
321 void XCoreAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
322   const MachineOperand &MO = MI->getOperand(opNum);
323   switch (MO.getType()) {
324   case MachineOperand::MO_Register:
325     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
326       O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
327     else
328       llvm_unreachable("not implemented");
329     break;
330   case MachineOperand::MO_Immediate:
331     O << MO.getImm();
332     break;
333   case MachineOperand::MO_MachineBasicBlock:
334     printBasicBlockLabel(MO.getMBB());
335     break;
336   case MachineOperand::MO_GlobalAddress:
337     O << Mang->getMangledName(MO.getGlobal());
338     break;
339   case MachineOperand::MO_ExternalSymbol:
340     O << MO.getSymbolName();
341     break;
342   case MachineOperand::MO_ConstantPoolIndex:
343     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber()
344       << '_' << MO.getIndex();
345     break;
346   case MachineOperand::MO_JumpTableIndex:
347     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
348       << '_' << MO.getIndex();
349     break;
350   default:
351     llvm_unreachable("not implemented");
352   }
353 }
354
355 /// PrintAsmOperand - Print out an operand for an inline asm expression.
356 ///
357 bool XCoreAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
358                                       unsigned AsmVariant, 
359                                       const char *ExtraCode) {
360   printOperand(MI, OpNo);
361   return false;
362 }
363
364 void XCoreAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
365   ++EmittedInsts;
366
367   // Check for mov mnemonic
368   unsigned src, dst, srcSR, dstSR;
369   if (TM.getInstrInfo()->isMoveInstr(*MI, src, dst, srcSR, dstSR)) {
370     O << "\tmov ";
371     O << TM.getRegisterInfo()->get(dst).AsmName;
372     O << ", ";
373     O << TM.getRegisterInfo()->get(src).AsmName;
374     O << "\n";
375     return;
376   }
377   if (printInstruction(MI)) {
378     return;
379   }
380   llvm_unreachable("Unhandled instruction in asm writer!");
381 }
382
383 bool XCoreAsmPrinter::doInitialization(Module &M) {
384   bool Result = AsmPrinter::doInitialization(M);
385   DW = getAnalysisIfAvailable<DwarfWriter>();
386   
387   return Result;
388 }
389
390 bool XCoreAsmPrinter::doFinalization(Module &M) {
391
392   // Print out module-level global variables.
393   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
394        I != E; ++I) {
395     emitGlobal(I);
396   }
397   
398   return AsmPrinter::doFinalization(M);
399 }