1 //===-- NVPTXAsmPrinter.h - NVPTX 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 NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H
16 #define LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H
19 #include "NVPTXSubtarget.h"
20 #include "NVPTXTargetMachine.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/IR/Function.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCExpr.h"
27 #include "llvm/MC/MCSymbol.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/FormattedStream.h"
30 #include "llvm/Target/TargetMachine.h"
33 // The ptx syntax and format is very different from that usually seem in a .s
35 // therefore we are not able to use the MCAsmStreamer interface here.
37 // We are handcrafting the output method here.
39 // A better approach is to clone the MCAsmStreamer to a MCPTXAsmStreamer
40 // (subclass of MCStreamer).
42 // This is defined in AsmPrinter.cpp.
43 // Used to process the constant expressions in initializers.
46 LowerConstant(const llvm::Constant *CV, llvm::AsmPrinter &AP);
56 std::string theFileName;
57 SmallVector<unsigned, 32> lineOffset;
59 LineReader(std::string filename) {
61 fstr.open(filename.c_str());
62 theFileName = filename;
64 std::string fileName() { return theFileName; }
65 ~LineReader() { fstr.close(); }
66 std::string readLine(unsigned line);
69 class LLVM_LIBRARY_VISIBILITY NVPTXAsmPrinter : public AsmPrinter {
72 // Used to buffer the emitted string for initializing global
75 // Normally an aggregate (array, vector or structure) is emitted
76 // as a u8[]. However, if one element/field of the aggregate
77 // is a non-NULL address, then the aggregate is emitted as u32[]
80 // We first layout the aggregate in 'buffer' in bytes, except for
81 // those symbol addresses. For the i-th symbol address in the
82 //aggregate, its corresponding 4-byte or 8-byte elements in 'buffer'
83 // are filled with 0s. symbolPosInBuffer[i-1] records its position
84 // in 'buffer', and Symbols[i-1] records the Value*.
86 // Once we have this AggBuffer setup, we can choose how to print
89 unsigned numSymbols; // number of symbol addresses
92 const unsigned size; // size of the buffer in bytes
93 std::vector<unsigned char> buffer; // the buffer
94 SmallVector<unsigned, 4> symbolPosInBuffer;
95 SmallVector<const Value *, 4> Symbols;
102 AggBuffer(unsigned _size, raw_ostream &_O, NVPTXAsmPrinter &_AP)
103 : size(_size), buffer(_size), O(_O), AP(_AP) {
106 EmitGeneric = AP.EmitGeneric;
108 unsigned addBytes(unsigned char *Ptr, int Num, int Bytes) {
109 assert((curpos + Num) <= size);
110 assert((curpos + Bytes) <= size);
111 for (int i = 0; i < Num; ++i) {
112 buffer[curpos] = Ptr[i];
115 for (int i = Num; i < Bytes; ++i) {
121 unsigned addZeros(int Num) {
122 assert((curpos + Num) <= size);
123 for (int i = 0; i < Num; ++i) {
129 void addSymbol(const Value *GVar) {
130 symbolPosInBuffer.push_back(curpos);
131 Symbols.push_back(GVar);
135 if (numSymbols == 0) {
136 // print out in bytes
137 for (unsigned i = 0; i < size; i++) {
140 O << (unsigned int) buffer[i];
143 // print out in 4-bytes or 8-bytes
144 unsigned int pos = 0;
145 unsigned int nSym = 0;
146 unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
147 unsigned int nBytes = 4;
148 if (AP.nvptxSubtarget.is64Bit())
150 for (pos = 0; pos < size; pos += nBytes) {
153 if (pos == nextSymbolPos) {
154 const Value *v = Symbols[nSym];
155 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
156 MCSymbol *Name = AP.getSymbol(GVar);
157 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
158 bool IsNonGenericPointer = false;
159 if (PTy && PTy->getAddressSpace() != 0) {
160 IsNonGenericPointer = true;
162 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
169 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(v)) {
170 O << *nvptx::LowerConstant(Cexpr, AP);
172 llvm_unreachable("symbol type unknown");
174 if (nSym >= numSymbols)
175 nextSymbolPos = size + 1;
177 nextSymbolPos = symbolPosInBuffer[nSym];
178 } else if (nBytes == 4)
179 O << *(unsigned int *)(&buffer[pos]);
181 O << *(unsigned long long *)(&buffer[pos]);
187 friend class AggBuffer;
189 void emitSrcInText(StringRef filename, unsigned line);
192 const char *getPassName() const override { return "NVPTX Assembly Printer"; }
195 std::string CurrentFnName;
197 void EmitFunctionEntryLabel() override;
198 void EmitFunctionBodyStart() override;
199 void EmitFunctionBodyEnd() override;
200 void emitImplicitDef(const MachineInstr *MI) const override;
202 void EmitInstruction(const MachineInstr *) override;
203 void lowerToMCInst(const MachineInstr *MI, MCInst &OutMI);
204 bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp);
205 MCOperand GetSymbolRef(const MCSymbol *Symbol);
206 unsigned encodeVirtualRegister(unsigned Reg);
208 void EmitAlignment(unsigned NumBits, const GlobalValue *GV = nullptr) const {}
210 void printVecModifiedImmediate(const MachineOperand &MO, const char *Modifier,
212 void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
213 const char *Modifier = nullptr);
214 void printImplicitDef(const MachineInstr *MI, raw_ostream &O) const;
215 void printModuleLevelGV(const GlobalVariable *GVar, raw_ostream &O,
217 void printParamName(int paramIndex, raw_ostream &O);
218 void printParamName(Function::const_arg_iterator I, int paramIndex,
220 void emitGlobals(const Module &M);
221 void emitHeader(Module &M, raw_ostream &O);
222 void emitKernelFunctionDirectives(const Function &F, raw_ostream &O) const;
223 void emitVirtualRegister(unsigned int vr, raw_ostream &);
224 void emitFunctionExternParamList(const MachineFunction &MF);
225 void emitFunctionParamList(const Function *, raw_ostream &O);
226 void emitFunctionParamList(const MachineFunction &MF, raw_ostream &O);
227 void setAndEmitFunctionVirtualRegisters(const MachineFunction &MF);
228 void emitFunctionTempData(const MachineFunction &MF, unsigned &FrameSize);
229 bool isImageType(const Type *Ty);
230 void printReturnValStr(const Function *, raw_ostream &O);
231 void printReturnValStr(const MachineFunction &MF, raw_ostream &O);
232 bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
233 unsigned AsmVariant, const char *ExtraCode,
234 raw_ostream &) override;
235 void printOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
236 const char *Modifier = nullptr);
237 bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
238 unsigned AsmVariant, const char *ExtraCode,
239 raw_ostream &) override;
241 bool doInitialization(Module &M) override;
242 bool doFinalization(Module &M) override;
245 std::string CurrentBankselLabelInBasicBlock;
249 // This is specific per MachineFunction.
250 const MachineRegisterInfo *MRI;
251 // The contents are specific for each
252 // MachineFunction. But the size of the
254 typedef DenseMap<unsigned, unsigned> VRegMap;
255 typedef DenseMap<const TargetRegisterClass *, VRegMap> VRegRCMap;
256 VRegRCMap VRegMapping;
257 // cache the subtarget here.
258 const NVPTXSubtarget &nvptxSubtarget;
259 // Build the map between type name and ID based on module's type
261 std::map<const Type *, std::string> TypeNameMap;
263 // List of variables demoted to a function scope.
264 std::map<const Function *, std::vector<const GlobalVariable *> > localDecls;
266 // To record filename to ID mapping
267 std::map<std::string, unsigned> filenameMap;
268 void recordAndEmitFilenames(Module &);
270 void emitPTXGlobalVariable(const GlobalVariable *GVar, raw_ostream &O);
271 void emitPTXAddressSpace(unsigned int AddressSpace, raw_ostream &O) const;
272 std::string getPTXFundamentalTypeStr(const Type *Ty, bool = true) const;
273 void printScalarConstant(const Constant *CPV, raw_ostream &O);
274 void printFPConstant(const ConstantFP *Fp, raw_ostream &O);
275 void bufferLEByte(const Constant *CPV, int Bytes, AggBuffer *aggBuffer);
276 void bufferAggregateConstant(const Constant *CV, AggBuffer *aggBuffer);
278 void printOperandProper(const MachineOperand &MO);
280 void emitLinkageDirective(const GlobalValue *V, raw_ostream &O);
281 void emitDeclarations(const Module &, raw_ostream &O);
282 void emitDeclaration(const Function *, raw_ostream &O);
284 static const char *getRegisterName(unsigned RegNo);
285 void emitDemotedVars(const Function *, raw_ostream &);
287 bool lowerImageHandleOperand(const MachineInstr *MI, unsigned OpNo,
289 void lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp);
292 LineReader *getReader(std::string);
294 // Used to control the need to emit .generic() in the initializer of
295 // module scope variables.
296 // Although ptx supports the hybrid mode like the following,
299 // .global .u32 addr[] = {a, generic(b)}
300 // we have difficulty representing the difference in the NVVM IR.
302 // Since the address value should always be generic in CUDA C and always
303 // be specific in OpenCL, we use this simple control here.
308 NVPTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
309 : AsmPrinter(TM, Streamer),
310 nvptxSubtarget(TM.getSubtarget<NVPTXSubtarget>()) {
311 CurrentBankselLabelInBasicBlock = "";
313 EmitGeneric = (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA);
321 bool ignoreLoc(const MachineInstr &);
323 std::string getVirtualRegisterName(unsigned) const;
325 DebugLoc prevDebugLoc;
326 void emitLineNumberAsDotLoc(const MachineInstr &);
328 } // end of namespace