abce85c39d74288ea0dd51f2500c7d5743b1b5a9
[oota-llvm.git] / lib / Target / NVPTX / NVPTXAsmPrinter.h
1 //===-- NVPTXAsmPrinter.h - NVPTX 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 NVPTX assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef NVPTXASMPRINTER_H
16 #define NVPTXASMPRINTER_H
17
18 #include "NVPTX.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"
31 #include <fstream>
32
33 // The ptx syntax and format is very different from that usually seem in a .s
34 // file,
35 // therefore we are not able to use the MCAsmStreamer interface here.
36 //
37 // We are handcrafting the output method here.
38 //
39 // A better approach is to clone the MCAsmStreamer to a MCPTXAsmStreamer
40 // (subclass of MCStreamer).
41
42 // This is defined in AsmPrinter.cpp.
43 // Used to process the constant expressions in initializers.
44 namespace nvptx {
45 const llvm::MCExpr *
46 LowerConstant(const llvm::Constant *CV, llvm::AsmPrinter &AP);
47 }
48
49 namespace llvm {
50
51 class LineReader {
52 private:
53   unsigned theCurLine;
54   std::ifstream fstr;
55   char buff[512];
56   std::string theFileName;
57   SmallVector<unsigned, 32> lineOffset;
58 public:
59   LineReader(std::string filename) {
60     theCurLine = 0;
61     fstr.open(filename.c_str());
62     theFileName = filename;
63   }
64   std::string fileName() { return theFileName; }
65   ~LineReader() { fstr.close(); }
66   std::string readLine(unsigned line);
67 };
68
69 class LLVM_LIBRARY_VISIBILITY NVPTXAsmPrinter : public AsmPrinter {
70
71   class AggBuffer {
72     // Used to buffer the emitted string for initializing global
73     // aggregates.
74     //
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[]
78     // or u64[].
79     //
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*.
85     //
86     // Once we have this AggBuffer setup, we can choose how to print
87     // it out.
88   public:
89     unsigned size;         // size of the buffer in bytes
90     unsigned char *buffer; // the buffer
91     unsigned numSymbols;   // number of symbol addresses
92     SmallVector<unsigned, 4> symbolPosInBuffer;
93     SmallVector<const Value *, 4> Symbols;
94
95   private:
96     unsigned curpos;
97     raw_ostream &O;
98     NVPTXAsmPrinter &AP;
99
100   public:
101     AggBuffer(unsigned _size, raw_ostream &_O, NVPTXAsmPrinter &_AP)
102         : O(_O), AP(_AP) {
103       buffer = new unsigned char[_size];
104       size = _size;
105       curpos = 0;
106       numSymbols = 0;
107     }
108     ~AggBuffer() { delete[] buffer; }
109     unsigned addBytes(unsigned char *Ptr, int Num, int Bytes) {
110       assert((curpos + Num) <= size);
111       assert((curpos + Bytes) <= size);
112       for (int i = 0; i < Num; ++i) {
113         buffer[curpos] = Ptr[i];
114         curpos++;
115       }
116       for (int i = Num; i < Bytes; ++i) {
117         buffer[curpos] = 0;
118         curpos++;
119       }
120       return curpos;
121     }
122     unsigned addZeros(int Num) {
123       assert((curpos + Num) <= size);
124       for (int i = 0; i < Num; ++i) {
125         buffer[curpos] = 0;
126         curpos++;
127       }
128       return curpos;
129     }
130     void addSymbol(const Value *GVar) {
131       symbolPosInBuffer.push_back(curpos);
132       Symbols.push_back(GVar);
133       numSymbols++;
134     }
135     void print() {
136       if (numSymbols == 0) {
137         // print out in bytes
138         for (unsigned i = 0; i < size; i++) {
139           if (i)
140             O << ", ";
141           O << (unsigned int) buffer[i];
142         }
143       } else {
144         // print out in 4-bytes or 8-bytes
145         unsigned int pos = 0;
146         unsigned int nSym = 0;
147         unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
148         unsigned int nBytes = 4;
149         if (AP.nvptxSubtarget.is64Bit())
150           nBytes = 8;
151         for (pos = 0; pos < size; pos += nBytes) {
152           if (pos)
153             O << ", ";
154           if (pos == nextSymbolPos) {
155             const Value *v = Symbols[nSym];
156             if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
157               MCSymbol *Name = AP.getSymbol(GVar);
158               O << *Name;
159             } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(v)) {
160               O << *nvptx::LowerConstant(Cexpr, AP);
161             } else
162               llvm_unreachable("symbol type unknown");
163             nSym++;
164             if (nSym >= numSymbols)
165               nextSymbolPos = size + 1;
166             else
167               nextSymbolPos = symbolPosInBuffer[nSym];
168           } else if (nBytes == 4)
169             O << *(unsigned int *)(buffer + pos);
170           else
171             O << *(unsigned long long *)(buffer + pos);
172         }
173       }
174     }
175   };
176
177   friend class AggBuffer;
178
179   virtual void emitSrcInText(StringRef filename, unsigned line);
180
181 private:
182   virtual const char *getPassName() const { return "NVPTX Assembly Printer"; }
183
184   const Function *F;
185   std::string CurrentFnName;
186
187   void EmitFunctionEntryLabel();
188   void EmitFunctionBodyStart();
189   void EmitFunctionBodyEnd();
190   void emitImplicitDef(const MachineInstr *MI) const;
191
192   void EmitInstruction(const MachineInstr *);
193   void lowerToMCInst(const MachineInstr *MI, MCInst &OutMI);
194   bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp);
195   MCOperand GetSymbolRef(const MachineOperand &MO, const MCSymbol *Symbol);
196   unsigned encodeVirtualRegister(unsigned Reg);
197
198   void EmitAlignment(unsigned NumBits, const GlobalValue *GV = 0) const {}
199
200   void printVecModifiedImmediate(const MachineOperand &MO, const char *Modifier,
201                                  raw_ostream &O);
202   void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
203                        const char *Modifier = 0);
204   void printImplicitDef(const MachineInstr *MI, raw_ostream &O) const;
205   void printModuleLevelGV(const GlobalVariable *GVar, raw_ostream &O,
206                           bool = false);
207   void printParamName(int paramIndex, raw_ostream &O);
208   void printParamName(Function::const_arg_iterator I, int paramIndex,
209                       raw_ostream &O);
210   void emitGlobals(const Module &M);
211   void emitHeader(Module &M, raw_ostream &O);
212   void emitKernelFunctionDirectives(const Function &F, raw_ostream &O) const;
213   void emitVirtualRegister(unsigned int vr, raw_ostream &);
214   void emitFunctionExternParamList(const MachineFunction &MF);
215   void emitFunctionParamList(const Function *, raw_ostream &O);
216   void emitFunctionParamList(const MachineFunction &MF, raw_ostream &O);
217   void setAndEmitFunctionVirtualRegisters(const MachineFunction &MF);
218   void emitFunctionTempData(const MachineFunction &MF, unsigned &FrameSize);
219   bool isImageType(const Type *Ty);
220   void printReturnValStr(const Function *, raw_ostream &O);
221   void printReturnValStr(const MachineFunction &MF, raw_ostream &O);
222   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
223                        unsigned AsmVariant, const char *ExtraCode,
224                        raw_ostream &);
225   void printOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
226                     const char *Modifier = 0);
227   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
228                              unsigned AsmVariant, const char *ExtraCode,
229                              raw_ostream &);
230 protected:
231   bool doInitialization(Module &M);
232   bool doFinalization(Module &M);
233
234 private:
235   std::string CurrentBankselLabelInBasicBlock;
236
237   bool GlobalsEmitted;
238   
239   // This is specific per MachineFunction.
240   const MachineRegisterInfo *MRI;
241   // The contents are specific for each
242   // MachineFunction. But the size of the
243   // array is not.
244   typedef DenseMap<unsigned, unsigned> VRegMap;
245   typedef DenseMap<const TargetRegisterClass *, VRegMap> VRegRCMap;
246   VRegRCMap VRegMapping;
247   // cache the subtarget here.
248   const NVPTXSubtarget &nvptxSubtarget;
249   // Build the map between type name and ID based on module's type
250   // symbol table.
251   std::map<const Type *, std::string> TypeNameMap;
252
253   // List of variables demoted to a function scope.
254   std::map<const Function *, std::vector<const GlobalVariable *> > localDecls;
255
256   // To record filename to ID mapping
257   std::map<std::string, unsigned> filenameMap;
258   void recordAndEmitFilenames(Module &);
259
260   void emitPTXGlobalVariable(const GlobalVariable *GVar, raw_ostream &O);
261   void emitPTXAddressSpace(unsigned int AddressSpace, raw_ostream &O) const;
262   std::string getPTXFundamentalTypeStr(const Type *Ty, bool = true) const;
263   void printScalarConstant(const Constant *CPV, raw_ostream &O);
264   void printFPConstant(const ConstantFP *Fp, raw_ostream &O);
265   void bufferLEByte(const Constant *CPV, int Bytes, AggBuffer *aggBuffer);
266   void bufferAggregateConstant(const Constant *CV, AggBuffer *aggBuffer);
267
268   void printOperandProper(const MachineOperand &MO);
269
270   void emitLinkageDirective(const GlobalValue *V, raw_ostream &O);
271   void emitDeclarations(const Module &, raw_ostream &O);
272   void emitDeclaration(const Function *, raw_ostream &O);
273
274   static const char *getRegisterName(unsigned RegNo);
275   void emitDemotedVars(const Function *, raw_ostream &);
276
277   LineReader *reader;
278   LineReader *getReader(std::string);
279
280   // Get the symbol name of the given global symbol.
281   //
282   // Cleans up the name so it's a valid in PTX assembly.
283   std::string getSymbolName(const GlobalValue *GV) const;
284 public:
285   NVPTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
286       : AsmPrinter(TM, Streamer),
287         nvptxSubtarget(TM.getSubtarget<NVPTXSubtarget>()) {
288     CurrentBankselLabelInBasicBlock = "";
289     reader = NULL;
290   }
291
292   ~NVPTXAsmPrinter() {
293     if (!reader)
294       delete reader;
295   }
296
297   bool ignoreLoc(const MachineInstr &);
298
299   std::string getVirtualRegisterName(unsigned) const;
300
301   DebugLoc prevDebugLoc;
302   void emitLineNumberAsDotLoc(const MachineInstr &);
303 };
304 } // end of namespace
305
306 #endif