LLVM API Documentation

NVPTXAsmPrinter.cpp
Go to the documentation of this file.
00001 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains a printer that converts from our internal representation
00011 // of machine-dependent LLVM code to NVPTX assembly language.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "NVPTXAsmPrinter.h"
00016 #include "InstPrinter/NVPTXInstPrinter.h"
00017 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
00018 #include "NVPTX.h"
00019 #include "NVPTXInstrInfo.h"
00020 #include "NVPTXMachineFunctionInfo.h"
00021 #include "NVPTXMCExpr.h"
00022 #include "NVPTXRegisterInfo.h"
00023 #include "NVPTXTargetMachine.h"
00024 #include "NVPTXUtilities.h"
00025 #include "cl_common_defines.h"
00026 #include "llvm/ADT/StringExtras.h"
00027 #include "llvm/Analysis/ConstantFolding.h"
00028 #include "llvm/CodeGen/Analysis.h"
00029 #include "llvm/CodeGen/MachineFrameInfo.h"
00030 #include "llvm/CodeGen/MachineModuleInfo.h"
00031 #include "llvm/CodeGen/MachineRegisterInfo.h"
00032 #include "llvm/IR/DebugInfo.h"
00033 #include "llvm/IR/DerivedTypes.h"
00034 #include "llvm/IR/Function.h"
00035 #include "llvm/IR/GlobalVariable.h"
00036 #include "llvm/IR/Mangler.h"
00037 #include "llvm/IR/Module.h"
00038 #include "llvm/IR/Operator.h"
00039 #include "llvm/MC/MCStreamer.h"
00040 #include "llvm/MC/MCSymbol.h"
00041 #include "llvm/Support/CommandLine.h"
00042 #include "llvm/Support/ErrorHandling.h"
00043 #include "llvm/Support/FormattedStream.h"
00044 #include "llvm/Support/Path.h"
00045 #include "llvm/Support/TargetRegistry.h"
00046 #include "llvm/Support/TimeValue.h"
00047 #include "llvm/Target/TargetLoweringObjectFile.h"
00048 #include <sstream>
00049 using namespace llvm;
00050 
00051 #define DEPOTNAME "__local_depot"
00052 
00053 static cl::opt<bool>
00054 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
00055                 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
00056                 cl::init(true));
00057 
00058 static cl::opt<bool>
00059 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
00060               cl::desc("NVPTX Specific: Emit source line in ptx file"),
00061               cl::init(false));
00062 
00063 namespace {
00064 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
00065 /// depends.
00066 void DiscoverDependentGlobals(const Value *V,
00067                               DenseSet<const GlobalVariable *> &Globals) {
00068   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00069     Globals.insert(GV);
00070   else {
00071     if (const User *U = dyn_cast<User>(V)) {
00072       for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
00073         DiscoverDependentGlobals(U->getOperand(i), Globals);
00074       }
00075     }
00076   }
00077 }
00078 
00079 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
00080 /// instances to be emitted, but only after any dependents have been added
00081 /// first.
00082 void VisitGlobalVariableForEmission(
00083     const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
00084     DenseSet<const GlobalVariable *> &Visited,
00085     DenseSet<const GlobalVariable *> &Visiting) {
00086   // Have we already visited this one?
00087   if (Visited.count(GV))
00088     return;
00089 
00090   // Do we have a circular dependency?
00091   if (Visiting.count(GV))
00092     report_fatal_error("Circular dependency found in global variable set");
00093 
00094   // Start visiting this global
00095   Visiting.insert(GV);
00096 
00097   // Make sure we visit all dependents first
00098   DenseSet<const GlobalVariable *> Others;
00099   for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
00100     DiscoverDependentGlobals(GV->getOperand(i), Others);
00101 
00102   for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
00103                                                   E = Others.end();
00104        I != E; ++I)
00105     VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
00106 
00107   // Now we can visit ourself
00108   Order.push_back(GV);
00109   Visited.insert(GV);
00110   Visiting.erase(GV);
00111 }
00112 }
00113 
00114 // @TODO: This is a copy from AsmPrinter.cpp.  The function is static, so we
00115 // cannot just link to the existing version.
00116 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
00117 ///
00118 using namespace nvptx;
00119 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
00120   MCContext &Ctx = AP.OutContext;
00121 
00122   if (CV->isNullValue() || isa<UndefValue>(CV))
00123     return MCConstantExpr::Create(0, Ctx);
00124 
00125   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
00126     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
00127 
00128   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
00129     return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
00130 
00131   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
00132     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
00133 
00134   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
00135   if (CE == 0)
00136     llvm_unreachable("Unknown constant value to lower!");
00137 
00138   switch (CE->getOpcode()) {
00139   default:
00140     // If the code isn't optimized, there may be outstanding folding
00141     // opportunities. Attempt to fold the expression using DataLayout as a
00142     // last resort before giving up.
00143     if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
00144       if (C != CE)
00145         return LowerConstant(C, AP);
00146 
00147     // Otherwise report the problem to the user.
00148     {
00149       std::string S;
00150       raw_string_ostream OS(S);
00151       OS << "Unsupported expression in static initializer: ";
00152       CE->printAsOperand(OS, /*PrintType=*/ false,
00153                          !AP.MF ? 0 : AP.MF->getFunction()->getParent());
00154       report_fatal_error(OS.str());
00155     }
00156   case Instruction::AddrSpaceCast: {
00157     // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
00158     // handled by the generic() logic in the MCExpr printer
00159     PointerType *DstTy            = cast<PointerType>(CE->getType());
00160     PointerType *SrcTy            = cast<PointerType>(CE->getOperand(0)->getType());
00161     if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
00162       return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
00163     }
00164     std::string S;
00165     raw_string_ostream OS(S);
00166     OS << "Unsupported expression in static initializer: ";
00167     CE->printAsOperand(OS, /*PrintType=*/ false,
00168                        !AP.MF ? 0 : AP.MF->getFunction()->getParent());
00169     report_fatal_error(OS.str());
00170   }
00171   case Instruction::GetElementPtr: {
00172     const DataLayout &TD = *AP.TM.getDataLayout();
00173     // Generate a symbolic expression for the byte address
00174     APInt OffsetAI(TD.getPointerSizeInBits(), 0);
00175     cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
00176 
00177     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
00178     if (!OffsetAI)
00179       return Base;
00180 
00181     int64_t Offset = OffsetAI.getSExtValue();
00182     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
00183                                    Ctx);
00184   }
00185 
00186   case Instruction::Trunc:
00187     // We emit the value and depend on the assembler to truncate the generated
00188     // expression properly.  This is important for differences between
00189     // blockaddress labels.  Since the two labels are in the same function, it
00190     // is reasonable to treat their delta as a 32-bit value.
00191   // FALL THROUGH.
00192   case Instruction::BitCast:
00193     return LowerConstant(CE->getOperand(0), AP);
00194 
00195   case Instruction::IntToPtr: {
00196     const DataLayout &TD = *AP.TM.getDataLayout();
00197     // Handle casts to pointers by changing them into casts to the appropriate
00198     // integer type.  This promotes constant folding and simplifies this code.
00199     Constant *Op = CE->getOperand(0);
00200     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
00201                                       false /*ZExt*/);
00202     return LowerConstant(Op, AP);
00203   }
00204 
00205   case Instruction::PtrToInt: {
00206     const DataLayout &TD = *AP.TM.getDataLayout();
00207     // Support only foldable casts to/from pointers that can be eliminated by
00208     // changing the pointer to the appropriately sized integer type.
00209     Constant *Op = CE->getOperand(0);
00210     Type *Ty = CE->getType();
00211 
00212     const MCExpr *OpExpr = LowerConstant(Op, AP);
00213 
00214     // We can emit the pointer value into this slot if the slot is an
00215     // integer slot equal to the size of the pointer.
00216     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
00217       return OpExpr;
00218 
00219     // Otherwise the pointer is smaller than the resultant integer, mask off
00220     // the high bits so we are sure to get a proper truncation if the input is
00221     // a constant expr.
00222     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
00223     const MCExpr *MaskExpr =
00224         MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
00225     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
00226   }
00227 
00228     // The MC library also has a right-shift operator, but it isn't consistently
00229   // signed or unsigned between different targets.
00230   case Instruction::Add:
00231   case Instruction::Sub:
00232   case Instruction::Mul:
00233   case Instruction::SDiv:
00234   case Instruction::SRem:
00235   case Instruction::Shl:
00236   case Instruction::And:
00237   case Instruction::Or:
00238   case Instruction::Xor: {
00239     const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
00240     const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
00241     switch (CE->getOpcode()) {
00242     default:
00243       llvm_unreachable("Unknown binary operator constant cast expr");
00244     case Instruction::Add:
00245       return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
00246     case Instruction::Sub:
00247       return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
00248     case Instruction::Mul:
00249       return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
00250     case Instruction::SDiv:
00251       return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
00252     case Instruction::SRem:
00253       return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
00254     case Instruction::Shl:
00255       return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
00256     case Instruction::And:
00257       return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
00258     case Instruction::Or:
00259       return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
00260     case Instruction::Xor:
00261       return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
00262     }
00263   }
00264   }
00265 }
00266 
00267 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
00268   if (!EmitLineNumbers)
00269     return;
00270   if (ignoreLoc(MI))
00271     return;
00272 
00273   DebugLoc curLoc = MI.getDebugLoc();
00274 
00275   if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
00276     return;
00277 
00278   if (prevDebugLoc == curLoc)
00279     return;
00280 
00281   prevDebugLoc = curLoc;
00282 
00283   if (curLoc.isUnknown())
00284     return;
00285 
00286   const MachineFunction *MF = MI.getParent()->getParent();
00287   //const TargetMachine &TM = MF->getTarget();
00288 
00289   const LLVMContext &ctx = MF->getFunction()->getContext();
00290   DIScope Scope(curLoc.getScope(ctx));
00291 
00292   assert((!Scope || Scope.isScope()) &&
00293     "Scope of a DebugLoc should be null or a DIScope.");
00294   if (!Scope)
00295      return;
00296 
00297   StringRef fileName(Scope.getFilename());
00298   StringRef dirName(Scope.getDirectory());
00299   SmallString<128> FullPathName = dirName;
00300   if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
00301     sys::path::append(FullPathName, fileName);
00302     fileName = FullPathName.str();
00303   }
00304 
00305   if (filenameMap.find(fileName.str()) == filenameMap.end())
00306     return;
00307 
00308   // Emit the line from the source file.
00309   if (InterleaveSrc)
00310     this->emitSrcInText(fileName.str(), curLoc.getLine());
00311 
00312   std::stringstream temp;
00313   temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
00314        << " " << curLoc.getCol();
00315   OutStreamer.EmitRawText(Twine(temp.str().c_str()));
00316 }
00317 
00318 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
00319   SmallString<128> Str;
00320   raw_svector_ostream OS(Str);
00321   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
00322     emitLineNumberAsDotLoc(*MI);
00323 
00324   MCInst Inst;
00325   lowerToMCInst(MI, Inst);
00326   EmitToStreamer(OutStreamer, Inst);
00327 }
00328 
00329 // Handle symbol backtracking for targets that do not support image handles
00330 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
00331                                            unsigned OpNo, MCOperand &MCOp) {
00332   const MachineOperand &MO = MI->getOperand(OpNo);
00333 
00334   switch (MI->getOpcode()) {
00335   default: return false;
00336   case NVPTX::TEX_1D_F32_I32:
00337   case NVPTX::TEX_1D_F32_F32:
00338   case NVPTX::TEX_1D_F32_F32_LEVEL:
00339   case NVPTX::TEX_1D_F32_F32_GRAD:
00340   case NVPTX::TEX_1D_I32_I32:
00341   case NVPTX::TEX_1D_I32_F32:
00342   case NVPTX::TEX_1D_I32_F32_LEVEL:
00343   case NVPTX::TEX_1D_I32_F32_GRAD:
00344   case NVPTX::TEX_1D_ARRAY_F32_I32:
00345   case NVPTX::TEX_1D_ARRAY_F32_F32:
00346   case NVPTX::TEX_1D_ARRAY_F32_F32_LEVEL:
00347   case NVPTX::TEX_1D_ARRAY_F32_F32_GRAD:
00348   case NVPTX::TEX_1D_ARRAY_I32_I32:
00349   case NVPTX::TEX_1D_ARRAY_I32_F32:
00350   case NVPTX::TEX_1D_ARRAY_I32_F32_LEVEL:
00351   case NVPTX::TEX_1D_ARRAY_I32_F32_GRAD:
00352   case NVPTX::TEX_2D_F32_I32:
00353   case NVPTX::TEX_2D_F32_F32:
00354   case NVPTX::TEX_2D_F32_F32_LEVEL:
00355   case NVPTX::TEX_2D_F32_F32_GRAD:
00356   case NVPTX::TEX_2D_I32_I32:
00357   case NVPTX::TEX_2D_I32_F32:
00358   case NVPTX::TEX_2D_I32_F32_LEVEL:
00359   case NVPTX::TEX_2D_I32_F32_GRAD:
00360   case NVPTX::TEX_2D_ARRAY_F32_I32:
00361   case NVPTX::TEX_2D_ARRAY_F32_F32:
00362   case NVPTX::TEX_2D_ARRAY_F32_F32_LEVEL:
00363   case NVPTX::TEX_2D_ARRAY_F32_F32_GRAD:
00364   case NVPTX::TEX_2D_ARRAY_I32_I32:
00365   case NVPTX::TEX_2D_ARRAY_I32_F32:
00366   case NVPTX::TEX_2D_ARRAY_I32_F32_LEVEL:
00367   case NVPTX::TEX_2D_ARRAY_I32_F32_GRAD:
00368   case NVPTX::TEX_3D_F32_I32:
00369   case NVPTX::TEX_3D_F32_F32:
00370   case NVPTX::TEX_3D_F32_F32_LEVEL:
00371   case NVPTX::TEX_3D_F32_F32_GRAD:
00372   case NVPTX::TEX_3D_I32_I32:
00373   case NVPTX::TEX_3D_I32_F32:
00374   case NVPTX::TEX_3D_I32_F32_LEVEL:
00375   case NVPTX::TEX_3D_I32_F32_GRAD:
00376    {
00377     // This is a texture fetch, so operand 4 is a texref and operand 5 is
00378     // a samplerref
00379     if (OpNo == 4) {
00380       lowerImageHandleSymbol(MO.getImm(), MCOp);
00381       return true;
00382     }
00383     if (OpNo == 5) {
00384       lowerImageHandleSymbol(MO.getImm(), MCOp);
00385       return true;
00386     }
00387 
00388     return false;
00389   }
00390   case NVPTX::SULD_1D_I8_TRAP:
00391   case NVPTX::SULD_1D_I16_TRAP:
00392   case NVPTX::SULD_1D_I32_TRAP:
00393   case NVPTX::SULD_1D_ARRAY_I8_TRAP:
00394   case NVPTX::SULD_1D_ARRAY_I16_TRAP:
00395   case NVPTX::SULD_1D_ARRAY_I32_TRAP:
00396   case NVPTX::SULD_2D_I8_TRAP:
00397   case NVPTX::SULD_2D_I16_TRAP:
00398   case NVPTX::SULD_2D_I32_TRAP:
00399   case NVPTX::SULD_2D_ARRAY_I8_TRAP:
00400   case NVPTX::SULD_2D_ARRAY_I16_TRAP:
00401   case NVPTX::SULD_2D_ARRAY_I32_TRAP:
00402   case NVPTX::SULD_3D_I8_TRAP:
00403   case NVPTX::SULD_3D_I16_TRAP:
00404   case NVPTX::SULD_3D_I32_TRAP: {
00405     // This is a V1 surface load, so operand 1 is a surfref
00406     if (OpNo == 1) {
00407       lowerImageHandleSymbol(MO.getImm(), MCOp);
00408       return true;
00409     }
00410 
00411     return false;
00412   }
00413   case NVPTX::SULD_1D_V2I8_TRAP:
00414   case NVPTX::SULD_1D_V2I16_TRAP:
00415   case NVPTX::SULD_1D_V2I32_TRAP:
00416   case NVPTX::SULD_1D_ARRAY_V2I8_TRAP:
00417   case NVPTX::SULD_1D_ARRAY_V2I16_TRAP:
00418   case NVPTX::SULD_1D_ARRAY_V2I32_TRAP:
00419   case NVPTX::SULD_2D_V2I8_TRAP:
00420   case NVPTX::SULD_2D_V2I16_TRAP:
00421   case NVPTX::SULD_2D_V2I32_TRAP:
00422   case NVPTX::SULD_2D_ARRAY_V2I8_TRAP:
00423   case NVPTX::SULD_2D_ARRAY_V2I16_TRAP:
00424   case NVPTX::SULD_2D_ARRAY_V2I32_TRAP:
00425   case NVPTX::SULD_3D_V2I8_TRAP:
00426   case NVPTX::SULD_3D_V2I16_TRAP:
00427   case NVPTX::SULD_3D_V2I32_TRAP: {
00428     // This is a V2 surface load, so operand 2 is a surfref
00429     if (OpNo == 2) {
00430       lowerImageHandleSymbol(MO.getImm(), MCOp);
00431       return true;
00432     }
00433 
00434     return false;
00435   }
00436   case NVPTX::SULD_1D_V4I8_TRAP:
00437   case NVPTX::SULD_1D_V4I16_TRAP:
00438   case NVPTX::SULD_1D_V4I32_TRAP:
00439   case NVPTX::SULD_1D_ARRAY_V4I8_TRAP:
00440   case NVPTX::SULD_1D_ARRAY_V4I16_TRAP:
00441   case NVPTX::SULD_1D_ARRAY_V4I32_TRAP:
00442   case NVPTX::SULD_2D_V4I8_TRAP:
00443   case NVPTX::SULD_2D_V4I16_TRAP:
00444   case NVPTX::SULD_2D_V4I32_TRAP:
00445   case NVPTX::SULD_2D_ARRAY_V4I8_TRAP:
00446   case NVPTX::SULD_2D_ARRAY_V4I16_TRAP:
00447   case NVPTX::SULD_2D_ARRAY_V4I32_TRAP:
00448   case NVPTX::SULD_3D_V4I8_TRAP:
00449   case NVPTX::SULD_3D_V4I16_TRAP:
00450   case NVPTX::SULD_3D_V4I32_TRAP: {
00451     // This is a V4 surface load, so operand 4 is a surfref
00452     if (OpNo == 4) {
00453       lowerImageHandleSymbol(MO.getImm(), MCOp);
00454       return true;
00455     }
00456 
00457     return false;
00458   }
00459   case NVPTX::SUST_B_1D_B8_TRAP:
00460   case NVPTX::SUST_B_1D_B16_TRAP:
00461   case NVPTX::SUST_B_1D_B32_TRAP:
00462   case NVPTX::SUST_B_1D_V2B8_TRAP:
00463   case NVPTX::SUST_B_1D_V2B16_TRAP:
00464   case NVPTX::SUST_B_1D_V2B32_TRAP:
00465   case NVPTX::SUST_B_1D_V4B8_TRAP:
00466   case NVPTX::SUST_B_1D_V4B16_TRAP:
00467   case NVPTX::SUST_B_1D_V4B32_TRAP:
00468   case NVPTX::SUST_B_1D_ARRAY_B8_TRAP:
00469   case NVPTX::SUST_B_1D_ARRAY_B16_TRAP:
00470   case NVPTX::SUST_B_1D_ARRAY_B32_TRAP:
00471   case NVPTX::SUST_B_1D_ARRAY_V2B8_TRAP:
00472   case NVPTX::SUST_B_1D_ARRAY_V2B16_TRAP:
00473   case NVPTX::SUST_B_1D_ARRAY_V2B32_TRAP:
00474   case NVPTX::SUST_B_1D_ARRAY_V4B8_TRAP:
00475   case NVPTX::SUST_B_1D_ARRAY_V4B16_TRAP:
00476   case NVPTX::SUST_B_1D_ARRAY_V4B32_TRAP:
00477   case NVPTX::SUST_B_2D_B8_TRAP:
00478   case NVPTX::SUST_B_2D_B16_TRAP:
00479   case NVPTX::SUST_B_2D_B32_TRAP:
00480   case NVPTX::SUST_B_2D_V2B8_TRAP:
00481   case NVPTX::SUST_B_2D_V2B16_TRAP:
00482   case NVPTX::SUST_B_2D_V2B32_TRAP:
00483   case NVPTX::SUST_B_2D_V4B8_TRAP:
00484   case NVPTX::SUST_B_2D_V4B16_TRAP:
00485   case NVPTX::SUST_B_2D_V4B32_TRAP:
00486   case NVPTX::SUST_B_2D_ARRAY_B8_TRAP:
00487   case NVPTX::SUST_B_2D_ARRAY_B16_TRAP:
00488   case NVPTX::SUST_B_2D_ARRAY_B32_TRAP:
00489   case NVPTX::SUST_B_2D_ARRAY_V2B8_TRAP:
00490   case NVPTX::SUST_B_2D_ARRAY_V2B16_TRAP:
00491   case NVPTX::SUST_B_2D_ARRAY_V2B32_TRAP:
00492   case NVPTX::SUST_B_2D_ARRAY_V4B8_TRAP:
00493   case NVPTX::SUST_B_2D_ARRAY_V4B16_TRAP:
00494   case NVPTX::SUST_B_2D_ARRAY_V4B32_TRAP:
00495   case NVPTX::SUST_B_3D_B8_TRAP:
00496   case NVPTX::SUST_B_3D_B16_TRAP:
00497   case NVPTX::SUST_B_3D_B32_TRAP:
00498   case NVPTX::SUST_B_3D_V2B8_TRAP:
00499   case NVPTX::SUST_B_3D_V2B16_TRAP:
00500   case NVPTX::SUST_B_3D_V2B32_TRAP:
00501   case NVPTX::SUST_B_3D_V4B8_TRAP:
00502   case NVPTX::SUST_B_3D_V4B16_TRAP:
00503   case NVPTX::SUST_B_3D_V4B32_TRAP:
00504   case NVPTX::SUST_P_1D_B8_TRAP:
00505   case NVPTX::SUST_P_1D_B16_TRAP:
00506   case NVPTX::SUST_P_1D_B32_TRAP:
00507   case NVPTX::SUST_P_1D_V2B8_TRAP:
00508   case NVPTX::SUST_P_1D_V2B16_TRAP:
00509   case NVPTX::SUST_P_1D_V2B32_TRAP:
00510   case NVPTX::SUST_P_1D_V4B8_TRAP:
00511   case NVPTX::SUST_P_1D_V4B16_TRAP:
00512   case NVPTX::SUST_P_1D_V4B32_TRAP:
00513   case NVPTX::SUST_P_1D_ARRAY_B8_TRAP:
00514   case NVPTX::SUST_P_1D_ARRAY_B16_TRAP:
00515   case NVPTX::SUST_P_1D_ARRAY_B32_TRAP:
00516   case NVPTX::SUST_P_1D_ARRAY_V2B8_TRAP:
00517   case NVPTX::SUST_P_1D_ARRAY_V2B16_TRAP:
00518   case NVPTX::SUST_P_1D_ARRAY_V2B32_TRAP:
00519   case NVPTX::SUST_P_1D_ARRAY_V4B8_TRAP:
00520   case NVPTX::SUST_P_1D_ARRAY_V4B16_TRAP:
00521   case NVPTX::SUST_P_1D_ARRAY_V4B32_TRAP:
00522   case NVPTX::SUST_P_2D_B8_TRAP:
00523   case NVPTX::SUST_P_2D_B16_TRAP:
00524   case NVPTX::SUST_P_2D_B32_TRAP:
00525   case NVPTX::SUST_P_2D_V2B8_TRAP:
00526   case NVPTX::SUST_P_2D_V2B16_TRAP:
00527   case NVPTX::SUST_P_2D_V2B32_TRAP:
00528   case NVPTX::SUST_P_2D_V4B8_TRAP:
00529   case NVPTX::SUST_P_2D_V4B16_TRAP:
00530   case NVPTX::SUST_P_2D_V4B32_TRAP:
00531   case NVPTX::SUST_P_2D_ARRAY_B8_TRAP:
00532   case NVPTX::SUST_P_2D_ARRAY_B16_TRAP:
00533   case NVPTX::SUST_P_2D_ARRAY_B32_TRAP:
00534   case NVPTX::SUST_P_2D_ARRAY_V2B8_TRAP:
00535   case NVPTX::SUST_P_2D_ARRAY_V2B16_TRAP:
00536   case NVPTX::SUST_P_2D_ARRAY_V2B32_TRAP:
00537   case NVPTX::SUST_P_2D_ARRAY_V4B8_TRAP:
00538   case NVPTX::SUST_P_2D_ARRAY_V4B16_TRAP:
00539   case NVPTX::SUST_P_2D_ARRAY_V4B32_TRAP:
00540   case NVPTX::SUST_P_3D_B8_TRAP:
00541   case NVPTX::SUST_P_3D_B16_TRAP:
00542   case NVPTX::SUST_P_3D_B32_TRAP:
00543   case NVPTX::SUST_P_3D_V2B8_TRAP:
00544   case NVPTX::SUST_P_3D_V2B16_TRAP:
00545   case NVPTX::SUST_P_3D_V2B32_TRAP:
00546   case NVPTX::SUST_P_3D_V4B8_TRAP:
00547   case NVPTX::SUST_P_3D_V4B16_TRAP:
00548   case NVPTX::SUST_P_3D_V4B32_TRAP: {
00549     // This is a surface store, so operand 0 is a surfref
00550     if (OpNo == 0) {
00551       lowerImageHandleSymbol(MO.getImm(), MCOp);
00552       return true;
00553     }
00554 
00555     return false;
00556   }
00557   case NVPTX::TXQ_CHANNEL_ORDER:
00558   case NVPTX::TXQ_CHANNEL_DATA_TYPE:
00559   case NVPTX::TXQ_WIDTH:
00560   case NVPTX::TXQ_HEIGHT:
00561   case NVPTX::TXQ_DEPTH:
00562   case NVPTX::TXQ_ARRAY_SIZE:
00563   case NVPTX::TXQ_NUM_SAMPLES:
00564   case NVPTX::TXQ_NUM_MIPMAP_LEVELS:
00565   case NVPTX::SUQ_CHANNEL_ORDER:
00566   case NVPTX::SUQ_CHANNEL_DATA_TYPE:
00567   case NVPTX::SUQ_WIDTH:
00568   case NVPTX::SUQ_HEIGHT:
00569   case NVPTX::SUQ_DEPTH:
00570   case NVPTX::SUQ_ARRAY_SIZE: {
00571     // This is a query, so operand 1 is a surfref/texref
00572     if (OpNo == 1) {
00573       lowerImageHandleSymbol(MO.getImm(), MCOp);
00574       return true;
00575     }
00576 
00577     return false;
00578   }
00579   }
00580 }
00581 
00582 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
00583   // Ewwww
00584   TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
00585   NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
00586   const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
00587   const char *Sym = MFI->getImageHandleSymbol(Index);
00588   std::string *SymNamePtr =
00589     nvTM.getManagedStrPool()->getManagedString(Sym);
00590   MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
00591     StringRef(SymNamePtr->c_str())));
00592 }
00593 
00594 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
00595   OutMI.setOpcode(MI->getOpcode());
00596   const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
00597 
00598   // Special: Do not mangle symbol operand of CALL_PROTOTYPE
00599   if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
00600     const MachineOperand &MO = MI->getOperand(0);
00601     OutMI.addOperand(GetSymbolRef(
00602       OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
00603     return;
00604   }
00605 
00606   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00607     const MachineOperand &MO = MI->getOperand(i);
00608 
00609     MCOperand MCOp;
00610     if (!ST.hasImageHandles()) {
00611       if (lowerImageHandleOperand(MI, i, MCOp)) {
00612         OutMI.addOperand(MCOp);
00613         continue;
00614       }
00615     }
00616 
00617     if (lowerOperand(MO, MCOp))
00618       OutMI.addOperand(MCOp);
00619   }
00620 }
00621 
00622 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
00623                                    MCOperand &MCOp) {
00624   switch (MO.getType()) {
00625   default: llvm_unreachable("unknown operand type");
00626   case MachineOperand::MO_Register:
00627     MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
00628     break;
00629   case MachineOperand::MO_Immediate:
00630     MCOp = MCOperand::CreateImm(MO.getImm());
00631     break;
00632   case MachineOperand::MO_MachineBasicBlock:
00633     MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
00634         MO.getMBB()->getSymbol(), OutContext));
00635     break;
00636   case MachineOperand::MO_ExternalSymbol:
00637     MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
00638     break;
00639   case MachineOperand::MO_GlobalAddress:
00640     MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
00641     break;
00642   case MachineOperand::MO_FPImmediate: {
00643     const ConstantFP *Cnt = MO.getFPImm();
00644     APFloat Val = Cnt->getValueAPF();
00645 
00646     switch (Cnt->getType()->getTypeID()) {
00647     default: report_fatal_error("Unsupported FP type"); break;
00648     case Type::FloatTyID:
00649       MCOp = MCOperand::CreateExpr(
00650         NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
00651       break;
00652     case Type::DoubleTyID:
00653       MCOp = MCOperand::CreateExpr(
00654         NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
00655       break;
00656     }
00657     break;
00658   }
00659   }
00660   return true;
00661 }
00662 
00663 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
00664   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00665     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
00666 
00667     DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
00668     unsigned RegNum = RegMap[Reg];
00669 
00670     // Encode the register class in the upper 4 bits
00671     // Must be kept in sync with NVPTXInstPrinter::printRegName
00672     unsigned Ret = 0;
00673     if (RC == &NVPTX::Int1RegsRegClass) {
00674       Ret = (1 << 28);
00675     } else if (RC == &NVPTX::Int16RegsRegClass) {
00676       Ret = (2 << 28);
00677     } else if (RC == &NVPTX::Int32RegsRegClass) {
00678       Ret = (3 << 28);
00679     } else if (RC == &NVPTX::Int64RegsRegClass) {
00680       Ret = (4 << 28);
00681     } else if (RC == &NVPTX::Float32RegsRegClass) {
00682       Ret = (5 << 28);
00683     } else if (RC == &NVPTX::Float64RegsRegClass) {
00684       Ret = (6 << 28);
00685     } else {
00686       report_fatal_error("Bad register class");
00687     }
00688 
00689     // Insert the vreg number
00690     Ret |= (RegNum & 0x0FFFFFFF);
00691     return Ret;
00692   } else {
00693     // Some special-use registers are actually physical registers.
00694     // Encode this as the register class ID of 0 and the real register ID.
00695     return Reg & 0x0FFFFFFF;
00696   }
00697 }
00698 
00699 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
00700   const MCExpr *Expr;
00701   Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
00702                                  OutContext);
00703   return MCOperand::CreateExpr(Expr);
00704 }
00705 
00706 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
00707   const DataLayout *TD = TM.getDataLayout();
00708   const TargetLowering *TLI = TM.getTargetLowering();
00709 
00710   Type *Ty = F->getReturnType();
00711 
00712   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
00713 
00714   if (Ty->getTypeID() == Type::VoidTyID)
00715     return;
00716 
00717   O << " (";
00718 
00719   if (isABI) {
00720     if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
00721       unsigned size = 0;
00722       if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
00723         size = ITy->getBitWidth();
00724         if (size < 32)
00725           size = 32;
00726       } else {
00727         assert(Ty->isFloatingPointTy() && "Floating point type expected here");
00728         size = Ty->getPrimitiveSizeInBits();
00729       }
00730 
00731       O << ".param .b" << size << " func_retval0";
00732     } else if (isa<PointerType>(Ty)) {
00733       O << ".param .b" << TLI->getPointerTy().getSizeInBits()
00734         << " func_retval0";
00735     } else {
00736       if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
00737         SmallVector<EVT, 16> vtparts;
00738         ComputeValueVTs(*TLI, Ty, vtparts);
00739         unsigned totalsz = 0;
00740         for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
00741           unsigned elems = 1;
00742           EVT elemtype = vtparts[i];
00743           if (vtparts[i].isVector()) {
00744             elems = vtparts[i].getVectorNumElements();
00745             elemtype = vtparts[i].getVectorElementType();
00746           }
00747           for (unsigned j = 0, je = elems; j != je; ++j) {
00748             unsigned sz = elemtype.getSizeInBits();
00749             if (elemtype.isInteger() && (sz < 8))
00750               sz = 8;
00751             totalsz += sz / 8;
00752           }
00753         }
00754         unsigned retAlignment = 0;
00755         if (!llvm::getAlign(*F, 0, retAlignment))
00756           retAlignment = TD->getABITypeAlignment(Ty);
00757         O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
00758           << "]";
00759       } else
00760         assert(false && "Unknown return type");
00761     }
00762   } else {
00763     SmallVector<EVT, 16> vtparts;
00764     ComputeValueVTs(*TLI, Ty, vtparts);
00765     unsigned idx = 0;
00766     for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
00767       unsigned elems = 1;
00768       EVT elemtype = vtparts[i];
00769       if (vtparts[i].isVector()) {
00770         elems = vtparts[i].getVectorNumElements();
00771         elemtype = vtparts[i].getVectorElementType();
00772       }
00773 
00774       for (unsigned j = 0, je = elems; j != je; ++j) {
00775         unsigned sz = elemtype.getSizeInBits();
00776         if (elemtype.isInteger() && (sz < 32))
00777           sz = 32;
00778         O << ".reg .b" << sz << " func_retval" << idx;
00779         if (j < je - 1)
00780           O << ", ";
00781         ++idx;
00782       }
00783       if (i < e - 1)
00784         O << ", ";
00785     }
00786   }
00787   O << ") ";
00788   return;
00789 }
00790 
00791 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
00792                                         raw_ostream &O) {
00793   const Function *F = MF.getFunction();
00794   printReturnValStr(F, O);
00795 }
00796 
00797 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
00798   SmallString<128> Str;
00799   raw_svector_ostream O(Str);
00800 
00801   if (!GlobalsEmitted) {
00802     emitGlobals(*MF->getFunction()->getParent());
00803     GlobalsEmitted = true;
00804   }
00805   
00806   // Set up
00807   MRI = &MF->getRegInfo();
00808   F = MF->getFunction();
00809   emitLinkageDirective(F, O);
00810   if (llvm::isKernelFunction(*F))
00811     O << ".entry ";
00812   else {
00813     O << ".func ";
00814     printReturnValStr(*MF, O);
00815   }
00816 
00817   O << *CurrentFnSym;
00818 
00819   emitFunctionParamList(*MF, O);
00820 
00821   if (llvm::isKernelFunction(*F))
00822     emitKernelFunctionDirectives(*F, O);
00823 
00824   OutStreamer.EmitRawText(O.str());
00825 
00826   prevDebugLoc = DebugLoc();
00827 }
00828 
00829 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
00830   VRegMapping.clear();
00831   OutStreamer.EmitRawText(StringRef("{\n"));
00832   setAndEmitFunctionVirtualRegisters(*MF);
00833 
00834   SmallString<128> Str;
00835   raw_svector_ostream O(Str);
00836   emitDemotedVars(MF->getFunction(), O);
00837   OutStreamer.EmitRawText(O.str());
00838 }
00839 
00840 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
00841   OutStreamer.EmitRawText(StringRef("}\n"));
00842   VRegMapping.clear();
00843 }
00844 
00845 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
00846   unsigned RegNo = MI->getOperand(0).getReg();
00847   const TargetRegisterInfo *TRI = TM.getRegisterInfo();
00848   if (TRI->isVirtualRegister(RegNo)) {
00849     OutStreamer.AddComment(Twine("implicit-def: ") +
00850                            getVirtualRegisterName(RegNo));
00851   } else {
00852     OutStreamer.AddComment(Twine("implicit-def: ") +
00853                            TM.getRegisterInfo()->getName(RegNo));
00854   }
00855   OutStreamer.AddBlankLine();
00856 }
00857 
00858 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
00859                                                    raw_ostream &O) const {
00860   // If the NVVM IR has some of reqntid* specified, then output
00861   // the reqntid directive, and set the unspecified ones to 1.
00862   // If none of reqntid* is specified, don't output reqntid directive.
00863   unsigned reqntidx, reqntidy, reqntidz;
00864   bool specified = false;
00865   if (llvm::getReqNTIDx(F, reqntidx) == false)
00866     reqntidx = 1;
00867   else
00868     specified = true;
00869   if (llvm::getReqNTIDy(F, reqntidy) == false)
00870     reqntidy = 1;
00871   else
00872     specified = true;
00873   if (llvm::getReqNTIDz(F, reqntidz) == false)
00874     reqntidz = 1;
00875   else
00876     specified = true;
00877 
00878   if (specified)
00879     O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
00880       << "\n";
00881 
00882   // If the NVVM IR has some of maxntid* specified, then output
00883   // the maxntid directive, and set the unspecified ones to 1.
00884   // If none of maxntid* is specified, don't output maxntid directive.
00885   unsigned maxntidx, maxntidy, maxntidz;
00886   specified = false;
00887   if (llvm::getMaxNTIDx(F, maxntidx) == false)
00888     maxntidx = 1;
00889   else
00890     specified = true;
00891   if (llvm::getMaxNTIDy(F, maxntidy) == false)
00892     maxntidy = 1;
00893   else
00894     specified = true;
00895   if (llvm::getMaxNTIDz(F, maxntidz) == false)
00896     maxntidz = 1;
00897   else
00898     specified = true;
00899 
00900   if (specified)
00901     O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
00902       << "\n";
00903 
00904   unsigned mincta;
00905   if (llvm::getMinCTASm(F, mincta))
00906     O << ".minnctapersm " << mincta << "\n";
00907 }
00908 
00909 std::string
00910 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
00911   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
00912 
00913   std::string Name;
00914   raw_string_ostream NameStr(Name);
00915 
00916   VRegRCMap::const_iterator I = VRegMapping.find(RC);
00917   assert(I != VRegMapping.end() && "Bad register class");
00918   const DenseMap<unsigned, unsigned> &RegMap = I->second;
00919 
00920   VRegMap::const_iterator VI = RegMap.find(Reg);
00921   assert(VI != RegMap.end() && "Bad virtual register");
00922   unsigned MappedVR = VI->second;
00923 
00924   NameStr << getNVPTXRegClassStr(RC) << MappedVR;
00925 
00926   NameStr.flush();
00927   return Name;
00928 }
00929 
00930 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
00931                                           raw_ostream &O) {
00932   O << getVirtualRegisterName(vr);
00933 }
00934 
00935 void NVPTXAsmPrinter::printVecModifiedImmediate(
00936     const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
00937   static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
00938   int Imm = (int) MO.getImm();
00939   if (0 == strcmp(Modifier, "vecelem"))
00940     O << "_" << vecelem[Imm];
00941   else if (0 == strcmp(Modifier, "vecv4comm1")) {
00942     if ((Imm < 0) || (Imm > 3))
00943       O << "//";
00944   } else if (0 == strcmp(Modifier, "vecv4comm2")) {
00945     if ((Imm < 4) || (Imm > 7))
00946       O << "//";
00947   } else if (0 == strcmp(Modifier, "vecv4pos")) {
00948     if (Imm < 0)
00949       Imm = 0;
00950     O << "_" << vecelem[Imm % 4];
00951   } else if (0 == strcmp(Modifier, "vecv2comm1")) {
00952     if ((Imm < 0) || (Imm > 1))
00953       O << "//";
00954   } else if (0 == strcmp(Modifier, "vecv2comm2")) {
00955     if ((Imm < 2) || (Imm > 3))
00956       O << "//";
00957   } else if (0 == strcmp(Modifier, "vecv2pos")) {
00958     if (Imm < 0)
00959       Imm = 0;
00960     O << "_" << vecelem[Imm % 2];
00961   } else
00962     llvm_unreachable("Unknown Modifier on immediate operand");
00963 }
00964 
00965 
00966 
00967 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
00968 
00969   emitLinkageDirective(F, O);
00970   if (llvm::isKernelFunction(*F))
00971     O << ".entry ";
00972   else
00973     O << ".func ";
00974   printReturnValStr(F, O);
00975   O << *getSymbol(F) << "\n";
00976   emitFunctionParamList(F, O);
00977   O << ";\n";
00978 }
00979 
00980 static bool usedInGlobalVarDef(const Constant *C) {
00981   if (!C)
00982     return false;
00983 
00984   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00985     if (GV->getName().str() == "llvm.used")
00986       return false;
00987     return true;
00988   }
00989 
00990   for (const User *U : C->users())
00991     if (const Constant *C = dyn_cast<Constant>(U))
00992       if (usedInGlobalVarDef(C))
00993         return true;
00994 
00995   return false;
00996 }
00997 
00998 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
00999   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
01000     if (othergv->getName().str() == "llvm.used")
01001       return true;
01002   }
01003 
01004   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
01005     if (instr->getParent() && instr->getParent()->getParent()) {
01006       const Function *curFunc = instr->getParent()->getParent();
01007       if (oneFunc && (curFunc != oneFunc))
01008         return false;
01009       oneFunc = curFunc;
01010       return true;
01011     } else
01012       return false;
01013   }
01014 
01015   if (const MDNode *md = dyn_cast<MDNode>(U))
01016     if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
01017                           (md->getName().str() == "llvm.dbg.sp")))
01018       return true;
01019 
01020   for (const User *UU : U->users())
01021     if (usedInOneFunc(UU, oneFunc) == false)
01022       return false;
01023 
01024   return true;
01025 }
01026 
01027 /* Find out if a global variable can be demoted to local scope.
01028  * Currently, this is valid for CUDA shared variables, which have local
01029  * scope and global lifetime. So the conditions to check are :
01030  * 1. Is the global variable in shared address space?
01031  * 2. Does it have internal linkage?
01032  * 3. Is the global variable referenced only in one function?
01033  */
01034 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
01035   if (gv->hasInternalLinkage() == false)
01036     return false;
01037   const PointerType *Pty = gv->getType();
01038   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
01039     return false;
01040 
01041   const Function *oneFunc = 0;
01042 
01043   bool flag = usedInOneFunc(gv, oneFunc);
01044   if (flag == false)
01045     return false;
01046   if (!oneFunc)
01047     return false;
01048   f = oneFunc;
01049   return true;
01050 }
01051 
01052 static bool useFuncSeen(const Constant *C,
01053                         llvm::DenseMap<const Function *, bool> &seenMap) {
01054   for (const User *U : C->users()) {
01055     if (const Constant *cu = dyn_cast<Constant>(U)) {
01056       if (useFuncSeen(cu, seenMap))
01057         return true;
01058     } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
01059       const BasicBlock *bb = I->getParent();
01060       if (!bb)
01061         continue;
01062       const Function *caller = bb->getParent();
01063       if (!caller)
01064         continue;
01065       if (seenMap.find(caller) != seenMap.end())
01066         return true;
01067     }
01068   }
01069   return false;
01070 }
01071 
01072 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
01073   llvm::DenseMap<const Function *, bool> seenMap;
01074   for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
01075     const Function *F = FI;
01076 
01077     if (F->isDeclaration()) {
01078       if (F->use_empty())
01079         continue;
01080       if (F->getIntrinsicID())
01081         continue;
01082       emitDeclaration(F, O);
01083       continue;
01084     }
01085     for (const User *U : F->users()) {
01086       if (const Constant *C = dyn_cast<Constant>(U)) {
01087         if (usedInGlobalVarDef(C)) {
01088           // The use is in the initialization of a global variable
01089           // that is a function pointer, so print a declaration
01090           // for the original function
01091           emitDeclaration(F, O);
01092           break;
01093         }
01094         // Emit a declaration of this function if the function that
01095         // uses this constant expr has already been seen.
01096         if (useFuncSeen(C, seenMap)) {
01097           emitDeclaration(F, O);
01098           break;
01099         }
01100       }
01101 
01102       if (!isa<Instruction>(U))
01103         continue;
01104       const Instruction *instr = cast<Instruction>(U);
01105       const BasicBlock *bb = instr->getParent();
01106       if (!bb)
01107         continue;
01108       const Function *caller = bb->getParent();
01109       if (!caller)
01110         continue;
01111 
01112       // If a caller has already been seen, then the caller is
01113       // appearing in the module before the callee. so print out
01114       // a declaration for the callee.
01115       if (seenMap.find(caller) != seenMap.end()) {
01116         emitDeclaration(F, O);
01117         break;
01118       }
01119     }
01120     seenMap[F] = true;
01121   }
01122 }
01123 
01124 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
01125   DebugInfoFinder DbgFinder;
01126   DbgFinder.processModule(M);
01127 
01128   unsigned i = 1;
01129   for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
01130     StringRef Filename(DIUnit.getFilename());
01131     StringRef Dirname(DIUnit.getDirectory());
01132     SmallString<128> FullPathName = Dirname;
01133     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
01134       sys::path::append(FullPathName, Filename);
01135       Filename = FullPathName.str();
01136     }
01137     if (filenameMap.find(Filename.str()) != filenameMap.end())
01138       continue;
01139     filenameMap[Filename.str()] = i;
01140     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
01141     ++i;
01142   }
01143 
01144   for (DISubprogram SP : DbgFinder.subprograms()) {
01145     StringRef Filename(SP.getFilename());
01146     StringRef Dirname(SP.getDirectory());
01147     SmallString<128> FullPathName = Dirname;
01148     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
01149       sys::path::append(FullPathName, Filename);
01150       Filename = FullPathName.str();
01151     }
01152     if (filenameMap.find(Filename.str()) != filenameMap.end())
01153       continue;
01154     filenameMap[Filename.str()] = i;
01155     ++i;
01156   }
01157 }
01158 
01159 bool NVPTXAsmPrinter::doInitialization(Module &M) {
01160 
01161   SmallString<128> Str1;
01162   raw_svector_ostream OS1(Str1);
01163 
01164   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
01165   MMI->AnalyzeModule(M);
01166 
01167   // We need to call the parent's one explicitly.
01168   //bool Result = AsmPrinter::doInitialization(M);
01169 
01170   // Initialize TargetLoweringObjectFile.
01171   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
01172       .Initialize(OutContext, TM);
01173 
01174   Mang = new Mangler(TM.getDataLayout());
01175 
01176   // Emit header before any dwarf directives are emitted below.
01177   emitHeader(M, OS1);
01178   OutStreamer.EmitRawText(OS1.str());
01179 
01180   // Already commented out
01181   //bool Result = AsmPrinter::doInitialization(M);
01182 
01183   // Emit module-level inline asm if it exists.
01184   if (!M.getModuleInlineAsm().empty()) {
01185     OutStreamer.AddComment("Start of file scope inline assembly");
01186     OutStreamer.AddBlankLine();
01187     OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
01188     OutStreamer.AddBlankLine();
01189     OutStreamer.AddComment("End of file scope inline assembly");
01190     OutStreamer.AddBlankLine();
01191   }
01192 
01193   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
01194     recordAndEmitFilenames(M);
01195 
01196   GlobalsEmitted = false;
01197     
01198   return false; // success
01199 }
01200 
01201 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
01202   SmallString<128> Str2;
01203   raw_svector_ostream OS2(Str2);
01204 
01205   emitDeclarations(M, OS2);
01206 
01207   // As ptxas does not support forward references of globals, we need to first
01208   // sort the list of module-level globals in def-use order. We visit each
01209   // global variable in order, and ensure that we emit it *after* its dependent
01210   // globals. We use a little extra memory maintaining both a set and a list to
01211   // have fast searches while maintaining a strict ordering.
01212   SmallVector<const GlobalVariable *, 8> Globals;
01213   DenseSet<const GlobalVariable *> GVVisited;
01214   DenseSet<const GlobalVariable *> GVVisiting;
01215 
01216   // Visit each global variable, in order
01217   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
01218        I != E; ++I)
01219     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
01220 
01221   assert(GVVisited.size() == M.getGlobalList().size() &&
01222          "Missed a global variable");
01223   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
01224 
01225   // Print out module-level global variables in proper order
01226   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
01227     printModuleLevelGV(Globals[i], OS2);
01228 
01229   OS2 << '\n';
01230 
01231   OutStreamer.EmitRawText(OS2.str());
01232 }
01233 
01234 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
01235   O << "//\n";
01236   O << "// Generated by LLVM NVPTX Back-End\n";
01237   O << "//\n";
01238   O << "\n";
01239 
01240   unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
01241   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
01242 
01243   O << ".target ";
01244   O << nvptxSubtarget.getTargetName();
01245 
01246   if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
01247     O << ", texmode_independent";
01248   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
01249     if (!nvptxSubtarget.hasDouble())
01250       O << ", map_f64_to_f32";
01251   }
01252 
01253   if (MAI->doesSupportDebugInformation())
01254     O << ", debug";
01255 
01256   O << "\n";
01257 
01258   O << ".address_size ";
01259   if (nvptxSubtarget.is64Bit())
01260     O << "64";
01261   else
01262     O << "32";
01263   O << "\n";
01264 
01265   O << "\n";
01266 }
01267 
01268 bool NVPTXAsmPrinter::doFinalization(Module &M) {
01269 
01270   // If we did not emit any functions, then the global declarations have not
01271   // yet been emitted.
01272   if (!GlobalsEmitted) {
01273     emitGlobals(M);
01274     GlobalsEmitted = true;
01275   }
01276 
01277   // XXX Temproarily remove global variables so that doFinalization() will not
01278   // emit them again (global variables are emitted at beginning).
01279 
01280   Module::GlobalListType &global_list = M.getGlobalList();
01281   int i, n = global_list.size();
01282   GlobalVariable **gv_array = new GlobalVariable *[n];
01283 
01284   // first, back-up GlobalVariable in gv_array
01285   i = 0;
01286   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
01287        I != E; ++I)
01288     gv_array[i++] = &*I;
01289 
01290   // second, empty global_list
01291   while (!global_list.empty())
01292     global_list.remove(global_list.begin());
01293 
01294   // call doFinalization
01295   bool ret = AsmPrinter::doFinalization(M);
01296 
01297   // now we restore global variables
01298   for (i = 0; i < n; i++)
01299     global_list.insert(global_list.end(), gv_array[i]);
01300 
01301   clearAnnotationCache(&M);
01302 
01303   delete[] gv_array;
01304   return ret;
01305 
01306   //bool Result = AsmPrinter::doFinalization(M);
01307   // Instead of calling the parents doFinalization, we may
01308   // clone parents doFinalization and customize here.
01309   // Currently, we if NVISA out the EmitGlobals() in
01310   // parent's doFinalization, which is too intrusive.
01311   //
01312   // Same for the doInitialization.
01313   //return Result;
01314 }
01315 
01316 // This function emits appropriate linkage directives for
01317 // functions and global variables.
01318 //
01319 // extern function declaration            -> .extern
01320 // extern function definition             -> .visible
01321 // external global variable with init     -> .visible
01322 // external without init                  -> .extern
01323 // appending                              -> not allowed, assert.
01324 
01325 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
01326                                            raw_ostream &O) {
01327   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
01328     if (V->hasExternalLinkage()) {
01329       if (isa<GlobalVariable>(V)) {
01330         const GlobalVariable *GVar = cast<GlobalVariable>(V);
01331         if (GVar) {
01332           if (GVar->hasInitializer())
01333             O << ".visible ";
01334           else
01335             O << ".extern ";
01336         }
01337       } else if (V->isDeclaration())
01338         O << ".extern ";
01339       else
01340         O << ".visible ";
01341     } else if (V->hasAppendingLinkage()) {
01342       std::string msg;
01343       msg.append("Error: ");
01344       msg.append("Symbol ");
01345       if (V->hasName())
01346         msg.append(V->getName().str());
01347       msg.append("has unsupported appending linkage type");
01348       llvm_unreachable(msg.c_str());
01349     }
01350   }
01351 }
01352 
01353 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
01354                                          raw_ostream &O,
01355                                          bool processDemoted) {
01356 
01357   // Skip meta data
01358   if (GVar->hasSection()) {
01359     if (GVar->getSection() == "llvm.metadata")
01360       return;
01361   }
01362 
01363   const DataLayout *TD = TM.getDataLayout();
01364 
01365   // GlobalVariables are always constant pointers themselves.
01366   const PointerType *PTy = GVar->getType();
01367   Type *ETy = PTy->getElementType();
01368 
01369   if (GVar->hasExternalLinkage()) {
01370     if (GVar->hasInitializer())
01371       O << ".visible ";
01372     else
01373       O << ".extern ";
01374   }
01375 
01376   if (llvm::isTexture(*GVar)) {
01377     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
01378     return;
01379   }
01380 
01381   if (llvm::isSurface(*GVar)) {
01382     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
01383     return;
01384   }
01385 
01386   if (GVar->isDeclaration()) {
01387     // (extern) declarations, no definition or initializer
01388     // Currently the only known declaration is for an automatic __local
01389     // (.shared) promoted to global.
01390     emitPTXGlobalVariable(GVar, O);
01391     O << ";\n";
01392     return;
01393   }
01394 
01395   if (llvm::isSampler(*GVar)) {
01396     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
01397 
01398     const Constant *Initializer = NULL;
01399     if (GVar->hasInitializer())
01400       Initializer = GVar->getInitializer();
01401     const ConstantInt *CI = NULL;
01402     if (Initializer)
01403       CI = dyn_cast<ConstantInt>(Initializer);
01404     if (CI) {
01405       unsigned sample = CI->getZExtValue();
01406 
01407       O << " = { ";
01408 
01409       for (int i = 0,
01410                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
01411            i < 3; i++) {
01412         O << "addr_mode_" << i << " = ";
01413         switch (addr) {
01414         case 0:
01415           O << "wrap";
01416           break;
01417         case 1:
01418           O << "clamp_to_border";
01419           break;
01420         case 2:
01421           O << "clamp_to_edge";
01422           break;
01423         case 3:
01424           O << "wrap";
01425           break;
01426         case 4:
01427           O << "mirror";
01428           break;
01429         }
01430         O << ", ";
01431       }
01432       O << "filter_mode = ";
01433       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
01434       case 0:
01435         O << "nearest";
01436         break;
01437       case 1:
01438         O << "linear";
01439         break;
01440       case 2:
01441         assert(0 && "Anisotropic filtering is not supported");
01442       default:
01443         O << "nearest";
01444         break;
01445       }
01446       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
01447         O << ", force_unnormalized_coords = 1";
01448       }
01449       O << " }";
01450     }
01451 
01452     O << ";\n";
01453     return;
01454   }
01455 
01456   if (GVar->hasPrivateLinkage()) {
01457 
01458     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
01459       return;
01460 
01461     // FIXME - need better way (e.g. Metadata) to avoid generating this global
01462     if (!strncmp(GVar->getName().data(), "filename", 8))
01463       return;
01464     if (GVar->use_empty())
01465       return;
01466   }
01467 
01468   const Function *demotedFunc = 0;
01469   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
01470     O << "// " << GVar->getName().str() << " has been demoted\n";
01471     if (localDecls.find(demotedFunc) != localDecls.end())
01472       localDecls[demotedFunc].push_back(GVar);
01473     else {
01474       std::vector<const GlobalVariable *> temp;
01475       temp.push_back(GVar);
01476       localDecls[demotedFunc] = temp;
01477     }
01478     return;
01479   }
01480 
01481   O << ".";
01482   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01483   if (GVar->getAlignment() == 0)
01484     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01485   else
01486     O << " .align " << GVar->getAlignment();
01487 
01488   if (ETy->isSingleValueType()) {
01489     O << " .";
01490     // Special case: ABI requires that we use .u8 for predicates
01491     if (ETy->isIntegerTy(1))
01492       O << "u8";
01493     else
01494       O << getPTXFundamentalTypeStr(ETy, false);
01495     O << " ";
01496     O << *getSymbol(GVar);
01497 
01498     // Ptx allows variable initilization only for constant and global state
01499     // spaces.
01500     if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01501          (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
01502         GVar->hasInitializer()) {
01503       const Constant *Initializer = GVar->getInitializer();
01504       if (!Initializer->isNullValue()) {
01505         O << " = ";
01506         printScalarConstant(Initializer, O);
01507       }
01508     }
01509   } else {
01510     unsigned int ElementSize = 0;
01511 
01512     // Although PTX has direct support for struct type and array type and
01513     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
01514     // targets that support these high level field accesses. Structs, arrays
01515     // and vectors are lowered into arrays of bytes.
01516     switch (ETy->getTypeID()) {
01517     case Type::StructTyID:
01518     case Type::ArrayTyID:
01519     case Type::VectorTyID:
01520       ElementSize = TD->getTypeStoreSize(ETy);
01521       // Ptx allows variable initilization only for constant and
01522       // global state spaces.
01523       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01524            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
01525           GVar->hasInitializer()) {
01526         const Constant *Initializer = GVar->getInitializer();
01527         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
01528           AggBuffer aggBuffer(ElementSize, O, *this);
01529           bufferAggregateConstant(Initializer, &aggBuffer);
01530           if (aggBuffer.numSymbols) {
01531             if (nvptxSubtarget.is64Bit()) {
01532               O << " .u64 " << *getSymbol(GVar) << "[";
01533               O << ElementSize / 8;
01534             } else {
01535               O << " .u32 " << *getSymbol(GVar) << "[";
01536               O << ElementSize / 4;
01537             }
01538             O << "]";
01539           } else {
01540             O << " .b8 " << *getSymbol(GVar) << "[";
01541             O << ElementSize;
01542             O << "]";
01543           }
01544           O << " = {";
01545           aggBuffer.print();
01546           O << "}";
01547         } else {
01548           O << " .b8 " << *getSymbol(GVar);
01549           if (ElementSize) {
01550             O << "[";
01551             O << ElementSize;
01552             O << "]";
01553           }
01554         }
01555       } else {
01556         O << " .b8 " << *getSymbol(GVar);
01557         if (ElementSize) {
01558           O << "[";
01559           O << ElementSize;
01560           O << "]";
01561         }
01562       }
01563       break;
01564     default:
01565       assert(0 && "type not supported yet");
01566     }
01567 
01568   }
01569   O << ";\n";
01570 }
01571 
01572 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
01573   if (localDecls.find(f) == localDecls.end())
01574     return;
01575 
01576   std::vector<const GlobalVariable *> &gvars = localDecls[f];
01577 
01578   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
01579     O << "\t// demoted variable\n\t";
01580     printModuleLevelGV(gvars[i], O, true);
01581   }
01582 }
01583 
01584 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
01585                                           raw_ostream &O) const {
01586   switch (AddressSpace) {
01587   case llvm::ADDRESS_SPACE_LOCAL:
01588     O << "local";
01589     break;
01590   case llvm::ADDRESS_SPACE_GLOBAL:
01591     O << "global";
01592     break;
01593   case llvm::ADDRESS_SPACE_CONST:
01594     O << "const";
01595     break;
01596   case llvm::ADDRESS_SPACE_SHARED:
01597     O << "shared";
01598     break;
01599   default:
01600     report_fatal_error("Bad address space found while emitting PTX");
01601     break;
01602   }
01603 }
01604 
01605 std::string
01606 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
01607   switch (Ty->getTypeID()) {
01608   default:
01609     llvm_unreachable("unexpected type");
01610     break;
01611   case Type::IntegerTyID: {
01612     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
01613     if (NumBits == 1)
01614       return "pred";
01615     else if (NumBits <= 64) {
01616       std::string name = "u";
01617       return name + utostr(NumBits);
01618     } else {
01619       llvm_unreachable("Integer too large");
01620       break;
01621     }
01622     break;
01623   }
01624   case Type::FloatTyID:
01625     return "f32";
01626   case Type::DoubleTyID:
01627     return "f64";
01628   case Type::PointerTyID:
01629     if (nvptxSubtarget.is64Bit())
01630       if (useB4PTR)
01631         return "b64";
01632       else
01633         return "u64";
01634     else if (useB4PTR)
01635       return "b32";
01636     else
01637       return "u32";
01638   }
01639   llvm_unreachable("unexpected type");
01640   return NULL;
01641 }
01642 
01643 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
01644                                             raw_ostream &O) {
01645 
01646   const DataLayout *TD = TM.getDataLayout();
01647 
01648   // GlobalVariables are always constant pointers themselves.
01649   const PointerType *PTy = GVar->getType();
01650   Type *ETy = PTy->getElementType();
01651 
01652   O << ".";
01653   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01654   if (GVar->getAlignment() == 0)
01655     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01656   else
01657     O << " .align " << GVar->getAlignment();
01658 
01659   if (ETy->isSingleValueType()) {
01660     O << " .";
01661     O << getPTXFundamentalTypeStr(ETy);
01662     O << " ";
01663     O << *getSymbol(GVar);
01664     return;
01665   }
01666 
01667   int64_t ElementSize = 0;
01668 
01669   // Although PTX has direct support for struct type and array type and LLVM IR
01670   // is very similar to PTX, the LLVM CodeGen does not support for targets that
01671   // support these high level field accesses. Structs and arrays are lowered
01672   // into arrays of bytes.
01673   switch (ETy->getTypeID()) {
01674   case Type::StructTyID:
01675   case Type::ArrayTyID:
01676   case Type::VectorTyID:
01677     ElementSize = TD->getTypeStoreSize(ETy);
01678     O << " .b8 " << *getSymbol(GVar) << "[";
01679     if (ElementSize) {
01680       O << itostr(ElementSize);
01681     }
01682     O << "]";
01683     break;
01684   default:
01685     assert(0 && "type not supported yet");
01686   }
01687   return;
01688 }
01689 
01690 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
01691   if (Ty->isSingleValueType())
01692     return TD->getPrefTypeAlignment(Ty);
01693 
01694   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
01695   if (ATy)
01696     return getOpenCLAlignment(TD, ATy->getElementType());
01697 
01698   const VectorType *VTy = dyn_cast<VectorType>(Ty);
01699   if (VTy) {
01700     Type *ETy = VTy->getElementType();
01701     unsigned int numE = VTy->getNumElements();
01702     unsigned int alignE = TD->getPrefTypeAlignment(ETy);
01703     if (numE == 3)
01704       return 4 * alignE;
01705     else
01706       return numE * alignE;
01707   }
01708 
01709   const StructType *STy = dyn_cast<StructType>(Ty);
01710   if (STy) {
01711     unsigned int alignStruct = 1;
01712     // Go through each element of the struct and find the
01713     // largest alignment.
01714     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
01715       Type *ETy = STy->getElementType(i);
01716       unsigned int align = getOpenCLAlignment(TD, ETy);
01717       if (align > alignStruct)
01718         alignStruct = align;
01719     }
01720     return alignStruct;
01721   }
01722 
01723   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
01724   if (FTy)
01725     return TD->getPointerPrefAlignment();
01726   return TD->getPrefTypeAlignment(Ty);
01727 }
01728 
01729 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
01730                                      int paramIndex, raw_ostream &O) {
01731   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
01732       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
01733     O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
01734   else {
01735     std::string argName = I->getName();
01736     const char *p = argName.c_str();
01737     while (*p) {
01738       if (*p == '.')
01739         O << "_";
01740       else
01741         O << *p;
01742       p++;
01743     }
01744   }
01745 }
01746 
01747 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
01748   Function::const_arg_iterator I, E;
01749   int i = 0;
01750 
01751   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
01752       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
01753     O << *CurrentFnSym << "_param_" << paramIndex;
01754     return;
01755   }
01756 
01757   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
01758     if (i == paramIndex) {
01759       printParamName(I, paramIndex, O);
01760       return;
01761     }
01762   }
01763   llvm_unreachable("paramIndex out of bound");
01764 }
01765 
01766 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
01767   const DataLayout *TD = TM.getDataLayout();
01768   const AttributeSet &PAL = F->getAttributes();
01769   const TargetLowering *TLI = TM.getTargetLowering();
01770   Function::const_arg_iterator I, E;
01771   unsigned paramIndex = 0;
01772   bool first = true;
01773   bool isKernelFunc = llvm::isKernelFunction(*F);
01774   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
01775   MVT thePointerTy = TLI->getPointerTy();
01776 
01777   O << "(\n";
01778 
01779   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
01780     Type *Ty = I->getType();
01781 
01782     if (!first)
01783       O << ",\n";
01784 
01785     first = false;
01786 
01787     // Handle image/sampler parameters
01788     if (isKernelFunction(*F)) {
01789       if (isSampler(*I) || isImage(*I)) {
01790         if (isImage(*I)) {
01791           std::string sname = I->getName();
01792           if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
01793             if (nvptxSubtarget.hasImageHandles())
01794               O << "\t.param .u64 .ptr .surfref ";
01795             else
01796               O << "\t.param .surfref ";
01797             O << *CurrentFnSym << "_param_" << paramIndex;
01798           }
01799           else { // Default image is read_only
01800             if (nvptxSubtarget.hasImageHandles())
01801               O << "\t.param .u64 .ptr .texref ";
01802             else
01803               O << "\t.param .texref ";
01804             O << *CurrentFnSym << "_param_" << paramIndex;
01805           }
01806         } else {
01807           if (nvptxSubtarget.hasImageHandles())
01808             O << "\t.param .u64 .ptr .samplerref ";
01809           else
01810             O << "\t.param .samplerref ";
01811           O << *CurrentFnSym << "_param_" << paramIndex;
01812         }
01813         continue;
01814       }
01815     }
01816 
01817     if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
01818       if (Ty->isAggregateType() || Ty->isVectorTy()) {
01819         // Just print .param .align <a> .b8 .param[size];
01820         // <a> = PAL.getparamalignment
01821         // size = typeallocsize of element type
01822         unsigned align = PAL.getParamAlignment(paramIndex + 1);
01823         if (align == 0)
01824           align = TD->getABITypeAlignment(Ty);
01825 
01826         unsigned sz = TD->getTypeAllocSize(Ty);
01827         O << "\t.param .align " << align << " .b8 ";
01828         printParamName(I, paramIndex, O);
01829         O << "[" << sz << "]";
01830 
01831         continue;
01832       }
01833       // Just a scalar
01834       const PointerType *PTy = dyn_cast<PointerType>(Ty);
01835       if (isKernelFunc) {
01836         if (PTy) {
01837           // Special handling for pointer arguments to kernel
01838           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
01839 
01840           if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
01841             Type *ETy = PTy->getElementType();
01842             int addrSpace = PTy->getAddressSpace();
01843             switch (addrSpace) {
01844             default:
01845               O << ".ptr ";
01846               break;
01847             case llvm::ADDRESS_SPACE_CONST:
01848               O << ".ptr .const ";
01849               break;
01850             case llvm::ADDRESS_SPACE_SHARED:
01851               O << ".ptr .shared ";
01852               break;
01853             case llvm::ADDRESS_SPACE_GLOBAL:
01854               O << ".ptr .global ";
01855               break;
01856             }
01857             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
01858           }
01859           printParamName(I, paramIndex, O);
01860           continue;
01861         }
01862 
01863         // non-pointer scalar to kernel func
01864         O << "\t.param .";
01865         // Special case: predicate operands become .u8 types
01866         if (Ty->isIntegerTy(1))
01867           O << "u8";
01868         else
01869           O << getPTXFundamentalTypeStr(Ty);
01870         O << " ";
01871         printParamName(I, paramIndex, O);
01872         continue;
01873       }
01874       // Non-kernel function, just print .param .b<size> for ABI
01875       // and .reg .b<size> for non-ABI
01876       unsigned sz = 0;
01877       if (isa<IntegerType>(Ty)) {
01878         sz = cast<IntegerType>(Ty)->getBitWidth();
01879         if (sz < 32)
01880           sz = 32;
01881       } else if (isa<PointerType>(Ty))
01882         sz = thePointerTy.getSizeInBits();
01883       else
01884         sz = Ty->getPrimitiveSizeInBits();
01885       if (isABI)
01886         O << "\t.param .b" << sz << " ";
01887       else
01888         O << "\t.reg .b" << sz << " ";
01889       printParamName(I, paramIndex, O);
01890       continue;
01891     }
01892 
01893     // param has byVal attribute. So should be a pointer
01894     const PointerType *PTy = dyn_cast<PointerType>(Ty);
01895     assert(PTy && "Param with byval attribute should be a pointer type");
01896     Type *ETy = PTy->getElementType();
01897 
01898     if (isABI || isKernelFunc) {
01899       // Just print .param .align <a> .b8 .param[size];
01900       // <a> = PAL.getparamalignment
01901       // size = typeallocsize of element type
01902       unsigned align = PAL.getParamAlignment(paramIndex + 1);
01903       if (align == 0)
01904         align = TD->getABITypeAlignment(ETy);
01905 
01906       unsigned sz = TD->getTypeAllocSize(ETy);
01907       O << "\t.param .align " << align << " .b8 ";
01908       printParamName(I, paramIndex, O);
01909       O << "[" << sz << "]";
01910       continue;
01911     } else {
01912       // Split the ETy into constituent parts and
01913       // print .param .b<size> <name> for each part.
01914       // Further, if a part is vector, print the above for
01915       // each vector element.
01916       SmallVector<EVT, 16> vtparts;
01917       ComputeValueVTs(*TLI, ETy, vtparts);
01918       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
01919         unsigned elems = 1;
01920         EVT elemtype = vtparts[i];
01921         if (vtparts[i].isVector()) {
01922           elems = vtparts[i].getVectorNumElements();
01923           elemtype = vtparts[i].getVectorElementType();
01924         }
01925 
01926         for (unsigned j = 0, je = elems; j != je; ++j) {
01927           unsigned sz = elemtype.getSizeInBits();
01928           if (elemtype.isInteger() && (sz < 32))
01929             sz = 32;
01930           O << "\t.reg .b" << sz << " ";
01931           printParamName(I, paramIndex, O);
01932           if (j < je - 1)
01933             O << ",\n";
01934           ++paramIndex;
01935         }
01936         if (i < e - 1)
01937           O << ",\n";
01938       }
01939       --paramIndex;
01940       continue;
01941     }
01942   }
01943 
01944   O << "\n)\n";
01945 }
01946 
01947 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
01948                                             raw_ostream &O) {
01949   const Function *F = MF.getFunction();
01950   emitFunctionParamList(F, O);
01951 }
01952 
01953 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
01954     const MachineFunction &MF) {
01955   SmallString<128> Str;
01956   raw_svector_ostream O(Str);
01957 
01958   // Map the global virtual register number to a register class specific
01959   // virtual register number starting from 1 with that class.
01960   const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
01961   //unsigned numRegClasses = TRI->getNumRegClasses();
01962 
01963   // Emit the Fake Stack Object
01964   const MachineFrameInfo *MFI = MF.getFrameInfo();
01965   int NumBytes = (int) MFI->getStackSize();
01966   if (NumBytes) {
01967     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
01968       << getFunctionNumber() << "[" << NumBytes << "];\n";
01969     if (nvptxSubtarget.is64Bit()) {
01970       O << "\t.reg .b64 \t%SP;\n";
01971       O << "\t.reg .b64 \t%SPL;\n";
01972     } else {
01973       O << "\t.reg .b32 \t%SP;\n";
01974       O << "\t.reg .b32 \t%SPL;\n";
01975     }
01976   }
01977 
01978   // Go through all virtual registers to establish the mapping between the
01979   // global virtual
01980   // register number and the per class virtual register number.
01981   // We use the per class virtual register number in the ptx output.
01982   unsigned int numVRs = MRI->getNumVirtRegs();
01983   for (unsigned i = 0; i < numVRs; i++) {
01984     unsigned int vr = TRI->index2VirtReg(i);
01985     const TargetRegisterClass *RC = MRI->getRegClass(vr);
01986     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
01987     int n = regmap.size();
01988     regmap.insert(std::make_pair(vr, n + 1));
01989   }
01990 
01991   // Emit register declarations
01992   // @TODO: Extract out the real register usage
01993   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
01994   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
01995   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
01996   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
01997   // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
01998   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
01999   // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
02000 
02001   // Emit declaration of the virtual registers or 'physical' registers for
02002   // each register class
02003   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
02004     const TargetRegisterClass *RC = TRI->getRegClass(i);
02005     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
02006     std::string rcname = getNVPTXRegClassName(RC);
02007     std::string rcStr = getNVPTXRegClassStr(RC);
02008     int n = regmap.size();
02009 
02010     // Only declare those registers that may be used.
02011     if (n) {
02012        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
02013          << ">;\n";
02014     }
02015   }
02016 
02017   OutStreamer.EmitRawText(O.str());
02018 }
02019 
02020 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
02021   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
02022   bool ignored;
02023   unsigned int numHex;
02024   const char *lead;
02025 
02026   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
02027     numHex = 8;
02028     lead = "0f";
02029     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
02030   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
02031     numHex = 16;
02032     lead = "0d";
02033     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
02034   } else
02035     llvm_unreachable("unsupported fp type");
02036 
02037   APInt API = APF.bitcastToAPInt();
02038   std::string hexstr(utohexstr(API.getZExtValue()));
02039   O << lead;
02040   if (hexstr.length() < numHex)
02041     O << std::string(numHex - hexstr.length(), '0');
02042   O << utohexstr(API.getZExtValue());
02043 }
02044 
02045 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
02046   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
02047     O << CI->getValue();
02048     return;
02049   }
02050   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
02051     printFPConstant(CFP, O);
02052     return;
02053   }
02054   if (isa<ConstantPointerNull>(CPV)) {
02055     O << "0";
02056     return;
02057   }
02058   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
02059     PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
02060     bool IsNonGenericPointer = false;
02061     if (PTy && PTy->getAddressSpace() != 0) {
02062       IsNonGenericPointer = true;
02063     }
02064     if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
02065       O << "generic(";
02066       O << *getSymbol(GVar);
02067       O << ")";
02068     } else {
02069       O << *getSymbol(GVar);
02070     }
02071     return;
02072   }
02073   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
02074     const Value *v = Cexpr->stripPointerCasts();
02075     PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
02076     bool IsNonGenericPointer = false;
02077     if (PTy && PTy->getAddressSpace() != 0) {
02078       IsNonGenericPointer = true;
02079     }
02080     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
02081       if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
02082         O << "generic(";
02083         O << *getSymbol(GVar);
02084         O << ")";
02085       } else {
02086         O << *getSymbol(GVar);
02087       }
02088       return;
02089     } else {
02090       O << *LowerConstant(CPV, *this);
02091       return;
02092     }
02093   }
02094   llvm_unreachable("Not scalar type found in printScalarConstant()");
02095 }
02096 
02097 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
02098                                    AggBuffer *aggBuffer) {
02099 
02100   const DataLayout *TD = TM.getDataLayout();
02101 
02102   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
02103     int s = TD->getTypeAllocSize(CPV->getType());
02104     if (s < Bytes)
02105       s = Bytes;
02106     aggBuffer->addZeros(s);
02107     return;
02108   }
02109 
02110   unsigned char *ptr;
02111   switch (CPV->getType()->getTypeID()) {
02112 
02113   case Type::IntegerTyID: {
02114     const Type *ETy = CPV->getType();
02115     if (ETy == Type::getInt8Ty(CPV->getContext())) {
02116       unsigned char c =
02117           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
02118       ptr = &c;
02119       aggBuffer->addBytes(ptr, 1, Bytes);
02120     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
02121       short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
02122       ptr = (unsigned char *)&int16;
02123       aggBuffer->addBytes(ptr, 2, Bytes);
02124     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
02125       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
02126         int int32 = (int)(constInt->getZExtValue());
02127         ptr = (unsigned char *)&int32;
02128         aggBuffer->addBytes(ptr, 4, Bytes);
02129         break;
02130       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
02131         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
02132                 ConstantFoldConstantExpression(Cexpr, TD))) {
02133           int int32 = (int)(constInt->getZExtValue());
02134           ptr = (unsigned char *)&int32;
02135           aggBuffer->addBytes(ptr, 4, Bytes);
02136           break;
02137         }
02138         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
02139           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
02140           aggBuffer->addSymbol(v);
02141           aggBuffer->addZeros(4);
02142           break;
02143         }
02144       }
02145       llvm_unreachable("unsupported integer const type");
02146     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
02147       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
02148         long long int64 = (long long)(constInt->getZExtValue());
02149         ptr = (unsigned char *)&int64;
02150         aggBuffer->addBytes(ptr, 8, Bytes);
02151         break;
02152       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
02153         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
02154                 ConstantFoldConstantExpression(Cexpr, TD))) {
02155           long long int64 = (long long)(constInt->getZExtValue());
02156           ptr = (unsigned char *)&int64;
02157           aggBuffer->addBytes(ptr, 8, Bytes);
02158           break;
02159         }
02160         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
02161           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
02162           aggBuffer->addSymbol(v);
02163           aggBuffer->addZeros(8);
02164           break;
02165         }
02166       }
02167       llvm_unreachable("unsupported integer const type");
02168     } else
02169       llvm_unreachable("unsupported integer const type");
02170     break;
02171   }
02172   case Type::FloatTyID:
02173   case Type::DoubleTyID: {
02174     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
02175     const Type *Ty = CFP->getType();
02176     if (Ty == Type::getFloatTy(CPV->getContext())) {
02177       float float32 = (float) CFP->getValueAPF().convertToFloat();
02178       ptr = (unsigned char *)&float32;
02179       aggBuffer->addBytes(ptr, 4, Bytes);
02180     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
02181       double float64 = CFP->getValueAPF().convertToDouble();
02182       ptr = (unsigned char *)&float64;
02183       aggBuffer->addBytes(ptr, 8, Bytes);
02184     } else {
02185       llvm_unreachable("unsupported fp const type");
02186     }
02187     break;
02188   }
02189   case Type::PointerTyID: {
02190     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
02191       aggBuffer->addSymbol(GVar);
02192     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
02193       const Value *v = Cexpr->stripPointerCasts();
02194       aggBuffer->addSymbol(v);
02195     }
02196     unsigned int s = TD->getTypeAllocSize(CPV->getType());
02197     aggBuffer->addZeros(s);
02198     break;
02199   }
02200 
02201   case Type::ArrayTyID:
02202   case Type::VectorTyID:
02203   case Type::StructTyID: {
02204     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
02205         isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
02206       int ElementSize = TD->getTypeAllocSize(CPV->getType());
02207       bufferAggregateConstant(CPV, aggBuffer);
02208       if (Bytes > ElementSize)
02209         aggBuffer->addZeros(Bytes - ElementSize);
02210     } else if (isa<ConstantAggregateZero>(CPV))
02211       aggBuffer->addZeros(Bytes);
02212     else
02213       llvm_unreachable("Unexpected Constant type");
02214     break;
02215   }
02216 
02217   default:
02218     llvm_unreachable("unsupported type");
02219   }
02220 }
02221 
02222 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
02223                                               AggBuffer *aggBuffer) {
02224   const DataLayout *TD = TM.getDataLayout();
02225   int Bytes;
02226 
02227   // Old constants
02228   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
02229     if (CPV->getNumOperands())
02230       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
02231         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
02232     return;
02233   }
02234 
02235   if (const ConstantDataSequential *CDS =
02236           dyn_cast<ConstantDataSequential>(CPV)) {
02237     if (CDS->getNumElements())
02238       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
02239         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
02240                      aggBuffer);
02241     return;
02242   }
02243 
02244   if (isa<ConstantStruct>(CPV)) {
02245     if (CPV->getNumOperands()) {
02246       StructType *ST = cast<StructType>(CPV->getType());
02247       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
02248         if (i == (e - 1))
02249           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
02250                   TD->getTypeAllocSize(ST) -
02251                   TD->getStructLayout(ST)->getElementOffset(i);
02252         else
02253           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
02254                   TD->getStructLayout(ST)->getElementOffset(i);
02255         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
02256       }
02257     }
02258     return;
02259   }
02260   llvm_unreachable("unsupported constant type in printAggregateConstant()");
02261 }
02262 
02263 // buildTypeNameMap - Run through symbol table looking for type names.
02264 //
02265 
02266 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
02267 
02268   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
02269 
02270   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
02271                                   !PI->second.compare("struct._image2d_t") ||
02272                                   !PI->second.compare("struct._image3d_t")))
02273     return true;
02274 
02275   return false;
02276 }
02277 
02278 
02279 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
02280   switch (MI.getOpcode()) {
02281   default:
02282     return false;
02283   case NVPTX::CallArgBeginInst:
02284   case NVPTX::CallArgEndInst0:
02285   case NVPTX::CallArgEndInst1:
02286   case NVPTX::CallArgF32:
02287   case NVPTX::CallArgF64:
02288   case NVPTX::CallArgI16:
02289   case NVPTX::CallArgI32:
02290   case NVPTX::CallArgI32imm:
02291   case NVPTX::CallArgI64:
02292   case NVPTX::CallArgParam:
02293   case NVPTX::CallVoidInst:
02294   case NVPTX::CallVoidInstReg:
02295   case NVPTX::Callseq_End:
02296   case NVPTX::CallVoidInstReg64:
02297   case NVPTX::DeclareParamInst:
02298   case NVPTX::DeclareRetMemInst:
02299   case NVPTX::DeclareRetRegInst:
02300   case NVPTX::DeclareRetScalarInst:
02301   case NVPTX::DeclareScalarParamInst:
02302   case NVPTX::DeclareScalarRegInst:
02303   case NVPTX::StoreParamF32:
02304   case NVPTX::StoreParamF64:
02305   case NVPTX::StoreParamI16:
02306   case NVPTX::StoreParamI32:
02307   case NVPTX::StoreParamI64:
02308   case NVPTX::StoreParamI8:
02309   case NVPTX::StoreRetvalF32:
02310   case NVPTX::StoreRetvalF64:
02311   case NVPTX::StoreRetvalI16:
02312   case NVPTX::StoreRetvalI32:
02313   case NVPTX::StoreRetvalI64:
02314   case NVPTX::StoreRetvalI8:
02315   case NVPTX::LastCallArgF32:
02316   case NVPTX::LastCallArgF64:
02317   case NVPTX::LastCallArgI16:
02318   case NVPTX::LastCallArgI32:
02319   case NVPTX::LastCallArgI32imm:
02320   case NVPTX::LastCallArgI64:
02321   case NVPTX::LastCallArgParam:
02322   case NVPTX::LoadParamMemF32:
02323   case NVPTX::LoadParamMemF64:
02324   case NVPTX::LoadParamMemI16:
02325   case NVPTX::LoadParamMemI32:
02326   case NVPTX::LoadParamMemI64:
02327   case NVPTX::LoadParamMemI8:
02328   case NVPTX::PrototypeInst:
02329   case NVPTX::DBG_VALUE:
02330     return true;
02331   }
02332   return false;
02333 }
02334 
02335 /// PrintAsmOperand - Print out an operand for an inline asm expression.
02336 ///
02337 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
02338                                       unsigned AsmVariant,
02339                                       const char *ExtraCode, raw_ostream &O) {
02340   if (ExtraCode && ExtraCode[0]) {
02341     if (ExtraCode[1] != 0)
02342       return true; // Unknown modifier.
02343 
02344     switch (ExtraCode[0]) {
02345     default:
02346       // See if this is a generic print operand
02347       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
02348     case 'r':
02349       break;
02350     }
02351   }
02352 
02353   printOperand(MI, OpNo, O);
02354 
02355   return false;
02356 }
02357 
02358 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
02359     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
02360     const char *ExtraCode, raw_ostream &O) {
02361   if (ExtraCode && ExtraCode[0])
02362     return true; // Unknown modifier
02363 
02364   O << '[';
02365   printMemOperand(MI, OpNo, O);
02366   O << ']';
02367 
02368   return false;
02369 }
02370 
02371 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
02372                                    raw_ostream &O, const char *Modifier) {
02373   const MachineOperand &MO = MI->getOperand(opNum);
02374   switch (MO.getType()) {
02375   case MachineOperand::MO_Register:
02376     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
02377       if (MO.getReg() == NVPTX::VRDepot)
02378         O << DEPOTNAME << getFunctionNumber();
02379       else
02380         O << NVPTXInstPrinter::getRegisterName(MO.getReg());
02381     } else {
02382       emitVirtualRegister(MO.getReg(), O);
02383     }
02384     return;
02385 
02386   case MachineOperand::MO_Immediate:
02387     if (!Modifier)
02388       O << MO.getImm();
02389     else if (strstr(Modifier, "vec") == Modifier)
02390       printVecModifiedImmediate(MO, Modifier, O);
02391     else
02392       llvm_unreachable(
02393           "Don't know how to handle modifier on immediate operand");
02394     return;
02395 
02396   case MachineOperand::MO_FPImmediate:
02397     printFPConstant(MO.getFPImm(), O);
02398     break;
02399 
02400   case MachineOperand::MO_GlobalAddress:
02401     O << *getSymbol(MO.getGlobal());
02402     break;
02403 
02404   case MachineOperand::MO_MachineBasicBlock:
02405     O << *MO.getMBB()->getSymbol();
02406     return;
02407 
02408   default:
02409     llvm_unreachable("Operand type not supported.");
02410   }
02411 }
02412 
02413 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
02414                                       raw_ostream &O, const char *Modifier) {
02415   printOperand(MI, opNum, O);
02416 
02417   if (Modifier && !strcmp(Modifier, "add")) {
02418     O << ", ";
02419     printOperand(MI, opNum + 1, O);
02420   } else {
02421     if (MI->getOperand(opNum + 1).isImm() &&
02422         MI->getOperand(opNum + 1).getImm() == 0)
02423       return; // don't print ',0' or '+0'
02424     O << "+";
02425     printOperand(MI, opNum + 1, O);
02426   }
02427 }
02428 
02429 
02430 // Force static initialization.
02431 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
02432   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
02433   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
02434 }
02435 
02436 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
02437   std::stringstream temp;
02438   LineReader *reader = this->getReader(filename.str());
02439   temp << "\n//";
02440   temp << filename.str();
02441   temp << ":";
02442   temp << line;
02443   temp << " ";
02444   temp << reader->readLine(line);
02445   temp << "\n";
02446   this->OutStreamer.EmitRawText(Twine(temp.str()));
02447 }
02448 
02449 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
02450   if (reader == NULL) {
02451     reader = new LineReader(filename);
02452   }
02453 
02454   if (reader->fileName() != filename) {
02455     delete reader;
02456     reader = new LineReader(filename);
02457   }
02458 
02459   return reader;
02460 }
02461 
02462 std::string LineReader::readLine(unsigned lineNum) {
02463   if (lineNum < theCurLine) {
02464     theCurLine = 0;
02465     fstr.seekg(0, std::ios::beg);
02466   }
02467   while (theCurLine < lineNum) {
02468     fstr.getline(buff, 500);
02469     theCurLine++;
02470   }
02471   return buff;
02472 }
02473 
02474 // Force static initialization.
02475 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
02476   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
02477   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
02478 }