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