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