now that MCSymbol::print doesn't use it's MAI argument, we can
[oota-llvm.git] / lib / Target / MSP430 / AsmPrinter / MSP430AsmPrinter.cpp
1 //===-- MSP430AsmPrinter.cpp - MSP430 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 MSP430 assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "MSP430.h"
17 #include "MSP430InstrInfo.h"
18 #include "MSP430InstPrinter.h"
19 #include "MSP430MCAsmInfo.h"
20 #include "MSP430MCInstLower.h"
21 #include "MSP430TargetMachine.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Assembly/Writer.h"
26 #include "llvm/CodeGen/AsmPrinter.h"
27 #include "llvm/CodeGen/DwarfWriter.h"
28 #include "llvm/CodeGen/MachineModuleInfo.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineInstr.h"
32 #include "llvm/MC/MCInst.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/Target/TargetData.h"
36 #include "llvm/Target/TargetLoweringObjectFile.h"
37 #include "llvm/Target/TargetRegistry.h"
38 #include "llvm/ADT/Statistic.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/ErrorHandling.h"
42 using namespace llvm;
43
44 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45
46 static cl::opt<bool>
47 EnableMCInst("enable-msp430-mcinst-printer", cl::Hidden,
48              cl::desc("enable experimental mcinst gunk in the msp430 backend"));
49
50 namespace {
51   class MSP430AsmPrinter : public AsmPrinter {
52   public:
53     MSP430AsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
54                      const MCAsmInfo *MAI, bool V)
55       : AsmPrinter(O, TM, MAI, V) {}
56
57     virtual const char *getPassName() const {
58       return "MSP430 Assembly Printer";
59     }
60
61     void printMCInst(const MCInst *MI) {
62       MSP430InstPrinter(O, *MAI).printInstruction(MI);
63     }
64     void printOperand(const MachineInstr *MI, int OpNum,
65                       const char* Modifier = 0);
66     void printPCRelImmOperand(const MachineInstr *MI, int OpNum) {
67       printOperand(MI, OpNum);
68     }
69     void printSrcMemOperand(const MachineInstr *MI, int OpNum,
70                             const char* Modifier = 0);
71     void printCCOperand(const MachineInstr *MI, int OpNum);
72     void printMachineInstruction(const MachineInstr * MI);
73     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
74                          unsigned AsmVariant,
75                          const char *ExtraCode);
76     bool PrintAsmMemoryOperand(const MachineInstr *MI,
77                                unsigned OpNo, unsigned AsmVariant,
78                                const char *ExtraCode);
79     void printInstructionThroughMCStreamer(const MachineInstr *MI);
80
81     void PrintGlobalVariable(const GlobalVariable* GVar);
82     void emitFunctionHeader(const MachineFunction &MF);
83     bool runOnMachineFunction(MachineFunction &F);
84
85     void getAnalysisUsage(AnalysisUsage &AU) const {
86       AsmPrinter::getAnalysisUsage(AU);
87       AU.setPreservesAll();
88     }
89   };
90 } // end of anonymous namespace
91
92 void MSP430AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
93   if (!GVar->hasInitializer())
94     return;   // External global require no code
95
96   // Check to see if this is a special global used by LLVM, if so, emit it.
97   if (EmitSpecialLLVMGlobal(GVar))
98     return;
99
100   const TargetData *TD = TM.getTargetData();
101
102   MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
103   Constant *C = GVar->getInitializer();
104   unsigned Size = TD->getTypeAllocSize(C->getType());
105   unsigned Align = TD->getPreferredAlignmentLog(GVar);
106
107   printVisibility(GVarSym, GVar->getVisibility());
108
109   O << "\t.type\t" << *GVarSym << ",@object\n";
110
111   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
112                                                                   TM));
113
114   if (C->isNullValue() && !GVar->hasSection() &&
115       !GVar->isThreadLocal() &&
116       (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
117
118     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
119
120     if (GVar->hasLocalLinkage())
121       O << "\t.local\t" << *GVarSym << '\n';
122
123     O << MAI->getCOMMDirective() << *GVarSym << ',' << Size;
124     if (MAI->getCOMMDirectiveTakesAlignment())
125       O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
126
127     if (VerboseAsm) {
128       O.PadToColumn(MAI->getCommentColumn());
129       O << MAI->getCommentString() << ' ';
130       WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
131     }
132     O << '\n';
133     return;
134   }
135
136   switch (GVar->getLinkage()) {
137   case GlobalValue::CommonLinkage:
138   case GlobalValue::LinkOnceAnyLinkage:
139   case GlobalValue::LinkOnceODRLinkage:
140   case GlobalValue::WeakAnyLinkage:
141   case GlobalValue::WeakODRLinkage:
142     O << "\t.weak\t" << *GVarSym << '\n';
143     break;
144   case GlobalValue::DLLExportLinkage:
145   case GlobalValue::AppendingLinkage:
146     // FIXME: appending linkage variables should go into a section of
147     // their name or something.  For now, just emit them as external.
148   case GlobalValue::ExternalLinkage:
149     // If external or appending, declare as a global symbol
150     O << "\t.globl " << *GVarSym << '\n';
151     // FALL THROUGH
152   case GlobalValue::PrivateLinkage:
153   case GlobalValue::LinkerPrivateLinkage:
154   case GlobalValue::InternalLinkage:
155      break;
156   default:
157     assert(0 && "Unknown linkage type!");
158   }
159
160   // Use 16-bit alignment by default to simplify bunch of stuff
161   EmitAlignment(Align, GVar);
162   O << *GVarSym << ":";
163   if (VerboseAsm) {
164     O.PadToColumn(MAI->getCommentColumn());
165     O << MAI->getCommentString() << ' ';
166     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
167   }
168   O << '\n';
169
170   EmitGlobalConstant(C);
171
172   if (MAI->hasDotTypeDotSizeDirective())
173     O << "\t.size\t" << *GVarSym << ", " << Size << '\n';
174 }
175
176 void MSP430AsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
177   const Function *F = MF.getFunction();
178
179   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
180
181   unsigned FnAlign = MF.getAlignment();
182   EmitAlignment(FnAlign, F);
183
184   switch (F->getLinkage()) {
185   default: llvm_unreachable("Unknown linkage type!");
186   case Function::InternalLinkage:  // Symbols default to internal.
187   case Function::PrivateLinkage:
188   case Function::LinkerPrivateLinkage:
189     break;
190   case Function::ExternalLinkage:
191     O << "\t.globl\t" << *CurrentFnSym << '\n';
192     break;
193   case Function::LinkOnceAnyLinkage:
194   case Function::LinkOnceODRLinkage:
195   case Function::WeakAnyLinkage:
196   case Function::WeakODRLinkage:
197     O << "\t.weak\t" << *CurrentFnSym << '\n';
198     break;
199   }
200
201   printVisibility(CurrentFnSym, F->getVisibility());
202
203   O << "\t.type\t" << *CurrentFnSym << ",@function\n";
204   O << *CurrentFnSym << ":\n";
205 }
206
207 bool MSP430AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
208   SetupMachineFunction(MF);
209   O << "\n\n";
210
211   // Print the 'header' of function
212   emitFunctionHeader(MF);
213
214   // Print out code for the function.
215   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
216        I != E; ++I) {
217     // Print a label for the basic block.
218     EmitBasicBlockStart(I);
219
220     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
221          II != E; ++II)
222       // Print the assembly for the instruction.
223       printMachineInstruction(II);
224   }
225
226   if (MAI->hasDotTypeDotSizeDirective())
227     O << "\t.size\t" << *CurrentFnSym << ", .-" << *CurrentFnSym << '\n';
228
229   // We didn't modify anything
230   return false;
231 }
232
233 void MSP430AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
234   ++EmittedInsts;
235
236   processDebugLoc(MI, true);
237
238   printInstructionThroughMCStreamer(MI);
239
240   if (VerboseAsm)
241     EmitComments(*MI);
242   O << '\n';
243
244   processDebugLoc(MI, false);
245 }
246
247 void MSP430AsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
248                                     const char* Modifier) {
249   const MachineOperand &MO = MI->getOperand(OpNum);
250   switch (MO.getType()) {
251   case MachineOperand::MO_Register:
252     O << MSP430InstPrinter::getRegisterName(MO.getReg());
253     return;
254   case MachineOperand::MO_Immediate:
255     if (!Modifier || strcmp(Modifier, "nohash"))
256       O << '#';
257     O << MO.getImm();
258     return;
259   case MachineOperand::MO_MachineBasicBlock:
260     O << *GetMBBSymbol(MO.getMBB()->getNumber());
261     return;
262   case MachineOperand::MO_GlobalAddress: {
263     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
264     uint64_t Offset = MO.getOffset();
265
266     O << (isMemOp ? '&' : '#');
267     if (Offset)
268       O << '(' << Offset << '+';
269
270     O << *GetGlobalValueSymbol(MO.getGlobal());
271     
272     if (Offset)
273       O << ')';
274
275     return;
276   }
277   case MachineOperand::MO_ExternalSymbol: {
278     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
279     O << (isMemOp ? '&' : '#');
280     O << MAI->getGlobalPrefix() << MO.getSymbolName();
281     return;
282   }
283   default:
284     llvm_unreachable("Not implemented yet!");
285   }
286 }
287
288 void MSP430AsmPrinter::printSrcMemOperand(const MachineInstr *MI, int OpNum,
289                                           const char* Modifier) {
290   const MachineOperand &Base = MI->getOperand(OpNum);
291   const MachineOperand &Disp = MI->getOperand(OpNum+1);
292
293   // Print displacement first
294   if (!Disp.isImm()) {
295     printOperand(MI, OpNum+1, "mem");
296   } else {
297     if (!Base.getReg())
298       O << '&';
299
300     printOperand(MI, OpNum+1, "nohash");
301   }
302
303
304   // Print register base field
305   if (Base.getReg()) {
306     O << '(';
307     printOperand(MI, OpNum);
308     O << ')';
309   }
310 }
311
312 void MSP430AsmPrinter::printCCOperand(const MachineInstr *MI, int OpNum) {
313   unsigned CC = MI->getOperand(OpNum).getImm();
314
315   switch (CC) {
316   default:
317    llvm_unreachable("Unsupported CC code");
318    break;
319   case MSP430CC::COND_E:
320    O << "eq";
321    break;
322   case MSP430CC::COND_NE:
323    O << "ne";
324    break;
325   case MSP430CC::COND_HS:
326    O << "hs";
327    break;
328   case MSP430CC::COND_LO:
329    O << "lo";
330    break;
331   case MSP430CC::COND_GE:
332    O << "ge";
333    break;
334   case MSP430CC::COND_L:
335    O << 'l';
336    break;
337   }
338 }
339
340 /// PrintAsmOperand - Print out an operand for an inline asm expression.
341 ///
342 bool MSP430AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
343                                        unsigned AsmVariant,
344                                        const char *ExtraCode) {
345   // Does this asm operand have a single letter operand modifier?
346   if (ExtraCode && ExtraCode[0])
347     return true; // Unknown modifier.
348
349   printOperand(MI, OpNo);
350   return false;
351 }
352
353 bool MSP430AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
354                                              unsigned OpNo, unsigned AsmVariant,
355                                              const char *ExtraCode) {
356   if (ExtraCode && ExtraCode[0]) {
357     return true; // Unknown modifier.
358   }
359   printSrcMemOperand(MI, OpNo);
360   return false;
361 }
362
363 //===----------------------------------------------------------------------===//
364 void MSP430AsmPrinter::printInstructionThroughMCStreamer(const MachineInstr *MI){
365
366   MSP430MCInstLower MCInstLowering(OutContext, *Mang, *this);
367
368   switch (MI->getOpcode()) {
369   case TargetInstrInfo::DBG_LABEL:
370   case TargetInstrInfo::EH_LABEL:
371   case TargetInstrInfo::GC_LABEL:
372     printLabel(MI);
373     return;
374   case TargetInstrInfo::KILL:
375     printKill(MI);
376     return;
377   case TargetInstrInfo::INLINEASM:
378     printInlineAsm(MI);
379     return;
380   case TargetInstrInfo::IMPLICIT_DEF:
381     printImplicitDef(MI);
382     return;
383   default: break;
384   }
385
386   MCInst TmpInst;
387   MCInstLowering.Lower(MI, TmpInst);
388
389   printMCInst(&TmpInst);
390 }
391
392 static MCInstPrinter *createMSP430MCInstPrinter(const Target &T,
393                                                 unsigned SyntaxVariant,
394                                                 const MCAsmInfo &MAI,
395                                                 raw_ostream &O) {
396   if (SyntaxVariant == 0)
397     return new MSP430InstPrinter(O, MAI);
398   return 0;
399 }
400
401 // Force static initialization.
402 extern "C" void LLVMInitializeMSP430AsmPrinter() {
403   RegisterAsmPrinter<MSP430AsmPrinter> X(TheMSP430Target);
404   TargetRegistry::RegisterMCInstPrinter(TheMSP430Target,
405                                         createMSP430MCInstPrinter);
406 }