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