SparcAsmPrinter.cpp revision b74ed07bfd3af42331b1964c24c39912610a08f4
1//===-- SparcAsmPrinter.cpp - Sparc LLVM assembly writer ------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the 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 GAS-format SPARC assembly language.
12//
13//===----------------------------------------------------------------------===//
14
15#include "Sparc.h"
16#include "SparcInstrInfo.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Module.h"
20#include "llvm/Assembly/Writer.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 <iostream>
35using namespace llvm;
36
37namespace {
38  Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
39
40  struct VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {
41    SparcAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
42      : AsmPrinter(O, TM, T) {
43    }
44
45    /// We name each basic block in a Function with a unique number, so
46    /// that we can consistently refer to them later. This is cleared
47    /// at the beginning of each call to runOnMachineFunction().
48    ///
49    typedef std::map<const Value *, unsigned> ValueMapTy;
50    ValueMapTy NumberForBB;
51
52    virtual const char *getPassName() const {
53      return "Sparc Assembly Printer";
54    }
55
56    void printOperand(const MachineInstr *MI, int opNum);
57    void printMemOperand(const MachineInstr *MI, int opNum,
58                         const char *Modifier = 0);
59    void printCCOperand(const MachineInstr *MI, int opNum);
60
61    bool printInstruction(const MachineInstr *MI);  // autogenerated.
62    bool runOnMachineFunction(MachineFunction &F);
63    bool doInitialization(Module &M);
64    bool doFinalization(Module &M);
65  };
66} // end of anonymous namespace
67
68#include "SparcGenAsmWriter.inc"
69
70/// createSparcCodePrinterPass - Returns a pass that prints the SPARC
71/// assembly code for a MachineFunction to the given output stream,
72/// using the given target machine description.  This should work
73/// regardless of whether the function is in SSA form.
74///
75FunctionPass *llvm::createSparcCodePrinterPass(std::ostream &o,
76                                               TargetMachine &tm) {
77  return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo());
78}
79
80/// runOnMachineFunction - This uses the printMachineInstruction()
81/// method to print assembly for each instruction.
82///
83bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
84  SetupMachineFunction(MF);
85
86  // Print out constants referenced by the function
87  EmitConstantPool(MF.getConstantPool());
88
89  // BBNumber is used here so that a given Printer will never give two
90  // BBs the same name. (If you have a better way, please let me know!)
91  static unsigned BBNumber = 0;
92
93  O << "\n\n";
94  // What's my mangled name?
95  CurrentFnName = Mang->getValueName(MF.getFunction());
96
97  // Print out labels for the function.
98  SwitchToTextSection(".text", MF.getFunction());
99  EmitAlignment(4, MF.getFunction());
100  O << "\t.globl\t" << CurrentFnName << "\n";
101  O << "\t.type\t" << CurrentFnName << ", #function\n";
102  O << CurrentFnName << ":\n";
103
104  // Number each basic block so that we can consistently refer to them
105  // in PC-relative references.
106  NumberForBB.clear();
107  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
108       I != E; ++I) {
109    NumberForBB[I->getBasicBlock()] = BBNumber++;
110  }
111
112  // Print out code for the function.
113  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
114       I != E; ++I) {
115    // Print a label for the basic block.
116    if (I != MF.begin()) {
117      printBasicBlockLabel(I, true);
118      O << '\n';
119    }
120    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
121         II != E; ++II) {
122      // Print the assembly for the instruction.
123      O << "\t";
124      printInstruction(II);
125      ++EmittedInsts;
126    }
127  }
128
129  // We didn't modify anything.
130  return false;
131}
132
133void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
134  const MachineOperand &MO = MI->getOperand (opNum);
135  const MRegisterInfo &RI = *TM.getRegisterInfo();
136  bool CloseParen = false;
137  if (MI->getOpcode() == SP::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
138    O << "%hi(";
139    CloseParen = true;
140  } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri)
141             && !MO.isRegister() && !MO.isImmediate()) {
142    O << "%lo(";
143    CloseParen = true;
144  }
145  switch (MO.getType()) {
146  case MachineOperand::MO_Register:
147    if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
148      O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
149    else
150      O << "%reg" << MO.getReg();
151    break;
152
153  case MachineOperand::MO_Immediate:
154    O << (int)MO.getImmedValue();
155    break;
156  case MachineOperand::MO_MachineBasicBlock:
157    printBasicBlockLabel(MO.getMachineBasicBlock());
158    return;
159  case MachineOperand::MO_GlobalAddress:
160    O << Mang->getValueName(MO.getGlobal());
161    break;
162  case MachineOperand::MO_ExternalSymbol:
163    O << MO.getSymbolName();
164    break;
165  case MachineOperand::MO_ConstantPoolIndex:
166    O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
167      << MO.getConstantPoolIndex();
168    break;
169  default:
170    O << "<unknown operand type>"; abort (); break;
171  }
172  if (CloseParen) O << ")";
173}
174
175void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
176                                      const char *Modifier) {
177  printOperand(MI, opNum);
178
179  // If this is an ADD operand, emit it like normal operands.
180  if (Modifier && !strcmp(Modifier, "arith")) {
181    O << ", ";
182    printOperand(MI, opNum+1);
183    return;
184  }
185
186  MachineOperand::MachineOperandType OpTy = MI->getOperand(opNum+1).getType();
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).getImmedValue() == 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).getImmedValue();
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->getTypeSize(C->getType());
233      unsigned Align = TD->getTypeAlignment(C->getType());
234
235      if (C->isNullValue() &&
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->getTypeSize(C->getType())
243          << "," << (unsigned)TD->getTypeAlignment(C->getType());
244        O << "\t\t! ";
245        WriteAsOperand(O, I, true, true, &M);
246        O << "\n";
247      } else {
248        switch (I->getLinkage()) {
249        case GlobalValue::LinkOnceLinkage:
250        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
251          // Nonnull linkonce -> weak
252          O << "\t.weak " << name << "\n";
253          SwitchToDataSection("", I);
254          O << "\t.section\t\".llvm.linkonce.d." << name
255            << "\",\"aw\",@progbits\n";
256          break;
257
258        case GlobalValue::AppendingLinkage:
259          // FIXME: appending linkage variables should go into a section of
260          // their name or something.  For now, just emit them as external.
261        case GlobalValue::ExternalLinkage:
262          // If external or appending, declare as a global symbol
263          O << "\t.globl " << name << "\n";
264          // FALL THROUGH
265        case GlobalValue::InternalLinkage:
266          if (C->isNullValue())
267            SwitchToDataSection(".bss", I);
268          else
269            SwitchToDataSection(".data", I);
270          break;
271        case GlobalValue::GhostLinkage:
272          std::cerr << "Should not have any unmaterialized functions!\n";
273          abort();
274        case GlobalValue::DLLImportLinkage:
275          std::cerr << "DLLImport linkage is not supported by this target!\n";
276          abort();
277        case GlobalValue::DLLExportLinkage:
278          std::cerr << "DLLExport linkage is not supported by this target!\n";
279          abort();
280        default:
281          assert(0 && "Unknown linkage type!");
282        }
283
284        O << "\t.align " << Align << "\n";
285        O << "\t.type " << name << ",#object\n";
286        O << "\t.size " << name << "," << Size << "\n";
287        O << name << ":\t\t\t\t! ";
288        WriteAsOperand(O, I, true, true, &M);
289        O << "\n";
290        EmitGlobalConstant(C);
291      }
292    }
293
294  AsmPrinter::doFinalization(M);
295  return false; // success
296}
297