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 "NVPTXMCExpr.h"
00021 #include "NVPTXMachineFunctionInfo.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/MachineLoopInfo.h"
00031 #include "llvm/CodeGen/MachineModuleInfo.h"
00032 #include "llvm/CodeGen/MachineRegisterInfo.h"
00033 #include "llvm/IR/DebugInfo.h"
00034 #include "llvm/IR/DerivedTypes.h"
00035 #include "llvm/IR/Function.h"
00036 #include "llvm/IR/GlobalVariable.h"
00037 #include "llvm/IR/Mangler.h"
00038 #include "llvm/IR/Module.h"
00039 #include "llvm/IR/Operator.h"
00040 #include "llvm/MC/MCStreamer.h"
00041 #include "llvm/MC/MCSymbol.h"
00042 #include "llvm/Support/CommandLine.h"
00043 #include "llvm/Support/ErrorHandling.h"
00044 #include "llvm/Support/FormattedStream.h"
00045 #include "llvm/Support/Path.h"
00046 #include "llvm/Support/TargetRegistry.h"
00047 #include "llvm/Support/TimeValue.h"
00048 #include "llvm/Target/TargetLoweringObjectFile.h"
00049 #include "llvm/Transforms/Utils/UnrollLoop.h"
00050 #include <sstream>
00051 using namespace llvm;
00052 
00053 #define DEPOTNAME "__local_depot"
00054 
00055 static cl::opt<bool>
00056 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
00057                 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
00058                 cl::init(true));
00059 
00060 static cl::opt<bool>
00061 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
00062               cl::desc("NVPTX Specific: Emit source line in ptx file"),
00063               cl::init(false));
00064 
00065 namespace {
00066 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
00067 /// depends.
00068 void DiscoverDependentGlobals(const Value *V,
00069                               DenseSet<const GlobalVariable *> &Globals) {
00070   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00071     Globals.insert(GV);
00072   else {
00073     if (const User *U = dyn_cast<User>(V)) {
00074       for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
00075         DiscoverDependentGlobals(U->getOperand(i), Globals);
00076       }
00077     }
00078   }
00079 }
00080 
00081 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
00082 /// instances to be emitted, but only after any dependents have been added
00083 /// first.
00084 void VisitGlobalVariableForEmission(
00085     const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
00086     DenseSet<const GlobalVariable *> &Visited,
00087     DenseSet<const GlobalVariable *> &Visiting) {
00088   // Have we already visited this one?
00089   if (Visited.count(GV))
00090     return;
00091 
00092   // Do we have a circular dependency?
00093   if (!Visiting.insert(GV).second)
00094     report_fatal_error("Circular dependency found in global variable set");
00095 
00096   // Make sure we visit all dependents first
00097   DenseSet<const GlobalVariable *> Others;
00098   for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
00099     DiscoverDependentGlobals(GV->getOperand(i), Others);
00100 
00101   for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
00102                                                   E = Others.end();
00103        I != E; ++I)
00104     VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
00105 
00106   // Now we can visit ourself
00107   Order.push_back(GV);
00108   Visited.insert(GV);
00109   Visiting.erase(GV);
00110 }
00111 }
00112 
00113 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
00114   if (!EmitLineNumbers)
00115     return;
00116   if (ignoreLoc(MI))
00117     return;
00118 
00119   DebugLoc curLoc = MI.getDebugLoc();
00120 
00121   if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
00122     return;
00123 
00124   if (prevDebugLoc == curLoc)
00125     return;
00126 
00127   prevDebugLoc = curLoc;
00128 
00129   if (curLoc.isUnknown())
00130     return;
00131 
00132   const MachineFunction *MF = MI.getParent()->getParent();
00133   //const TargetMachine &TM = MF->getTarget();
00134 
00135   const LLVMContext &ctx = MF->getFunction()->getContext();
00136   DIScope Scope(curLoc.getScope(ctx));
00137 
00138   assert((!Scope || Scope.isScope()) &&
00139     "Scope of a DebugLoc should be null or a DIScope.");
00140   if (!Scope)
00141      return;
00142 
00143   StringRef fileName(Scope.getFilename());
00144   StringRef dirName(Scope.getDirectory());
00145   SmallString<128> FullPathName = dirName;
00146   if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
00147     sys::path::append(FullPathName, fileName);
00148     fileName = FullPathName.str();
00149   }
00150 
00151   if (filenameMap.find(fileName.str()) == filenameMap.end())
00152     return;
00153 
00154   // Emit the line from the source file.
00155   if (InterleaveSrc)
00156     this->emitSrcInText(fileName.str(), curLoc.getLine());
00157 
00158   std::stringstream temp;
00159   temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
00160        << " " << curLoc.getCol();
00161   OutStreamer.EmitRawText(Twine(temp.str().c_str()));
00162 }
00163 
00164 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
00165   SmallString<128> Str;
00166   raw_svector_ostream OS(Str);
00167   if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
00168     emitLineNumberAsDotLoc(*MI);
00169 
00170   MCInst Inst;
00171   lowerToMCInst(MI, Inst);
00172   EmitToStreamer(OutStreamer, Inst);
00173 }
00174 
00175 // Handle symbol backtracking for targets that do not support image handles
00176 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
00177                                            unsigned OpNo, MCOperand &MCOp) {
00178   const MachineOperand &MO = MI->getOperand(OpNo);
00179   const MCInstrDesc &MCID = MI->getDesc();
00180 
00181   if (MCID.TSFlags & NVPTXII::IsTexFlag) {
00182     // This is a texture fetch, so operand 4 is a texref and operand 5 is
00183     // a samplerref
00184     if (OpNo == 4 && MO.isImm()) {
00185       lowerImageHandleSymbol(MO.getImm(), MCOp);
00186       return true;
00187     }
00188     if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
00189       lowerImageHandleSymbol(MO.getImm(), MCOp);
00190       return true;
00191     }
00192 
00193     return false;
00194   } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
00195     unsigned VecSize =
00196       1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
00197 
00198     // For a surface load of vector size N, the Nth operand will be the surfref
00199     if (OpNo == VecSize && MO.isImm()) {
00200       lowerImageHandleSymbol(MO.getImm(), MCOp);
00201       return true;
00202     }
00203 
00204     return false;
00205   } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
00206     // This is a surface store, so operand 0 is a surfref
00207     if (OpNo == 0 && MO.isImm()) {
00208       lowerImageHandleSymbol(MO.getImm(), MCOp);
00209       return true;
00210     }
00211 
00212     return false;
00213   } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
00214     // This is a query, so operand 1 is a surfref/texref
00215     if (OpNo == 1 && MO.isImm()) {
00216       lowerImageHandleSymbol(MO.getImm(), MCOp);
00217       return true;
00218     }
00219 
00220     return false;
00221   }
00222 
00223   return false;
00224 }
00225 
00226 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
00227   // Ewwww
00228   TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
00229   NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
00230   const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
00231   const char *Sym = MFI->getImageHandleSymbol(Index);
00232   std::string *SymNamePtr =
00233     nvTM.getManagedStrPool()->getManagedString(Sym);
00234   MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
00235     StringRef(SymNamePtr->c_str())));
00236 }
00237 
00238 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
00239   OutMI.setOpcode(MI->getOpcode());
00240   // Special: Do not mangle symbol operand of CALL_PROTOTYPE
00241   if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
00242     const MachineOperand &MO = MI->getOperand(0);
00243     OutMI.addOperand(GetSymbolRef(
00244       OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
00245     return;
00246   }
00247 
00248   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
00249     const MachineOperand &MO = MI->getOperand(i);
00250 
00251     MCOperand MCOp;
00252     if (!nvptxSubtarget->hasImageHandles()) {
00253       if (lowerImageHandleOperand(MI, i, MCOp)) {
00254         OutMI.addOperand(MCOp);
00255         continue;
00256       }
00257     }
00258 
00259     if (lowerOperand(MO, MCOp))
00260       OutMI.addOperand(MCOp);
00261   }
00262 }
00263 
00264 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
00265                                    MCOperand &MCOp) {
00266   switch (MO.getType()) {
00267   default: llvm_unreachable("unknown operand type");
00268   case MachineOperand::MO_Register:
00269     MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
00270     break;
00271   case MachineOperand::MO_Immediate:
00272     MCOp = MCOperand::CreateImm(MO.getImm());
00273     break;
00274   case MachineOperand::MO_MachineBasicBlock:
00275     MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
00276         MO.getMBB()->getSymbol(), OutContext));
00277     break;
00278   case MachineOperand::MO_ExternalSymbol:
00279     MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
00280     break;
00281   case MachineOperand::MO_GlobalAddress:
00282     MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
00283     break;
00284   case MachineOperand::MO_FPImmediate: {
00285     const ConstantFP *Cnt = MO.getFPImm();
00286     APFloat Val = Cnt->getValueAPF();
00287 
00288     switch (Cnt->getType()->getTypeID()) {
00289     default: report_fatal_error("Unsupported FP type"); break;
00290     case Type::FloatTyID:
00291       MCOp = MCOperand::CreateExpr(
00292         NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
00293       break;
00294     case Type::DoubleTyID:
00295       MCOp = MCOperand::CreateExpr(
00296         NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
00297       break;
00298     }
00299     break;
00300   }
00301   }
00302   return true;
00303 }
00304 
00305 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
00306   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
00307     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
00308 
00309     DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
00310     unsigned RegNum = RegMap[Reg];
00311 
00312     // Encode the register class in the upper 4 bits
00313     // Must be kept in sync with NVPTXInstPrinter::printRegName
00314     unsigned Ret = 0;
00315     if (RC == &NVPTX::Int1RegsRegClass) {
00316       Ret = (1 << 28);
00317     } else if (RC == &NVPTX::Int16RegsRegClass) {
00318       Ret = (2 << 28);
00319     } else if (RC == &NVPTX::Int32RegsRegClass) {
00320       Ret = (3 << 28);
00321     } else if (RC == &NVPTX::Int64RegsRegClass) {
00322       Ret = (4 << 28);
00323     } else if (RC == &NVPTX::Float32RegsRegClass) {
00324       Ret = (5 << 28);
00325     } else if (RC == &NVPTX::Float64RegsRegClass) {
00326       Ret = (6 << 28);
00327     } else {
00328       report_fatal_error("Bad register class");
00329     }
00330 
00331     // Insert the vreg number
00332     Ret |= (RegNum & 0x0FFFFFFF);
00333     return Ret;
00334   } else {
00335     // Some special-use registers are actually physical registers.
00336     // Encode this as the register class ID of 0 and the real register ID.
00337     return Reg & 0x0FFFFFFF;
00338   }
00339 }
00340 
00341 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
00342   const MCExpr *Expr;
00343   Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
00344                                  OutContext);
00345   return MCOperand::CreateExpr(Expr);
00346 }
00347 
00348 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
00349   const DataLayout *TD = TM.getDataLayout();
00350   const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
00351 
00352   Type *Ty = F->getReturnType();
00353 
00354   bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
00355 
00356   if (Ty->getTypeID() == Type::VoidTyID)
00357     return;
00358 
00359   O << " (";
00360 
00361   if (isABI) {
00362     if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
00363       unsigned size = 0;
00364       if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
00365         size = ITy->getBitWidth();
00366         if (size < 32)
00367           size = 32;
00368       } else {
00369         assert(Ty->isFloatingPointTy() && "Floating point type expected here");
00370         size = Ty->getPrimitiveSizeInBits();
00371       }
00372 
00373       O << ".param .b" << size << " func_retval0";
00374     } else if (isa<PointerType>(Ty)) {
00375       O << ".param .b" << TLI->getPointerTy().getSizeInBits()
00376         << " func_retval0";
00377     } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
00378        unsigned totalsz = TD->getTypeAllocSize(Ty);
00379        unsigned retAlignment = 0;
00380        if (!llvm::getAlign(*F, 0, retAlignment))
00381          retAlignment = TD->getABITypeAlignment(Ty);
00382        O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
00383          << "]";
00384     } else
00385       llvm_unreachable("Unknown return type");
00386   } else {
00387     SmallVector<EVT, 16> vtparts;
00388     ComputeValueVTs(*TLI, Ty, vtparts);
00389     unsigned idx = 0;
00390     for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
00391       unsigned elems = 1;
00392       EVT elemtype = vtparts[i];
00393       if (vtparts[i].isVector()) {
00394         elems = vtparts[i].getVectorNumElements();
00395         elemtype = vtparts[i].getVectorElementType();
00396       }
00397 
00398       for (unsigned j = 0, je = elems; j != je; ++j) {
00399         unsigned sz = elemtype.getSizeInBits();
00400         if (elemtype.isInteger() && (sz < 32))
00401           sz = 32;
00402         O << ".reg .b" << sz << " func_retval" << idx;
00403         if (j < je - 1)
00404           O << ", ";
00405         ++idx;
00406       }
00407       if (i < e - 1)
00408         O << ", ";
00409     }
00410   }
00411   O << ") ";
00412   return;
00413 }
00414 
00415 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
00416                                         raw_ostream &O) {
00417   const Function *F = MF.getFunction();
00418   printReturnValStr(F, O);
00419 }
00420 
00421 // Return true if MBB is the header of a loop marked with
00422 // llvm.loop.unroll.disable.
00423 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
00424 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
00425     const MachineBasicBlock &MBB) const {
00426   MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
00427   // TODO: isLoopHeader() should take "const MachineBasicBlock *".
00428   // We insert .pragma "nounroll" only to the loop header.
00429   if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
00430     return false;
00431 
00432   // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
00433   // we iterate through each back edge of the loop with header MBB, and check
00434   // whether its metadata contains llvm.loop.unroll.disable.
00435   for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
00436     const MachineBasicBlock *PMBB = *I;
00437     if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
00438       // Edges from other loops to MBB are not back edges.
00439       continue;
00440     }
00441     if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
00442       if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
00443         if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
00444           return true;
00445       }
00446     }
00447   }
00448   return false;
00449 }
00450 
00451 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
00452   AsmPrinter::EmitBasicBlockStart(MBB);
00453   if (isLoopHeaderOfNoUnroll(MBB))
00454     OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
00455 }
00456 
00457 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
00458   SmallString<128> Str;
00459   raw_svector_ostream O(Str);
00460 
00461   if (!GlobalsEmitted) {
00462     emitGlobals(*MF->getFunction()->getParent());
00463     GlobalsEmitted = true;
00464   }
00465   
00466   // Set up
00467   MRI = &MF->getRegInfo();
00468   F = MF->getFunction();
00469   emitLinkageDirective(F, O);
00470   if (llvm::isKernelFunction(*F))
00471     O << ".entry ";
00472   else {
00473     O << ".func ";
00474     printReturnValStr(*MF, O);
00475   }
00476 
00477   O << *CurrentFnSym;
00478 
00479   emitFunctionParamList(*MF, O);
00480 
00481   if (llvm::isKernelFunction(*F))
00482     emitKernelFunctionDirectives(*F, O);
00483 
00484   OutStreamer.EmitRawText(O.str());
00485 
00486   prevDebugLoc = DebugLoc();
00487 }
00488 
00489 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
00490   VRegMapping.clear();
00491   OutStreamer.EmitRawText(StringRef("{\n"));
00492   setAndEmitFunctionVirtualRegisters(*MF);
00493 
00494   SmallString<128> Str;
00495   raw_svector_ostream O(Str);
00496   emitDemotedVars(MF->getFunction(), O);
00497   OutStreamer.EmitRawText(O.str());
00498 }
00499 
00500 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
00501   OutStreamer.EmitRawText(StringRef("}\n"));
00502   VRegMapping.clear();
00503 }
00504 
00505 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
00506   unsigned RegNo = MI->getOperand(0).getReg();
00507   const TargetRegisterInfo *TRI = nvptxSubtarget->getRegisterInfo();
00508   if (TRI->isVirtualRegister(RegNo)) {
00509     OutStreamer.AddComment(Twine("implicit-def: ") +
00510                            getVirtualRegisterName(RegNo));
00511   } else {
00512     OutStreamer.AddComment(Twine("implicit-def: ") +
00513                            nvptxSubtarget->getRegisterInfo()->getName(RegNo));
00514   }
00515   OutStreamer.AddBlankLine();
00516 }
00517 
00518 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
00519                                                    raw_ostream &O) const {
00520   // If the NVVM IR has some of reqntid* specified, then output
00521   // the reqntid directive, and set the unspecified ones to 1.
00522   // If none of reqntid* is specified, don't output reqntid directive.
00523   unsigned reqntidx, reqntidy, reqntidz;
00524   bool specified = false;
00525   if (llvm::getReqNTIDx(F, reqntidx) == false)
00526     reqntidx = 1;
00527   else
00528     specified = true;
00529   if (llvm::getReqNTIDy(F, reqntidy) == false)
00530     reqntidy = 1;
00531   else
00532     specified = true;
00533   if (llvm::getReqNTIDz(F, reqntidz) == false)
00534     reqntidz = 1;
00535   else
00536     specified = true;
00537 
00538   if (specified)
00539     O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
00540       << "\n";
00541 
00542   // If the NVVM IR has some of maxntid* specified, then output
00543   // the maxntid directive, and set the unspecified ones to 1.
00544   // If none of maxntid* is specified, don't output maxntid directive.
00545   unsigned maxntidx, maxntidy, maxntidz;
00546   specified = false;
00547   if (llvm::getMaxNTIDx(F, maxntidx) == false)
00548     maxntidx = 1;
00549   else
00550     specified = true;
00551   if (llvm::getMaxNTIDy(F, maxntidy) == false)
00552     maxntidy = 1;
00553   else
00554     specified = true;
00555   if (llvm::getMaxNTIDz(F, maxntidz) == false)
00556     maxntidz = 1;
00557   else
00558     specified = true;
00559 
00560   if (specified)
00561     O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
00562       << "\n";
00563 
00564   unsigned mincta;
00565   if (llvm::getMinCTASm(F, mincta))
00566     O << ".minnctapersm " << mincta << "\n";
00567 }
00568 
00569 std::string
00570 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
00571   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
00572 
00573   std::string Name;
00574   raw_string_ostream NameStr(Name);
00575 
00576   VRegRCMap::const_iterator I = VRegMapping.find(RC);
00577   assert(I != VRegMapping.end() && "Bad register class");
00578   const DenseMap<unsigned, unsigned> &RegMap = I->second;
00579 
00580   VRegMap::const_iterator VI = RegMap.find(Reg);
00581   assert(VI != RegMap.end() && "Bad virtual register");
00582   unsigned MappedVR = VI->second;
00583 
00584   NameStr << getNVPTXRegClassStr(RC) << MappedVR;
00585 
00586   NameStr.flush();
00587   return Name;
00588 }
00589 
00590 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
00591                                           raw_ostream &O) {
00592   O << getVirtualRegisterName(vr);
00593 }
00594 
00595 void NVPTXAsmPrinter::printVecModifiedImmediate(
00596     const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
00597   static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
00598   int Imm = (int) MO.getImm();
00599   if (0 == strcmp(Modifier, "vecelem"))
00600     O << "_" << vecelem[Imm];
00601   else if (0 == strcmp(Modifier, "vecv4comm1")) {
00602     if ((Imm < 0) || (Imm > 3))
00603       O << "//";
00604   } else if (0 == strcmp(Modifier, "vecv4comm2")) {
00605     if ((Imm < 4) || (Imm > 7))
00606       O << "//";
00607   } else if (0 == strcmp(Modifier, "vecv4pos")) {
00608     if (Imm < 0)
00609       Imm = 0;
00610     O << "_" << vecelem[Imm % 4];
00611   } else if (0 == strcmp(Modifier, "vecv2comm1")) {
00612     if ((Imm < 0) || (Imm > 1))
00613       O << "//";
00614   } else if (0 == strcmp(Modifier, "vecv2comm2")) {
00615     if ((Imm < 2) || (Imm > 3))
00616       O << "//";
00617   } else if (0 == strcmp(Modifier, "vecv2pos")) {
00618     if (Imm < 0)
00619       Imm = 0;
00620     O << "_" << vecelem[Imm % 2];
00621   } else
00622     llvm_unreachable("Unknown Modifier on immediate operand");
00623 }
00624 
00625 
00626 
00627 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
00628 
00629   emitLinkageDirective(F, O);
00630   if (llvm::isKernelFunction(*F))
00631     O << ".entry ";
00632   else
00633     O << ".func ";
00634   printReturnValStr(F, O);
00635   O << *getSymbol(F) << "\n";
00636   emitFunctionParamList(F, O);
00637   O << ";\n";
00638 }
00639 
00640 static bool usedInGlobalVarDef(const Constant *C) {
00641   if (!C)
00642     return false;
00643 
00644   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
00645     if (GV->getName().str() == "llvm.used")
00646       return false;
00647     return true;
00648   }
00649 
00650   for (const User *U : C->users())
00651     if (const Constant *C = dyn_cast<Constant>(U))
00652       if (usedInGlobalVarDef(C))
00653         return true;
00654 
00655   return false;
00656 }
00657 
00658 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
00659   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
00660     if (othergv->getName().str() == "llvm.used")
00661       return true;
00662   }
00663 
00664   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
00665     if (instr->getParent() && instr->getParent()->getParent()) {
00666       const Function *curFunc = instr->getParent()->getParent();
00667       if (oneFunc && (curFunc != oneFunc))
00668         return false;
00669       oneFunc = curFunc;
00670       return true;
00671     } else
00672       return false;
00673   }
00674 
00675   for (const User *UU : U->users())
00676     if (usedInOneFunc(UU, oneFunc) == false)
00677       return false;
00678 
00679   return true;
00680 }
00681 
00682 /* Find out if a global variable can be demoted to local scope.
00683  * Currently, this is valid for CUDA shared variables, which have local
00684  * scope and global lifetime. So the conditions to check are :
00685  * 1. Is the global variable in shared address space?
00686  * 2. Does it have internal linkage?
00687  * 3. Is the global variable referenced only in one function?
00688  */
00689 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
00690   if (gv->hasInternalLinkage() == false)
00691     return false;
00692   const PointerType *Pty = gv->getType();
00693   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
00694     return false;
00695 
00696   const Function *oneFunc = nullptr;
00697 
00698   bool flag = usedInOneFunc(gv, oneFunc);
00699   if (flag == false)
00700     return false;
00701   if (!oneFunc)
00702     return false;
00703   f = oneFunc;
00704   return true;
00705 }
00706 
00707 static bool useFuncSeen(const Constant *C,
00708                         llvm::DenseMap<const Function *, bool> &seenMap) {
00709   for (const User *U : C->users()) {
00710     if (const Constant *cu = dyn_cast<Constant>(U)) {
00711       if (useFuncSeen(cu, seenMap))
00712         return true;
00713     } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
00714       const BasicBlock *bb = I->getParent();
00715       if (!bb)
00716         continue;
00717       const Function *caller = bb->getParent();
00718       if (!caller)
00719         continue;
00720       if (seenMap.find(caller) != seenMap.end())
00721         return true;
00722     }
00723   }
00724   return false;
00725 }
00726 
00727 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
00728   llvm::DenseMap<const Function *, bool> seenMap;
00729   for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
00730     const Function *F = FI;
00731 
00732     if (F->isDeclaration()) {
00733       if (F->use_empty())
00734         continue;
00735       if (F->getIntrinsicID())
00736         continue;
00737       emitDeclaration(F, O);
00738       continue;
00739     }
00740     for (const User *U : F->users()) {
00741       if (const Constant *C = dyn_cast<Constant>(U)) {
00742         if (usedInGlobalVarDef(C)) {
00743           // The use is in the initialization of a global variable
00744           // that is a function pointer, so print a declaration
00745           // for the original function
00746           emitDeclaration(F, O);
00747           break;
00748         }
00749         // Emit a declaration of this function if the function that
00750         // uses this constant expr has already been seen.
00751         if (useFuncSeen(C, seenMap)) {
00752           emitDeclaration(F, O);
00753           break;
00754         }
00755       }
00756 
00757       if (!isa<Instruction>(U))
00758         continue;
00759       const Instruction *instr = cast<Instruction>(U);
00760       const BasicBlock *bb = instr->getParent();
00761       if (!bb)
00762         continue;
00763       const Function *caller = bb->getParent();
00764       if (!caller)
00765         continue;
00766 
00767       // If a caller has already been seen, then the caller is
00768       // appearing in the module before the callee. so print out
00769       // a declaration for the callee.
00770       if (seenMap.find(caller) != seenMap.end()) {
00771         emitDeclaration(F, O);
00772         break;
00773       }
00774     }
00775     seenMap[F] = true;
00776   }
00777 }
00778 
00779 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
00780   DebugInfoFinder DbgFinder;
00781   DbgFinder.processModule(M);
00782 
00783   unsigned i = 1;
00784   for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
00785     StringRef Filename(DIUnit.getFilename());
00786     StringRef Dirname(DIUnit.getDirectory());
00787     SmallString<128> FullPathName = Dirname;
00788     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
00789       sys::path::append(FullPathName, Filename);
00790       Filename = FullPathName.str();
00791     }
00792     if (filenameMap.find(Filename.str()) != filenameMap.end())
00793       continue;
00794     filenameMap[Filename.str()] = i;
00795     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
00796     ++i;
00797   }
00798 
00799   for (DISubprogram SP : DbgFinder.subprograms()) {
00800     StringRef Filename(SP.getFilename());
00801     StringRef Dirname(SP.getDirectory());
00802     SmallString<128> FullPathName = Dirname;
00803     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
00804       sys::path::append(FullPathName, Filename);
00805       Filename = FullPathName.str();
00806     }
00807     if (filenameMap.find(Filename.str()) != filenameMap.end())
00808       continue;
00809     filenameMap[Filename.str()] = i;
00810     ++i;
00811   }
00812 }
00813 
00814 bool NVPTXAsmPrinter::doInitialization(Module &M) {
00815   // Construct a default subtarget off of the TargetMachine defaults. The
00816   // rest of NVPTX isn't friendly to change subtargets per function and
00817   // so the default TargetMachine will have all of the options.
00818   StringRef TT = TM.getTargetTriple();
00819   StringRef CPU = TM.getTargetCPU();
00820   StringRef FS = TM.getTargetFeatureString();
00821   const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
00822   const NVPTXSubtarget STI(TT, CPU, FS, NTM);
00823 
00824   SmallString<128> Str1;
00825   raw_svector_ostream OS1(Str1);
00826 
00827   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
00828   MMI->AnalyzeModule(M);
00829 
00830   // We need to call the parent's one explicitly.
00831   //bool Result = AsmPrinter::doInitialization(M);
00832 
00833   // Initialize TargetLoweringObjectFile.
00834   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
00835       .Initialize(OutContext, TM);
00836 
00837   Mang = new Mangler(TM.getDataLayout());
00838 
00839   // Emit header before any dwarf directives are emitted below.
00840   emitHeader(M, OS1, STI);
00841   OutStreamer.EmitRawText(OS1.str());
00842 
00843   // Already commented out
00844   //bool Result = AsmPrinter::doInitialization(M);
00845 
00846   // Emit module-level inline asm if it exists.
00847   if (!M.getModuleInlineAsm().empty()) {
00848     OutStreamer.AddComment("Start of file scope inline assembly");
00849     OutStreamer.AddBlankLine();
00850     OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
00851     OutStreamer.AddBlankLine();
00852     OutStreamer.AddComment("End of file scope inline assembly");
00853     OutStreamer.AddBlankLine();
00854   }
00855 
00856   // If we're not NVCL we're CUDA, go ahead and emit filenames.
00857   if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
00858     recordAndEmitFilenames(M);
00859 
00860   GlobalsEmitted = false;
00861     
00862   return false; // success
00863 }
00864 
00865 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
00866   SmallString<128> Str2;
00867   raw_svector_ostream OS2(Str2);
00868 
00869   emitDeclarations(M, OS2);
00870 
00871   // As ptxas does not support forward references of globals, we need to first
00872   // sort the list of module-level globals in def-use order. We visit each
00873   // global variable in order, and ensure that we emit it *after* its dependent
00874   // globals. We use a little extra memory maintaining both a set and a list to
00875   // have fast searches while maintaining a strict ordering.
00876   SmallVector<const GlobalVariable *, 8> Globals;
00877   DenseSet<const GlobalVariable *> GVVisited;
00878   DenseSet<const GlobalVariable *> GVVisiting;
00879 
00880   // Visit each global variable, in order
00881   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00882        I != E; ++I)
00883     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
00884 
00885   assert(GVVisited.size() == M.getGlobalList().size() &&
00886          "Missed a global variable");
00887   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
00888 
00889   // Print out module-level global variables in proper order
00890   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
00891     printModuleLevelGV(Globals[i], OS2);
00892 
00893   OS2 << '\n';
00894 
00895   OutStreamer.EmitRawText(OS2.str());
00896 }
00897 
00898 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
00899                                  const NVPTXSubtarget &STI) {
00900   O << "//\n";
00901   O << "// Generated by LLVM NVPTX Back-End\n";
00902   O << "//\n";
00903   O << "\n";
00904 
00905   unsigned PTXVersion = STI.getPTXVersion();
00906   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
00907 
00908   O << ".target ";
00909   O << STI.getTargetName();
00910 
00911   const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
00912   if (NTM.getDrvInterface() == NVPTX::NVCL)
00913     O << ", texmode_independent";
00914   else {
00915     if (!STI.hasDouble())
00916       O << ", map_f64_to_f32";
00917   }
00918 
00919   if (MAI->doesSupportDebugInformation())
00920     O << ", debug";
00921 
00922   O << "\n";
00923 
00924   O << ".address_size ";
00925   if (NTM.is64Bit())
00926     O << "64";
00927   else
00928     O << "32";
00929   O << "\n";
00930 
00931   O << "\n";
00932 }
00933 
00934 bool NVPTXAsmPrinter::doFinalization(Module &M) {
00935   // If we did not emit any functions, then the global declarations have not
00936   // yet been emitted.
00937   if (!GlobalsEmitted) {
00938     emitGlobals(M);
00939     GlobalsEmitted = true;
00940   }
00941 
00942   // XXX Temproarily remove global variables so that doFinalization() will not
00943   // emit them again (global variables are emitted at beginning).
00944 
00945   Module::GlobalListType &global_list = M.getGlobalList();
00946   int i, n = global_list.size();
00947   GlobalVariable **gv_array = new GlobalVariable *[n];
00948 
00949   // first, back-up GlobalVariable in gv_array
00950   i = 0;
00951   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
00952        I != E; ++I)
00953     gv_array[i++] = &*I;
00954 
00955   // second, empty global_list
00956   while (!global_list.empty())
00957     global_list.remove(global_list.begin());
00958 
00959   // call doFinalization
00960   bool ret = AsmPrinter::doFinalization(M);
00961 
00962   // now we restore global variables
00963   for (i = 0; i < n; i++)
00964     global_list.insert(global_list.end(), gv_array[i]);
00965 
00966   clearAnnotationCache(&M);
00967 
00968   delete[] gv_array;
00969   return ret;
00970 
00971   //bool Result = AsmPrinter::doFinalization(M);
00972   // Instead of calling the parents doFinalization, we may
00973   // clone parents doFinalization and customize here.
00974   // Currently, we if NVISA out the EmitGlobals() in
00975   // parent's doFinalization, which is too intrusive.
00976   //
00977   // Same for the doInitialization.
00978   //return Result;
00979 }
00980 
00981 // This function emits appropriate linkage directives for
00982 // functions and global variables.
00983 //
00984 // extern function declaration            -> .extern
00985 // extern function definition             -> .visible
00986 // external global variable with init     -> .visible
00987 // external without init                  -> .extern
00988 // appending                              -> not allowed, assert.
00989 // for any linkage other than
00990 // internal, private, linker_private,
00991 // linker_private_weak, linker_private_weak_def_auto,
00992 // we emit                                -> .weak.
00993 
00994 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
00995                                            raw_ostream &O) {
00996   if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
00997     if (V->hasExternalLinkage()) {
00998       if (isa<GlobalVariable>(V)) {
00999         const GlobalVariable *GVar = cast<GlobalVariable>(V);
01000         if (GVar) {
01001           if (GVar->hasInitializer())
01002             O << ".visible ";
01003           else
01004             O << ".extern ";
01005         }
01006       } else if (V->isDeclaration())
01007         O << ".extern ";
01008       else
01009         O << ".visible ";
01010     } else if (V->hasAppendingLinkage()) {
01011       std::string msg;
01012       msg.append("Error: ");
01013       msg.append("Symbol ");
01014       if (V->hasName())
01015         msg.append(V->getName().str());
01016       msg.append("has unsupported appending linkage type");
01017       llvm_unreachable(msg.c_str());
01018     } else if (!V->hasInternalLinkage() &&
01019                !V->hasPrivateLinkage()) {
01020       O << ".weak ";
01021     }
01022   }
01023 }
01024 
01025 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
01026                                          raw_ostream &O,
01027                                          bool processDemoted) {
01028 
01029   // Skip meta data
01030   if (GVar->hasSection()) {
01031     if (GVar->getSection() == StringRef("llvm.metadata"))
01032       return;
01033   }
01034 
01035   // Skip LLVM intrinsic global variables
01036   if (GVar->getName().startswith("llvm.") ||
01037       GVar->getName().startswith("nvvm."))
01038     return;
01039 
01040   const DataLayout *TD = TM.getDataLayout();
01041 
01042   // GlobalVariables are always constant pointers themselves.
01043   const PointerType *PTy = GVar->getType();
01044   Type *ETy = PTy->getElementType();
01045 
01046   if (GVar->hasExternalLinkage()) {
01047     if (GVar->hasInitializer())
01048       O << ".visible ";
01049     else
01050       O << ".extern ";
01051   } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
01052              GVar->hasAvailableExternallyLinkage() ||
01053              GVar->hasCommonLinkage()) {
01054     O << ".weak ";
01055   }
01056 
01057   if (llvm::isTexture(*GVar)) {
01058     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
01059     return;
01060   }
01061 
01062   if (llvm::isSurface(*GVar)) {
01063     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
01064     return;
01065   }
01066 
01067   if (GVar->isDeclaration()) {
01068     // (extern) declarations, no definition or initializer
01069     // Currently the only known declaration is for an automatic __local
01070     // (.shared) promoted to global.
01071     emitPTXGlobalVariable(GVar, O);
01072     O << ";\n";
01073     return;
01074   }
01075 
01076   if (llvm::isSampler(*GVar)) {
01077     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
01078 
01079     const Constant *Initializer = nullptr;
01080     if (GVar->hasInitializer())
01081       Initializer = GVar->getInitializer();
01082     const ConstantInt *CI = nullptr;
01083     if (Initializer)
01084       CI = dyn_cast<ConstantInt>(Initializer);
01085     if (CI) {
01086       unsigned sample = CI->getZExtValue();
01087 
01088       O << " = { ";
01089 
01090       for (int i = 0,
01091                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
01092            i < 3; i++) {
01093         O << "addr_mode_" << i << " = ";
01094         switch (addr) {
01095         case 0:
01096           O << "wrap";
01097           break;
01098         case 1:
01099           O << "clamp_to_border";
01100           break;
01101         case 2:
01102           O << "clamp_to_edge";
01103           break;
01104         case 3:
01105           O << "wrap";
01106           break;
01107         case 4:
01108           O << "mirror";
01109           break;
01110         }
01111         O << ", ";
01112       }
01113       O << "filter_mode = ";
01114       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
01115       case 0:
01116         O << "nearest";
01117         break;
01118       case 1:
01119         O << "linear";
01120         break;
01121       case 2:
01122         llvm_unreachable("Anisotropic filtering is not supported");
01123       default:
01124         O << "nearest";
01125         break;
01126       }
01127       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
01128         O << ", force_unnormalized_coords = 1";
01129       }
01130       O << " }";
01131     }
01132 
01133     O << ";\n";
01134     return;
01135   }
01136 
01137   if (GVar->hasPrivateLinkage()) {
01138 
01139     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
01140       return;
01141 
01142     // FIXME - need better way (e.g. Metadata) to avoid generating this global
01143     if (!strncmp(GVar->getName().data(), "filename", 8))
01144       return;
01145     if (GVar->use_empty())
01146       return;
01147   }
01148 
01149   const Function *demotedFunc = nullptr;
01150   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
01151     O << "// " << GVar->getName().str() << " has been demoted\n";
01152     if (localDecls.find(demotedFunc) != localDecls.end())
01153       localDecls[demotedFunc].push_back(GVar);
01154     else {
01155       std::vector<const GlobalVariable *> temp;
01156       temp.push_back(GVar);
01157       localDecls[demotedFunc] = temp;
01158     }
01159     return;
01160   }
01161 
01162   O << ".";
01163   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01164 
01165   if (isManaged(*GVar)) {
01166     O << " .attribute(.managed)";
01167   }
01168 
01169   if (GVar->getAlignment() == 0)
01170     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01171   else
01172     O << " .align " << GVar->getAlignment();
01173 
01174   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
01175     O << " .";
01176     // Special case: ABI requires that we use .u8 for predicates
01177     if (ETy->isIntegerTy(1))
01178       O << "u8";
01179     else
01180       O << getPTXFundamentalTypeStr(ETy, false);
01181     O << " ";
01182     O << *getSymbol(GVar);
01183 
01184     // Ptx allows variable initilization only for constant and global state
01185     // spaces.
01186     if (GVar->hasInitializer()) {
01187       if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01188           (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
01189         const Constant *Initializer = GVar->getInitializer();
01190         // 'undef' is treated as there is no value spefied.
01191         if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
01192           O << " = ";
01193           printScalarConstant(Initializer, O);
01194         }
01195       } else {
01196         // The frontend adds zero-initializer to variables that don't have an
01197         // initial value, so skip warning for this case.
01198         if (!GVar->getInitializer()->isNullValue()) {
01199           std::string warnMsg = "initial value of '" + GVar->getName().str() +
01200               "' is not allowed in addrspace(" +
01201               llvm::utostr_32(PTy->getAddressSpace()) + ")";
01202           report_fatal_error(warnMsg.c_str());
01203         }
01204       }
01205     }
01206   } else {
01207     unsigned int ElementSize = 0;
01208 
01209     // Although PTX has direct support for struct type and array type and
01210     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
01211     // targets that support these high level field accesses. Structs, arrays
01212     // and vectors are lowered into arrays of bytes.
01213     switch (ETy->getTypeID()) {
01214     case Type::StructTyID:
01215     case Type::ArrayTyID:
01216     case Type::VectorTyID:
01217       ElementSize = TD->getTypeStoreSize(ETy);
01218       // Ptx allows variable initilization only for constant and
01219       // global state spaces.
01220       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
01221            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
01222           GVar->hasInitializer()) {
01223         const Constant *Initializer = GVar->getInitializer();
01224         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
01225           AggBuffer aggBuffer(ElementSize, O, *this);
01226           bufferAggregateConstant(Initializer, &aggBuffer);
01227           if (aggBuffer.numSymbols) {
01228             if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
01229               O << " .u64 " << *getSymbol(GVar) << "[";
01230               O << ElementSize / 8;
01231             } else {
01232               O << " .u32 " << *getSymbol(GVar) << "[";
01233               O << ElementSize / 4;
01234             }
01235             O << "]";
01236           } else {
01237             O << " .b8 " << *getSymbol(GVar) << "[";
01238             O << ElementSize;
01239             O << "]";
01240           }
01241           O << " = {";
01242           aggBuffer.print();
01243           O << "}";
01244         } else {
01245           O << " .b8 " << *getSymbol(GVar);
01246           if (ElementSize) {
01247             O << "[";
01248             O << ElementSize;
01249             O << "]";
01250           }
01251         }
01252       } else {
01253         O << " .b8 " << *getSymbol(GVar);
01254         if (ElementSize) {
01255           O << "[";
01256           O << ElementSize;
01257           O << "]";
01258         }
01259       }
01260       break;
01261     default:
01262       llvm_unreachable("type not supported yet");
01263     }
01264 
01265   }
01266   O << ";\n";
01267 }
01268 
01269 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
01270   if (localDecls.find(f) == localDecls.end())
01271     return;
01272 
01273   std::vector<const GlobalVariable *> &gvars = localDecls[f];
01274 
01275   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
01276     O << "\t// demoted variable\n\t";
01277     printModuleLevelGV(gvars[i], O, true);
01278   }
01279 }
01280 
01281 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
01282                                           raw_ostream &O) const {
01283   switch (AddressSpace) {
01284   case llvm::ADDRESS_SPACE_LOCAL:
01285     O << "local";
01286     break;
01287   case llvm::ADDRESS_SPACE_GLOBAL:
01288     O << "global";
01289     break;
01290   case llvm::ADDRESS_SPACE_CONST:
01291     O << "const";
01292     break;
01293   case llvm::ADDRESS_SPACE_SHARED:
01294     O << "shared";
01295     break;
01296   default:
01297     report_fatal_error("Bad address space found while emitting PTX");
01298     break;
01299   }
01300 }
01301 
01302 std::string
01303 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
01304   switch (Ty->getTypeID()) {
01305   default:
01306     llvm_unreachable("unexpected type");
01307     break;
01308   case Type::IntegerTyID: {
01309     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
01310     if (NumBits == 1)
01311       return "pred";
01312     else if (NumBits <= 64) {
01313       std::string name = "u";
01314       return name + utostr(NumBits);
01315     } else {
01316       llvm_unreachable("Integer too large");
01317       break;
01318     }
01319     break;
01320   }
01321   case Type::FloatTyID:
01322     return "f32";
01323   case Type::DoubleTyID:
01324     return "f64";
01325   case Type::PointerTyID:
01326     if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
01327       if (useB4PTR)
01328         return "b64";
01329       else
01330         return "u64";
01331     else if (useB4PTR)
01332       return "b32";
01333     else
01334       return "u32";
01335   }
01336   llvm_unreachable("unexpected type");
01337   return nullptr;
01338 }
01339 
01340 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
01341                                             raw_ostream &O) {
01342 
01343   const DataLayout *TD = TM.getDataLayout();
01344 
01345   // GlobalVariables are always constant pointers themselves.
01346   const PointerType *PTy = GVar->getType();
01347   Type *ETy = PTy->getElementType();
01348 
01349   O << ".";
01350   emitPTXAddressSpace(PTy->getAddressSpace(), O);
01351   if (GVar->getAlignment() == 0)
01352     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
01353   else
01354     O << " .align " << GVar->getAlignment();
01355 
01356   if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
01357     O << " .";
01358     O << getPTXFundamentalTypeStr(ETy);
01359     O << " ";
01360     O << *getSymbol(GVar);
01361     return;
01362   }
01363 
01364   int64_t ElementSize = 0;
01365 
01366   // Although PTX has direct support for struct type and array type and LLVM IR
01367   // is very similar to PTX, the LLVM CodeGen does not support for targets that
01368   // support these high level field accesses. Structs and arrays are lowered
01369   // into arrays of bytes.
01370   switch (ETy->getTypeID()) {
01371   case Type::StructTyID:
01372   case Type::ArrayTyID:
01373   case Type::VectorTyID:
01374     ElementSize = TD->getTypeStoreSize(ETy);
01375     O << " .b8 " << *getSymbol(GVar) << "[";
01376     if (ElementSize) {
01377       O << itostr(ElementSize);
01378     }
01379     O << "]";
01380     break;
01381   default:
01382     llvm_unreachable("type not supported yet");
01383   }
01384   return;
01385 }
01386 
01387 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
01388   if (Ty->isSingleValueType())
01389     return TD->getPrefTypeAlignment(Ty);
01390 
01391   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
01392   if (ATy)
01393     return getOpenCLAlignment(TD, ATy->getElementType());
01394 
01395   const StructType *STy = dyn_cast<StructType>(Ty);
01396   if (STy) {
01397     unsigned int alignStruct = 1;
01398     // Go through each element of the struct and find the
01399     // largest alignment.
01400     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
01401       Type *ETy = STy->getElementType(i);
01402       unsigned int align = getOpenCLAlignment(TD, ETy);
01403       if (align > alignStruct)
01404         alignStruct = align;
01405     }
01406     return alignStruct;
01407   }
01408 
01409   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
01410   if (FTy)
01411     return TD->getPointerPrefAlignment();
01412   return TD->getPrefTypeAlignment(Ty);
01413 }
01414 
01415 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
01416                                      int paramIndex, raw_ostream &O) {
01417   O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
01418 }
01419 
01420 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
01421   O << *CurrentFnSym << "_param_" << paramIndex;
01422 }
01423 
01424 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
01425   const DataLayout *TD = TM.getDataLayout();
01426   const AttributeSet &PAL = F->getAttributes();
01427   const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
01428   Function::const_arg_iterator I, E;
01429   unsigned paramIndex = 0;
01430   bool first = true;
01431   bool isKernelFunc = llvm::isKernelFunction(*F);
01432   bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
01433   MVT thePointerTy = TLI->getPointerTy();
01434 
01435   O << "(\n";
01436 
01437   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
01438     Type *Ty = I->getType();
01439 
01440     if (!first)
01441       O << ",\n";
01442 
01443     first = false;
01444 
01445     // Handle image/sampler parameters
01446     if (isKernelFunction(*F)) {
01447       if (isSampler(*I) || isImage(*I)) {
01448         if (isImage(*I)) {
01449           std::string sname = I->getName();
01450           if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
01451             if (nvptxSubtarget->hasImageHandles())
01452               O << "\t.param .u64 .ptr .surfref ";
01453             else
01454               O << "\t.param .surfref ";
01455             O << *CurrentFnSym << "_param_" << paramIndex;
01456           }
01457           else { // Default image is read_only
01458             if (nvptxSubtarget->hasImageHandles())
01459               O << "\t.param .u64 .ptr .texref ";
01460             else
01461               O << "\t.param .texref ";
01462             O << *CurrentFnSym << "_param_" << paramIndex;
01463           }
01464         } else {
01465           if (nvptxSubtarget->hasImageHandles())
01466             O << "\t.param .u64 .ptr .samplerref ";
01467           else
01468             O << "\t.param .samplerref ";
01469           O << *CurrentFnSym << "_param_" << paramIndex;
01470         }
01471         continue;
01472       }
01473     }
01474 
01475     if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
01476       if (Ty->isAggregateType() || Ty->isVectorTy()) {
01477         // Just print .param .align <a> .b8 .param[size];
01478         // <a> = PAL.getparamalignment
01479         // size = typeallocsize of element type
01480         unsigned align = PAL.getParamAlignment(paramIndex + 1);
01481         if (align == 0)
01482           align = TD->getABITypeAlignment(Ty);
01483 
01484         unsigned sz = TD->getTypeAllocSize(Ty);
01485         O << "\t.param .align " << align << " .b8 ";
01486         printParamName(I, paramIndex, O);
01487         O << "[" << sz << "]";
01488 
01489         continue;
01490       }
01491       // Just a scalar
01492       const PointerType *PTy = dyn_cast<PointerType>(Ty);
01493       if (isKernelFunc) {
01494         if (PTy) {
01495           // Special handling for pointer arguments to kernel
01496           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
01497 
01498           if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
01499               NVPTX::CUDA) {
01500             Type *ETy = PTy->getElementType();
01501             int addrSpace = PTy->getAddressSpace();
01502             switch (addrSpace) {
01503             default:
01504               O << ".ptr ";
01505               break;
01506             case llvm::ADDRESS_SPACE_CONST:
01507               O << ".ptr .const ";
01508               break;
01509             case llvm::ADDRESS_SPACE_SHARED:
01510               O << ".ptr .shared ";
01511               break;
01512             case llvm::ADDRESS_SPACE_GLOBAL:
01513               O << ".ptr .global ";
01514               break;
01515             }
01516             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
01517           }
01518           printParamName(I, paramIndex, O);
01519           continue;
01520         }
01521 
01522         // non-pointer scalar to kernel func
01523         O << "\t.param .";
01524         // Special case: predicate operands become .u8 types
01525         if (Ty->isIntegerTy(1))
01526           O << "u8";
01527         else
01528           O << getPTXFundamentalTypeStr(Ty);
01529         O << " ";
01530         printParamName(I, paramIndex, O);
01531         continue;
01532       }
01533       // Non-kernel function, just print .param .b<size> for ABI
01534       // and .reg .b<size> for non-ABI
01535       unsigned sz = 0;
01536       if (isa<IntegerType>(Ty)) {
01537         sz = cast<IntegerType>(Ty)->getBitWidth();
01538         if (sz < 32)
01539           sz = 32;
01540       } else if (isa<PointerType>(Ty))
01541         sz = thePointerTy.getSizeInBits();
01542       else
01543         sz = Ty->getPrimitiveSizeInBits();
01544       if (isABI)
01545         O << "\t.param .b" << sz << " ";
01546       else
01547         O << "\t.reg .b" << sz << " ";
01548       printParamName(I, paramIndex, O);
01549       continue;
01550     }
01551 
01552     // param has byVal attribute. So should be a pointer
01553     const PointerType *PTy = dyn_cast<PointerType>(Ty);
01554     assert(PTy && "Param with byval attribute should be a pointer type");
01555     Type *ETy = PTy->getElementType();
01556 
01557     if (isABI || isKernelFunc) {
01558       // Just print .param .align <a> .b8 .param[size];
01559       // <a> = PAL.getparamalignment
01560       // size = typeallocsize of element type
01561       unsigned align = PAL.getParamAlignment(paramIndex + 1);
01562       if (align == 0)
01563         align = TD->getABITypeAlignment(ETy);
01564 
01565       unsigned sz = TD->getTypeAllocSize(ETy);
01566       O << "\t.param .align " << align << " .b8 ";
01567       printParamName(I, paramIndex, O);
01568       O << "[" << sz << "]";
01569       continue;
01570     } else {
01571       // Split the ETy into constituent parts and
01572       // print .param .b<size> <name> for each part.
01573       // Further, if a part is vector, print the above for
01574       // each vector element.
01575       SmallVector<EVT, 16> vtparts;
01576       ComputeValueVTs(*TLI, ETy, vtparts);
01577       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
01578         unsigned elems = 1;
01579         EVT elemtype = vtparts[i];
01580         if (vtparts[i].isVector()) {
01581           elems = vtparts[i].getVectorNumElements();
01582           elemtype = vtparts[i].getVectorElementType();
01583         }
01584 
01585         for (unsigned j = 0, je = elems; j != je; ++j) {
01586           unsigned sz = elemtype.getSizeInBits();
01587           if (elemtype.isInteger() && (sz < 32))
01588             sz = 32;
01589           O << "\t.reg .b" << sz << " ";
01590           printParamName(I, paramIndex, O);
01591           if (j < je - 1)
01592             O << ",\n";
01593           ++paramIndex;
01594         }
01595         if (i < e - 1)
01596           O << ",\n";
01597       }
01598       --paramIndex;
01599       continue;
01600     }
01601   }
01602 
01603   O << "\n)\n";
01604 }
01605 
01606 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
01607                                             raw_ostream &O) {
01608   const Function *F = MF.getFunction();
01609   emitFunctionParamList(F, O);
01610 }
01611 
01612 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
01613     const MachineFunction &MF) {
01614   SmallString<128> Str;
01615   raw_svector_ostream O(Str);
01616 
01617   // Map the global virtual register number to a register class specific
01618   // virtual register number starting from 1 with that class.
01619   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
01620   //unsigned numRegClasses = TRI->getNumRegClasses();
01621 
01622   // Emit the Fake Stack Object
01623   const MachineFrameInfo *MFI = MF.getFrameInfo();
01624   int NumBytes = (int) MFI->getStackSize();
01625   if (NumBytes) {
01626     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
01627       << getFunctionNumber() << "[" << NumBytes << "];\n";
01628     if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
01629       O << "\t.reg .b64 \t%SP;\n";
01630       O << "\t.reg .b64 \t%SPL;\n";
01631     } else {
01632       O << "\t.reg .b32 \t%SP;\n";
01633       O << "\t.reg .b32 \t%SPL;\n";
01634     }
01635   }
01636 
01637   // Go through all virtual registers to establish the mapping between the
01638   // global virtual
01639   // register number and the per class virtual register number.
01640   // We use the per class virtual register number in the ptx output.
01641   unsigned int numVRs = MRI->getNumVirtRegs();
01642   for (unsigned i = 0; i < numVRs; i++) {
01643     unsigned int vr = TRI->index2VirtReg(i);
01644     const TargetRegisterClass *RC = MRI->getRegClass(vr);
01645     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
01646     int n = regmap.size();
01647     regmap.insert(std::make_pair(vr, n + 1));
01648   }
01649 
01650   // Emit register declarations
01651   // @TODO: Extract out the real register usage
01652   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
01653   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
01654   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
01655   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
01656   // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
01657   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
01658   // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
01659 
01660   // Emit declaration of the virtual registers or 'physical' registers for
01661   // each register class
01662   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
01663     const TargetRegisterClass *RC = TRI->getRegClass(i);
01664     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
01665     std::string rcname = getNVPTXRegClassName(RC);
01666     std::string rcStr = getNVPTXRegClassStr(RC);
01667     int n = regmap.size();
01668 
01669     // Only declare those registers that may be used.
01670     if (n) {
01671        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
01672          << ">;\n";
01673     }
01674   }
01675 
01676   OutStreamer.EmitRawText(O.str());
01677 }
01678 
01679 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
01680   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
01681   bool ignored;
01682   unsigned int numHex;
01683   const char *lead;
01684 
01685   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
01686     numHex = 8;
01687     lead = "0f";
01688     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
01689   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
01690     numHex = 16;
01691     lead = "0d";
01692     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
01693   } else
01694     llvm_unreachable("unsupported fp type");
01695 
01696   APInt API = APF.bitcastToAPInt();
01697   std::string hexstr(utohexstr(API.getZExtValue()));
01698   O << lead;
01699   if (hexstr.length() < numHex)
01700     O << std::string(numHex - hexstr.length(), '0');
01701   O << utohexstr(API.getZExtValue());
01702 }
01703 
01704 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
01705   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
01706     O << CI->getValue();
01707     return;
01708   }
01709   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
01710     printFPConstant(CFP, O);
01711     return;
01712   }
01713   if (isa<ConstantPointerNull>(CPV)) {
01714     O << "0";
01715     return;
01716   }
01717   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
01718     PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
01719     bool IsNonGenericPointer = false;
01720     if (PTy && PTy->getAddressSpace() != 0) {
01721       IsNonGenericPointer = true;
01722     }
01723     if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
01724       O << "generic(";
01725       O << *getSymbol(GVar);
01726       O << ")";
01727     } else {
01728       O << *getSymbol(GVar);
01729     }
01730     return;
01731   }
01732   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01733     const Value *v = Cexpr->stripPointerCasts();
01734     PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
01735     bool IsNonGenericPointer = false;
01736     if (PTy && PTy->getAddressSpace() != 0) {
01737       IsNonGenericPointer = true;
01738     }
01739     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
01740       if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
01741         O << "generic(";
01742         O << *getSymbol(GVar);
01743         O << ")";
01744       } else {
01745         O << *getSymbol(GVar);
01746       }
01747       return;
01748     } else {
01749       O << *lowerConstant(CPV);
01750       return;
01751     }
01752   }
01753   llvm_unreachable("Not scalar type found in printScalarConstant()");
01754 }
01755 
01756 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
01757                                    AggBuffer *aggBuffer) {
01758 
01759   const DataLayout *TD = TM.getDataLayout();
01760 
01761   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
01762     int s = TD->getTypeAllocSize(CPV->getType());
01763     if (s < Bytes)
01764       s = Bytes;
01765     aggBuffer->addZeros(s);
01766     return;
01767   }
01768 
01769   unsigned char *ptr;
01770   switch (CPV->getType()->getTypeID()) {
01771 
01772   case Type::IntegerTyID: {
01773     const Type *ETy = CPV->getType();
01774     if (ETy == Type::getInt8Ty(CPV->getContext())) {
01775       unsigned char c =
01776           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
01777       ptr = &c;
01778       aggBuffer->addBytes(ptr, 1, Bytes);
01779     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
01780       short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
01781       ptr = (unsigned char *)&int16;
01782       aggBuffer->addBytes(ptr, 2, Bytes);
01783     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
01784       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
01785         int int32 = (int)(constInt->getZExtValue());
01786         ptr = (unsigned char *)&int32;
01787         aggBuffer->addBytes(ptr, 4, Bytes);
01788         break;
01789       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01790         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
01791                 ConstantFoldConstantExpression(Cexpr, TD))) {
01792           int int32 = (int)(constInt->getZExtValue());
01793           ptr = (unsigned char *)&int32;
01794           aggBuffer->addBytes(ptr, 4, Bytes);
01795           break;
01796         }
01797         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
01798           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
01799           aggBuffer->addSymbol(v);
01800           aggBuffer->addZeros(4);
01801           break;
01802         }
01803       }
01804       llvm_unreachable("unsupported integer const type");
01805     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
01806       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
01807         long long int64 = (long long)(constInt->getZExtValue());
01808         ptr = (unsigned char *)&int64;
01809         aggBuffer->addBytes(ptr, 8, Bytes);
01810         break;
01811       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01812         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
01813                 ConstantFoldConstantExpression(Cexpr, TD))) {
01814           long long int64 = (long long)(constInt->getZExtValue());
01815           ptr = (unsigned char *)&int64;
01816           aggBuffer->addBytes(ptr, 8, Bytes);
01817           break;
01818         }
01819         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
01820           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
01821           aggBuffer->addSymbol(v);
01822           aggBuffer->addZeros(8);
01823           break;
01824         }
01825       }
01826       llvm_unreachable("unsupported integer const type");
01827     } else
01828       llvm_unreachable("unsupported integer const type");
01829     break;
01830   }
01831   case Type::FloatTyID:
01832   case Type::DoubleTyID: {
01833     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
01834     const Type *Ty = CFP->getType();
01835     if (Ty == Type::getFloatTy(CPV->getContext())) {
01836       float float32 = (float) CFP->getValueAPF().convertToFloat();
01837       ptr = (unsigned char *)&float32;
01838       aggBuffer->addBytes(ptr, 4, Bytes);
01839     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
01840       double float64 = CFP->getValueAPF().convertToDouble();
01841       ptr = (unsigned char *)&float64;
01842       aggBuffer->addBytes(ptr, 8, Bytes);
01843     } else {
01844       llvm_unreachable("unsupported fp const type");
01845     }
01846     break;
01847   }
01848   case Type::PointerTyID: {
01849     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
01850       aggBuffer->addSymbol(GVar);
01851     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
01852       const Value *v = Cexpr->stripPointerCasts();
01853       aggBuffer->addSymbol(v);
01854     }
01855     unsigned int s = TD->getTypeAllocSize(CPV->getType());
01856     aggBuffer->addZeros(s);
01857     break;
01858   }
01859 
01860   case Type::ArrayTyID:
01861   case Type::VectorTyID:
01862   case Type::StructTyID: {
01863     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
01864         isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
01865       int ElementSize = TD->getTypeAllocSize(CPV->getType());
01866       bufferAggregateConstant(CPV, aggBuffer);
01867       if (Bytes > ElementSize)
01868         aggBuffer->addZeros(Bytes - ElementSize);
01869     } else if (isa<ConstantAggregateZero>(CPV))
01870       aggBuffer->addZeros(Bytes);
01871     else
01872       llvm_unreachable("Unexpected Constant type");
01873     break;
01874   }
01875 
01876   default:
01877     llvm_unreachable("unsupported type");
01878   }
01879 }
01880 
01881 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
01882                                               AggBuffer *aggBuffer) {
01883   const DataLayout *TD = TM.getDataLayout();
01884   int Bytes;
01885 
01886   // Old constants
01887   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
01888     if (CPV->getNumOperands())
01889       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
01890         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
01891     return;
01892   }
01893 
01894   if (const ConstantDataSequential *CDS =
01895           dyn_cast<ConstantDataSequential>(CPV)) {
01896     if (CDS->getNumElements())
01897       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
01898         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
01899                      aggBuffer);
01900     return;
01901   }
01902 
01903   if (isa<ConstantStruct>(CPV)) {
01904     if (CPV->getNumOperands()) {
01905       StructType *ST = cast<StructType>(CPV->getType());
01906       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
01907         if (i == (e - 1))
01908           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
01909                   TD->getTypeAllocSize(ST) -
01910                   TD->getStructLayout(ST)->getElementOffset(i);
01911         else
01912           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
01913                   TD->getStructLayout(ST)->getElementOffset(i);
01914         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
01915       }
01916     }
01917     return;
01918   }
01919   llvm_unreachable("unsupported constant type in printAggregateConstant()");
01920 }
01921 
01922 // buildTypeNameMap - Run through symbol table looking for type names.
01923 //
01924 
01925 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
01926 
01927   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
01928 
01929   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
01930                                   !PI->second.compare("struct._image2d_t") ||
01931                                   !PI->second.compare("struct._image3d_t")))
01932     return true;
01933 
01934   return false;
01935 }
01936 
01937 
01938 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
01939   switch (MI.getOpcode()) {
01940   default:
01941     return false;
01942   case NVPTX::CallArgBeginInst:
01943   case NVPTX::CallArgEndInst0:
01944   case NVPTX::CallArgEndInst1:
01945   case NVPTX::CallArgF32:
01946   case NVPTX::CallArgF64:
01947   case NVPTX::CallArgI16:
01948   case NVPTX::CallArgI32:
01949   case NVPTX::CallArgI32imm:
01950   case NVPTX::CallArgI64:
01951   case NVPTX::CallArgParam:
01952   case NVPTX::CallVoidInst:
01953   case NVPTX::CallVoidInstReg:
01954   case NVPTX::Callseq_End:
01955   case NVPTX::CallVoidInstReg64:
01956   case NVPTX::DeclareParamInst:
01957   case NVPTX::DeclareRetMemInst:
01958   case NVPTX::DeclareRetRegInst:
01959   case NVPTX::DeclareRetScalarInst:
01960   case NVPTX::DeclareScalarParamInst:
01961   case NVPTX::DeclareScalarRegInst:
01962   case NVPTX::StoreParamF32:
01963   case NVPTX::StoreParamF64:
01964   case NVPTX::StoreParamI16:
01965   case NVPTX::StoreParamI32:
01966   case NVPTX::StoreParamI64:
01967   case NVPTX::StoreParamI8:
01968   case NVPTX::StoreRetvalF32:
01969   case NVPTX::StoreRetvalF64:
01970   case NVPTX::StoreRetvalI16:
01971   case NVPTX::StoreRetvalI32:
01972   case NVPTX::StoreRetvalI64:
01973   case NVPTX::StoreRetvalI8:
01974   case NVPTX::LastCallArgF32:
01975   case NVPTX::LastCallArgF64:
01976   case NVPTX::LastCallArgI16:
01977   case NVPTX::LastCallArgI32:
01978   case NVPTX::LastCallArgI32imm:
01979   case NVPTX::LastCallArgI64:
01980   case NVPTX::LastCallArgParam:
01981   case NVPTX::LoadParamMemF32:
01982   case NVPTX::LoadParamMemF64:
01983   case NVPTX::LoadParamMemI16:
01984   case NVPTX::LoadParamMemI32:
01985   case NVPTX::LoadParamMemI64:
01986   case NVPTX::LoadParamMemI8:
01987   case NVPTX::PrototypeInst:
01988   case NVPTX::DBG_VALUE:
01989     return true;
01990   }
01991   return false;
01992 }
01993 
01994 /// PrintAsmOperand - Print out an operand for an inline asm expression.
01995 ///
01996 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
01997                                       unsigned AsmVariant,
01998                                       const char *ExtraCode, raw_ostream &O) {
01999   if (ExtraCode && ExtraCode[0]) {
02000     if (ExtraCode[1] != 0)
02001       return true; // Unknown modifier.
02002 
02003     switch (ExtraCode[0]) {
02004     default:
02005       // See if this is a generic print operand
02006       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
02007     case 'r':
02008       break;
02009     }
02010   }
02011 
02012   printOperand(MI, OpNo, O);
02013 
02014   return false;
02015 }
02016 
02017 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
02018     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
02019     const char *ExtraCode, raw_ostream &O) {
02020   if (ExtraCode && ExtraCode[0])
02021     return true; // Unknown modifier
02022 
02023   O << '[';
02024   printMemOperand(MI, OpNo, O);
02025   O << ']';
02026 
02027   return false;
02028 }
02029 
02030 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
02031                                    raw_ostream &O, const char *Modifier) {
02032   const MachineOperand &MO = MI->getOperand(opNum);
02033   switch (MO.getType()) {
02034   case MachineOperand::MO_Register:
02035     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
02036       if (MO.getReg() == NVPTX::VRDepot)
02037         O << DEPOTNAME << getFunctionNumber();
02038       else
02039         O << NVPTXInstPrinter::getRegisterName(MO.getReg());
02040     } else {
02041       emitVirtualRegister(MO.getReg(), O);
02042     }
02043     return;
02044 
02045   case MachineOperand::MO_Immediate:
02046     if (!Modifier)
02047       O << MO.getImm();
02048     else if (strstr(Modifier, "vec") == Modifier)
02049       printVecModifiedImmediate(MO, Modifier, O);
02050     else
02051       llvm_unreachable(
02052           "Don't know how to handle modifier on immediate operand");
02053     return;
02054 
02055   case MachineOperand::MO_FPImmediate:
02056     printFPConstant(MO.getFPImm(), O);
02057     break;
02058 
02059   case MachineOperand::MO_GlobalAddress:
02060     O << *getSymbol(MO.getGlobal());
02061     break;
02062 
02063   case MachineOperand::MO_MachineBasicBlock:
02064     O << *MO.getMBB()->getSymbol();
02065     return;
02066 
02067   default:
02068     llvm_unreachable("Operand type not supported.");
02069   }
02070 }
02071 
02072 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
02073                                       raw_ostream &O, const char *Modifier) {
02074   printOperand(MI, opNum, O);
02075 
02076   if (Modifier && !strcmp(Modifier, "add")) {
02077     O << ", ";
02078     printOperand(MI, opNum + 1, O);
02079   } else {
02080     if (MI->getOperand(opNum + 1).isImm() &&
02081         MI->getOperand(opNum + 1).getImm() == 0)
02082       return; // don't print ',0' or '+0'
02083     O << "+";
02084     printOperand(MI, opNum + 1, O);
02085   }
02086 }
02087 
02088 
02089 // Force static initialization.
02090 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
02091   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
02092   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
02093 }
02094 
02095 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
02096   std::stringstream temp;
02097   LineReader *reader = this->getReader(filename.str());
02098   temp << "\n//";
02099   temp << filename.str();
02100   temp << ":";
02101   temp << line;
02102   temp << " ";
02103   temp << reader->readLine(line);
02104   temp << "\n";
02105   this->OutStreamer.EmitRawText(Twine(temp.str()));
02106 }
02107 
02108 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
02109   if (!reader) {
02110     reader = new LineReader(filename);
02111   }
02112 
02113   if (reader->fileName() != filename) {
02114     delete reader;
02115     reader = new LineReader(filename);
02116   }
02117 
02118   return reader;
02119 }
02120 
02121 std::string LineReader::readLine(unsigned lineNum) {
02122   if (lineNum < theCurLine) {
02123     theCurLine = 0;
02124     fstr.seekg(0, std::ios::beg);
02125   }
02126   while (theCurLine < lineNum) {
02127     fstr.getline(buff, 500);
02128     theCurLine++;
02129   }
02130   return buff;
02131 }
02132 
02133 // Force static initialization.
02134 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
02135   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
02136   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
02137 }