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