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);
65 void printPredicateOperand(const MachineInstr *MI, raw_ostream &O);
68 void printInstruction(const MachineInstr *MI, raw_ostream &OS);
69 static const char *getRegisterName(unsigned RegNo);
72 void EmitVariableDeclaration(const GlobalVariable *gv);
73 void EmitFunctionDeclaration();
74 }; // class PTXAsmPrinter
77 static const char PARAM_PREFIX[] = "__param_";
79 static const char *getRegisterTypeName(unsigned RegNo) {
80 #define TEST_REGCLS(cls, clsstr) \
81 if (PTX::cls ## RegisterClass->contains(RegNo)) return # clsstr;
82 TEST_REGCLS(Preds, pred);
83 TEST_REGCLS(RRegu16, u16);
84 TEST_REGCLS(RRegu32, u32);
85 TEST_REGCLS(RRegu64, u64);
86 TEST_REGCLS(RRegf32, f32);
87 TEST_REGCLS(RRegf64, f64);
90 llvm_unreachable("Not in any register class!");
94 static const char *getStateSpaceName(unsigned addressSpace) {
95 switch (addressSpace) {
96 default: llvm_unreachable("Unknown state space");
97 case PTX::GLOBAL: return "global";
98 case PTX::CONSTANT: return "const";
99 case PTX::LOCAL: return "local";
100 case PTX::PARAMETER: return "param";
101 case PTX::SHARED: return "shared";
106 static const char *getTypeName(const Type* type) {
108 switch (type->getTypeID()) {
109 default: llvm_unreachable("Unknown type");
110 case Type::FloatTyID: return ".f32";
111 case Type::DoubleTyID: return ".f64";
112 case Type::IntegerTyID:
113 switch (type->getPrimitiveSizeInBits()) {
114 default: llvm_unreachable("Unknown integer bit-width");
115 case 16: return ".u16";
116 case 32: return ".u32";
117 case 64: return ".u64";
119 case Type::ArrayTyID:
120 case Type::PointerTyID:
121 type = dyn_cast<const SequentialType>(type)->getElementType();
128 bool PTXAsmPrinter::doFinalization(Module &M) {
129 // XXX Temproarily remove global variables so that doFinalization() will not
130 // emit them again (global variables are emitted at beginning).
132 Module::GlobalListType &global_list = M.getGlobalList();
133 int i, n = global_list.size();
134 GlobalVariable **gv_array = new GlobalVariable* [n];
136 // first, back-up GlobalVariable in gv_array
138 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
142 // second, empty global_list
143 while (!global_list.empty())
144 global_list.remove(global_list.begin());
146 // call doFinalization
147 bool ret = AsmPrinter::doFinalization(M);
149 // now we restore global variables
150 for (i = 0; i < n; i ++)
151 global_list.insert(global_list.end(), gv_array[i]);
157 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
159 const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
161 OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString()));
162 OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() +
163 (ST.supportsDouble() ? ""
164 : ", map_f64_to_f32")));
165 OutStreamer.AddBlankLine();
167 // declare global variables
168 for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
170 EmitVariableDeclaration(i);
173 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
174 SetupMachineFunction(MF);
175 EmitFunctionDeclaration();
180 void PTXAsmPrinter::EmitFunctionBodyStart() {
181 OutStreamer.EmitRawText(Twine("{"));
183 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
185 // Print local variable definition
186 for (PTXMachineFunctionInfo::reg_iterator
187 i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
190 std::string def = "\t.reg .";
191 def += getRegisterTypeName(reg);
193 def += getRegisterName(reg);
195 OutStreamer.EmitRawText(Twine(def));
199 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
203 raw_string_ostream OS(str);
206 printPredicateOperand(MI, OS);
208 // Write instruction to str
209 printInstruction(MI, OS);
213 StringRef strref = StringRef(str);
214 OutStreamer.EmitRawText(strref);
217 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
219 const MachineOperand &MO = MI->getOperand(opNum);
221 switch (MO.getType()) {
223 llvm_unreachable("<unknown operand type>");
225 case MachineOperand::MO_GlobalAddress:
226 OS << *Mang->getSymbol(MO.getGlobal());
228 case MachineOperand::MO_Immediate:
229 OS << (long) MO.getImm();
231 case MachineOperand::MO_MachineBasicBlock:
232 OS << *MO.getMBB()->getSymbol();
234 case MachineOperand::MO_Register:
235 OS << getRegisterName(MO.getReg());
237 case MachineOperand::MO_FPImmediate:
238 APInt constFP = MO.getFPImm()->getValueAPF().bitcastToAPInt();
239 bool isFloat = MO.getFPImm()->getType()->getTypeID() == Type::FloatTyID;
240 // Emit 0F for 32-bit floats and 0D for 64-bit doubles.
247 // Emit the encoded floating-point value.
248 if (constFP.getZExtValue() > 0) {
249 OS << constFP.toString(16, false);
253 // If We have a double-precision zero, pad to 8-bytes.
262 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
263 raw_ostream &OS, const char *Modifier) {
264 printOperand(MI, opNum, OS);
266 if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
267 return; // don't print "+0"
270 printOperand(MI, opNum+1, OS);
273 void PTXAsmPrinter::printParamOperand(const MachineInstr *MI, int opNum,
274 raw_ostream &OS, const char *Modifier) {
275 OS << PARAM_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
278 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
279 // Check to see if this is a special global used by LLVM, if so, emit it.
280 if (EmitSpecialLLVMGlobal(gv))
283 MCSymbol *gvsym = Mang->getSymbol(gv);
285 assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
289 // check if it is defined in some other translation unit
290 if (gv->isDeclaration())
293 // state space: e.g., .global
295 decl += getStateSpaceName(gv->getType()->getAddressSpace());
298 // alignment (optional)
299 unsigned alignment = gv->getAlignment();
300 if (alignment != 0) {
302 decl += utostr(Log2_32(gv->getAlignment()));
307 if (PointerType::classof(gv->getType())) {
308 const PointerType* pointerTy = dyn_cast<const PointerType>(gv->getType());
309 const Type* elementTy = pointerTy->getElementType();
312 decl += gvsym->getName();
315 if (elementTy->isArrayTy())
317 assert(elementTy->isArrayTy() && "Only pointers to arrays are supported");
319 const ArrayType* arrayTy = dyn_cast<const ArrayType>(elementTy);
320 elementTy = arrayTy->getElementType();
322 unsigned numElements = arrayTy->getNumElements();
324 while (elementTy->isArrayTy()) {
326 arrayTy = dyn_cast<const ArrayType>(elementTy);
327 elementTy = arrayTy->getElementType();
329 numElements *= arrayTy->getNumElements();
332 // FIXME: isPrimitiveType() == false for i16?
333 assert(elementTy->isSingleValueType() &&
334 "Non-primitive types are not handled");
336 // Compute the size of the array, in bytes.
337 uint64_t arraySize = (elementTy->getPrimitiveSizeInBits() >> 3)
340 decl += utostr(arraySize);
345 // handle string constants (assume ConstantArray means string)
347 if (gv->hasInitializer())
349 Constant *C = gv->getInitializer();
350 if (const ConstantArray *CA = dyn_cast<ConstantArray>(C))
354 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
356 if (i > 0) decl += ",";
358 decl += "0x" + utohexstr(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
366 // Note: this is currently the fall-through case and most likely generates
368 decl += getTypeName(gv->getType());
371 decl += gvsym->getName();
373 if (ArrayType::classof(gv->getType()) ||
374 PointerType::classof(gv->getType()))
380 OutStreamer.EmitRawText(Twine(decl));
382 OutStreamer.AddBlankLine();
385 void PTXAsmPrinter::EmitFunctionDeclaration() {
386 // The function label could have already been emitted if two symbols end up
387 // conflicting due to asm renaming. Detect this and emit an error.
388 if (!CurrentFnSym->isUndefined()) {
389 report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
390 "' label emitted multiple times to assembly file");
394 const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
395 const bool isKernel = MFI->isKernel();
398 std::string decl = isKernel ? ".entry" : ".func";
400 // Print return register
402 if (!isKernel && reg != PTX::NoRegister) {
403 decl += " (.reg ."; // FIXME: could it return in .param space?
404 decl += getRegisterTypeName(reg);
406 decl += getRegisterName(reg);
410 // Print function name
412 decl += CurrentFnSym->getName().str();
414 // Print parameter list
415 if (!MFI->argRegEmpty()) {
419 for(PTXMachineFunctionInfo::reg_iterator
420 i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i;
423 assert(reg != PTX::NoRegister && "Not a valid register!");
427 decl += getRegisterTypeName(reg);
429 decl += PARAM_PREFIX;
430 decl += utostr(++cnt);
433 for (PTXMachineFunctionInfo::reg_iterator
434 i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i;
437 assert(reg != PTX::NoRegister && "Not a valid register!");
441 decl += getRegisterTypeName(reg);
443 decl += getRegisterName(reg);
449 OutStreamer.EmitRawText(Twine(decl));
453 printPredicateOperand(const MachineInstr *MI, raw_ostream &O) {
454 int i = MI->findFirstPredOperandIdx();
456 llvm_unreachable("missing predicate operand");
458 unsigned reg = MI->getOperand(i).getReg();
459 int predOp = MI->getOperand(i+1).getImm();
461 DEBUG(dbgs() << "predicate: (" << reg << ", " << predOp << ")\n");
463 if (reg != PTX::NoRegister) {
465 if (predOp == PTX::PRED_NEGATE)
467 O << getRegisterName(reg);
471 #include "PTXGenAsmWriter.inc"
473 // Force static initialization.
474 extern "C" void LLVMInitializePTXAsmPrinter() {
475 RegisterAsmPrinter<PTXAsmPrinter> X(ThePTX32Target);
476 RegisterAsmPrinter<PTXAsmPrinter> Y(ThePTX64Target);