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