[NVPTX] Emits "generic()" depending on the original address space
[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 LLVM_LIB_TARGET_NVPTX_NVPTXASMPRINTER_H
16 #define LLVM_LIB_TARGET_NVPTX_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 namespace llvm {
43
44 class LineReader {
45 private:
46   unsigned theCurLine;
47   std::ifstream fstr;
48   char buff[512];
49   std::string theFileName;
50   SmallVector<unsigned, 32> lineOffset;
51 public:
52   LineReader(std::string filename) {
53     theCurLine = 0;
54     fstr.open(filename.c_str());
55     theFileName = filename;
56   }
57   std::string fileName() { return theFileName; }
58   ~LineReader() { fstr.close(); }
59   std::string readLine(unsigned line);
60 };
61
62 class LLVM_LIBRARY_VISIBILITY NVPTXAsmPrinter : public AsmPrinter {
63
64   class AggBuffer {
65     // Used to buffer the emitted string for initializing global
66     // aggregates.
67     //
68     // Normally an aggregate (array, vector or structure) is emitted
69     // as a u8[]. However, if one element/field of the aggregate
70     // is a non-NULL address, then the aggregate is emitted as u32[]
71     // or u64[].
72     //
73     // We first layout the aggregate in 'buffer' in bytes, except for
74     // those symbol addresses. For the i-th symbol address in the
75     //aggregate, its corresponding 4-byte or 8-byte elements in 'buffer'
76     // are filled with 0s. symbolPosInBuffer[i-1] records its position
77     // in 'buffer', and Symbols[i-1] records the Value*.
78     //
79     // Once we have this AggBuffer setup, we can choose how to print
80     // it out.
81   public:
82     unsigned numSymbols;   // number of symbol addresses
83
84   private:
85     const unsigned size;   // size of the buffer in bytes
86     std::vector<unsigned char> buffer; // the buffer
87     SmallVector<unsigned, 4> symbolPosInBuffer;
88     SmallVector<const Value *, 4> Symbols;
89     // SymbolsBeforeStripping[i] is the original form of Symbols[i] before
90     // stripping pointer casts, i.e.,
91     // Symbols[i] == SymbolsBeforeStripping[i]->stripPointerCasts().
92     //
93     // We need to keep these values because AggBuffer::print decides whether to
94     // emit a "generic()" cast for Symbols[i] depending on the address space of
95     // SymbolsBeforeStripping[i].
96     SmallVector<const Value *, 4> SymbolsBeforeStripping;
97     unsigned curpos;
98     raw_ostream &O;
99     NVPTXAsmPrinter &AP;
100     bool EmitGeneric;
101
102   public:
103     AggBuffer(unsigned size, raw_ostream &O, NVPTXAsmPrinter &AP)
104         : size(size), buffer(size), O(O), AP(AP) {
105       curpos = 0;
106       numSymbols = 0;
107       EmitGeneric = AP.EmitGeneric;
108     }
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, const Value *GVarBeforeStripping) {
131       symbolPosInBuffer.push_back(curpos);
132       Symbols.push_back(GVar);
133       SymbolsBeforeStripping.push_back(GVarBeforeStripping);
134       numSymbols++;
135     }
136     void print() {
137       if (numSymbols == 0) {
138         // print out in bytes
139         for (unsigned i = 0; i < size; i++) {
140           if (i)
141             O << ", ";
142           O << (unsigned int) buffer[i];
143         }
144       } else {
145         // print out in 4-bytes or 8-bytes
146         unsigned int pos = 0;
147         unsigned int nSym = 0;
148         unsigned int nextSymbolPos = symbolPosInBuffer[nSym];
149         unsigned int nBytes = 4;
150         if (static_cast<const NVPTXTargetMachine &>(AP.TM).is64Bit())
151           nBytes = 8;
152         for (pos = 0; pos < size; pos += nBytes) {
153           if (pos)
154             O << ", ";
155           if (pos == nextSymbolPos) {
156             const Value *v = Symbols[nSym];
157             const Value *v0 = SymbolsBeforeStripping[nSym];
158             if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
159               MCSymbol *Name = AP.getSymbol(GVar);
160               PointerType *PTy = dyn_cast<PointerType>(v0->getType());
161               bool IsNonGenericPointer = false; // Is v0 a non-generic pointer?
162               if (PTy && PTy->getAddressSpace() != 0) {
163                 IsNonGenericPointer = true;
164               }
165               if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
166                 O << "generic(";
167                 O << *Name;
168                 O << ")";
169               } else {
170                 O << *Name;
171               }
172             } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(v)) {
173               O << *AP.lowerConstant(Cexpr);
174             } else
175               llvm_unreachable("symbol type unknown");
176             nSym++;
177             if (nSym >= numSymbols)
178               nextSymbolPos = size + 1;
179             else
180               nextSymbolPos = symbolPosInBuffer[nSym];
181           } else if (nBytes == 4)
182             O << *(unsigned int *)(&buffer[pos]);
183           else
184             O << *(unsigned long long *)(&buffer[pos]);
185         }
186       }
187     }
188   };
189
190   friend class AggBuffer;
191
192   void emitSrcInText(StringRef filename, unsigned line);
193
194 private:
195   const char *getPassName() const override { return "NVPTX Assembly Printer"; }
196
197   const Function *F;
198   std::string CurrentFnName;
199
200   void EmitBasicBlockStart(const MachineBasicBlock &MBB) const override;
201   void EmitFunctionEntryLabel() override;
202   void EmitFunctionBodyStart() override;
203   void EmitFunctionBodyEnd() override;
204   void emitImplicitDef(const MachineInstr *MI) const override;
205
206   void EmitInstruction(const MachineInstr *) override;
207   void lowerToMCInst(const MachineInstr *MI, MCInst &OutMI);
208   bool lowerOperand(const MachineOperand &MO, MCOperand &MCOp);
209   MCOperand GetSymbolRef(const MCSymbol *Symbol);
210   unsigned encodeVirtualRegister(unsigned Reg);
211
212   void EmitAlignment(unsigned NumBits, const GlobalValue *GV = nullptr) const {}
213
214   void printVecModifiedImmediate(const MachineOperand &MO, const char *Modifier,
215                                  raw_ostream &O);
216   void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
217                        const char *Modifier = nullptr);
218   void printImplicitDef(const MachineInstr *MI, raw_ostream &O) const;
219   void printModuleLevelGV(const GlobalVariable *GVar, raw_ostream &O,
220                           bool = false);
221   void printParamName(int paramIndex, raw_ostream &O);
222   void printParamName(Function::const_arg_iterator I, int paramIndex,
223                       raw_ostream &O);
224   void emitGlobals(const Module &M);
225   void emitHeader(Module &M, raw_ostream &O, const NVPTXSubtarget &STI);
226   void emitKernelFunctionDirectives(const Function &F, raw_ostream &O) const;
227   void emitVirtualRegister(unsigned int vr, raw_ostream &);
228   void emitFunctionExternParamList(const MachineFunction &MF);
229   void emitFunctionParamList(const Function *, raw_ostream &O);
230   void emitFunctionParamList(const MachineFunction &MF, raw_ostream &O);
231   void setAndEmitFunctionVirtualRegisters(const MachineFunction &MF);
232   void emitFunctionTempData(const MachineFunction &MF, unsigned &FrameSize);
233   bool isImageType(const Type *Ty);
234   void printReturnValStr(const Function *, raw_ostream &O);
235   void printReturnValStr(const MachineFunction &MF, raw_ostream &O);
236   bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
237                        unsigned AsmVariant, const char *ExtraCode,
238                        raw_ostream &) override;
239   void printOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
240                     const char *Modifier = nullptr);
241   bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
242                              unsigned AsmVariant, const char *ExtraCode,
243                              raw_ostream &) override;
244 protected:
245   bool doInitialization(Module &M) override;
246   bool doFinalization(Module &M) override;
247
248 private:
249   std::string CurrentBankselLabelInBasicBlock;
250
251   bool GlobalsEmitted;
252   
253   // This is specific per MachineFunction.
254   const MachineRegisterInfo *MRI;
255   // The contents are specific for each
256   // MachineFunction. But the size of the
257   // array is not.
258   typedef DenseMap<unsigned, unsigned> VRegMap;
259   typedef DenseMap<const TargetRegisterClass *, VRegMap> VRegRCMap;
260   VRegRCMap VRegMapping;
261
262   // Cache the subtarget here.
263   const NVPTXSubtarget *nvptxSubtarget;
264
265   // Build the map between type name and ID based on module's type
266   // symbol table.
267   std::map<const Type *, std::string> TypeNameMap;
268
269   // List of variables demoted to a function scope.
270   std::map<const Function *, std::vector<const GlobalVariable *> > localDecls;
271
272   // To record filename to ID mapping
273   std::map<std::string, unsigned> filenameMap;
274   void recordAndEmitFilenames(Module &);
275
276   void emitPTXGlobalVariable(const GlobalVariable *GVar, raw_ostream &O);
277   void emitPTXAddressSpace(unsigned int AddressSpace, raw_ostream &O) const;
278   std::string getPTXFundamentalTypeStr(const Type *Ty, bool = true) const;
279   void printScalarConstant(const Constant *CPV, raw_ostream &O);
280   void printFPConstant(const ConstantFP *Fp, raw_ostream &O);
281   void bufferLEByte(const Constant *CPV, int Bytes, AggBuffer *aggBuffer);
282   void bufferAggregateConstant(const Constant *CV, AggBuffer *aggBuffer);
283
284   void printOperandProper(const MachineOperand &MO);
285
286   void emitLinkageDirective(const GlobalValue *V, raw_ostream &O);
287   void emitDeclarations(const Module &, raw_ostream &O);
288   void emitDeclaration(const Function *, raw_ostream &O);
289
290   static const char *getRegisterName(unsigned RegNo);
291   void emitDemotedVars(const Function *, raw_ostream &);
292
293   bool lowerImageHandleOperand(const MachineInstr *MI, unsigned OpNo,
294                                MCOperand &MCOp);
295   void lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp);
296
297   bool isLoopHeaderOfNoUnroll(const MachineBasicBlock &MBB) const;
298
299   LineReader *reader;
300   LineReader *getReader(std::string);
301
302   // Used to control the need to emit .generic() in the initializer of
303   // module scope variables.
304   // Although ptx supports the hybrid mode like the following,
305   //    .global .u32 a;
306   //    .global .u32 b;
307   //    .global .u32 addr[] = {a, generic(b)}
308   // we have difficulty representing the difference in the NVVM IR.
309   //
310   // Since the address value should always be generic in CUDA C and always
311   // be specific in OpenCL, we use this simple control here.
312   //
313   bool EmitGeneric;
314
315 public:
316   NVPTXAsmPrinter(TargetMachine &TM, std::unique_ptr<MCStreamer> Streamer)
317       : AsmPrinter(TM, std::move(Streamer)),
318         EmitGeneric(static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() ==
319                     NVPTX::CUDA) {
320     CurrentBankselLabelInBasicBlock = "";
321     reader = nullptr;
322   }
323
324   ~NVPTXAsmPrinter() {
325     if (!reader)
326       delete reader;
327   }
328
329   bool runOnMachineFunction(MachineFunction &F) override {
330     nvptxSubtarget = &F.getSubtarget<NVPTXSubtarget>();
331     return AsmPrinter::runOnMachineFunction(F);
332   }
333   void getAnalysisUsage(AnalysisUsage &AU) const override {
334     AU.addRequired<MachineLoopInfo>();
335     AsmPrinter::getAnalysisUsage(AU);
336   }
337
338   bool ignoreLoc(const MachineInstr &);
339
340   std::string getVirtualRegisterName(unsigned) const;
341
342   DebugLoc prevDebugLoc;
343   void emitLineNumberAsDotLoc(const MachineInstr &);
344 };
345 } // end of namespace
346
347 #endif