Add constpool lowering / printing
[oota-llvm.git] / lib / Target / SystemZ / AsmPrinter / SystemZAsmPrinter.cpp
1 //===-- SystemZAsmPrinter.cpp - SystemZ 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 SystemZ assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "SystemZ.h"
17 #include "SystemZInstrInfo.h"
18 #include "SystemZTargetMachine.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/Support/raw_ostream.h"
34
35 using namespace llvm;
36
37 STATISTIC(EmittedInsts, "Number of machine instrs printed");
38
39 namespace {
40   class VISIBILITY_HIDDEN SystemZAsmPrinter : public AsmPrinter {
41   public:
42     SystemZAsmPrinter(raw_ostream &O, SystemZTargetMachine &TM,
43                      const TargetAsmInfo *TAI,
44                      CodeGenOpt::Level OL, bool V)
45       : AsmPrinter(O, TM, TAI, OL, V) {}
46
47     virtual const char *getPassName() const {
48       return "SystemZ Assembly Printer";
49     }
50
51     void printOperand(const MachineInstr *MI, int OpNum,
52                       const char* Modifier = 0);
53     void printPCRelImmOperand(const MachineInstr *MI, int OpNum);
54     void printRIAddrOperand(const MachineInstr *MI, int OpNum,
55                             const char* Modifier = 0);
56     void printRRIAddrOperand(const MachineInstr *MI, int OpNum,
57                              const char* Modifier = 0);
58     void printS16ImmOperand(const MachineInstr *MI, int OpNum) {
59       O << (int16_t)MI->getOperand(OpNum).getImm();
60     }
61     void printS32ImmOperand(const MachineInstr *MI, int OpNum) {
62       O << (int32_t)MI->getOperand(OpNum).getImm();
63     }
64
65     bool printInstruction(const MachineInstr *MI);  // autogenerated.
66     void printMachineInstruction(const MachineInstr * MI);
67
68     void emitFunctionHeader(const MachineFunction &MF);
69     bool runOnMachineFunction(MachineFunction &F);
70     bool doInitialization(Module &M);
71     bool doFinalization(Module &M);
72     void printModuleLevelGV(const GlobalVariable* GVar);
73
74     void getAnalysisUsage(AnalysisUsage &AU) const {
75       AsmPrinter::getAnalysisUsage(AU);
76       AU.setPreservesAll();
77     }
78   };
79 } // end of anonymous namespace
80
81 #include "SystemZGenAsmWriter.inc"
82
83 /// createSystemZCodePrinterPass - Returns a pass that prints the SystemZ
84 /// assembly code for a MachineFunction to the given output stream,
85 /// using the given target machine description.  This should work
86 /// regardless of whether the function is in SSA form.
87 ///
88 FunctionPass *llvm::createSystemZCodePrinterPass(raw_ostream &o,
89                                                 SystemZTargetMachine &tm,
90                                                 CodeGenOpt::Level OptLevel,
91                                                 bool verbose) {
92   return new SystemZAsmPrinter(o, tm, tm.getTargetAsmInfo(), OptLevel, verbose);
93 }
94
95 bool SystemZAsmPrinter::doInitialization(Module &M) {
96   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
97   return false; // success
98 }
99
100
101 bool SystemZAsmPrinter::doFinalization(Module &M) {
102   // Print out module-level global variables here.
103   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
104        I != E; ++I)
105     printModuleLevelGV(I);
106
107   return AsmPrinter::doFinalization(M);
108 }
109
110 void SystemZAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
111   const Function *F = MF.getFunction();
112
113   SwitchToSection(TAI->SectionForGlobal(F));
114
115   unsigned FnAlign = 4;
116   if (F->hasFnAttr(Attribute::OptimizeForSize))
117     FnAlign = 1;
118
119   EmitAlignment(FnAlign, F);
120
121   switch (F->getLinkage()) {
122   default: assert(0 && "Unknown linkage type!");
123   case Function::InternalLinkage:  // Symbols default to internal.
124   case Function::PrivateLinkage:
125     break;
126   case Function::ExternalLinkage:
127     O << "\t.globl\t" << CurrentFnName << '\n';
128     break;
129   case Function::LinkOnceAnyLinkage:
130   case Function::LinkOnceODRLinkage:
131   case Function::WeakAnyLinkage:
132   case Function::WeakODRLinkage:
133     O << "\t.weak\t" << CurrentFnName << '\n';
134     break;
135   }
136
137   printVisibility(CurrentFnName, F->getVisibility());
138
139   O << "\t.type\t" << CurrentFnName << ",@function\n"
140     << CurrentFnName << ":\n";
141 }
142
143 bool SystemZAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
144   SetupMachineFunction(MF);
145   O << "\n\n";
146
147   // Print out constants referenced by the function
148   EmitConstantPool(MF.getConstantPool());
149
150   // Print the 'header' of function
151   emitFunctionHeader(MF);
152
153   // Print out code for the function.
154   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
155        I != E; ++I) {
156     // Print a label for the basic block.
157     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
158       // This is an entry block or a block that's only reachable via a
159       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
160     } else {
161       printBasicBlockLabel(I, true, true, VerboseAsm);
162       O << '\n';
163     }
164
165     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
166          II != E; ++II)
167       // Print the assembly for the instruction.
168       printMachineInstruction(II);
169   }
170
171   if (TAI->hasDotTypeDotSizeDirective())
172     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
173
174   // Print out jump tables referenced by the function.
175   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
176
177   O.flush();
178
179   // We didn't modify anything
180   return false;
181 }
182
183 void SystemZAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
184   ++EmittedInsts;
185
186   // Call the autogenerated instruction printer routines.
187   if (printInstruction(MI))
188     return;
189
190   assert(0 && "Should not happen");
191 }
192
193 void SystemZAsmPrinter::printPCRelImmOperand(const MachineInstr *MI, int OpNum) {
194   const MachineOperand &MO = MI->getOperand(OpNum);
195   switch (MO.getType()) {
196   case MachineOperand::MO_Immediate:
197     O << MO.getImm();
198     return;
199   case MachineOperand::MO_MachineBasicBlock:
200     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
201     return;
202   case MachineOperand::MO_GlobalAddress: {
203     const GlobalValue *GV = MO.getGlobal();
204     std::string Name = Mang->getValueName(GV);
205
206     O << Name;
207
208     // Assemble calls via PLT for externally visible symbols if PIC.
209     if (TM.getRelocationModel() == Reloc::PIC_ &&
210         !GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
211         !GV->hasLocalLinkage())
212       O << "@PLT";
213
214     printOffset(MO.getOffset());
215     return;
216   }
217   case MachineOperand::MO_ExternalSymbol: {
218     std::string Name(TAI->getGlobalPrefix());
219     Name += MO.getSymbolName();
220     O << Name;
221
222     if (TM.getRelocationModel() == Reloc::PIC_)
223       O << "@PLT";
224
225     return;
226   }
227   default:
228     assert(0 && "Not implemented yet!");
229   }
230 }
231
232
233 void SystemZAsmPrinter::printOperand(const MachineInstr *MI, int OpNum,
234                                      const char* Modifier) {
235   const MachineOperand &MO = MI->getOperand(OpNum);
236   switch (MO.getType()) {
237   case MachineOperand::MO_Register: {
238     assert (TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
239             "Virtual registers should be already mapped!");
240     unsigned Reg = MO.getReg();
241     if (Modifier && strncmp(Modifier, "subreg", 6) == 0) {
242       if (strncmp(Modifier + 7, "even", 4) == 0)
243         Reg = TRI->getSubReg(Reg, SystemZ::SUBREG_EVEN);
244       else if (strncmp(Modifier + 7, "odd", 3) == 0)
245         Reg = TRI->getSubReg(Reg, SystemZ::SUBREG_ODD);
246       else
247         assert(0 && "Invalid subreg modifier");
248     }
249
250     O << '%' << TRI->getAsmName(Reg);
251     return;
252   }
253   case MachineOperand::MO_Immediate:
254     O << MO.getImm();
255     return;
256   case MachineOperand::MO_MachineBasicBlock:
257     printBasicBlockLabel(MO.getMBB());
258     return;
259   case MachineOperand::MO_JumpTableIndex:
260     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
261       << MO.getIndex();
262
263     return;
264   case MachineOperand::MO_ConstantPoolIndex:
265     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
266       << MO.getIndex();
267
268     printOffset(MO.getOffset());
269     break;
270   case MachineOperand::MO_GlobalAddress: {
271     const GlobalValue *GV = MO.getGlobal();
272     std::string Name = Mang->getValueName(GV);
273
274     O << Name;
275     break;
276   }
277   case MachineOperand::MO_ExternalSymbol: {
278     std::string Name(TAI->getGlobalPrefix());
279     Name += MO.getSymbolName();
280     O << Name;
281     break;
282   }
283   default:
284     assert(0 && "Not implemented yet!");
285   }
286
287   switch (MO.getTargetFlags()) {
288   default:
289     assert(0 && "Unknown target flag on GV operand");
290   case SystemZII::MO_NO_FLAG:
291     break;
292   case SystemZII::MO_GOTENT:    O << "@GOTENT";    break;
293   case SystemZII::MO_PLT:       O << "@PLT";       break;
294   }
295
296   printOffset(MO.getOffset());
297 }
298
299 void SystemZAsmPrinter::printRIAddrOperand(const MachineInstr *MI, int OpNum,
300                                            const char* Modifier) {
301   const MachineOperand &Base = MI->getOperand(OpNum);
302
303   // Print displacement operand.
304   printOperand(MI, OpNum+1);
305
306   // Print base operand (if any)
307   if (Base.getReg()) {
308     O << '(';
309     printOperand(MI, OpNum);
310     O << ')';
311   }
312 }
313
314 void SystemZAsmPrinter::printRRIAddrOperand(const MachineInstr *MI, int OpNum,
315                                             const char* Modifier) {
316   const MachineOperand &Base = MI->getOperand(OpNum);
317   const MachineOperand &Index = MI->getOperand(OpNum+2);
318
319   // Print displacement operand.
320   printOperand(MI, OpNum+1);
321
322   // Print base operand (if any)
323   if (Base.getReg()) {
324     O << '(';
325     printOperand(MI, OpNum);
326     if (Index.getReg()) {
327       O << ',';
328       printOperand(MI, OpNum+2);
329     }
330     O << ')';
331   } else
332     assert(!Index.getReg() && "Should allocate base register first!");
333 }
334
335 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
336 /// Don't print things like \\n or \\0.
337 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
338   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
339        Name != E; ++Name)
340     if (isprint(*Name))
341       OS << *Name;
342 }
343
344 void SystemZAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
345   const TargetData *TD = TM.getTargetData();
346
347   if (!GVar->hasInitializer())
348     return;   // External global require no code
349
350   // Check to see if this is a special global used by LLVM, if so, emit it.
351   if (EmitSpecialLLVMGlobal(GVar))
352     return;
353
354   std::string name = Mang->getValueName(GVar);
355   Constant *C = GVar->getInitializer();
356   const Type *Type = C->getType();
357   unsigned Size = TD->getTypeAllocSize(Type);
358   unsigned Align = std::max(1U, TD->getPreferredAlignmentLog(GVar));
359
360   printVisibility(name, GVar->getVisibility());
361
362   O << "\t.type\t" << name << ",@object\n";
363
364   SwitchToSection(TAI->SectionForGlobal(GVar));
365
366   if (C->isNullValue() && !GVar->hasSection() &&
367       !GVar->isThreadLocal() &&
368       (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
369
370     if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
371
372     if (GVar->hasLocalLinkage())
373       O << "\t.local\t" << name << '\n';
374
375     O << TAI->getCOMMDirective()  << name << ',' << Size;
376     if (TAI->getCOMMDirectiveTakesAlignment())
377       O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
378
379     if (VerboseAsm) {
380       O << "\t\t" << TAI->getCommentString() << ' ';
381       PrintUnmangledNameSafely(GVar, O);
382     }
383     O << '\n';
384     return;
385   }
386
387   switch (GVar->getLinkage()) {
388   case GlobalValue::CommonLinkage:
389   case GlobalValue::LinkOnceAnyLinkage:
390   case GlobalValue::LinkOnceODRLinkage:
391   case GlobalValue::WeakAnyLinkage:
392   case GlobalValue::WeakODRLinkage:
393     O << "\t.weak\t" << name << '\n';
394     break;
395   case GlobalValue::DLLExportLinkage:
396   case GlobalValue::AppendingLinkage:
397     // FIXME: appending linkage variables should go into a section of
398     // their name or something.  For now, just emit them as external.
399   case GlobalValue::ExternalLinkage:
400     // If external or appending, declare as a global symbol
401     O << "\t.globl " << name << '\n';
402     // FALL THROUGH
403   case GlobalValue::PrivateLinkage:
404   case GlobalValue::InternalLinkage:
405      break;
406   default:
407     assert(0 && "Unknown linkage type!");
408   }
409
410   // Use 16-bit alignment by default to simplify bunch of stuff
411   EmitAlignment(Align, GVar, 1);
412   O << name << ":";
413   if (VerboseAsm) {
414     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
415     PrintUnmangledNameSafely(GVar, O);
416   }
417   O << '\n';
418   if (TAI->hasDotTypeDotSizeDirective())
419     O << "\t.size\t" << name << ", " << Size << '\n';
420
421   EmitGlobalConstant(C);
422 }