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