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