3f99d1d0e4afeac99b37abbbcc0702999f875a1d
[oota-llvm.git] / lib / Target / NVPTX / NVPTXAsmPrinter.cpp
1 //===-- NVPTXAsmPrinter.cpp - 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 #include "NVPTXAsmPrinter.h"
16 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
17 #include "NVPTX.h"
18 #include "NVPTXInstrInfo.h"
19 #include "NVPTXNumRegisters.h"
20 #include "NVPTXRegisterInfo.h"
21 #include "NVPTXTargetMachine.h"
22 #include "NVPTXUtilities.h"
23 #include "cl_common_defines.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TimeValue.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 #include <sstream>
48 using namespace llvm;
49
50
51 #include "NVPTXGenAsmWriter.inc"
52
53 bool RegAllocNilUsed = true;
54
55 #define DEPOTNAME "__local_depot"
56
57 static cl::opt<bool>
58 EmitLineNumbers("nvptx-emit-line-numbers",
59                 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
60                 cl::init(true));
61
62 namespace llvm  {
63 bool InterleaveSrcInPtx = false;
64 }
65
66 static cl::opt<bool, true>InterleaveSrc("nvptx-emit-src",
67                                         cl::ZeroOrMore,
68                        cl::desc("NVPTX Specific: Emit source line in ptx file"),
69                                         cl::location(llvm::InterleaveSrcInPtx));
70
71
72 namespace {
73 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
74 /// depends.
75 void DiscoverDependentGlobals(Value *V,
76                               DenseSet<GlobalVariable*> &Globals) {
77   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
78     Globals.insert(GV);
79   else {
80     if (User *U = dyn_cast<User>(V)) {
81       for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
82         DiscoverDependentGlobals(U->getOperand(i), Globals);
83       }
84     }
85   }
86 }
87
88 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
89 /// instances to be emitted, but only after any dependents have been added
90 /// first.
91 void VisitGlobalVariableForEmission(GlobalVariable *GV,
92                                     SmallVectorImpl<GlobalVariable*> &Order,
93                                     DenseSet<GlobalVariable*> &Visited,
94                                     DenseSet<GlobalVariable*> &Visiting) {
95   // Have we already visited this one?
96   if (Visited.count(GV)) return;
97
98   // Do we have a circular dependency?
99   if (Visiting.count(GV))
100     report_fatal_error("Circular dependency found in global variable set");
101
102   // Start visiting this global
103   Visiting.insert(GV);
104
105   // Make sure we visit all dependents first
106   DenseSet<GlobalVariable*> Others;
107   for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
108     DiscoverDependentGlobals(GV->getOperand(i), Others);
109   
110   for (DenseSet<GlobalVariable*>::iterator I = Others.begin(),
111        E = Others.end(); I != E; ++I)
112     VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
113
114   // Now we can visit ourself
115   Order.push_back(GV);
116   Visited.insert(GV);
117   Visiting.erase(GV);
118 }
119 }
120
121 // @TODO: This is a copy from AsmPrinter.cpp.  The function is static, so we
122 // cannot just link to the existing version.
123 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
124 ///
125 using namespace nvptx;
126 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
127   MCContext &Ctx = AP.OutContext;
128
129   if (CV->isNullValue() || isa<UndefValue>(CV))
130     return MCConstantExpr::Create(0, Ctx);
131
132   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
133     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
134
135   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
136     return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
137
138   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
139     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
140
141   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
142   if (CE == 0)
143     llvm_unreachable("Unknown constant value to lower!");
144
145
146   switch (CE->getOpcode()) {
147   default:
148     // If the code isn't optimized, there may be outstanding folding
149     // opportunities. Attempt to fold the expression using DataLayout as a
150     // last resort before giving up.
151     if (Constant *C =
152         ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
153       if (C != CE)
154         return LowerConstant(C, AP);
155
156     // Otherwise report the problem to the user.
157     {
158         std::string S;
159         raw_string_ostream OS(S);
160         OS << "Unsupported expression in static initializer: ";
161         WriteAsOperand(OS, CE, /*PrintType=*/false,
162                        !AP.MF ? 0 : AP.MF->getFunction()->getParent());
163         report_fatal_error(OS.str());
164     }
165   case Instruction::GetElementPtr: {
166     const DataLayout &TD = *AP.TM.getDataLayout();
167     // Generate a symbolic expression for the byte address
168     APInt OffsetAI(TD.getPointerSizeInBits(), 0);
169     cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
170
171     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
172     if (!OffsetAI)
173       return Base;
174
175     int64_t Offset = OffsetAI.getSExtValue();
176     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
177                                    Ctx);
178   }
179
180   case Instruction::Trunc:
181     // We emit the value and depend on the assembler to truncate the generated
182     // expression properly.  This is important for differences between
183     // blockaddress labels.  Since the two labels are in the same function, it
184     // is reasonable to treat their delta as a 32-bit value.
185     // FALL THROUGH.
186   case Instruction::BitCast:
187     return LowerConstant(CE->getOperand(0), AP);
188
189   case Instruction::IntToPtr: {
190     const DataLayout &TD = *AP.TM.getDataLayout();
191     // Handle casts to pointers by changing them into casts to the appropriate
192     // integer type.  This promotes constant folding and simplifies this code.
193     Constant *Op = CE->getOperand(0);
194     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
195                                       false/*ZExt*/);
196     return LowerConstant(Op, AP);
197   }
198
199   case Instruction::PtrToInt: {
200     const DataLayout &TD = *AP.TM.getDataLayout();
201     // Support only foldable casts to/from pointers that can be eliminated by
202     // changing the pointer to the appropriately sized integer type.
203     Constant *Op = CE->getOperand(0);
204     Type *Ty = CE->getType();
205
206     const MCExpr *OpExpr = LowerConstant(Op, AP);
207
208     // We can emit the pointer value into this slot if the slot is an
209     // integer slot equal to the size of the pointer.
210     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
211       return OpExpr;
212
213     // Otherwise the pointer is smaller than the resultant integer, mask off
214     // the high bits so we are sure to get a proper truncation if the input is
215     // a constant expr.
216     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
217     const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
218     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
219   }
220
221   // The MC library also has a right-shift operator, but it isn't consistently
222   // signed or unsigned between different targets.
223   case Instruction::Add:
224   case Instruction::Sub:
225   case Instruction::Mul:
226   case Instruction::SDiv:
227   case Instruction::SRem:
228   case Instruction::Shl:
229   case Instruction::And:
230   case Instruction::Or:
231   case Instruction::Xor: {
232     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
233     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
234     switch (CE->getOpcode()) {
235     default: llvm_unreachable("Unknown binary operator constant cast expr");
236     case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
237     case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
238     case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
239     case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
240     case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
241     case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
242     case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
243     case Instruction::Or:  return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
244     case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
245     }
246   }
247   }
248 }
249
250
251 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI)
252 {
253   if (!EmitLineNumbers)
254     return;
255   if (ignoreLoc(MI))
256     return;
257
258   DebugLoc curLoc = MI.getDebugLoc();
259
260   if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
261     return;
262
263   if (prevDebugLoc == curLoc)
264     return;
265
266   prevDebugLoc = curLoc;
267
268   if (curLoc.isUnknown())
269     return;
270
271
272   const MachineFunction *MF = MI.getParent()->getParent();
273   //const TargetMachine &TM = MF->getTarget();
274
275   const LLVMContext &ctx = MF->getFunction()->getContext();
276   DIScope Scope(curLoc.getScope(ctx));
277
278   if (!Scope.Verify())
279     return;
280
281   StringRef fileName(Scope.getFilename());
282   StringRef dirName(Scope.getDirectory());
283   SmallString<128> FullPathName = dirName;
284   if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
285     sys::path::append(FullPathName, fileName);
286     fileName = FullPathName.str();
287   }
288
289   if (filenameMap.find(fileName.str()) == filenameMap.end())
290     return;
291
292
293   // Emit the line from the source file.
294   if (llvm::InterleaveSrcInPtx)
295     this->emitSrcInText(fileName.str(), curLoc.getLine());
296
297   std::stringstream temp;
298   temp << "\t.loc " << filenameMap[fileName.str()]
299        << " " << curLoc.getLine() << " " << curLoc.getCol();
300   OutStreamer.EmitRawText(Twine(temp.str().c_str()));
301 }
302
303 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
304   SmallString<128> Str;
305   raw_svector_ostream OS(Str);
306   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
307     emitLineNumberAsDotLoc(*MI);
308   printInstruction(MI, OS);
309   OutStreamer.EmitRawText(OS.str());
310 }
311
312 void NVPTXAsmPrinter::printReturnValStr(const Function *F,
313                                         raw_ostream &O)
314 {
315   const DataLayout *TD = TM.getDataLayout();
316   const TargetLowering *TLI = TM.getTargetLowering();
317
318   Type *Ty = F->getReturnType();
319
320   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
321
322   if (Ty->getTypeID() == Type::VoidTyID)
323     return;
324
325   O << " (";
326
327   if (isABI) {
328     if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
329       unsigned size = 0;
330       if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
331         size = ITy->getBitWidth();
332         if (size < 32) size = 32;
333       } else {
334         assert(Ty->isFloatingPointTy() &&
335                "Floating point type expected here");
336         size = Ty->getPrimitiveSizeInBits();
337       }
338
339       O << ".param .b" << size << " func_retval0";
340     }
341     else if (isa<PointerType>(Ty)) {
342       O << ".param .b" << TLI->getPointerTy().getSizeInBits()
343             << " func_retval0";
344     } else {
345       if ((Ty->getTypeID() == Type::StructTyID) ||
346           isa<VectorType>(Ty)) {
347         SmallVector<EVT, 16> vtparts;
348         ComputeValueVTs(*TLI, Ty, vtparts);
349         unsigned totalsz = 0;
350         for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
351           unsigned elems = 1;
352           EVT elemtype = vtparts[i];
353           if (vtparts[i].isVector()) {
354             elems = vtparts[i].getVectorNumElements();
355             elemtype = vtparts[i].getVectorElementType();
356           }
357           for (unsigned j=0, je=elems; j!=je; ++j) {
358             unsigned sz = elemtype.getSizeInBits();
359             if (elemtype.isInteger() && (sz < 8)) sz = 8;
360             totalsz += sz/8;
361           }
362         }
363         unsigned retAlignment = 0;
364         if (!llvm::getAlign(*F, 0, retAlignment))
365           retAlignment = TD->getABITypeAlignment(Ty);
366         O << ".param .align "
367             << retAlignment
368             << " .b8 func_retval0["
369             << totalsz << "]";
370       } else
371         assert(false &&
372                "Unknown return type");
373     }
374   } else {
375     SmallVector<EVT, 16> vtparts;
376     ComputeValueVTs(*TLI, Ty, vtparts);
377     unsigned idx = 0;
378     for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
379       unsigned elems = 1;
380       EVT elemtype = vtparts[i];
381       if (vtparts[i].isVector()) {
382         elems = vtparts[i].getVectorNumElements();
383         elemtype = vtparts[i].getVectorElementType();
384       }
385
386       for (unsigned j=0, je=elems; j!=je; ++j) {
387         unsigned sz = elemtype.getSizeInBits();
388         if (elemtype.isInteger() && (sz < 32)) sz = 32;
389         O << ".reg .b" << sz << " func_retval" << idx;
390         if (j<je-1) O << ", ";
391         ++idx;
392       }
393       if (i < e-1)
394         O << ", ";
395     }
396   }
397   O << ") ";
398   return;
399 }
400
401 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
402                                         raw_ostream &O) {
403   const Function *F = MF.getFunction();
404   printReturnValStr(F, O);
405 }
406
407 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
408   SmallString<128> Str;
409   raw_svector_ostream O(Str);
410
411   // Set up
412   MRI = &MF->getRegInfo();
413   F = MF->getFunction();
414   emitLinkageDirective(F,O);
415   if (llvm::isKernelFunction(*F))
416     O << ".entry ";
417   else {
418     O << ".func ";
419     printReturnValStr(*MF, O);
420   }
421
422   O << *CurrentFnSym;
423
424   emitFunctionParamList(*MF, O);
425
426   if (llvm::isKernelFunction(*F))
427     emitKernelFunctionDirectives(*F, O);
428
429   OutStreamer.EmitRawText(O.str());
430
431   prevDebugLoc = DebugLoc();
432 }
433
434 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
435   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
436   unsigned numRegClasses = TRI.getNumRegClasses();
437   VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses+1];
438   OutStreamer.EmitRawText(StringRef("{\n"));
439   setAndEmitFunctionVirtualRegisters(*MF);
440
441   SmallString<128> Str;
442   raw_svector_ostream O(Str);
443   emitDemotedVars(MF->getFunction(), O);
444   OutStreamer.EmitRawText(O.str());
445 }
446
447 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
448   OutStreamer.EmitRawText(StringRef("}\n"));
449   delete []VRidGlobal2LocalMap;
450 }
451
452
453 void
454 NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function& F,
455                                               raw_ostream &O) const {
456   // If the NVVM IR has some of reqntid* specified, then output
457   // the reqntid directive, and set the unspecified ones to 1.
458   // If none of reqntid* is specified, don't output reqntid directive.
459   unsigned reqntidx, reqntidy, reqntidz;
460   bool specified = false;
461   if (llvm::getReqNTIDx(F, reqntidx) == false) reqntidx = 1;
462   else specified = true;
463   if (llvm::getReqNTIDy(F, reqntidy) == false) reqntidy = 1;
464   else specified = true;
465   if (llvm::getReqNTIDz(F, reqntidz) == false) reqntidz = 1;
466   else specified = true;
467
468   if (specified)
469     O << ".reqntid " << reqntidx << ", "
470     << reqntidy << ", " << reqntidz << "\n";
471
472   // If the NVVM IR has some of maxntid* specified, then output
473   // the maxntid directive, and set the unspecified ones to 1.
474   // If none of maxntid* is specified, don't output maxntid directive.
475   unsigned maxntidx, maxntidy, maxntidz;
476   specified = false;
477   if (llvm::getMaxNTIDx(F, maxntidx) == false) maxntidx = 1;
478   else specified = true;
479   if (llvm::getMaxNTIDy(F, maxntidy) == false) maxntidy = 1;
480   else specified = true;
481   if (llvm::getMaxNTIDz(F, maxntidz) == false) maxntidz = 1;
482   else specified = true;
483
484   if (specified)
485     O << ".maxntid " << maxntidx << ", "
486     << maxntidy << ", " << maxntidz << "\n";
487
488   unsigned mincta;
489   if (llvm::getMinCTASm(F, mincta))
490     O << ".minnctapersm " << mincta << "\n";
491 }
492
493 void
494 NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
495                                         raw_ostream &O) {
496   const TargetRegisterClass * RC = MRI->getRegClass(vr);
497   unsigned id = RC->getID();
498
499   std::map<unsigned, unsigned> &regmap = VRidGlobal2LocalMap[id];
500   unsigned mapped_vr = regmap[vr];
501
502   if (!isVec) {
503     O << getNVPTXRegClassStr(RC) << mapped_vr;
504     return;
505   }
506   // Vector virtual register
507   if (getNVPTXVectorSize(RC) == 4)
508     O << "{"
509     << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
510     << getNVPTXRegClassStr(RC) << mapped_vr << "_1, "
511     << getNVPTXRegClassStr(RC) << mapped_vr << "_2, "
512     << getNVPTXRegClassStr(RC) << mapped_vr << "_3"
513     << "}";
514   else if (getNVPTXVectorSize(RC) == 2)
515     O << "{"
516     << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
517     << getNVPTXRegClassStr(RC) << mapped_vr << "_1"
518     << "}";
519   else
520     llvm_unreachable("Unsupported vector size");
521 }
522
523 void
524 NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
525                                      raw_ostream &O) {
526   getVirtualRegisterName(vr, isVec, O);
527 }
528
529 void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
530                                                 const char *Modifier,
531                                                 raw_ostream &O) {
532   static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
533   int Imm = (int)MO.getImm();
534   if(0 == strcmp(Modifier, "vecelem"))
535     O << "_" << vecelem[Imm];
536   else if(0 == strcmp(Modifier, "vecv4comm1")) {
537     if((Imm < 0) || (Imm > 3))
538       O << "//";
539   }
540   else if(0 == strcmp(Modifier, "vecv4comm2")) {
541     if((Imm < 4) || (Imm > 7))
542       O << "//";
543   }
544   else if(0 == strcmp(Modifier, "vecv4pos")) {
545     if(Imm < 0) Imm = 0;
546     O << "_" << vecelem[Imm%4];
547   }
548   else if(0 == strcmp(Modifier, "vecv2comm1")) {
549     if((Imm < 0) || (Imm > 1))
550       O << "//";
551   }
552   else if(0 == strcmp(Modifier, "vecv2comm2")) {
553     if((Imm < 2) || (Imm > 3))
554       O << "//";
555   }
556   else if(0 == strcmp(Modifier, "vecv2pos")) {
557     if(Imm < 0) Imm = 0;
558     O << "_" << vecelem[Imm%2];
559   }
560   else
561     llvm_unreachable("Unknown Modifier on immediate operand");
562 }
563
564 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
565                                    raw_ostream &O, const char *Modifier) {
566   const MachineOperand &MO = MI->getOperand(opNum);
567   switch (MO.getType()) {
568   case MachineOperand::MO_Register:
569     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
570       if (MO.getReg() == NVPTX::VRDepot)
571         O << DEPOTNAME << getFunctionNumber();
572       else
573         O << getRegisterName(MO.getReg());
574     } else {
575       if (!Modifier)
576         emitVirtualRegister(MO.getReg(), false, O);
577       else {
578         if (strcmp(Modifier, "vecfull") == 0)
579           emitVirtualRegister(MO.getReg(), true, O);
580         else
581           llvm_unreachable(
582                  "Don't know how to handle the modifier on virtual register.");
583       }
584     }
585     return;
586
587   case MachineOperand::MO_Immediate:
588     if (!Modifier)
589       O << MO.getImm();
590     else if (strstr(Modifier, "vec") == Modifier)
591       printVecModifiedImmediate(MO, Modifier, O);
592     else
593       llvm_unreachable("Don't know how to handle modifier on immediate operand");
594     return;
595
596   case MachineOperand::MO_FPImmediate:
597     printFPConstant(MO.getFPImm(), O);
598     break;
599
600   case MachineOperand::MO_GlobalAddress:
601     O << *Mang->getSymbol(MO.getGlobal());
602     break;
603
604   case MachineOperand::MO_ExternalSymbol: {
605     const char * symbname = MO.getSymbolName();
606     if (strstr(symbname, ".PARAM") == symbname) {
607       unsigned index;
608       sscanf(symbname+6, "%u[];", &index);
609       printParamName(index, O);
610     }
611     else if (strstr(symbname, ".HLPPARAM") == symbname) {
612       unsigned index;
613       sscanf(symbname+9, "%u[];", &index);
614       O << *CurrentFnSym << "_param_" << index << "_offset";
615     }
616     else
617       O << symbname;
618     break;
619   }
620
621   case MachineOperand::MO_MachineBasicBlock:
622     O << *MO.getMBB()->getSymbol();
623     return;
624
625   default:
626     llvm_unreachable("Operand type not supported.");
627   }
628 }
629
630 void NVPTXAsmPrinter::
631 printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
632 #ifndef __OPTIMIZE__
633   O << "\t// Implicit def :";
634   //printOperand(MI, 0);
635   O << "\n";
636 #endif
637 }
638
639 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
640                                       raw_ostream &O, const char *Modifier) {
641   printOperand(MI, opNum, O);
642
643   if (Modifier && !strcmp(Modifier, "add")) {
644     O << ", ";
645     printOperand(MI, opNum+1, O);
646   } else {
647     if (MI->getOperand(opNum+1).isImm() &&
648         MI->getOperand(opNum+1).getImm() == 0)
649       return; // don't print ',0' or '+0'
650     O << "+";
651     printOperand(MI, opNum+1, O);
652   }
653 }
654
655 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
656                                     raw_ostream &O, const char *Modifier)
657 {
658   if (Modifier) {
659     const MachineOperand &MO = MI->getOperand(opNum);
660     int Imm = (int)MO.getImm();
661     if (!strcmp(Modifier, "volatile")) {
662       if (Imm)
663         O << ".volatile";
664     } else if (!strcmp(Modifier, "addsp")) {
665       switch (Imm) {
666       case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
667       case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
668       case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
669       case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
670       case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
671       case NVPTX::PTXLdStInstCode::GENERIC:
672         if (!nvptxSubtarget.hasGenericLdSt())
673           O << ".global";
674         break;
675       default:
676         llvm_unreachable("Wrong Address Space");
677       }
678     }
679     else if (!strcmp(Modifier, "sign")) {
680       if (Imm==NVPTX::PTXLdStInstCode::Signed)
681         O << "s";
682       else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
683         O << "u";
684       else
685         O << "f";
686     }
687     else if (!strcmp(Modifier, "vec")) {
688       if (Imm==NVPTX::PTXLdStInstCode::V2)
689         O << ".v2";
690       else if (Imm==NVPTX::PTXLdStInstCode::V4)
691         O << ".v4";
692     }
693     else
694       llvm_unreachable("Unknown Modifier");
695   }
696   else
697     llvm_unreachable("Empty Modifier");
698 }
699
700 void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
701
702   emitLinkageDirective(F,O);
703   if (llvm::isKernelFunction(*F))
704     O << ".entry ";
705   else
706     O << ".func ";
707   printReturnValStr(F, O);
708   O << *CurrentFnSym << "\n";
709   emitFunctionParamList(F, O);
710   O << ";\n";
711 }
712
713 static bool usedInGlobalVarDef(const Constant *C)
714 {
715   if (!C)
716     return false;
717
718   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
719     if (GV->getName().str() == "llvm.used")
720       return false;
721     return true;
722   }
723
724   for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
725       ui!=ue; ++ui) {
726     const Constant *C = dyn_cast<Constant>(*ui);
727     if (usedInGlobalVarDef(C))
728       return true;
729   }
730   return false;
731 }
732
733 static bool usedInOneFunc(const User *U, Function const *&oneFunc)
734 {
735   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
736     if (othergv->getName().str() == "llvm.used")
737       return true;
738   }
739
740   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
741     if (instr->getParent() && instr->getParent()->getParent()) {
742       const Function *curFunc = instr->getParent()->getParent();
743       if (oneFunc && (curFunc != oneFunc))
744         return false;
745       oneFunc = curFunc;
746       return true;
747     }
748     else
749       return false;
750   }
751
752   if (const MDNode *md = dyn_cast<MDNode>(U))
753     if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
754         (md->getName().str() == "llvm.dbg.sp")))
755       return true;
756
757
758   for (User::const_use_iterator ui=U->use_begin(), ue=U->use_end();
759       ui!=ue; ++ui) {
760     if (usedInOneFunc(*ui, oneFunc) == false)
761       return false;
762   }
763   return true;
764 }
765
766 /* Find out if a global variable can be demoted to local scope.
767  * Currently, this is valid for CUDA shared variables, which have local
768  * scope and global lifetime. So the conditions to check are :
769  * 1. Is the global variable in shared address space?
770  * 2. Does it have internal linkage?
771  * 3. Is the global variable referenced only in one function?
772  */
773 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
774   if (gv->hasInternalLinkage() == false)
775     return false;
776   const PointerType *Pty = gv->getType();
777   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
778     return false;
779
780   const Function *oneFunc = 0;
781
782   bool flag = usedInOneFunc(gv, oneFunc);
783   if (flag == false)
784     return false;
785   if (!oneFunc)
786     return false;
787   f = oneFunc;
788   return true;
789 }
790
791 static bool useFuncSeen(const Constant *C,
792                         llvm::DenseMap<const Function *, bool> &seenMap) {
793   for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
794       ui!=ue; ++ui) {
795     if (const Constant *cu = dyn_cast<Constant>(*ui)) {
796       if (useFuncSeen(cu, seenMap))
797         return true;
798     } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
799       const BasicBlock *bb = I->getParent();
800       if (!bb) continue;
801       const Function *caller = bb->getParent();
802       if (!caller) continue;
803       if (seenMap.find(caller) != seenMap.end())
804         return true;
805     }
806   }
807   return false;
808 }
809
810 void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
811   llvm::DenseMap<const Function *, bool> seenMap;
812   for (Module::const_iterator FI=M.begin(), FE=M.end();
813       FI!=FE; ++FI) {
814     const Function *F = FI;
815
816     if (F->isDeclaration()) {
817       if (F->use_empty())
818         continue;
819       if (F->getIntrinsicID())
820         continue;
821       CurrentFnSym = Mang->getSymbol(F);
822       emitDeclaration(F, O);
823       continue;
824     }
825     for (Value::const_use_iterator iter=F->use_begin(),
826         iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
827       if (const Constant *C = dyn_cast<Constant>(*iter)) {
828         if (usedInGlobalVarDef(C)) {
829           // The use is in the initialization of a global variable
830           // that is a function pointer, so print a declaration
831           // for the original function
832           CurrentFnSym = Mang->getSymbol(F);
833           emitDeclaration(F, O);
834           break;
835         }
836         // Emit a declaration of this function if the function that
837         // uses this constant expr has already been seen.
838         if (useFuncSeen(C, seenMap)) {
839           CurrentFnSym = Mang->getSymbol(F);
840           emitDeclaration(F, O);
841           break;
842         }
843       }
844
845       if (!isa<Instruction>(*iter)) continue;
846       const Instruction *instr = cast<Instruction>(*iter);
847       const BasicBlock *bb = instr->getParent();
848       if (!bb) continue;
849       const Function *caller = bb->getParent();
850       if (!caller) continue;
851
852       // If a caller has already been seen, then the caller is
853       // appearing in the module before the callee. so print out
854       // a declaration for the callee.
855       if (seenMap.find(caller) != seenMap.end()) {
856         CurrentFnSym = Mang->getSymbol(F);
857         emitDeclaration(F, O);
858         break;
859       }
860     }
861     seenMap[F] = true;
862   }
863 }
864
865 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
866   DebugInfoFinder DbgFinder;
867   DbgFinder.processModule(M);
868
869   unsigned i=1;
870   for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
871       E = DbgFinder.compile_unit_end(); I != E; ++I) {
872     DICompileUnit DIUnit(*I);
873     StringRef Filename(DIUnit.getFilename());
874     StringRef Dirname(DIUnit.getDirectory());
875     SmallString<128> FullPathName = Dirname;
876     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
877       sys::path::append(FullPathName, Filename);
878       Filename = FullPathName.str();
879     }
880     if (filenameMap.find(Filename.str()) != filenameMap.end())
881       continue;
882     filenameMap[Filename.str()] = i;
883     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
884     ++i;
885   }
886
887   for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
888       E = DbgFinder.subprogram_end(); I != E; ++I) {
889     DISubprogram SP(*I);
890     StringRef Filename(SP.getFilename());
891     StringRef Dirname(SP.getDirectory());
892     SmallString<128> FullPathName = Dirname;
893     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
894       sys::path::append(FullPathName, Filename);
895       Filename = FullPathName.str();
896     }
897     if (filenameMap.find(Filename.str()) != filenameMap.end())
898       continue;
899     filenameMap[Filename.str()] = i;
900     ++i;
901   }
902 }
903
904 bool NVPTXAsmPrinter::doInitialization (Module &M) {
905
906   SmallString<128> Str1;
907   raw_svector_ostream OS1(Str1);
908
909   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
910   MMI->AnalyzeModule(M);
911
912   // We need to call the parent's one explicitly.
913   //bool Result = AsmPrinter::doInitialization(M);
914
915   // Initialize TargetLoweringObjectFile.
916   const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
917           .Initialize(OutContext, TM);
918
919   Mang = new Mangler(OutContext, *TM.getDataLayout());
920
921   // Emit header before any dwarf directives are emitted below.
922   emitHeader(M, OS1);
923   OutStreamer.EmitRawText(OS1.str());
924
925
926   // Already commented out
927   //bool Result = AsmPrinter::doInitialization(M);
928
929
930   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
931     recordAndEmitFilenames(M);
932
933   SmallString<128> Str2;
934   raw_svector_ostream OS2(Str2);
935
936   emitDeclarations(M, OS2);
937
938   // As ptxas does not support forward references of globals, we need to first
939   // sort the list of module-level globals in def-use order. We visit each
940   // global variable in order, and ensure that we emit it *after* its dependent
941   // globals. We use a little extra memory maintaining both a set and a list to
942   // have fast searches while maintaining a strict ordering.
943   SmallVector<GlobalVariable*,8> Globals;
944   DenseSet<GlobalVariable*> GVVisited;
945   DenseSet<GlobalVariable*> GVVisiting;
946
947   // Visit each global variable, in order
948   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
949        I != E; ++I)
950     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
951
952   assert(GVVisited.size() == M.getGlobalList().size() && 
953          "Missed a global variable");
954   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
955
956   // Print out module-level global variables in proper order
957   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
958     printModuleLevelGV(Globals[i], OS2);
959
960   OS2 << '\n';
961
962   OutStreamer.EmitRawText(OS2.str());
963   return false;  // success
964 }
965
966 void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
967   O << "//\n";
968   O << "// Generated by LLVM NVPTX Back-End\n";
969   O << "//\n";
970   O << "\n";
971
972   unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
973   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
974
975   O << ".target ";
976   O << nvptxSubtarget.getTargetName();
977
978   if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
979     O << ", texmode_independent";
980   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
981     if (!nvptxSubtarget.hasDouble())
982       O << ", map_f64_to_f32";
983   }
984
985   if (MAI->doesSupportDebugInformation())
986     O << ", debug";
987
988   O << "\n";
989
990   O << ".address_size ";
991   if (nvptxSubtarget.is64Bit())
992     O << "64";
993   else
994     O << "32";
995   O << "\n";
996
997   O << "\n";
998 }
999
1000 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1001   // XXX Temproarily remove global variables so that doFinalization() will not
1002   // emit them again (global variables are emitted at beginning).
1003
1004   Module::GlobalListType &global_list = M.getGlobalList();
1005   int i, n = global_list.size();
1006   GlobalVariable **gv_array = new GlobalVariable* [n];
1007
1008   // first, back-up GlobalVariable in gv_array
1009   i = 0;
1010   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1011       I != E; ++I)
1012     gv_array[i++] = &*I;
1013
1014   // second, empty global_list
1015   while (!global_list.empty())
1016     global_list.remove(global_list.begin());
1017
1018   // call doFinalization
1019   bool ret = AsmPrinter::doFinalization(M);
1020
1021   // now we restore global variables
1022   for (i = 0; i < n; i ++)
1023     global_list.insert(global_list.end(), gv_array[i]);
1024
1025   delete[] gv_array;
1026   return ret;
1027
1028
1029   //bool Result = AsmPrinter::doFinalization(M);
1030   // Instead of calling the parents doFinalization, we may
1031   // clone parents doFinalization and customize here.
1032   // Currently, we if NVISA out the EmitGlobals() in
1033   // parent's doFinalization, which is too intrusive.
1034   //
1035   // Same for the doInitialization.
1036   //return Result;
1037 }
1038
1039 // This function emits appropriate linkage directives for
1040 // functions and global variables.
1041 //
1042 // extern function declaration            -> .extern
1043 // extern function definition             -> .visible
1044 // external global variable with init     -> .visible
1045 // external without init                  -> .extern
1046 // appending                              -> not allowed, assert.
1047
1048 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
1049 {
1050   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1051     if (V->hasExternalLinkage()) {
1052       if (isa<GlobalVariable>(V)) {
1053         const GlobalVariable *GVar = cast<GlobalVariable>(V);
1054         if (GVar) {
1055           if (GVar->hasInitializer())
1056             O << ".visible ";
1057           else
1058             O << ".extern ";
1059         }
1060       } else if (V->isDeclaration())
1061         O << ".extern ";
1062       else
1063         O << ".visible ";
1064     } else if (V->hasAppendingLinkage()) {
1065       std::string msg;
1066       msg.append("Error: ");
1067       msg.append("Symbol ");
1068       if (V->hasName())
1069         msg.append(V->getName().str());
1070       msg.append("has unsupported appending linkage type");
1071       llvm_unreachable(msg.c_str());
1072     }
1073   }
1074 }
1075
1076
1077 void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1078                                          bool processDemoted) {
1079
1080   // Skip meta data
1081   if (GVar->hasSection()) {
1082     if (GVar->getSection() == "llvm.metadata")
1083       return;
1084   }
1085
1086   const DataLayout *TD = TM.getDataLayout();
1087
1088   // GlobalVariables are always constant pointers themselves.
1089   const PointerType *PTy = GVar->getType();
1090   Type *ETy = PTy->getElementType();
1091
1092   if (GVar->hasExternalLinkage()) {
1093     if (GVar->hasInitializer())
1094       O << ".visible ";
1095     else
1096       O << ".extern ";
1097   }
1098
1099   if (llvm::isTexture(*GVar)) {
1100     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1101     return;
1102   }
1103
1104   if (llvm::isSurface(*GVar)) {
1105     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1106     return;
1107   }
1108
1109   if (GVar->isDeclaration()) {
1110     // (extern) declarations, no definition or initializer
1111     // Currently the only known declaration is for an automatic __local
1112     // (.shared) promoted to global.
1113     emitPTXGlobalVariable(GVar, O);
1114     O << ";\n";
1115     return;
1116   }
1117
1118   if (llvm::isSampler(*GVar)) {
1119     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1120
1121     Constant *Initializer = NULL;
1122     if (GVar->hasInitializer())
1123       Initializer = GVar->getInitializer();
1124     ConstantInt *CI = NULL;
1125     if (Initializer)
1126       CI = dyn_cast<ConstantInt>(Initializer);
1127     if (CI) {
1128       unsigned sample=CI->getZExtValue();
1129
1130       O << " = { ";
1131
1132       for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1133           __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1134         O << "addr_mode_" << i << " = ";
1135         switch (addr) {
1136         case 0: O << "wrap"; break;
1137         case 1: O << "clamp_to_border"; break;
1138         case 2: O << "clamp_to_edge"; break;
1139         case 3: O << "wrap"; break;
1140         case 4: O << "mirror"; break;
1141         }
1142         O <<", ";
1143       }
1144       O << "filter_mode = ";
1145       switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1146       case 0: O << "nearest"; break;
1147       case 1: O << "linear";  break;
1148       case 2: assert ( 0 && "Anisotropic filtering is not supported");
1149       default: O << "nearest"; break;
1150       }
1151       if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1152         O << ", force_unnormalized_coords = 1";
1153       }
1154       O << " }";
1155     }
1156
1157     O << ";\n";
1158     return;
1159   }
1160
1161   if (GVar->hasPrivateLinkage()) {
1162
1163     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1164       return;
1165
1166     // FIXME - need better way (e.g. Metadata) to avoid generating this global
1167     if (!strncmp(GVar->getName().data(), "filename", 8))
1168       return;
1169     if (GVar->use_empty())
1170       return;
1171   }
1172
1173   const Function *demotedFunc = 0;
1174   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1175     O << "// " << GVar->getName().str() << " has been demoted\n";
1176     if (localDecls.find(demotedFunc) != localDecls.end())
1177       localDecls[demotedFunc].push_back(GVar);
1178     else {
1179       std::vector<GlobalVariable *> temp;
1180       temp.push_back(GVar);
1181       localDecls[demotedFunc] = temp;
1182     }
1183     return;
1184   }
1185
1186   O << ".";
1187   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1188   if (GVar->getAlignment() == 0)
1189     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1190   else
1191     O << " .align " << GVar->getAlignment();
1192
1193
1194   if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1195     O << " .";
1196     O << getPTXFundamentalTypeStr(ETy, false);
1197     O << " ";
1198     O << *Mang->getSymbol(GVar);
1199
1200     // Ptx allows variable initilization only for constant and global state
1201     // spaces.
1202     if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1203         (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1204         (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1205         && GVar->hasInitializer()) {
1206       Constant *Initializer = GVar->getInitializer();
1207       if (!Initializer->isNullValue()) {
1208         O << " = " ;
1209         printScalarConstant(Initializer, O);
1210       }
1211     }
1212   } else {
1213     unsigned int ElementSize =0;
1214
1215     // Although PTX has direct support for struct type and array type and
1216     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1217     // targets that support these high level field accesses. Structs, arrays
1218     // and vectors are lowered into arrays of bytes.
1219     switch (ETy->getTypeID()) {
1220     case Type::StructTyID:
1221     case Type::ArrayTyID:
1222     case Type::VectorTyID:
1223       ElementSize = TD->getTypeStoreSize(ETy);
1224       // Ptx allows variable initilization only for constant and
1225       // global state spaces.
1226       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1227           (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1228           (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1229           && GVar->hasInitializer()) {
1230         Constant *Initializer = GVar->getInitializer();
1231         if (!isa<UndefValue>(Initializer) &&
1232             !Initializer->isNullValue()) {
1233           AggBuffer aggBuffer(ElementSize, O, *this);
1234           bufferAggregateConstant(Initializer, &aggBuffer);
1235           if (aggBuffer.numSymbols) {
1236             if (nvptxSubtarget.is64Bit()) {
1237               O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1238               O << ElementSize/8;
1239             }
1240             else {
1241               O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1242               O << ElementSize/4;
1243             }
1244             O << "]";
1245           }
1246           else {
1247             O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1248             O << ElementSize;
1249             O << "]";
1250           }
1251           O << " = {" ;
1252           aggBuffer.print();
1253           O << "}";
1254         }
1255         else {
1256           O << " .b8 " << *Mang->getSymbol(GVar) ;
1257           if (ElementSize) {
1258             O <<"[" ;
1259             O << ElementSize;
1260             O << "]";
1261           }
1262         }
1263       }
1264       else {
1265         O << " .b8 " << *Mang->getSymbol(GVar);
1266         if (ElementSize) {
1267           O <<"[" ;
1268           O << ElementSize;
1269           O << "]";
1270         }
1271       }
1272       break;
1273     default:
1274       assert( 0 && "type not supported yet");
1275     }
1276
1277   }
1278   O << ";\n";
1279 }
1280
1281 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1282   if (localDecls.find(f) == localDecls.end())
1283     return;
1284
1285   std::vector<GlobalVariable *> &gvars = localDecls[f];
1286
1287   for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1288     O << "\t// demoted variable\n\t";
1289     printModuleLevelGV(gvars[i], O, true);
1290   }
1291 }
1292
1293 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1294                                           raw_ostream &O) const {
1295   switch (AddressSpace) {
1296   case llvm::ADDRESS_SPACE_LOCAL:
1297     O << "local" ;
1298     break;
1299   case llvm::ADDRESS_SPACE_GLOBAL:
1300     O << "global" ;
1301     break;
1302   case llvm::ADDRESS_SPACE_CONST:
1303     // This logic should be consistent with that in
1304     // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1305     if (nvptxSubtarget.hasGenericLdSt())
1306       O << "global" ;
1307     else
1308       O << "const" ;
1309     break;
1310   case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1311     O << "const" ;
1312     break;
1313   case llvm::ADDRESS_SPACE_SHARED:
1314     O << "shared" ;
1315     break;
1316   default:
1317     report_fatal_error("Bad address space found while emitting PTX");
1318     break;
1319   }
1320 }
1321
1322 std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1323                                                       bool useB4PTR) const {
1324   switch (Ty->getTypeID()) {
1325   default:
1326     llvm_unreachable("unexpected type");
1327     break;
1328   case Type::IntegerTyID: {
1329     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1330     if (NumBits == 1)
1331       return "pred";
1332     else if (NumBits <= 64) {
1333       std::string name = "u";
1334       return name + utostr(NumBits);
1335     } else {
1336       llvm_unreachable("Integer too large");
1337       break;
1338     }
1339     break;
1340   }
1341   case Type::FloatTyID:
1342     return "f32";
1343   case Type::DoubleTyID:
1344     return "f64";
1345   case Type::PointerTyID:
1346     if (nvptxSubtarget.is64Bit())
1347       if (useB4PTR) return "b64";
1348       else return "u64";
1349     else
1350       if (useB4PTR) return "b32";
1351       else return "u32";
1352   }
1353   llvm_unreachable("unexpected type");
1354   return NULL;
1355 }
1356
1357 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1358                                             raw_ostream &O) {
1359
1360   const DataLayout *TD = TM.getDataLayout();
1361
1362   // GlobalVariables are always constant pointers themselves.
1363   const PointerType *PTy = GVar->getType();
1364   Type *ETy = PTy->getElementType();
1365
1366   O << ".";
1367   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1368   if (GVar->getAlignment() == 0)
1369     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1370   else
1371     O << " .align " << GVar->getAlignment();
1372
1373   if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1374     O << " .";
1375     O << getPTXFundamentalTypeStr(ETy);
1376     O << " ";
1377     O << *Mang->getSymbol(GVar);
1378     return;
1379   }
1380
1381   int64_t ElementSize =0;
1382
1383   // Although PTX has direct support for struct type and array type and LLVM IR
1384   // is very similar to PTX, the LLVM CodeGen does not support for targets that
1385   // support these high level field accesses. Structs and arrays are lowered
1386   // into arrays of bytes.
1387   switch (ETy->getTypeID()) {
1388   case Type::StructTyID:
1389   case Type::ArrayTyID:
1390   case Type::VectorTyID:
1391     ElementSize = TD->getTypeStoreSize(ETy);
1392     O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1393     if (ElementSize) {
1394       O << itostr(ElementSize) ;
1395     }
1396     O << "]";
1397     break;
1398   default:
1399     assert( 0 && "type not supported yet");
1400   }
1401   return ;
1402 }
1403
1404
1405 static unsigned int
1406 getOpenCLAlignment(const DataLayout *TD,
1407                    Type *Ty) {
1408   if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1409     return TD->getPrefTypeAlignment(Ty);
1410
1411   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1412   if (ATy)
1413     return getOpenCLAlignment(TD, ATy->getElementType());
1414
1415   const VectorType *VTy = dyn_cast<VectorType>(Ty);
1416   if (VTy) {
1417     Type *ETy = VTy->getElementType();
1418     unsigned int numE = VTy->getNumElements();
1419     unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1420     if (numE == 3)
1421       return 4*alignE;
1422     else
1423       return numE*alignE;
1424   }
1425
1426   const StructType *STy = dyn_cast<StructType>(Ty);
1427   if (STy) {
1428     unsigned int alignStruct = 1;
1429     // Go through each element of the struct and find the
1430     // largest alignment.
1431     for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1432       Type *ETy = STy->getElementType(i);
1433       unsigned int align = getOpenCLAlignment(TD, ETy);
1434       if (align > alignStruct)
1435         alignStruct = align;
1436     }
1437     return alignStruct;
1438   }
1439
1440   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1441   if (FTy)
1442     return TD->getPointerPrefAlignment();
1443   return TD->getPrefTypeAlignment(Ty);
1444 }
1445
1446 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1447                                      int paramIndex, raw_ostream &O) {
1448   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1449       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1450     O << *CurrentFnSym << "_param_" << paramIndex;
1451   else {
1452     std::string argName = I->getName();
1453     const char *p = argName.c_str();
1454     while (*p) {
1455       if (*p == '.')
1456         O << "_";
1457       else
1458         O << *p;
1459       p++;
1460     }
1461   }
1462 }
1463
1464 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1465   Function::const_arg_iterator I, E;
1466   int i = 0;
1467
1468   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1469       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1470     O << *CurrentFnSym << "_param_" << paramIndex;
1471     return;
1472   }
1473
1474   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1475     if (i==paramIndex) {
1476       printParamName(I, paramIndex, O);
1477       return;
1478     }
1479   }
1480   llvm_unreachable("paramIndex out of bound");
1481 }
1482
1483 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1484                                             raw_ostream &O) {
1485   const DataLayout *TD = TM.getDataLayout();
1486   const AttributeSet &PAL = F->getAttributes();
1487   const TargetLowering *TLI = TM.getTargetLowering();
1488   Function::const_arg_iterator I, E;
1489   unsigned paramIndex = 0;
1490   bool first = true;
1491   bool isKernelFunc = llvm::isKernelFunction(*F);
1492   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1493   MVT thePointerTy = TLI->getPointerTy();
1494
1495   O << "(\n";
1496
1497   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1498     const Type *Ty = I->getType();
1499
1500     if (!first)
1501       O << ",\n";
1502
1503     first = false;
1504
1505     // Handle image/sampler parameters
1506     if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1507       if (llvm::isImage(*I)) {
1508         std::string sname = I->getName();
1509         if (llvm::isImageWriteOnly(*I))
1510           O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1511         else // Default image is read_only
1512           O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1513       }
1514       else // Should be llvm::isSampler(*I)
1515         O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1516         << paramIndex;
1517       continue;
1518     }
1519
1520     if (PAL.hasAttribute(paramIndex+1, Attribute::ByVal) == false) {
1521       // Just a scalar
1522       const PointerType *PTy = dyn_cast<PointerType>(Ty);
1523       if (isKernelFunc) {
1524         if (PTy) {
1525           // Special handling for pointer arguments to kernel
1526           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1527
1528           if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1529             Type *ETy = PTy->getElementType();
1530             int addrSpace = PTy->getAddressSpace();
1531             switch(addrSpace) {
1532             default:
1533               O << ".ptr ";
1534               break;
1535             case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1536               O << ".ptr .const ";
1537               break;
1538             case llvm::ADDRESS_SPACE_SHARED:
1539               O << ".ptr .shared ";
1540               break;
1541             case llvm::ADDRESS_SPACE_GLOBAL:
1542             case llvm::ADDRESS_SPACE_CONST:
1543               O << ".ptr .global ";
1544               break;
1545             }
1546             O << ".align " << (int)getOpenCLAlignment(TD, ETy) << " ";
1547           }
1548           printParamName(I, paramIndex, O);
1549           continue;
1550         }
1551
1552         // non-pointer scalar to kernel func
1553         O << "\t.param ."
1554             << getPTXFundamentalTypeStr(Ty) << " ";
1555         printParamName(I, paramIndex, O);
1556         continue;
1557       }
1558       // Non-kernel function, just print .param .b<size> for ABI
1559       // and .reg .b<size> for non ABY
1560       unsigned sz = 0;
1561       if (isa<IntegerType>(Ty)) {
1562         sz = cast<IntegerType>(Ty)->getBitWidth();
1563         if (sz < 32) sz = 32;
1564       }
1565       else if (isa<PointerType>(Ty))
1566         sz = thePointerTy.getSizeInBits();
1567       else
1568         sz = Ty->getPrimitiveSizeInBits();
1569       if (isABI)
1570         O << "\t.param .b" << sz << " ";
1571       else
1572         O << "\t.reg .b" << sz << " ";
1573       printParamName(I, paramIndex, O);
1574       continue;
1575     }
1576
1577     // param has byVal attribute. So should be a pointer
1578     const PointerType *PTy = dyn_cast<PointerType>(Ty);
1579     assert(PTy &&
1580            "Param with byval attribute should be a pointer type");
1581     Type *ETy = PTy->getElementType();
1582
1583     if (isABI || isKernelFunc) {
1584       // Just print .param .b8 .align <a> .param[size];
1585       // <a> = PAL.getparamalignment
1586       // size = typeallocsize of element type
1587       unsigned align = PAL.getParamAlignment(paramIndex+1);
1588       if (align == 0)
1589         align = TD->getABITypeAlignment(ETy);
1590
1591       unsigned sz = TD->getTypeAllocSize(ETy);
1592       O << "\t.param .align " << align
1593           << " .b8 ";
1594       printParamName(I, paramIndex, O);
1595       O << "[" << sz << "]";
1596       continue;
1597     } else {
1598       // Split the ETy into constituent parts and
1599       // print .param .b<size> <name> for each part.
1600       // Further, if a part is vector, print the above for
1601       // each vector element.
1602       SmallVector<EVT, 16> vtparts;
1603       ComputeValueVTs(*TLI, ETy, vtparts);
1604       for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
1605         unsigned elems = 1;
1606         EVT elemtype = vtparts[i];
1607         if (vtparts[i].isVector()) {
1608           elems = vtparts[i].getVectorNumElements();
1609           elemtype = vtparts[i].getVectorElementType();
1610         }
1611
1612         for (unsigned j=0,je=elems; j!=je; ++j) {
1613           unsigned sz = elemtype.getSizeInBits();
1614           if (elemtype.isInteger() && (sz < 32)) sz = 32;
1615           O << "\t.reg .b" << sz << " ";
1616           printParamName(I, paramIndex, O);
1617           if (j<je-1) O << ",\n";
1618           ++paramIndex;
1619         }
1620         if (i<e-1)
1621           O << ",\n";
1622       }
1623       --paramIndex;
1624       continue;
1625     }
1626   }
1627
1628   O << "\n)\n";
1629 }
1630
1631 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1632                                             raw_ostream &O) {
1633   const Function *F = MF.getFunction();
1634   emitFunctionParamList(F, O);
1635 }
1636
1637
1638 void NVPTXAsmPrinter::
1639 setAndEmitFunctionVirtualRegisters(const MachineFunction &MF) {
1640   SmallString<128> Str;
1641   raw_svector_ostream O(Str);
1642
1643   // Map the global virtual register number to a register class specific
1644   // virtual register number starting from 1 with that class.
1645   const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1646   //unsigned numRegClasses = TRI->getNumRegClasses();
1647
1648   // Emit the Fake Stack Object
1649   const MachineFrameInfo *MFI = MF.getFrameInfo();
1650   int NumBytes = (int) MFI->getStackSize();
1651   if (NumBytes) {
1652     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t"
1653         << DEPOTNAME
1654         << getFunctionNumber() << "[" << NumBytes << "];\n";
1655     if (nvptxSubtarget.is64Bit()) {
1656       O << "\t.reg .b64 \t%SP;\n";
1657       O << "\t.reg .b64 \t%SPL;\n";
1658     }
1659     else {
1660       O << "\t.reg .b32 \t%SP;\n";
1661       O << "\t.reg .b32 \t%SPL;\n";
1662     }
1663   }
1664
1665   // Go through all virtual registers to establish the mapping between the
1666   // global virtual
1667   // register number and the per class virtual register number.
1668   // We use the per class virtual register number in the ptx output.
1669   unsigned int numVRs = MRI->getNumVirtRegs();
1670   for (unsigned i=0; i< numVRs; i++) {
1671     unsigned int vr = TRI->index2VirtReg(i);
1672     const TargetRegisterClass *RC = MRI->getRegClass(vr);
1673     std::map<unsigned, unsigned> &regmap = VRidGlobal2LocalMap[RC->getID()];
1674     int n = regmap.size();
1675     regmap.insert(std::make_pair(vr, n+1));
1676   }
1677
1678   // Emit register declarations
1679   // @TODO: Extract out the real register usage
1680   O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1681   O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1682   O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1683   O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1684   O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1685   O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1686   O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1687
1688   // Emit declaration of the virtual registers or 'physical' registers for
1689   // each register class
1690   //for (unsigned i=0; i< numRegClasses; i++) {
1691   //    std::map<unsigned, unsigned> &regmap = VRidGlobal2LocalMap[i];
1692   //    const TargetRegisterClass *RC = TRI->getRegClass(i);
1693   //    std::string rcname = getNVPTXRegClassName(RC);
1694   //    std::string rcStr = getNVPTXRegClassStr(RC);
1695   //    //int n = regmap.size();
1696   //    if (!isNVPTXVectorRegClass(RC)) {
1697   //      O << "\t.reg " << rcname << " \t" << rcStr << "<"
1698   //        << NVPTXNumRegisters << ">;\n";
1699   //    }
1700
1701   // Only declare those registers that may be used. And do not emit vector
1702   // registers as
1703   // they are all elementized to scalar registers.
1704   //if (n && !isNVPTXVectorRegClass(RC)) {
1705   //    if (RegAllocNilUsed) {
1706   //        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1707   //          << ">;\n";
1708   //    }
1709   //    else {
1710   //        O << "\t.reg " << rcname << " \t" << StrToUpper(rcStr)
1711   //          << "<" << 32 << ">;\n";
1712   //    }
1713   //}
1714   //}
1715
1716   OutStreamer.EmitRawText(O.str());
1717 }
1718
1719
1720 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1721   APFloat APF = APFloat(Fp->getValueAPF());  // make a copy
1722   bool ignored;
1723   unsigned int numHex;
1724   const char *lead;
1725
1726   if (Fp->getType()->getTypeID()==Type::FloatTyID) {
1727     numHex = 8;
1728     lead = "0f";
1729     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1730                 &ignored);
1731   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1732     numHex = 16;
1733     lead = "0d";
1734     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1735                 &ignored);
1736   } else
1737     llvm_unreachable("unsupported fp type");
1738
1739   APInt API = APF.bitcastToAPInt();
1740   std::string hexstr(utohexstr(API.getZExtValue()));
1741   O << lead;
1742   if (hexstr.length() < numHex)
1743     O << std::string(numHex - hexstr.length(), '0');
1744   O << utohexstr(API.getZExtValue());
1745 }
1746
1747 void NVPTXAsmPrinter::printScalarConstant(Constant *CPV, raw_ostream &O) {
1748   if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1749     O << CI->getValue();
1750     return;
1751   }
1752   if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1753     printFPConstant(CFP, O);
1754     return;
1755   }
1756   if (isa<ConstantPointerNull>(CPV)) {
1757     O << "0";
1758     return;
1759   }
1760   if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1761     O << *Mang->getSymbol(GVar);
1762     return;
1763   }
1764   if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1765     Value *v = Cexpr->stripPointerCasts();
1766     if (GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1767       O << *Mang->getSymbol(GVar);
1768       return;
1769     } else {
1770       O << *LowerConstant(CPV, *this);
1771       return;
1772     }
1773   }
1774   llvm_unreachable("Not scalar type found in printScalarConstant()");
1775 }
1776
1777
1778 void NVPTXAsmPrinter::bufferLEByte(Constant *CPV, int Bytes,
1779                                    AggBuffer *aggBuffer) {
1780
1781   const DataLayout *TD = TM.getDataLayout();
1782
1783   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1784     int s = TD->getTypeAllocSize(CPV->getType());
1785     if (s<Bytes)
1786       s = Bytes;
1787     aggBuffer->addZeros(s);
1788     return;
1789   }
1790
1791   unsigned char *ptr;
1792   switch (CPV->getType()->getTypeID()) {
1793
1794   case Type::IntegerTyID: {
1795     const Type *ETy = CPV->getType();
1796     if ( ETy == Type::getInt8Ty(CPV->getContext()) ){
1797       unsigned char c =
1798           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1799       ptr = &c;
1800       aggBuffer->addBytes(ptr, 1, Bytes);
1801     } else if ( ETy == Type::getInt16Ty(CPV->getContext()) ) {
1802       short int16 =
1803           (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1804       ptr = (unsigned char*)&int16;
1805       aggBuffer->addBytes(ptr, 2, Bytes);
1806     } else if ( ETy == Type::getInt32Ty(CPV->getContext()) ) {
1807       if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1808         int int32 =(int)(constInt->getZExtValue());
1809         ptr = (unsigned char*)&int32;
1810         aggBuffer->addBytes(ptr, 4, Bytes);
1811         break;
1812       } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1813         if (ConstantInt *constInt =
1814             dyn_cast<ConstantInt>(ConstantFoldConstantExpression(
1815                 Cexpr, TD))) {
1816           int int32 =(int)(constInt->getZExtValue());
1817           ptr = (unsigned char*)&int32;
1818           aggBuffer->addBytes(ptr, 4, Bytes);
1819           break;
1820         }
1821         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1822           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1823           aggBuffer->addSymbol(v);
1824           aggBuffer->addZeros(4);
1825           break;
1826         }
1827       }
1828       llvm_unreachable("unsupported integer const type");
1829     } else if (ETy == Type::getInt64Ty(CPV->getContext()) ) {
1830       if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1831         long long int64 =(long long)(constInt->getZExtValue());
1832         ptr = (unsigned char*)&int64;
1833         aggBuffer->addBytes(ptr, 8, Bytes);
1834         break;
1835       } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1836         if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1837             ConstantFoldConstantExpression(Cexpr, TD))) {
1838           long long int64 =(long long)(constInt->getZExtValue());
1839           ptr = (unsigned char*)&int64;
1840           aggBuffer->addBytes(ptr, 8, Bytes);
1841           break;
1842         }
1843         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1844           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1845           aggBuffer->addSymbol(v);
1846           aggBuffer->addZeros(8);
1847           break;
1848         }
1849       }
1850       llvm_unreachable("unsupported integer const type");
1851     } else
1852       llvm_unreachable("unsupported integer const type");
1853     break;
1854   }
1855   case Type::FloatTyID:
1856   case Type::DoubleTyID: {
1857     ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1858     const Type* Ty = CFP->getType();
1859     if (Ty == Type::getFloatTy(CPV->getContext())) {
1860       float float32 = (float)CFP->getValueAPF().convertToFloat();
1861       ptr = (unsigned char*)&float32;
1862       aggBuffer->addBytes(ptr, 4, Bytes);
1863     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1864       double float64 = CFP->getValueAPF().convertToDouble();
1865       ptr = (unsigned char*)&float64;
1866       aggBuffer->addBytes(ptr, 8, Bytes);
1867     }
1868     else {
1869       llvm_unreachable("unsupported fp const type");
1870     }
1871     break;
1872   }
1873   case Type::PointerTyID: {
1874     if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1875       aggBuffer->addSymbol(GVar);
1876     }
1877     else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1878       Value *v = Cexpr->stripPointerCasts();
1879       aggBuffer->addSymbol(v);
1880     }
1881     unsigned int s = TD->getTypeAllocSize(CPV->getType());
1882     aggBuffer->addZeros(s);
1883     break;
1884   }
1885
1886   case Type::ArrayTyID:
1887   case Type::VectorTyID:
1888   case Type::StructTyID: {
1889     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1890         isa<ConstantStruct>(CPV)) {
1891       int ElementSize = TD->getTypeAllocSize(CPV->getType());
1892       bufferAggregateConstant(CPV, aggBuffer);
1893       if ( Bytes > ElementSize )
1894         aggBuffer->addZeros(Bytes-ElementSize);
1895     }
1896     else if (isa<ConstantAggregateZero>(CPV))
1897       aggBuffer->addZeros(Bytes);
1898     else
1899       llvm_unreachable("Unexpected Constant type");
1900     break;
1901   }
1902
1903   default:
1904     llvm_unreachable("unsupported type");
1905   }
1906 }
1907
1908 void NVPTXAsmPrinter::bufferAggregateConstant(Constant *CPV,
1909                                               AggBuffer *aggBuffer) {
1910   const DataLayout *TD = TM.getDataLayout();
1911   int Bytes;
1912
1913   // Old constants
1914   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1915     if (CPV->getNumOperands())
1916       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1917         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1918     return;
1919   }
1920
1921   if (const ConstantDataSequential *CDS =
1922       dyn_cast<ConstantDataSequential>(CPV)) {
1923     if (CDS->getNumElements())
1924       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1925         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1926                      aggBuffer);
1927     return;
1928   }
1929
1930
1931   if (isa<ConstantStruct>(CPV)) {
1932     if (CPV->getNumOperands()) {
1933       StructType *ST = cast<StructType>(CPV->getType());
1934       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1935         if ( i == (e - 1))
1936           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1937           TD->getTypeAllocSize(ST)
1938           - TD->getStructLayout(ST)->getElementOffset(i);
1939         else
1940           Bytes = TD->getStructLayout(ST)->getElementOffset(i+1) -
1941           TD->getStructLayout(ST)->getElementOffset(i);
1942         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes,
1943                      aggBuffer);
1944       }
1945     }
1946     return;
1947   }
1948   llvm_unreachable("unsupported constant type in printAggregateConstant()");
1949 }
1950
1951 // buildTypeNameMap - Run through symbol table looking for type names.
1952 //
1953
1954
1955 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1956
1957   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1958
1959   if (PI != TypeNameMap.end() &&
1960       (!PI->second.compare("struct._image1d_t") ||
1961           !PI->second.compare("struct._image2d_t") ||
1962           !PI->second.compare("struct._image3d_t")))
1963     return true;
1964
1965   return false;
1966 }
1967
1968 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1969 ///
1970 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1971                                       unsigned AsmVariant,
1972                                       const char *ExtraCode,
1973                                       raw_ostream &O) {
1974   if (ExtraCode && ExtraCode[0]) {
1975     if (ExtraCode[1] != 0) return true; // Unknown modifier.
1976
1977     switch (ExtraCode[0]) {
1978     default:
1979       // See if this is a generic print operand
1980       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
1981     case 'r':
1982       break;
1983     }
1984   }
1985
1986   printOperand(MI, OpNo, O);
1987
1988   return false;
1989 }
1990
1991 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1992                                             unsigned OpNo,
1993                                             unsigned AsmVariant,
1994                                             const char *ExtraCode,
1995                                             raw_ostream &O) {
1996   if (ExtraCode && ExtraCode[0])
1997     return true;  // Unknown modifier
1998
1999   O << '[';
2000   printMemOperand(MI, OpNo, O);
2001   O << ']';
2002
2003   return false;
2004 }
2005
2006 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI)
2007 {
2008   switch(MI.getOpcode()) {
2009   default:
2010     return false;
2011   case NVPTX::CallArgBeginInst:  case NVPTX::CallArgEndInst0:
2012   case NVPTX::CallArgEndInst1:  case NVPTX::CallArgF32:
2013   case NVPTX::CallArgF64:  case NVPTX::CallArgI16:
2014   case NVPTX::CallArgI32:  case NVPTX::CallArgI32imm:
2015   case NVPTX::CallArgI64:  case NVPTX::CallArgI8:
2016   case NVPTX::CallArgParam:  case NVPTX::CallVoidInst:
2017   case NVPTX::CallVoidInstReg:  case NVPTX::Callseq_End:
2018   case NVPTX::CallVoidInstReg64:
2019   case NVPTX::DeclareParamInst:  case NVPTX::DeclareRetMemInst:
2020   case NVPTX::DeclareRetRegInst:  case NVPTX::DeclareRetScalarInst:
2021   case NVPTX::DeclareScalarParamInst:  case NVPTX::DeclareScalarRegInst:
2022   case NVPTX::StoreParamF32:  case NVPTX::StoreParamF64:
2023   case NVPTX::StoreParamI16:  case NVPTX::StoreParamI32:
2024   case NVPTX::StoreParamI64:  case NVPTX::StoreParamI8:
2025   case NVPTX::StoreParamS32I8:  case NVPTX::StoreParamU32I8:
2026   case NVPTX::StoreParamS32I16:  case NVPTX::StoreParamU32I16:
2027   case NVPTX::StoreParamScalar2F32:  case NVPTX::StoreParamScalar2F64:
2028   case NVPTX::StoreParamScalar2I16:  case NVPTX::StoreParamScalar2I32:
2029   case NVPTX::StoreParamScalar2I64:  case NVPTX::StoreParamScalar2I8:
2030   case NVPTX::StoreParamScalar4F32:  case NVPTX::StoreParamScalar4I16:
2031   case NVPTX::StoreParamScalar4I32:  case NVPTX::StoreParamScalar4I8:
2032   case NVPTX::StoreParamV2F32:  case NVPTX::StoreParamV2F64:
2033   case NVPTX::StoreParamV2I16:  case NVPTX::StoreParamV2I32:
2034   case NVPTX::StoreParamV2I64:  case NVPTX::StoreParamV2I8:
2035   case NVPTX::StoreParamV4F32:  case NVPTX::StoreParamV4I16:
2036   case NVPTX::StoreParamV4I32:  case NVPTX::StoreParamV4I8:
2037   case NVPTX::StoreRetvalF32:  case NVPTX::StoreRetvalF64:
2038   case NVPTX::StoreRetvalI16:  case NVPTX::StoreRetvalI32:
2039   case NVPTX::StoreRetvalI64:  case NVPTX::StoreRetvalI8:
2040   case NVPTX::StoreRetvalScalar2F32:  case NVPTX::StoreRetvalScalar2F64:
2041   case NVPTX::StoreRetvalScalar2I16:  case NVPTX::StoreRetvalScalar2I32:
2042   case NVPTX::StoreRetvalScalar2I64:  case NVPTX::StoreRetvalScalar2I8:
2043   case NVPTX::StoreRetvalScalar4F32:  case NVPTX::StoreRetvalScalar4I16:
2044   case NVPTX::StoreRetvalScalar4I32:  case NVPTX::StoreRetvalScalar4I8:
2045   case NVPTX::StoreRetvalV2F32:  case NVPTX::StoreRetvalV2F64:
2046   case NVPTX::StoreRetvalV2I16:  case NVPTX::StoreRetvalV2I32:
2047   case NVPTX::StoreRetvalV2I64:  case NVPTX::StoreRetvalV2I8:
2048   case NVPTX::StoreRetvalV4F32:  case NVPTX::StoreRetvalV4I16:
2049   case NVPTX::StoreRetvalV4I32:  case NVPTX::StoreRetvalV4I8:
2050   case NVPTX::LastCallArgF32:  case NVPTX::LastCallArgF64:
2051   case NVPTX::LastCallArgI16:  case NVPTX::LastCallArgI32:
2052   case NVPTX::LastCallArgI32imm:  case NVPTX::LastCallArgI64:
2053   case NVPTX::LastCallArgI8:  case NVPTX::LastCallArgParam:
2054   case NVPTX::LoadParamMemF32:  case NVPTX::LoadParamMemF64:
2055   case NVPTX::LoadParamMemI16:  case NVPTX::LoadParamMemI32:
2056   case NVPTX::LoadParamMemI64:  case NVPTX::LoadParamMemI8:
2057   case NVPTX::LoadParamRegF32:  case NVPTX::LoadParamRegF64:
2058   case NVPTX::LoadParamRegI16:  case NVPTX::LoadParamRegI32:
2059   case NVPTX::LoadParamRegI64:  case NVPTX::LoadParamRegI8:
2060   case NVPTX::LoadParamScalar2F32:  case NVPTX::LoadParamScalar2F64:
2061   case NVPTX::LoadParamScalar2I16:  case NVPTX::LoadParamScalar2I32:
2062   case NVPTX::LoadParamScalar2I64:  case NVPTX::LoadParamScalar2I8:
2063   case NVPTX::LoadParamScalar4F32:  case NVPTX::LoadParamScalar4I16:
2064   case NVPTX::LoadParamScalar4I32:  case NVPTX::LoadParamScalar4I8:
2065   case NVPTX::LoadParamV2F32:  case NVPTX::LoadParamV2F64:
2066   case NVPTX::LoadParamV2I16:  case NVPTX::LoadParamV2I32:
2067   case NVPTX::LoadParamV2I64:  case NVPTX::LoadParamV2I8:
2068   case NVPTX::LoadParamV4F32:  case NVPTX::LoadParamV4I16:
2069   case NVPTX::LoadParamV4I32:  case NVPTX::LoadParamV4I8:
2070   case NVPTX::PrototypeInst:   case NVPTX::DBG_VALUE:
2071     return true;
2072   }
2073   return false;
2074 }
2075
2076 // Force static initialization.
2077 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2078   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2079   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2080 }
2081
2082
2083 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2084   std::stringstream temp;
2085   LineReader * reader = this->getReader(filename.str());
2086   temp << "\n//";
2087   temp << filename.str();
2088   temp << ":";
2089   temp << line;
2090   temp << " ";
2091   temp << reader->readLine(line);
2092   temp << "\n";
2093   this->OutStreamer.EmitRawText(Twine(temp.str()));
2094 }
2095
2096
2097 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2098   if (reader == NULL)  {
2099     reader =  new LineReader(filename);
2100   }
2101
2102   if (reader->fileName() != filename) {
2103     delete reader;
2104     reader =  new LineReader(filename);
2105   }
2106
2107   return reader;
2108 }
2109
2110
2111 std::string
2112 LineReader::readLine(unsigned lineNum) {
2113   if (lineNum < theCurLine) {
2114     theCurLine = 0;
2115     fstr.seekg(0,std::ios::beg);
2116   }
2117   while (theCurLine < lineNum) {
2118     fstr.getline(buff,500);
2119     theCurLine++;
2120   }
2121   return buff;
2122 }
2123
2124 // Force static initialization.
2125 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2126   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2127   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2128 }