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