1 //===-- PTXAsmPrinter.cpp - PTX LLVM assembly writer ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to PTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "ptx-asm-printer"
18 #include "PTXMachineFunctionInfo.h"
19 #include "PTXTargetMachine.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/CodeGen/AsmPrinter.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Target/Mangler.h"
31 #include "llvm/Target/TargetLoweringObjectFile.h"
32 #include "llvm/Target/TargetRegistry.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
42 class PTXAsmPrinter : public AsmPrinter {
44 explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
45 : AsmPrinter(TM, Streamer) {}
47 const char *getPassName() const { return "PTX Assembly Printer"; }
49 bool doFinalization(Module &M);
51 virtual void EmitStartOfAsmFile(Module &M);
53 virtual bool runOnMachineFunction(MachineFunction &MF);
55 virtual void EmitFunctionBodyStart();
56 virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); }
58 virtual void EmitInstruction(const MachineInstr *MI);
60 void printOperand(const MachineInstr *MI, int opNum, raw_ostream &OS);
61 void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
62 const char *Modifier = 0);
63 void printParamOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
64 const char *Modifier = 0);
67 void printInstruction(const MachineInstr *MI, raw_ostream &OS);
68 static const char *getRegisterName(unsigned RegNo);
71 void EmitVariableDeclaration(const GlobalVariable *gv);
72 void EmitFunctionDeclaration();
73 }; // class PTXAsmPrinter
76 static const char PARAM_PREFIX[] = "__param_";
78 static const char *getRegisterTypeName(unsigned RegNo) {
79 #define TEST_REGCLS(cls, clsstr) \
80 if (PTX::cls ## RegisterClass->contains(RegNo)) return # clsstr;
81 TEST_REGCLS(Preds, pred);
82 TEST_REGCLS(RRegu16, u16);
83 TEST_REGCLS(RRegu32, u32);
84 TEST_REGCLS(RRegu64, u64);
85 TEST_REGCLS(RRegf32, f32);
86 TEST_REGCLS(RRegf64, f64);
89 llvm_unreachable("Not in any register class!");
93 static const char *getInstructionTypeName(const MachineInstr *MI) {
94 for (int i = 0, e = MI->getNumOperands(); i != e; ++i) {
95 const MachineOperand &MO = MI->getOperand(i);
96 if (MO.getType() == MachineOperand::MO_Register)
97 return getRegisterTypeName(MO.getReg());
100 llvm_unreachable("No reg operand found in instruction!");
104 static const char *getStateSpaceName(unsigned addressSpace) {
105 switch (addressSpace) {
106 default: llvm_unreachable("Unknown state space");
107 case PTX::GLOBAL: return "global";
108 case PTX::CONSTANT: return "const";
109 case PTX::LOCAL: return "local";
110 case PTX::PARAMETER: return "param";
111 case PTX::SHARED: return "shared";
116 static const char *getTypeName(const Type* type) {
118 switch (type->getTypeID()) {
119 default: llvm_unreachable("Unknown type");
120 case Type::FloatTyID: return ".f32";
121 case Type::DoubleTyID: return ".f64";
122 case Type::IntegerTyID:
123 switch (type->getPrimitiveSizeInBits()) {
124 default: llvm_unreachable("Unknown integer bit-width");
125 case 16: return ".u16";
126 case 32: return ".u32";
127 case 64: return ".u64";
129 case Type::ArrayTyID:
130 case Type::PointerTyID:
131 type = dyn_cast<const SequentialType>(type)->getElementType();
138 bool PTXAsmPrinter::doFinalization(Module &M) {
139 // XXX Temproarily remove global variables so that doFinalization() will not
140 // emit them again (global variables are emitted at beginning).
142 Module::GlobalListType &global_list = M.getGlobalList();
143 int i, n = global_list.size();
144 GlobalVariable **gv_array = new GlobalVariable* [n];
146 // first, back-up GlobalVariable in gv_array
148 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
152 // second, empty global_list
153 while (!global_list.empty())
154 global_list.remove(global_list.begin());
156 // call doFinalization
157 bool ret = AsmPrinter::doFinalization(M);
159 // now we restore global variables
160 for (i = 0; i < n; i ++)
161 global_list.insert(global_list.end(), gv_array[i]);
167 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
169 const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
171 OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString()));
172 OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() +
173 (ST.supportsDouble() ? ""
174 : ", map_f64_to_f32")));
175 OutStreamer.AddBlankLine();
177 // declare global variables
178 for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
180 EmitVariableDeclaration(i);
183 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
184 SetupMachineFunction(MF);
185 EmitFunctionDeclaration();
190 void PTXAsmPrinter::EmitFunctionBodyStart() {
191 OutStreamer.EmitRawText(Twine("{"));
193 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
195 // Print local variable definition
196 for (PTXMachineFunctionInfo::reg_iterator
197 i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
200 std::string def = "\t.reg .";
201 def += getRegisterTypeName(reg);
203 def += getRegisterName(reg);
205 OutStreamer.EmitRawText(Twine(def));
209 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
213 // Write instruction to str
214 raw_string_ostream OS(str);
215 printInstruction(MI, OS);
219 // Replace "%type" if found
221 if ((pos = str.find("%type")) != std::string::npos)
222 str.replace(pos, /*strlen("%type")==*/5, getInstructionTypeName(MI));
224 StringRef strref = StringRef(str);
225 OutStreamer.EmitRawText(strref);
228 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
230 const MachineOperand &MO = MI->getOperand(opNum);
232 switch (MO.getType()) {
234 llvm_unreachable("<unknown operand type>");
236 case MachineOperand::MO_GlobalAddress:
237 OS << *Mang->getSymbol(MO.getGlobal());
239 case MachineOperand::MO_Immediate:
240 OS << (int) MO.getImm();
242 case MachineOperand::MO_Register:
243 OS << getRegisterName(MO.getReg());
245 case MachineOperand::MO_FPImmediate:
246 APInt constFP = MO.getFPImm()->getValueAPF().bitcastToAPInt();
247 bool isFloat = MO.getFPImm()->getType()->getTypeID() == Type::FloatTyID;
248 // Emit 0F for 32-bit floats and 0D for 64-bit doubles.
255 // Emit the encoded floating-point value.
256 if (constFP.getZExtValue() > 0) {
257 OS << constFP.toString(16, false);
261 // If We have a double-precision zero, pad to 8-bytes.
270 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
271 raw_ostream &OS, const char *Modifier) {
272 printOperand(MI, opNum, OS);
274 if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
275 return; // don't print "+0"
278 printOperand(MI, opNum+1, OS);
281 void PTXAsmPrinter::printParamOperand(const MachineInstr *MI, int opNum,
282 raw_ostream &OS, const char *Modifier) {
283 OS << PARAM_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
286 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
287 // Check to see if this is a special global used by LLVM, if so, emit it.
288 if (EmitSpecialLLVMGlobal(gv))
291 MCSymbol *gvsym = Mang->getSymbol(gv);
293 assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
297 // check if it is defined in some other translation unit
298 if (gv->isDeclaration())
301 // state space: e.g., .global
303 decl += getStateSpaceName(gv->getType()->getAddressSpace());
306 // alignment (optional)
307 unsigned alignment = gv->getAlignment();
308 if (alignment != 0) {
310 decl += utostr(Log2_32(gv->getAlignment()));
314 decl += getTypeName(gv->getType());
317 decl += gvsym->getName();
319 if (ArrayType::classof(gv->getType()) || PointerType::classof(gv->getType()))
324 OutStreamer.EmitRawText(Twine(decl));
326 OutStreamer.AddBlankLine();
329 void PTXAsmPrinter::EmitFunctionDeclaration() {
330 // The function label could have already been emitted if two symbols end up
331 // conflicting due to asm renaming. Detect this and emit an error.
332 if (!CurrentFnSym->isUndefined()) {
333 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
334 "' label emitted multiple times to assembly file");
338 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
339 const bool isKernel = MFI->isKernel();
342 std::string decl = isKernel ? ".entry" : ".func";
344 // Print return register
346 if (!isKernel && reg != PTX::NoRegister) {
347 decl += " (.reg ."; // FIXME: could it return in .param space?
348 decl += getRegisterTypeName(reg);
350 decl += getRegisterName(reg);
354 // Print function name
356 decl += CurrentFnSym->getName().str();
358 // Print parameter list
359 if (!MFI->argRegEmpty()) {
363 //for (int i = 0, e = MFI->getNumArg(); i != e; ++i) {
364 for(PTXMachineFunctionInfo::reg_reverse_iterator
365 i = MFI->argRegReverseBegin(), e = MFI->argRegReverseEnd(), b = i;
368 assert(reg != PTX::NoRegister && "Not a valid register!");
372 decl += getRegisterTypeName(reg);
374 decl += PARAM_PREFIX;
375 decl += utostr(++cnt);
378 for (PTXMachineFunctionInfo::reg_reverse_iterator
379 i = MFI->argRegReverseBegin(), e = MFI->argRegReverseEnd(), b = i;
382 assert(reg != PTX::NoRegister && "Not a valid register!");
386 decl += getRegisterTypeName(reg);
388 decl += getRegisterName(reg);
394 OutStreamer.EmitRawText(Twine(decl));
397 #include "PTXGenAsmWriter.inc"
399 // Force static initialization.
400 extern "C" void LLVMInitializePTXAsmPrinter() {
401 RegisterAsmPrinter<PTXAsmPrinter> X(ThePTXTarget);