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