5d7e4c3ff7987326169ca3afb866d301bac3782f
[oota-llvm.git] / lib / Target / PTX / PTXAsmPrinter.cpp
1 //===-- PTXAsmPrinter.cpp - PTX 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 PTX assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "ptx-asm-printer"
16
17 #include "PTX.h"
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/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSymbol.h"
31 #include "llvm/Target/Mangler.h"
32 #include "llvm/Target/TargetLoweringObjectFile.h"
33 #include "llvm/Target/TargetRegistry.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
39
40 using namespace llvm;
41
42 namespace {
43 class PTXAsmPrinter : public AsmPrinter {
44 public:
45   explicit PTXAsmPrinter(TargetMachine &TM, MCStreamer &Streamer)
46     : AsmPrinter(TM, Streamer) {}
47
48   const char *getPassName() const { return "PTX Assembly Printer"; }
49
50   bool doFinalization(Module &M);
51
52   virtual void EmitStartOfAsmFile(Module &M);
53
54   virtual bool runOnMachineFunction(MachineFunction &MF);
55
56   virtual void EmitFunctionBodyStart();
57   virtual void EmitFunctionBodyEnd() { OutStreamer.EmitRawText(Twine("}")); }
58
59   virtual void EmitInstruction(const MachineInstr *MI);
60
61   void printOperand(const MachineInstr *MI, int opNum, raw_ostream &OS);
62   void printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
63                        const char *Modifier = 0);
64   void printParamOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
65                          const char *Modifier = 0);
66   void printReturnOperand(const MachineInstr *MI, int opNum, raw_ostream &OS,
67                           const char *Modifier = 0); 
68   void printPredicateOperand(const MachineInstr *MI, raw_ostream &O);
69
70   // autogen'd.
71   void printInstruction(const MachineInstr *MI, raw_ostream &OS);
72   static const char *getRegisterName(unsigned RegNo);
73
74 private:
75   void EmitVariableDeclaration(const GlobalVariable *gv);
76   void EmitFunctionDeclaration();
77 }; // class PTXAsmPrinter
78 } // namespace
79
80 static const char PARAM_PREFIX[] = "__param_";
81 static const char RETURN_PREFIX[] = "__ret_";
82
83 static const char *getRegisterTypeName(unsigned RegNo) {
84 #define TEST_REGCLS(cls, clsstr)                \
85   if (PTX::cls ## RegisterClass->contains(RegNo)) return # clsstr;
86   TEST_REGCLS(RegPred, pred);
87   TEST_REGCLS(RegI16, b16);
88   TEST_REGCLS(RegI32, b32);
89   TEST_REGCLS(RegI64, b64);
90   TEST_REGCLS(RegF32, b32);
91   TEST_REGCLS(RegF64, b64);
92 #undef TEST_REGCLS
93
94   llvm_unreachable("Not in any register class!");
95   return NULL;
96 }
97
98 static const char *getStateSpaceName(unsigned addressSpace) {
99   switch (addressSpace) {
100   default: llvm_unreachable("Unknown state space");
101   case PTX::GLOBAL:    return "global";
102   case PTX::CONSTANT:  return "const";
103   case PTX::LOCAL:     return "local";
104   case PTX::PARAMETER: return "param";
105   case PTX::SHARED:    return "shared";
106   }
107   return NULL;
108 }
109
110 static const char *getTypeName(const Type* type) {
111   while (true) {
112     switch (type->getTypeID()) {
113       default: llvm_unreachable("Unknown type");
114       case Type::FloatTyID: return ".f32";
115       case Type::DoubleTyID: return ".f64";
116       case Type::IntegerTyID:
117         switch (type->getPrimitiveSizeInBits()) {
118           default: llvm_unreachable("Unknown integer bit-width");
119           case 16: return ".u16";
120           case 32: return ".u32";
121           case 64: return ".u64";
122         }
123       case Type::ArrayTyID:
124       case Type::PointerTyID:
125         type = dyn_cast<const SequentialType>(type)->getElementType();
126         break;
127     }
128   }
129   return NULL;
130 }
131
132 bool PTXAsmPrinter::doFinalization(Module &M) {
133   // XXX Temproarily remove global variables so that doFinalization() will not
134   // emit them again (global variables are emitted at beginning).
135
136   Module::GlobalListType &global_list = M.getGlobalList();
137   int i, n = global_list.size();
138   GlobalVariable **gv_array = new GlobalVariable* [n];
139
140   // first, back-up GlobalVariable in gv_array
141   i = 0;
142   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
143        I != E; ++I)
144     gv_array[i++] = &*I;
145
146   // second, empty global_list
147   while (!global_list.empty())
148     global_list.remove(global_list.begin());
149
150   // call doFinalization
151   bool ret = AsmPrinter::doFinalization(M);
152
153   // now we restore global variables
154   for (i = 0; i < n; i ++)
155     global_list.insert(global_list.end(), gv_array[i]);
156
157   delete[] gv_array;
158   return ret;
159 }
160
161 void PTXAsmPrinter::EmitStartOfAsmFile(Module &M)
162 {
163   const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
164
165   OutStreamer.EmitRawText(Twine("\t.version " + ST.getPTXVersionString()));
166   OutStreamer.EmitRawText(Twine("\t.target " + ST.getTargetString() +
167                                 (ST.supportsDouble() ? ""
168                                                      : ", map_f64_to_f32")));
169   // .address_size directive is optional, but it must immediately follow
170   // the .target directive if present within a module
171   if (ST.supportsPTX23()) {
172     std::string addrSize = ST.is64Bit() ? "64" : "32";
173     OutStreamer.EmitRawText(Twine("\t.address_size " + addrSize));
174   }
175
176   OutStreamer.AddBlankLine();
177
178   // declare global variables
179   for (Module::const_global_iterator i = M.global_begin(), e = M.global_end();
180        i != e; ++i)
181     EmitVariableDeclaration(i);
182 }
183
184 bool PTXAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
185   SetupMachineFunction(MF);
186   EmitFunctionDeclaration();
187   EmitFunctionBody();
188   return false;
189 }
190
191 void PTXAsmPrinter::EmitFunctionBodyStart() {
192   OutStreamer.EmitRawText(Twine("{"));
193
194   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
195
196   // Print local variable definition
197   for (PTXMachineFunctionInfo::reg_iterator
198        i = MFI->localVarRegBegin(), e = MFI->localVarRegEnd(); i != e; ++ i) {
199     unsigned reg = *i;
200
201     std::string def = "\t.reg .";
202     def += getRegisterTypeName(reg);
203     def += ' ';
204     def += getRegisterName(reg);
205     def += ';';
206     OutStreamer.EmitRawText(Twine(def));
207   }
208
209   const MachineFrameInfo* FrameInfo = MF->getFrameInfo();
210   DEBUG(dbgs() << "Have " << FrameInfo->getNumObjects()
211                << " frame object(s)\n");
212   for (unsigned i = 0, e = FrameInfo->getNumObjects(); i != e; ++i) {
213     DEBUG(dbgs() << "Size of object: " << FrameInfo->getObjectSize(i) << "\n");
214     if (FrameInfo->getObjectSize(i) > 0) {
215       std::string def = "\t.reg .b";
216       def += utostr(FrameInfo->getObjectSize(i)*8); // Convert to bits
217       def += " s";
218       def += utostr(i);
219       def += ";";
220       OutStreamer.EmitRawText(Twine(def));
221     }
222   }
223 }
224
225 void PTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
226   std::string str;
227   str.reserve(64);
228
229   raw_string_ostream OS(str);
230
231   // Emit predicate
232   printPredicateOperand(MI, OS);
233
234   // Write instruction to str
235   printInstruction(MI, OS);
236   OS << ';';
237   OS.flush();
238
239   StringRef strref = StringRef(str);
240   OutStreamer.EmitRawText(strref);
241 }
242
243 void PTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
244                                  raw_ostream &OS) {
245   const MachineOperand &MO = MI->getOperand(opNum);
246
247   switch (MO.getType()) {
248     default:
249       llvm_unreachable("<unknown operand type>");
250       break;
251     case MachineOperand::MO_GlobalAddress:
252       OS << *Mang->getSymbol(MO.getGlobal());
253       break;
254     case MachineOperand::MO_Immediate:
255       OS << (long) MO.getImm();
256       break;
257     case MachineOperand::MO_MachineBasicBlock:
258       OS << *MO.getMBB()->getSymbol();
259       break;
260     case MachineOperand::MO_Register:
261       OS << getRegisterName(MO.getReg());
262       break;
263     case MachineOperand::MO_FPImmediate:
264       APInt constFP = MO.getFPImm()->getValueAPF().bitcastToAPInt();
265       bool  isFloat = MO.getFPImm()->getType()->getTypeID() == Type::FloatTyID;
266       // Emit 0F for 32-bit floats and 0D for 64-bit doubles.
267       if (isFloat) {
268         OS << "0F";
269       }
270       else {
271         OS << "0D";
272       }
273       // Emit the encoded floating-point value.
274       if (constFP.getZExtValue() > 0) {
275         OS << constFP.toString(16, false);
276       }
277       else {
278         OS << "00000000";
279         // If We have a double-precision zero, pad to 8-bytes.
280         if (!isFloat) {
281           OS << "00000000";
282         }
283       }
284       break;
285   }
286 }
287
288 void PTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
289                                     raw_ostream &OS, const char *Modifier) {
290   printOperand(MI, opNum, OS);
291
292   if (MI->getOperand(opNum+1).isImm() && MI->getOperand(opNum+1).getImm() == 0)
293     return; // don't print "+0"
294
295   OS << "+";
296   printOperand(MI, opNum+1, OS);
297 }
298
299 void PTXAsmPrinter::printParamOperand(const MachineInstr *MI, int opNum,
300                                       raw_ostream &OS, const char *Modifier) {
301   OS << PARAM_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
302 }
303
304 void PTXAsmPrinter::printReturnOperand(const MachineInstr *MI, int opNum,
305                                        raw_ostream &OS, const char *Modifier) {
306   OS << RETURN_PREFIX << (int) MI->getOperand(opNum).getImm() + 1;
307 }
308
309 void PTXAsmPrinter::EmitVariableDeclaration(const GlobalVariable *gv) {
310   // Check to see if this is a special global used by LLVM, if so, emit it.
311   if (EmitSpecialLLVMGlobal(gv))
312     return;
313
314   MCSymbol *gvsym = Mang->getSymbol(gv);
315
316   assert(gvsym->isUndefined() && "Cannot define a symbol twice!");
317
318   std::string decl;
319
320   // check if it is defined in some other translation unit
321   if (gv->isDeclaration())
322     decl += ".extern ";
323
324   // state space: e.g., .global
325   decl += ".";
326   decl += getStateSpaceName(gv->getType()->getAddressSpace());
327   decl += " ";
328
329   // alignment (optional)
330   unsigned alignment = gv->getAlignment();
331   if (alignment != 0) {
332     decl += ".align ";
333     decl += utostr(Log2_32(gv->getAlignment()));
334     decl += " ";
335   }
336
337
338   if (PointerType::classof(gv->getType())) {
339     const PointerType* pointerTy = dyn_cast<const PointerType>(gv->getType());
340     const Type* elementTy = pointerTy->getElementType();
341
342     decl += ".b8 ";
343     decl += gvsym->getName();
344     decl += "[";
345
346     if (elementTy->isArrayTy())
347     {
348       assert(elementTy->isArrayTy() && "Only pointers to arrays are supported");
349
350       const ArrayType* arrayTy = dyn_cast<const ArrayType>(elementTy);
351       elementTy = arrayTy->getElementType();
352
353       unsigned numElements = arrayTy->getNumElements();
354
355       while (elementTy->isArrayTy()) {
356
357         arrayTy = dyn_cast<const ArrayType>(elementTy);
358         elementTy = arrayTy->getElementType();
359
360         numElements *= arrayTy->getNumElements();
361       }
362
363       // FIXME: isPrimitiveType() == false for i16?
364       assert(elementTy->isSingleValueType() &&
365               "Non-primitive types are not handled");
366
367       // Compute the size of the array, in bytes.
368       uint64_t arraySize = (elementTy->getPrimitiveSizeInBits() >> 3)
369                         * numElements;
370
371       decl += utostr(arraySize);
372     }
373
374     decl += "]";
375
376     // handle string constants (assume ConstantArray means string)
377
378     if (gv->hasInitializer())
379     {
380       const Constant *C = gv->getInitializer();  
381       if (const ConstantArray *CA = dyn_cast<ConstantArray>(C))
382       {
383         decl += " = {";
384
385         for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
386         {
387           if (i > 0)   decl += ",";
388
389           decl += "0x" +
390                 utohexstr(cast<ConstantInt>(CA->getOperand(i))->getZExtValue());
391         }
392
393         decl += "}";
394       }
395     }
396   }
397   else {
398     // Note: this is currently the fall-through case and most likely generates
399     //       incorrect code.
400     decl += getTypeName(gv->getType());
401     decl += " ";
402
403     decl += gvsym->getName();
404
405     if (ArrayType::classof(gv->getType()) ||
406         PointerType::classof(gv->getType()))
407       decl += "[]";
408   }
409
410   decl += ";";
411
412   OutStreamer.EmitRawText(Twine(decl));
413
414   OutStreamer.AddBlankLine();
415 }
416
417 void PTXAsmPrinter::EmitFunctionDeclaration() {
418   // The function label could have already been emitted if two symbols end up
419   // conflicting due to asm renaming.  Detect this and emit an error.
420   if (!CurrentFnSym->isUndefined()) {
421     report_fatal_error("'" + Twine(CurrentFnSym->getName()) +
422                        "' label emitted multiple times to assembly file");
423     return;
424   }
425
426   const PTXMachineFunctionInfo *MFI = MF->getInfo<PTXMachineFunctionInfo>();
427   const bool isKernel = MFI->isKernel();
428   const PTXSubtarget& ST = TM.getSubtarget<PTXSubtarget>();
429
430   std::string decl = isKernel ? ".entry" : ".func";
431
432   unsigned cnt = 0;
433
434   if (!isKernel) {
435     decl += " (";
436     for (PTXMachineFunctionInfo::ret_iterator
437          i = MFI->retRegBegin(), e = MFI->retRegEnd(), b = i;
438          i != e; ++i) {
439       if (i != b) {
440         decl += ", ";
441       }
442       decl += ".reg .";
443       decl += getRegisterTypeName(*i);
444       decl += " ";
445       decl += getRegisterName(*i);
446     }
447     decl += ")";
448   }
449
450   // Print function name
451   decl += " ";
452   decl += CurrentFnSym->getName().str();
453
454   decl += " (";
455
456   cnt = 0;
457
458   // Print parameters
459   for (PTXMachineFunctionInfo::reg_iterator
460        i = MFI->argRegBegin(), e = MFI->argRegEnd(), b = i;
461        i != e; ++i) {
462     if (i != b) {
463       decl += ", ";
464     }
465     if (isKernel || ST.getShaderModel() >= PTXSubtarget::PTX_SM_2_0) {
466       decl += ".param .b";
467       decl += utostr(*i);
468       decl += " ";
469       decl += PARAM_PREFIX;
470       decl += utostr(++cnt);
471     } else {
472       decl += ".reg .";
473       decl += getRegisterTypeName(*i);
474       decl += " ";
475       decl += getRegisterName(*i);
476     }
477   }
478   decl += ")";
479
480   OutStreamer.EmitRawText(Twine(decl));
481 }
482
483 void PTXAsmPrinter::
484 printPredicateOperand(const MachineInstr *MI, raw_ostream &O) {
485   int i = MI->findFirstPredOperandIdx();
486   if (i == -1)
487     llvm_unreachable("missing predicate operand");
488
489   unsigned reg = MI->getOperand(i).getReg();
490   int predOp = MI->getOperand(i+1).getImm();
491
492   DEBUG(dbgs() << "predicate: (" << reg << ", " << predOp << ")\n");
493
494   if (reg != PTX::NoRegister) {
495     O << '@';
496     if (predOp == PTX::PRED_NEGATE)
497       O << '!';
498     O << getRegisterName(reg);
499   }
500 }
501
502 #include "PTXGenAsmWriter.inc"
503
504 // Force static initialization.
505 extern "C" void LLVMInitializePTXAsmPrinter() {
506   RegisterAsmPrinter<PTXAsmPrinter> X(ThePTX32Target);
507   RegisterAsmPrinter<PTXAsmPrinter> Y(ThePTX64Target);
508 }