SparcAsmPrinter.cpp revision c007848b5aa0883715b3cf0ded82f7bff750896b
1//===-- SparcAsmPrinter.cpp - Sparc 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 GAS-format SPARC assembly language.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "asm-printer"
16#include "Sparc.h"
17#include "SparcInstrInfo.h"
18#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Module.h"
21#include "llvm/CodeGen/AsmPrinter.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineConstantPool.h"
24#include "llvm/CodeGen/MachineInstr.h"
25#include "llvm/Target/TargetAsmInfo.h"
26#include "llvm/Target/TargetData.h"
27#include "llvm/Target/TargetMachine.h"
28#include "llvm/Support/Mangler.h"
29#include "llvm/ADT/Statistic.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/MathExtras.h"
33#include <cctype>
34#include <cstring>
35#include <map>
36using namespace llvm;
37
38STATISTIC(EmittedInsts, "Number of machine instrs printed");
39
40namespace {
41  struct VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {
42    SparcAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
43      : AsmPrinter(O, TM, T) {
44    }
45
46    /// We name each basic block in a Function with a unique number, so
47    /// that we can consistently refer to them later. This is cleared
48    /// at the beginning of each call to runOnMachineFunction().
49    ///
50    typedef std::map<const Value *, unsigned> ValueMapTy;
51    ValueMapTy NumberForBB;
52
53    virtual const char *getPassName() const {
54      return "Sparc Assembly Printer";
55    }
56
57    void printOperand(const MachineInstr *MI, int opNum);
58    void printMemOperand(const MachineInstr *MI, int opNum,
59                         const char *Modifier = 0);
60    void printCCOperand(const MachineInstr *MI, int opNum);
61
62    bool printInstruction(const MachineInstr *MI);  // autogenerated.
63    bool runOnMachineFunction(MachineFunction &F);
64    bool doInitialization(Module &M);
65    bool doFinalization(Module &M);
66  };
67} // end of anonymous namespace
68
69#include "SparcGenAsmWriter.inc"
70
71/// createSparcCodePrinterPass - Returns a pass that prints the SPARC
72/// assembly code for a MachineFunction to the given output stream,
73/// using the given target machine description.  This should work
74/// regardless of whether the function is in SSA form.
75///
76FunctionPass *llvm::createSparcCodePrinterPass(std::ostream &o,
77                                               TargetMachine &tm) {
78  return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo());
79}
80
81/// runOnMachineFunction - This uses the printInstruction()
82/// method to print assembly for each instruction.
83///
84bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
85  SetupMachineFunction(MF);
86
87  // Print out constants referenced by the function
88  EmitConstantPool(MF.getConstantPool());
89
90  // BBNumber is used here so that a given Printer will never give two
91  // BBs the same name. (If you have a better way, please let me know!)
92  static unsigned BBNumber = 0;
93
94  O << "\n\n";
95  // What's my mangled name?
96  CurrentFnName = Mang->getValueName(MF.getFunction());
97
98  // Print out the label for the function.
99  const Function *F = MF.getFunction();
100  SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
101  EmitAlignment(4, F);
102  O << "\t.globl\t" << CurrentFnName << "\n";
103  O << "\t.type\t" << CurrentFnName << ", #function\n";
104  O << CurrentFnName << ":\n";
105
106  // Number each basic block so that we can consistently refer to them
107  // in PC-relative references.
108  // FIXME: Why not use the MBB numbers?
109  NumberForBB.clear();
110  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
111       I != E; ++I) {
112    NumberForBB[I->getBasicBlock()] = BBNumber++;
113  }
114
115  // Print out code for the function.
116  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
117       I != E; ++I) {
118    // Print a label for the basic block.
119    if (I != MF.begin()) {
120      printBasicBlockLabel(I, true, true);
121      O << '\n';
122    }
123    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
124         II != E; ++II) {
125      // Print the assembly for the instruction.
126      printInstruction(II);
127      ++EmittedInsts;
128    }
129  }
130
131  // We didn't modify anything.
132  return false;
133}
134
135void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
136  const MachineOperand &MO = MI->getOperand (opNum);
137  const TargetRegisterInfo &RI = *TM.getRegisterInfo();
138  bool CloseParen = false;
139  if (MI->getOpcode() == SP::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
140    O << "%hi(";
141    CloseParen = true;
142  } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri)
143             && !MO.isRegister() && !MO.isImmediate()) {
144    O << "%lo(";
145    CloseParen = true;
146  }
147  switch (MO.getType()) {
148  case MachineOperand::MO_Register:
149    if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
150      O << "%" << LowercaseString (RI.get(MO.getReg()).AsmName);
151    else
152      O << "%reg" << MO.getReg();
153    break;
154
155  case MachineOperand::MO_Immediate:
156    O << (int)MO.getImm();
157    break;
158  case MachineOperand::MO_MachineBasicBlock:
159    printBasicBlockLabel(MO.getMBB());
160    return;
161  case MachineOperand::MO_GlobalAddress:
162    O << Mang->getValueName(MO.getGlobal());
163    break;
164  case MachineOperand::MO_ExternalSymbol:
165    O << MO.getSymbolName();
166    break;
167  case MachineOperand::MO_ConstantPoolIndex:
168    O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
169      << MO.getIndex();
170    break;
171  default:
172    O << "<unknown operand type>"; abort (); break;
173  }
174  if (CloseParen) O << ")";
175}
176
177void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
178                                      const char *Modifier) {
179  printOperand(MI, opNum);
180
181  // If this is an ADD operand, emit it like normal operands.
182  if (Modifier && !strcmp(Modifier, "arith")) {
183    O << ", ";
184    printOperand(MI, opNum+1);
185    return;
186  }
187
188  if (MI->getOperand(opNum+1).isRegister() &&
189      MI->getOperand(opNum+1).getReg() == SP::G0)
190    return;   // don't print "+%g0"
191  if (MI->getOperand(opNum+1).isImmediate() &&
192      MI->getOperand(opNum+1).getImm() == 0)
193    return;   // don't print "+0"
194
195  O << "+";
196  if (MI->getOperand(opNum+1).isGlobalAddress() ||
197      MI->getOperand(opNum+1).isConstantPoolIndex()) {
198    O << "%lo(";
199    printOperand(MI, opNum+1);
200    O << ")";
201  } else {
202    printOperand(MI, opNum+1);
203  }
204}
205
206void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
207  int CC = (int)MI->getOperand(opNum).getImm();
208  O << SPARCCondCodeToString((SPCC::CondCodes)CC);
209}
210
211
212
213bool SparcAsmPrinter::doInitialization(Module &M) {
214  Mang = new Mangler(M);
215  return false; // success
216}
217
218bool SparcAsmPrinter::doFinalization(Module &M) {
219  const TargetData *TD = TM.getTargetData();
220
221  // Print out module-level global variables here.
222  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
223       I != E; ++I)
224    if (I->hasInitializer()) {   // External global require no code
225      // Check to see if this is a special global used by LLVM, if so, emit it.
226      if (EmitSpecialLLVMGlobal(I))
227        continue;
228
229      O << "\n\n";
230      std::string name = Mang->getValueName(I);
231      Constant *C = I->getInitializer();
232      unsigned Size = TD->getABITypeSize(C->getType());
233      unsigned Align = TD->getPreferredAlignment(I);
234
235      if (C->isNullValue() && (I->hasCommonLinkage() ||
236           I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
237           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
238        SwitchToDataSection(".data", I);
239        if (I->hasInternalLinkage())
240          O << "\t.local " << name << "\n";
241
242        O << "\t.comm " << name << "," << TD->getABITypeSize(C->getType())
243          << "," << Align;
244        O << "\n";
245      } else {
246        switch (I->getLinkage()) {
247        case GlobalValue::CommonLinkage:
248        case GlobalValue::LinkOnceLinkage:
249        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
250          // Nonnull linkonce -> weak
251          O << "\t.weak " << name << "\n";
252          SwitchToDataSection("", I);
253          O << "\t.section\t\".llvm.linkonce.d." << name
254            << "\",\"aw\",@progbits\n";
255          break;
256
257        case GlobalValue::AppendingLinkage:
258          // FIXME: appending linkage variables should go into a section of
259          // their name or something.  For now, just emit them as external.
260        case GlobalValue::ExternalLinkage:
261          // If external or appending, declare as a global symbol
262          O << "\t.globl " << name << "\n";
263          // FALL THROUGH
264        case GlobalValue::InternalLinkage:
265          if (C->isNullValue())
266            SwitchToDataSection(".bss", I);
267          else
268            SwitchToDataSection(".data", I);
269          break;
270        case GlobalValue::GhostLinkage:
271          cerr << "Should not have any unmaterialized functions!\n";
272          abort();
273        case GlobalValue::DLLImportLinkage:
274          cerr << "DLLImport linkage is not supported by this target!\n";
275          abort();
276        case GlobalValue::DLLExportLinkage:
277          cerr << "DLLExport linkage is not supported by this target!\n";
278          abort();
279        default:
280          assert(0 && "Unknown linkage type!");
281        }
282
283        O << "\t.align " << Align << "\n";
284        O << "\t.type " << name << ",#object\n";
285        O << "\t.size " << name << "," << Size << "\n";
286        O << name << ":\n";
287        EmitGlobalConstant(C);
288      }
289    }
290
291  return AsmPrinter::doFinalization(M);
292}
293