Switch IA64 to new section-handling stuff
[oota-llvm.git] / lib / Target / IA64 / IA64AsmPrinter.cpp
1 //===-- IA64AsmPrinter.cpp - Print out IA64 LLVM as assembly --------------===//
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 assembly accepted by the GNU binutils 'gas'
12 // assembler. The Intel 'ias' and HP-UX 'as' assemblers *may* choke on this
13 // output, but if so that's a bug I'd like to hear about: please file a bug
14 // report in bugzilla. FYI, the not too bad 'ias' assembler is bundled with
15 // the Intel C/C++ compiler for Itanium Linux.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "asm-printer"
20 #include "IA64.h"
21 #include "IA64TargetMachine.h"
22 #include "llvm/Module.h"
23 #include "llvm/Type.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/Target/TargetAsmInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/ADT/Statistic.h"
30 using namespace llvm;
31
32 STATISTIC(EmittedInsts, "Number of machine instrs printed");
33
34 namespace {
35   struct IA64AsmPrinter : public AsmPrinter {
36     std::set<std::string> ExternalFunctionNames, ExternalObjectNames;
37
38     IA64AsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
39       : AsmPrinter(O, TM, T) {
40     }
41
42     virtual const char *getPassName() const {
43       return "IA64 Assembly Printer";
44     }
45
46     /// printInstruction - This method is automatically generated by tablegen
47     /// from the instruction set description.  This method returns true if the
48     /// machine instruction was sufficiently described to print it, otherwise it
49     /// returns false.
50     bool printInstruction(const MachineInstr *MI);
51
52     // This method is used by the tablegen'erated instruction printer.
53     void printOperand(const MachineInstr *MI, unsigned OpNo){
54       const MachineOperand &MO = MI->getOperand(OpNo);
55       if (MO.getType() == MachineOperand::MO_Register) {
56         assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
57                "Not physref??");
58         //XXX Bug Workaround: See note in Printer::doInitialization about %.
59         O << TM.getRegisterInfo()->get(MO.getReg()).AsmName;
60       } else {
61         printOp(MO);
62       }
63     }
64
65     void printS8ImmOperand(const MachineInstr *MI, unsigned OpNo) {
66       int val=(unsigned int)MI->getOperand(OpNo).getImm();
67       if(val>=128) val=val-256; // if negative, flip sign
68       O << val;
69     }
70     void printS14ImmOperand(const MachineInstr *MI, unsigned OpNo) {
71       int val=(unsigned int)MI->getOperand(OpNo).getImm();
72       if(val>=8192) val=val-16384; // if negative, flip sign
73       O << val;
74     }
75     void printS22ImmOperand(const MachineInstr *MI, unsigned OpNo) {
76       int val=(unsigned int)MI->getOperand(OpNo).getImm();
77       if(val>=2097152) val=val-4194304; // if negative, flip sign
78       O << val;
79     }
80     void printU64ImmOperand(const MachineInstr *MI, unsigned OpNo) {
81       O << (uint64_t)MI->getOperand(OpNo).getImm();
82     }
83     void printS64ImmOperand(const MachineInstr *MI, unsigned OpNo) {
84 // XXX : nasty hack to avoid GPREL22 "relocation truncated to fit" linker
85 // errors - instead of add rX = @gprel(CPI<whatever>), r1;; we now
86 // emit movl rX = @gprel(CPI<whatever);;
87 //      add  rX = rX, r1;
88 // this gives us 64 bits instead of 22 (for the add long imm) to play
89 // with, which shuts up the linker. The problem is that the constant
90 // pool entries aren't immediates at this stage, so we check here.
91 // If it's an immediate, print it the old fashioned way. If it's
92 // not, we print it as a constant pool index.
93       if(MI->getOperand(OpNo).isImmediate()) {
94         O << (int64_t)MI->getOperand(OpNo).getImm();
95       } else { // this is a constant pool reference: FIXME: assert this
96         printOp(MI->getOperand(OpNo));
97       }
98     }
99
100     void printGlobalOperand(const MachineInstr *MI, unsigned OpNo) {
101       printOp(MI->getOperand(OpNo), false); // this is NOT a br.call instruction
102     }
103
104     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
105       printOp(MI->getOperand(OpNo), true); // this is a br.call instruction
106     }
107
108     std::string getSectionForFunction(const Function &F) const;
109
110     void printMachineInstruction(const MachineInstr *MI);
111     void printOp(const MachineOperand &MO, bool isBRCALLinsn= false);
112     void printModuleLevelGV(const GlobalVariable* GVar);
113     bool runOnMachineFunction(MachineFunction &F);
114     bool doInitialization(Module &M);
115     bool doFinalization(Module &M);
116   };
117 } // end of anonymous namespace
118
119
120 // Include the auto-generated portion of the assembly writer.
121 #include "IA64GenAsmWriter.inc"
122
123
124 // Substitute old hook with new one temporary
125 std::string IA64AsmPrinter::getSectionForFunction(const Function &F) const {
126   return TAI->SectionForGlobal(&F);
127 }
128
129 /// runOnMachineFunction - This uses the printMachineInstruction()
130 /// method to print assembly for each instruction.
131 ///
132 bool IA64AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
133   SetupMachineFunction(MF);
134   O << "\n\n";
135
136   // Print out constants referenced by the function
137   EmitConstantPool(MF.getConstantPool());
138
139   const Function *F = MF.getFunction();
140   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
141
142   // Print out labels for the function.
143   EmitAlignment(5);
144   O << "\t.global\t" << CurrentFnName << "\n";
145   O << "\t.type\t" << CurrentFnName << ", @function\n";
146   O << CurrentFnName << ":\n";
147
148   // Print out code for the function.
149   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
150        I != E; ++I) {
151     // Print a label for the basic block if there are any predecessors.
152     if (!I->pred_empty()) {
153       printBasicBlockLabel(I, true, true);
154       O << '\n';
155     }
156     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
157          II != E; ++II) {
158       // Print the assembly for the instruction.
159       printMachineInstruction(II);
160     }
161   }
162
163   // We didn't modify anything.
164   return false;
165 }
166
167 void IA64AsmPrinter::printOp(const MachineOperand &MO,
168                              bool isBRCALLinsn /* = false */) {
169   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
170   switch (MO.getType()) {
171   case MachineOperand::MO_Register:
172     O << RI.get(MO.getReg()).AsmName;
173     return;
174
175   case MachineOperand::MO_Immediate:
176     O << MO.getImm();
177     return;
178   case MachineOperand::MO_MachineBasicBlock:
179     printBasicBlockLabel(MO.getMBB());
180     return;
181   case MachineOperand::MO_ConstantPoolIndex: {
182     O << "@gprel(" << TAI->getPrivateGlobalPrefix()
183       << "CPI" << getFunctionNumber() << "_" << MO.getIndex() << ")";
184     return;
185   }
186
187   case MachineOperand::MO_GlobalAddress: {
188
189     // functions need @ltoff(@fptr(fn_name)) form
190     GlobalValue *GV = MO.getGlobal();
191     Function *F = dyn_cast<Function>(GV);
192
193     bool Needfptr=false; // if we're computing an address @ltoff(X), do
194                          // we need to decorate it so it becomes
195                          // @ltoff(@fptr(X)) ?
196     if (F && !isBRCALLinsn /*&& F->isDeclaration()*/)
197       Needfptr=true;
198
199     // if this is the target of a call instruction, we should define
200     // the function somewhere (GNU gas has no problem without this, but
201     // Intel ias rightly complains of an 'undefined symbol')
202
203     if (F /*&& isBRCALLinsn*/ && F->isDeclaration())
204       ExternalFunctionNames.insert(Mang->getValueName(MO.getGlobal()));
205     else
206       if (GV->isDeclaration()) // e.g. stuff like 'stdin'
207         ExternalObjectNames.insert(Mang->getValueName(MO.getGlobal()));
208
209     if (!isBRCALLinsn)
210       O << "@ltoff(";
211     if (Needfptr)
212       O << "@fptr(";
213     O << Mang->getValueName(MO.getGlobal());
214
215     if (Needfptr && !isBRCALLinsn)
216       O << "#))"; // close both fptr( and ltoff(
217     else {
218       if (Needfptr)
219         O << "#)"; // close only fptr(
220       if (!isBRCALLinsn)
221         O << "#)"; // close only ltoff(
222     }
223
224     int Offset = MO.getOffset();
225     if (Offset > 0)
226       O << " + " << Offset;
227     else if (Offset < 0)
228       O << " - " << -Offset;
229     return;
230   }
231   case MachineOperand::MO_ExternalSymbol:
232     O << MO.getSymbolName();
233     ExternalFunctionNames.insert(MO.getSymbolName());
234     return;
235   default:
236     O << "<AsmPrinter: unknown operand type: " << MO.getType() << " >"; return;
237   }
238 }
239
240 /// printMachineInstruction -- Print out a single IA64 LLVM instruction
241 /// MI to the current output stream.
242 ///
243 void IA64AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
244   ++EmittedInsts;
245
246   // Call the autogenerated instruction printer routines.
247   printInstruction(MI);
248 }
249
250 bool IA64AsmPrinter::doInitialization(Module &M) {
251   bool Result = AsmPrinter::doInitialization(M);
252
253   O << "\n.ident \"LLVM-ia64\"\n\n"
254     << "\t.psr    lsb\n"  // should be "msb" on HP-UX, for starters
255     << "\t.radix  C\n"
256     << "\t.psr    abi64\n"; // we only support 64 bits for now
257   return Result;
258 }
259
260 void IA64AsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
261   const TargetData *TD = TM.getTargetData();
262
263   if (!GVar->hasInitializer())
264     return; // External global require no code
265
266   // Check to see if this is a special global used by LLVM, if so, emit it.
267   if (EmitSpecialLLVMGlobal(GVar))
268     return;
269
270   O << "\n\n";
271   std::string SectionName = TAI->SectionForGlobal(GVar);
272   std::string name = Mang->getValueName(GVar);
273   Constant *C = GVar->getInitializer();
274   unsigned Size = TD->getABITypeSize(C->getType());
275   unsigned Align = TD->getPreferredAlignmentLog(GVar);
276
277   // FIXME: ELF supports visibility
278
279   SwitchToDataSection(SectionName.c_str());
280
281   if (C->isNullValue() && !GVar->hasSection()) {
282     if (!GVar->isThreadLocal() &&
283         (GVar->hasInternalLinkage() || GVar->isWeakForLinker())) {
284       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
285
286       if (GVar->hasInternalLinkage()) {
287         O << "\t.lcomm " << name << "#," << Size
288           << "," << (1 << Align);
289         O << "\n";
290       } else {
291         O << "\t.common " << name << "#," << Size
292           << "," << (1 << Align);
293         O << "\n";
294       }
295
296       return;
297     }
298   }
299
300   switch (GVar->getLinkage()) {
301    case GlobalValue::LinkOnceLinkage:
302    case GlobalValue::CommonLinkage:
303    case GlobalValue::WeakLinkage:
304     // Nonnull linkonce -> weak
305     O << "\t.weak " << name << "\n";
306     break;
307    case GlobalValue::AppendingLinkage:
308     // FIXME: appending linkage variables should go into a section of
309     // their name or something.  For now, just emit them as external.
310    case GlobalValue::ExternalLinkage:
311     // If external or appending, declare as a global symbol
312     O << TAI->getGlobalDirective() << name << "\n";
313     // FALL THROUGH
314    case GlobalValue::InternalLinkage:
315     break;
316    case GlobalValue::GhostLinkage:
317     cerr << "GhostLinkage cannot appear in IA64AsmPrinter!\n";
318     abort();
319    case GlobalValue::DLLImportLinkage:
320     cerr << "DLLImport linkage is not supported by this target!\n";
321     abort();
322    case GlobalValue::DLLExportLinkage:
323     cerr << "DLLExport linkage is not supported by this target!\n";
324     abort();
325    default:
326     assert(0 && "Unknown linkage type!");
327   }
328
329   EmitAlignment(Align);
330
331   if (TAI->hasDotTypeDotSizeDirective()) {
332     O << "\t.type " << name << ",@object\n";
333     O << "\t.size " << name << "," << Size << "\n";
334   }
335
336   O << name << ":\t\t\t\t// " << *C << "\n";
337   EmitGlobalConstant(C);
338 }
339
340
341 bool IA64AsmPrinter::doFinalization(Module &M) {
342   // Print out module-level global variables here.
343   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
344        I != E; ++I)
345     printModuleLevelGV(I);
346
347   // we print out ".global X \n .type X, @function" for each external function
348   O << "\n\n// br.call targets referenced (and not defined) above: \n";
349   for (std::set<std::string>::iterator i = ExternalFunctionNames.begin(),
350        e = ExternalFunctionNames.end(); i!=e; ++i) {
351     O << "\t.global " << *i << "\n\t.type " << *i << ", @function\n";
352   }
353   O << "\n\n";
354
355   // we print out ".global X \n .type X, @object" for each external object
356   O << "\n\n// (external) symbols referenced (and not defined) above: \n";
357   for (std::set<std::string>::iterator i = ExternalObjectNames.begin(),
358        e = ExternalObjectNames.end(); i!=e; ++i) {
359     O << "\t.global " << *i << "\n\t.type " << *i << ", @object\n";
360   }
361   O << "\n\n";
362
363   return AsmPrinter::doFinalization(M);
364 }
365
366 /// createIA64CodePrinterPass - Returns a pass that prints the IA64
367 /// assembly code for a MachineFunction to the given output stream, using
368 /// the given target machine description.
369 ///
370 FunctionPass *llvm::createIA64CodePrinterPass(std::ostream &o,
371                                               IA64TargetMachine &tm) {
372   return new IA64AsmPrinter(o, tm, tm.getTargetAsmInfo());
373 }