1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMachineFunctionInfo.h"
21 #include "NVPTXMCExpr.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TimeValue.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #define DEPOTNAME "__local_depot"
54 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
55 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
60 cl::desc("NVPTX Specific: Emit source line in ptx file"),
64 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
66 void DiscoverDependentGlobals(const Value *V,
67 DenseSet<const GlobalVariable *> &Globals) {
68 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
71 if (const User *U = dyn_cast<User>(V)) {
72 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
73 DiscoverDependentGlobals(U->getOperand(i), Globals);
79 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
80 /// instances to be emitted, but only after any dependents have been added
82 void VisitGlobalVariableForEmission(
83 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
84 DenseSet<const GlobalVariable *> &Visited,
85 DenseSet<const GlobalVariable *> &Visiting) {
86 // Have we already visited this one?
87 if (Visited.count(GV))
90 // Do we have a circular dependency?
91 if (Visiting.count(GV))
92 report_fatal_error("Circular dependency found in global variable set");
94 // Start visiting this global
97 // Make sure we visit all dependents first
98 DenseSet<const GlobalVariable *> Others;
99 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
100 DiscoverDependentGlobals(GV->getOperand(i), Others);
102 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
105 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
107 // Now we can visit ourself
114 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
115 // cannot just link to the existing version.
116 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
118 using namespace nvptx;
119 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
120 MCContext &Ctx = AP.OutContext;
122 if (CV->isNullValue() || isa<UndefValue>(CV))
123 return MCConstantExpr::Create(0, Ctx);
125 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
126 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
128 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
129 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
131 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
132 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
134 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
136 llvm_unreachable("Unknown constant value to lower!");
138 switch (CE->getOpcode()) {
140 // If the code isn't optimized, there may be outstanding folding
141 // opportunities. Attempt to fold the expression using DataLayout as a
142 // last resort before giving up.
143 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
145 return LowerConstant(C, AP);
147 // Otherwise report the problem to the user.
150 raw_string_ostream OS(S);
151 OS << "Unsupported expression in static initializer: ";
152 CE->printAsOperand(OS, /*PrintType=*/ false,
153 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
154 report_fatal_error(OS.str());
156 case Instruction::AddrSpaceCast: {
157 // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
158 // handled by the generic() logic in the MCExpr printer
159 PointerType *DstTy = cast<PointerType>(CE->getType());
160 PointerType *SrcTy = cast<PointerType>(CE->getOperand(0)->getType());
161 if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
162 return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
165 raw_string_ostream OS(S);
166 OS << "Unsupported expression in static initializer: ";
167 CE->printAsOperand(OS, /*PrintType=*/ false,
168 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
169 report_fatal_error(OS.str());
171 case Instruction::GetElementPtr: {
172 const DataLayout &TD = *AP.TM.getDataLayout();
173 // Generate a symbolic expression for the byte address
174 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
175 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
177 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
181 int64_t Offset = OffsetAI.getSExtValue();
182 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
186 case Instruction::Trunc:
187 // We emit the value and depend on the assembler to truncate the generated
188 // expression properly. This is important for differences between
189 // blockaddress labels. Since the two labels are in the same function, it
190 // is reasonable to treat their delta as a 32-bit value.
192 case Instruction::BitCast:
193 return LowerConstant(CE->getOperand(0), AP);
195 case Instruction::IntToPtr: {
196 const DataLayout &TD = *AP.TM.getDataLayout();
197 // Handle casts to pointers by changing them into casts to the appropriate
198 // integer type. This promotes constant folding and simplifies this code.
199 Constant *Op = CE->getOperand(0);
200 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
202 return LowerConstant(Op, AP);
205 case Instruction::PtrToInt: {
206 const DataLayout &TD = *AP.TM.getDataLayout();
207 // Support only foldable casts to/from pointers that can be eliminated by
208 // changing the pointer to the appropriately sized integer type.
209 Constant *Op = CE->getOperand(0);
210 Type *Ty = CE->getType();
212 const MCExpr *OpExpr = LowerConstant(Op, AP);
214 // We can emit the pointer value into this slot if the slot is an
215 // integer slot equal to the size of the pointer.
216 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
219 // Otherwise the pointer is smaller than the resultant integer, mask off
220 // the high bits so we are sure to get a proper truncation if the input is
222 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
223 const MCExpr *MaskExpr =
224 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
225 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
228 // The MC library also has a right-shift operator, but it isn't consistently
229 // signed or unsigned between different targets.
230 case Instruction::Add:
231 case Instruction::Sub:
232 case Instruction::Mul:
233 case Instruction::SDiv:
234 case Instruction::SRem:
235 case Instruction::Shl:
236 case Instruction::And:
237 case Instruction::Or:
238 case Instruction::Xor: {
239 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
240 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
241 switch (CE->getOpcode()) {
243 llvm_unreachable("Unknown binary operator constant cast expr");
244 case Instruction::Add:
245 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
246 case Instruction::Sub:
247 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
248 case Instruction::Mul:
249 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
250 case Instruction::SDiv:
251 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
252 case Instruction::SRem:
253 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
254 case Instruction::Shl:
255 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
256 case Instruction::And:
257 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
258 case Instruction::Or:
259 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
260 case Instruction::Xor:
261 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
267 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
268 if (!EmitLineNumbers)
273 DebugLoc curLoc = MI.getDebugLoc();
275 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
278 if (prevDebugLoc == curLoc)
281 prevDebugLoc = curLoc;
283 if (curLoc.isUnknown())
286 const MachineFunction *MF = MI.getParent()->getParent();
287 //const TargetMachine &TM = MF->getTarget();
289 const LLVMContext &ctx = MF->getFunction()->getContext();
290 DIScope Scope(curLoc.getScope(ctx));
292 assert((!Scope || Scope.isScope()) &&
293 "Scope of a DebugLoc should be null or a DIScope.");
297 StringRef fileName(Scope.getFilename());
298 StringRef dirName(Scope.getDirectory());
299 SmallString<128> FullPathName = dirName;
300 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
301 sys::path::append(FullPathName, fileName);
302 fileName = FullPathName.str();
305 if (filenameMap.find(fileName.str()) == filenameMap.end())
308 // Emit the line from the source file.
310 this->emitSrcInText(fileName.str(), curLoc.getLine());
312 std::stringstream temp;
313 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
314 << " " << curLoc.getCol();
315 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
318 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
319 SmallString<128> Str;
320 raw_svector_ostream OS(Str);
321 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
322 emitLineNumberAsDotLoc(*MI);
325 lowerToMCInst(MI, Inst);
326 EmitToStreamer(OutStreamer, Inst);
329 // Handle symbol backtracking for targets that do not support image handles
330 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
331 unsigned OpNo, MCOperand &MCOp) {
332 const MachineOperand &MO = MI->getOperand(OpNo);
333 const MCInstrDesc &MCID = MI->getDesc();
335 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
336 // This is a texture fetch, so operand 4 is a texref and operand 5 is
338 if (OpNo == 4 && MO.isImm()) {
339 lowerImageHandleSymbol(MO.getImm(), MCOp);
342 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
343 lowerImageHandleSymbol(MO.getImm(), MCOp);
348 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
350 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
352 // For a surface load of vector size N, the Nth operand will be the surfref
353 if (OpNo == VecSize && MO.isImm()) {
354 lowerImageHandleSymbol(MO.getImm(), MCOp);
359 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
360 // This is a surface store, so operand 0 is a surfref
361 if (OpNo == 0 && MO.isImm()) {
362 lowerImageHandleSymbol(MO.getImm(), MCOp);
367 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
368 // This is a query, so operand 1 is a surfref/texref
369 if (OpNo == 1 && MO.isImm()) {
370 lowerImageHandleSymbol(MO.getImm(), MCOp);
380 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
382 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
383 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
384 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
385 const char *Sym = MFI->getImageHandleSymbol(Index);
386 std::string *SymNamePtr =
387 nvTM.getManagedStrPool()->getManagedString(Sym);
388 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
389 StringRef(SymNamePtr->c_str())));
392 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
393 OutMI.setOpcode(MI->getOpcode());
394 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
396 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
397 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
398 const MachineOperand &MO = MI->getOperand(0);
399 OutMI.addOperand(GetSymbolRef(
400 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
404 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
405 const MachineOperand &MO = MI->getOperand(i);
408 if (!ST.hasImageHandles()) {
409 if (lowerImageHandleOperand(MI, i, MCOp)) {
410 OutMI.addOperand(MCOp);
415 if (lowerOperand(MO, MCOp))
416 OutMI.addOperand(MCOp);
420 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
422 switch (MO.getType()) {
423 default: llvm_unreachable("unknown operand type");
424 case MachineOperand::MO_Register:
425 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
427 case MachineOperand::MO_Immediate:
428 MCOp = MCOperand::CreateImm(MO.getImm());
430 case MachineOperand::MO_MachineBasicBlock:
431 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
432 MO.getMBB()->getSymbol(), OutContext));
434 case MachineOperand::MO_ExternalSymbol:
435 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
437 case MachineOperand::MO_GlobalAddress:
438 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
440 case MachineOperand::MO_FPImmediate: {
441 const ConstantFP *Cnt = MO.getFPImm();
442 APFloat Val = Cnt->getValueAPF();
444 switch (Cnt->getType()->getTypeID()) {
445 default: report_fatal_error("Unsupported FP type"); break;
446 case Type::FloatTyID:
447 MCOp = MCOperand::CreateExpr(
448 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
450 case Type::DoubleTyID:
451 MCOp = MCOperand::CreateExpr(
452 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
461 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
462 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
463 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
465 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
466 unsigned RegNum = RegMap[Reg];
468 // Encode the register class in the upper 4 bits
469 // Must be kept in sync with NVPTXInstPrinter::printRegName
471 if (RC == &NVPTX::Int1RegsRegClass) {
473 } else if (RC == &NVPTX::Int16RegsRegClass) {
475 } else if (RC == &NVPTX::Int32RegsRegClass) {
477 } else if (RC == &NVPTX::Int64RegsRegClass) {
479 } else if (RC == &NVPTX::Float32RegsRegClass) {
481 } else if (RC == &NVPTX::Float64RegsRegClass) {
484 report_fatal_error("Bad register class");
487 // Insert the vreg number
488 Ret |= (RegNum & 0x0FFFFFFF);
491 // Some special-use registers are actually physical registers.
492 // Encode this as the register class ID of 0 and the real register ID.
493 return Reg & 0x0FFFFFFF;
497 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
499 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
501 return MCOperand::CreateExpr(Expr);
504 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
505 const DataLayout *TD = TM.getDataLayout();
506 const TargetLowering *TLI = TM.getTargetLowering();
508 Type *Ty = F->getReturnType();
510 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
512 if (Ty->getTypeID() == Type::VoidTyID)
518 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
520 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
521 size = ITy->getBitWidth();
525 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
526 size = Ty->getPrimitiveSizeInBits();
529 O << ".param .b" << size << " func_retval0";
530 } else if (isa<PointerType>(Ty)) {
531 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
534 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
535 unsigned totalsz = TD->getTypeAllocSize(Ty);
536 unsigned retAlignment = 0;
537 if (!llvm::getAlign(*F, 0, retAlignment))
538 retAlignment = TD->getABITypeAlignment(Ty);
539 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
542 assert(false && "Unknown return type");
545 SmallVector<EVT, 16> vtparts;
546 ComputeValueVTs(*TLI, Ty, vtparts);
548 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
550 EVT elemtype = vtparts[i];
551 if (vtparts[i].isVector()) {
552 elems = vtparts[i].getVectorNumElements();
553 elemtype = vtparts[i].getVectorElementType();
556 for (unsigned j = 0, je = elems; j != je; ++j) {
557 unsigned sz = elemtype.getSizeInBits();
558 if (elemtype.isInteger() && (sz < 32))
560 O << ".reg .b" << sz << " func_retval" << idx;
573 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
575 const Function *F = MF.getFunction();
576 printReturnValStr(F, O);
579 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
580 SmallString<128> Str;
581 raw_svector_ostream O(Str);
583 if (!GlobalsEmitted) {
584 emitGlobals(*MF->getFunction()->getParent());
585 GlobalsEmitted = true;
589 MRI = &MF->getRegInfo();
590 F = MF->getFunction();
591 emitLinkageDirective(F, O);
592 if (llvm::isKernelFunction(*F))
596 printReturnValStr(*MF, O);
601 emitFunctionParamList(*MF, O);
603 if (llvm::isKernelFunction(*F))
604 emitKernelFunctionDirectives(*F, O);
606 OutStreamer.EmitRawText(O.str());
608 prevDebugLoc = DebugLoc();
611 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
613 OutStreamer.EmitRawText(StringRef("{\n"));
614 setAndEmitFunctionVirtualRegisters(*MF);
616 SmallString<128> Str;
617 raw_svector_ostream O(Str);
618 emitDemotedVars(MF->getFunction(), O);
619 OutStreamer.EmitRawText(O.str());
622 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
623 OutStreamer.EmitRawText(StringRef("}\n"));
627 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
628 unsigned RegNo = MI->getOperand(0).getReg();
629 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
630 if (TRI->isVirtualRegister(RegNo)) {
631 OutStreamer.AddComment(Twine("implicit-def: ") +
632 getVirtualRegisterName(RegNo));
634 OutStreamer.AddComment(Twine("implicit-def: ") +
635 TM.getRegisterInfo()->getName(RegNo));
637 OutStreamer.AddBlankLine();
640 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
641 raw_ostream &O) const {
642 // If the NVVM IR has some of reqntid* specified, then output
643 // the reqntid directive, and set the unspecified ones to 1.
644 // If none of reqntid* is specified, don't output reqntid directive.
645 unsigned reqntidx, reqntidy, reqntidz;
646 bool specified = false;
647 if (llvm::getReqNTIDx(F, reqntidx) == false)
651 if (llvm::getReqNTIDy(F, reqntidy) == false)
655 if (llvm::getReqNTIDz(F, reqntidz) == false)
661 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
664 // If the NVVM IR has some of maxntid* specified, then output
665 // the maxntid directive, and set the unspecified ones to 1.
666 // If none of maxntid* is specified, don't output maxntid directive.
667 unsigned maxntidx, maxntidy, maxntidz;
669 if (llvm::getMaxNTIDx(F, maxntidx) == false)
673 if (llvm::getMaxNTIDy(F, maxntidy) == false)
677 if (llvm::getMaxNTIDz(F, maxntidz) == false)
683 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
687 if (llvm::getMinCTASm(F, mincta))
688 O << ".minnctapersm " << mincta << "\n";
692 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
693 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
696 raw_string_ostream NameStr(Name);
698 VRegRCMap::const_iterator I = VRegMapping.find(RC);
699 assert(I != VRegMapping.end() && "Bad register class");
700 const DenseMap<unsigned, unsigned> &RegMap = I->second;
702 VRegMap::const_iterator VI = RegMap.find(Reg);
703 assert(VI != RegMap.end() && "Bad virtual register");
704 unsigned MappedVR = VI->second;
706 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
712 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
714 O << getVirtualRegisterName(vr);
717 void NVPTXAsmPrinter::printVecModifiedImmediate(
718 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
719 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
720 int Imm = (int) MO.getImm();
721 if (0 == strcmp(Modifier, "vecelem"))
722 O << "_" << vecelem[Imm];
723 else if (0 == strcmp(Modifier, "vecv4comm1")) {
724 if ((Imm < 0) || (Imm > 3))
726 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
727 if ((Imm < 4) || (Imm > 7))
729 } else if (0 == strcmp(Modifier, "vecv4pos")) {
732 O << "_" << vecelem[Imm % 4];
733 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
734 if ((Imm < 0) || (Imm > 1))
736 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
737 if ((Imm < 2) || (Imm > 3))
739 } else if (0 == strcmp(Modifier, "vecv2pos")) {
742 O << "_" << vecelem[Imm % 2];
744 llvm_unreachable("Unknown Modifier on immediate operand");
749 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
751 emitLinkageDirective(F, O);
752 if (llvm::isKernelFunction(*F))
756 printReturnValStr(F, O);
757 O << *getSymbol(F) << "\n";
758 emitFunctionParamList(F, O);
762 static bool usedInGlobalVarDef(const Constant *C) {
766 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
767 if (GV->getName().str() == "llvm.used")
772 for (const User *U : C->users())
773 if (const Constant *C = dyn_cast<Constant>(U))
774 if (usedInGlobalVarDef(C))
780 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
781 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
782 if (othergv->getName().str() == "llvm.used")
786 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
787 if (instr->getParent() && instr->getParent()->getParent()) {
788 const Function *curFunc = instr->getParent()->getParent();
789 if (oneFunc && (curFunc != oneFunc))
797 if (const MDNode *md = dyn_cast<MDNode>(U))
798 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
799 (md->getName().str() == "llvm.dbg.sp")))
802 for (const User *UU : U->users())
803 if (usedInOneFunc(UU, oneFunc) == false)
809 /* Find out if a global variable can be demoted to local scope.
810 * Currently, this is valid for CUDA shared variables, which have local
811 * scope and global lifetime. So the conditions to check are :
812 * 1. Is the global variable in shared address space?
813 * 2. Does it have internal linkage?
814 * 3. Is the global variable referenced only in one function?
816 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
817 if (gv->hasInternalLinkage() == false)
819 const PointerType *Pty = gv->getType();
820 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
823 const Function *oneFunc = nullptr;
825 bool flag = usedInOneFunc(gv, oneFunc);
834 static bool useFuncSeen(const Constant *C,
835 llvm::DenseMap<const Function *, bool> &seenMap) {
836 for (const User *U : C->users()) {
837 if (const Constant *cu = dyn_cast<Constant>(U)) {
838 if (useFuncSeen(cu, seenMap))
840 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
841 const BasicBlock *bb = I->getParent();
844 const Function *caller = bb->getParent();
847 if (seenMap.find(caller) != seenMap.end())
854 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
855 llvm::DenseMap<const Function *, bool> seenMap;
856 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
857 const Function *F = FI;
859 if (F->isDeclaration()) {
862 if (F->getIntrinsicID())
864 emitDeclaration(F, O);
867 for (const User *U : F->users()) {
868 if (const Constant *C = dyn_cast<Constant>(U)) {
869 if (usedInGlobalVarDef(C)) {
870 // The use is in the initialization of a global variable
871 // that is a function pointer, so print a declaration
872 // for the original function
873 emitDeclaration(F, O);
876 // Emit a declaration of this function if the function that
877 // uses this constant expr has already been seen.
878 if (useFuncSeen(C, seenMap)) {
879 emitDeclaration(F, O);
884 if (!isa<Instruction>(U))
886 const Instruction *instr = cast<Instruction>(U);
887 const BasicBlock *bb = instr->getParent();
890 const Function *caller = bb->getParent();
894 // If a caller has already been seen, then the caller is
895 // appearing in the module before the callee. so print out
896 // a declaration for the callee.
897 if (seenMap.find(caller) != seenMap.end()) {
898 emitDeclaration(F, O);
906 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
907 DebugInfoFinder DbgFinder;
908 DbgFinder.processModule(M);
911 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
912 StringRef Filename(DIUnit.getFilename());
913 StringRef Dirname(DIUnit.getDirectory());
914 SmallString<128> FullPathName = Dirname;
915 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
916 sys::path::append(FullPathName, Filename);
917 Filename = FullPathName.str();
919 if (filenameMap.find(Filename.str()) != filenameMap.end())
921 filenameMap[Filename.str()] = i;
922 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
926 for (DISubprogram SP : DbgFinder.subprograms()) {
927 StringRef Filename(SP.getFilename());
928 StringRef Dirname(SP.getDirectory());
929 SmallString<128> FullPathName = Dirname;
930 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
931 sys::path::append(FullPathName, Filename);
932 Filename = FullPathName.str();
934 if (filenameMap.find(Filename.str()) != filenameMap.end())
936 filenameMap[Filename.str()] = i;
941 bool NVPTXAsmPrinter::doInitialization(Module &M) {
943 SmallString<128> Str1;
944 raw_svector_ostream OS1(Str1);
946 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
947 MMI->AnalyzeModule(M);
949 // We need to call the parent's one explicitly.
950 //bool Result = AsmPrinter::doInitialization(M);
952 // Initialize TargetLoweringObjectFile.
953 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
954 .Initialize(OutContext, TM);
956 Mang = new Mangler(TM.getDataLayout());
958 // Emit header before any dwarf directives are emitted below.
960 OutStreamer.EmitRawText(OS1.str());
962 // Already commented out
963 //bool Result = AsmPrinter::doInitialization(M);
965 // Emit module-level inline asm if it exists.
966 if (!M.getModuleInlineAsm().empty()) {
967 OutStreamer.AddComment("Start of file scope inline assembly");
968 OutStreamer.AddBlankLine();
969 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
970 OutStreamer.AddBlankLine();
971 OutStreamer.AddComment("End of file scope inline assembly");
972 OutStreamer.AddBlankLine();
975 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
976 recordAndEmitFilenames(M);
978 GlobalsEmitted = false;
980 return false; // success
983 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
984 SmallString<128> Str2;
985 raw_svector_ostream OS2(Str2);
987 emitDeclarations(M, OS2);
989 // As ptxas does not support forward references of globals, we need to first
990 // sort the list of module-level globals in def-use order. We visit each
991 // global variable in order, and ensure that we emit it *after* its dependent
992 // globals. We use a little extra memory maintaining both a set and a list to
993 // have fast searches while maintaining a strict ordering.
994 SmallVector<const GlobalVariable *, 8> Globals;
995 DenseSet<const GlobalVariable *> GVVisited;
996 DenseSet<const GlobalVariable *> GVVisiting;
998 // Visit each global variable, in order
999 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1001 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1003 assert(GVVisited.size() == M.getGlobalList().size() &&
1004 "Missed a global variable");
1005 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1007 // Print out module-level global variables in proper order
1008 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1009 printModuleLevelGV(Globals[i], OS2);
1013 OutStreamer.EmitRawText(OS2.str());
1016 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1018 O << "// Generated by LLVM NVPTX Back-End\n";
1022 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1023 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1026 O << nvptxSubtarget.getTargetName();
1028 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1029 O << ", texmode_independent";
1030 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1031 if (!nvptxSubtarget.hasDouble())
1032 O << ", map_f64_to_f32";
1035 if (MAI->doesSupportDebugInformation())
1040 O << ".address_size ";
1041 if (nvptxSubtarget.is64Bit())
1050 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1052 // If we did not emit any functions, then the global declarations have not
1053 // yet been emitted.
1054 if (!GlobalsEmitted) {
1056 GlobalsEmitted = true;
1059 // XXX Temproarily remove global variables so that doFinalization() will not
1060 // emit them again (global variables are emitted at beginning).
1062 Module::GlobalListType &global_list = M.getGlobalList();
1063 int i, n = global_list.size();
1064 GlobalVariable **gv_array = new GlobalVariable *[n];
1066 // first, back-up GlobalVariable in gv_array
1068 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1070 gv_array[i++] = &*I;
1072 // second, empty global_list
1073 while (!global_list.empty())
1074 global_list.remove(global_list.begin());
1076 // call doFinalization
1077 bool ret = AsmPrinter::doFinalization(M);
1079 // now we restore global variables
1080 for (i = 0; i < n; i++)
1081 global_list.insert(global_list.end(), gv_array[i]);
1083 clearAnnotationCache(&M);
1088 //bool Result = AsmPrinter::doFinalization(M);
1089 // Instead of calling the parents doFinalization, we may
1090 // clone parents doFinalization and customize here.
1091 // Currently, we if NVISA out the EmitGlobals() in
1092 // parent's doFinalization, which is too intrusive.
1094 // Same for the doInitialization.
1098 // This function emits appropriate linkage directives for
1099 // functions and global variables.
1101 // extern function declaration -> .extern
1102 // extern function definition -> .visible
1103 // external global variable with init -> .visible
1104 // external without init -> .extern
1105 // appending -> not allowed, assert.
1106 // for any linkage other than
1107 // internal, private, linker_private,
1108 // linker_private_weak, linker_private_weak_def_auto,
1109 // we emit -> .weak.
1111 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1113 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1114 if (V->hasExternalLinkage()) {
1115 if (isa<GlobalVariable>(V)) {
1116 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1118 if (GVar->hasInitializer())
1123 } else if (V->isDeclaration())
1127 } else if (V->hasAppendingLinkage()) {
1129 msg.append("Error: ");
1130 msg.append("Symbol ");
1132 msg.append(V->getName().str());
1133 msg.append("has unsupported appending linkage type");
1134 llvm_unreachable(msg.c_str());
1135 } else if (!V->hasInternalLinkage() &&
1136 !V->hasPrivateLinkage()) {
1142 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1144 bool processDemoted) {
1147 if (GVar->hasSection()) {
1148 if (GVar->getSection() == StringRef("llvm.metadata"))
1152 // Skip LLVM intrinsic global variables
1153 if (GVar->getName().startswith("llvm.") ||
1154 GVar->getName().startswith("nvvm."))
1157 const DataLayout *TD = TM.getDataLayout();
1159 // GlobalVariables are always constant pointers themselves.
1160 const PointerType *PTy = GVar->getType();
1161 Type *ETy = PTy->getElementType();
1163 if (GVar->hasExternalLinkage()) {
1164 if (GVar->hasInitializer())
1168 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1169 GVar->hasAvailableExternallyLinkage() ||
1170 GVar->hasCommonLinkage()) {
1174 if (llvm::isTexture(*GVar)) {
1175 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1179 if (llvm::isSurface(*GVar)) {
1180 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1184 if (GVar->isDeclaration()) {
1185 // (extern) declarations, no definition or initializer
1186 // Currently the only known declaration is for an automatic __local
1187 // (.shared) promoted to global.
1188 emitPTXGlobalVariable(GVar, O);
1193 if (llvm::isSampler(*GVar)) {
1194 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1196 const Constant *Initializer = nullptr;
1197 if (GVar->hasInitializer())
1198 Initializer = GVar->getInitializer();
1199 const ConstantInt *CI = nullptr;
1201 CI = dyn_cast<ConstantInt>(Initializer);
1203 unsigned sample = CI->getZExtValue();
1208 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1210 O << "addr_mode_" << i << " = ";
1216 O << "clamp_to_border";
1219 O << "clamp_to_edge";
1230 O << "filter_mode = ";
1231 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1239 llvm_unreachable("Anisotropic filtering is not supported");
1244 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1245 O << ", force_unnormalized_coords = 1";
1254 if (GVar->hasPrivateLinkage()) {
1256 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1259 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1260 if (!strncmp(GVar->getName().data(), "filename", 8))
1262 if (GVar->use_empty())
1266 const Function *demotedFunc = nullptr;
1267 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1268 O << "// " << GVar->getName().str() << " has been demoted\n";
1269 if (localDecls.find(demotedFunc) != localDecls.end())
1270 localDecls[demotedFunc].push_back(GVar);
1272 std::vector<const GlobalVariable *> temp;
1273 temp.push_back(GVar);
1274 localDecls[demotedFunc] = temp;
1280 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1282 if (isManaged(*GVar)) {
1283 O << " .attribute(.managed)";
1286 if (GVar->getAlignment() == 0)
1287 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1289 O << " .align " << GVar->getAlignment();
1291 if (ETy->isSingleValueType()) {
1293 // Special case: ABI requires that we use .u8 for predicates
1294 if (ETy->isIntegerTy(1))
1297 O << getPTXFundamentalTypeStr(ETy, false);
1299 O << *getSymbol(GVar);
1301 // Ptx allows variable initilization only for constant and global state
1303 if (GVar->hasInitializer()) {
1304 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1305 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1306 const Constant *Initializer = GVar->getInitializer();
1307 // 'undef' is treated as there is no value spefied.
1308 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1310 printScalarConstant(Initializer, O);
1313 // The frontend adds zero-initializer to variables that don't have an
1314 // initial value, so skip warning for this case.
1315 if (!GVar->getInitializer()->isNullValue()) {
1316 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1317 "' is not allowed in addrspace(" +
1318 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1319 report_fatal_error(warnMsg.c_str());
1324 unsigned int ElementSize = 0;
1326 // Although PTX has direct support for struct type and array type and
1327 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1328 // targets that support these high level field accesses. Structs, arrays
1329 // and vectors are lowered into arrays of bytes.
1330 switch (ETy->getTypeID()) {
1331 case Type::StructTyID:
1332 case Type::ArrayTyID:
1333 case Type::VectorTyID:
1334 ElementSize = TD->getTypeStoreSize(ETy);
1335 // Ptx allows variable initilization only for constant and
1336 // global state spaces.
1337 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1338 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1339 GVar->hasInitializer()) {
1340 const Constant *Initializer = GVar->getInitializer();
1341 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1342 AggBuffer aggBuffer(ElementSize, O, *this);
1343 bufferAggregateConstant(Initializer, &aggBuffer);
1344 if (aggBuffer.numSymbols) {
1345 if (nvptxSubtarget.is64Bit()) {
1346 O << " .u64 " << *getSymbol(GVar) << "[";
1347 O << ElementSize / 8;
1349 O << " .u32 " << *getSymbol(GVar) << "[";
1350 O << ElementSize / 4;
1354 O << " .b8 " << *getSymbol(GVar) << "[";
1362 O << " .b8 " << *getSymbol(GVar);
1370 O << " .b8 " << *getSymbol(GVar);
1379 llvm_unreachable("type not supported yet");
1386 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1387 if (localDecls.find(f) == localDecls.end())
1390 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1392 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1393 O << "\t// demoted variable\n\t";
1394 printModuleLevelGV(gvars[i], O, true);
1398 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1399 raw_ostream &O) const {
1400 switch (AddressSpace) {
1401 case llvm::ADDRESS_SPACE_LOCAL:
1404 case llvm::ADDRESS_SPACE_GLOBAL:
1407 case llvm::ADDRESS_SPACE_CONST:
1410 case llvm::ADDRESS_SPACE_SHARED:
1414 report_fatal_error("Bad address space found while emitting PTX");
1420 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1421 switch (Ty->getTypeID()) {
1423 llvm_unreachable("unexpected type");
1425 case Type::IntegerTyID: {
1426 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1429 else if (NumBits <= 64) {
1430 std::string name = "u";
1431 return name + utostr(NumBits);
1433 llvm_unreachable("Integer too large");
1438 case Type::FloatTyID:
1440 case Type::DoubleTyID:
1442 case Type::PointerTyID:
1443 if (nvptxSubtarget.is64Bit())
1453 llvm_unreachable("unexpected type");
1457 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1460 const DataLayout *TD = TM.getDataLayout();
1462 // GlobalVariables are always constant pointers themselves.
1463 const PointerType *PTy = GVar->getType();
1464 Type *ETy = PTy->getElementType();
1467 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1468 if (GVar->getAlignment() == 0)
1469 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1471 O << " .align " << GVar->getAlignment();
1473 if (ETy->isSingleValueType()) {
1475 O << getPTXFundamentalTypeStr(ETy);
1477 O << *getSymbol(GVar);
1481 int64_t ElementSize = 0;
1483 // Although PTX has direct support for struct type and array type and LLVM IR
1484 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1485 // support these high level field accesses. Structs and arrays are lowered
1486 // into arrays of bytes.
1487 switch (ETy->getTypeID()) {
1488 case Type::StructTyID:
1489 case Type::ArrayTyID:
1490 case Type::VectorTyID:
1491 ElementSize = TD->getTypeStoreSize(ETy);
1492 O << " .b8 " << *getSymbol(GVar) << "[";
1494 O << itostr(ElementSize);
1499 llvm_unreachable("type not supported yet");
1504 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1505 if (Ty->isSingleValueType())
1506 return TD->getPrefTypeAlignment(Ty);
1508 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1510 return getOpenCLAlignment(TD, ATy->getElementType());
1512 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1514 Type *ETy = VTy->getElementType();
1515 unsigned int numE = VTy->getNumElements();
1516 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1520 return numE * alignE;
1523 const StructType *STy = dyn_cast<StructType>(Ty);
1525 unsigned int alignStruct = 1;
1526 // Go through each element of the struct and find the
1527 // largest alignment.
1528 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1529 Type *ETy = STy->getElementType(i);
1530 unsigned int align = getOpenCLAlignment(TD, ETy);
1531 if (align > alignStruct)
1532 alignStruct = align;
1537 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1539 return TD->getPointerPrefAlignment();
1540 return TD->getPrefTypeAlignment(Ty);
1543 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1544 int paramIndex, raw_ostream &O) {
1545 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1546 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1547 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1549 std::string argName = I->getName();
1550 const char *p = argName.c_str();
1561 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1562 Function::const_arg_iterator I, E;
1565 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1566 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1567 O << *CurrentFnSym << "_param_" << paramIndex;
1571 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1572 if (i == paramIndex) {
1573 printParamName(I, paramIndex, O);
1577 llvm_unreachable("paramIndex out of bound");
1580 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1581 const DataLayout *TD = TM.getDataLayout();
1582 const AttributeSet &PAL = F->getAttributes();
1583 const TargetLowering *TLI = TM.getTargetLowering();
1584 Function::const_arg_iterator I, E;
1585 unsigned paramIndex = 0;
1587 bool isKernelFunc = llvm::isKernelFunction(*F);
1588 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1589 MVT thePointerTy = TLI->getPointerTy();
1593 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1594 Type *Ty = I->getType();
1601 // Handle image/sampler parameters
1602 if (isKernelFunction(*F)) {
1603 if (isSampler(*I) || isImage(*I)) {
1605 std::string sname = I->getName();
1606 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1607 if (nvptxSubtarget.hasImageHandles())
1608 O << "\t.param .u64 .ptr .surfref ";
1610 O << "\t.param .surfref ";
1611 O << *CurrentFnSym << "_param_" << paramIndex;
1613 else { // Default image is read_only
1614 if (nvptxSubtarget.hasImageHandles())
1615 O << "\t.param .u64 .ptr .texref ";
1617 O << "\t.param .texref ";
1618 O << *CurrentFnSym << "_param_" << paramIndex;
1621 if (nvptxSubtarget.hasImageHandles())
1622 O << "\t.param .u64 .ptr .samplerref ";
1624 O << "\t.param .samplerref ";
1625 O << *CurrentFnSym << "_param_" << paramIndex;
1631 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1632 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1633 // Just print .param .align <a> .b8 .param[size];
1634 // <a> = PAL.getparamalignment
1635 // size = typeallocsize of element type
1636 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1638 align = TD->getABITypeAlignment(Ty);
1640 unsigned sz = TD->getTypeAllocSize(Ty);
1641 O << "\t.param .align " << align << " .b8 ";
1642 printParamName(I, paramIndex, O);
1643 O << "[" << sz << "]";
1648 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1651 // Special handling for pointer arguments to kernel
1652 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1654 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1655 Type *ETy = PTy->getElementType();
1656 int addrSpace = PTy->getAddressSpace();
1657 switch (addrSpace) {
1661 case llvm::ADDRESS_SPACE_CONST:
1662 O << ".ptr .const ";
1664 case llvm::ADDRESS_SPACE_SHARED:
1665 O << ".ptr .shared ";
1667 case llvm::ADDRESS_SPACE_GLOBAL:
1668 O << ".ptr .global ";
1671 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1673 printParamName(I, paramIndex, O);
1677 // non-pointer scalar to kernel func
1679 // Special case: predicate operands become .u8 types
1680 if (Ty->isIntegerTy(1))
1683 O << getPTXFundamentalTypeStr(Ty);
1685 printParamName(I, paramIndex, O);
1688 // Non-kernel function, just print .param .b<size> for ABI
1689 // and .reg .b<size> for non-ABI
1691 if (isa<IntegerType>(Ty)) {
1692 sz = cast<IntegerType>(Ty)->getBitWidth();
1695 } else if (isa<PointerType>(Ty))
1696 sz = thePointerTy.getSizeInBits();
1698 sz = Ty->getPrimitiveSizeInBits();
1700 O << "\t.param .b" << sz << " ";
1702 O << "\t.reg .b" << sz << " ";
1703 printParamName(I, paramIndex, O);
1707 // param has byVal attribute. So should be a pointer
1708 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1709 assert(PTy && "Param with byval attribute should be a pointer type");
1710 Type *ETy = PTy->getElementType();
1712 if (isABI || isKernelFunc) {
1713 // Just print .param .align <a> .b8 .param[size];
1714 // <a> = PAL.getparamalignment
1715 // size = typeallocsize of element type
1716 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1718 align = TD->getABITypeAlignment(ETy);
1720 unsigned sz = TD->getTypeAllocSize(ETy);
1721 O << "\t.param .align " << align << " .b8 ";
1722 printParamName(I, paramIndex, O);
1723 O << "[" << sz << "]";
1726 // Split the ETy into constituent parts and
1727 // print .param .b<size> <name> for each part.
1728 // Further, if a part is vector, print the above for
1729 // each vector element.
1730 SmallVector<EVT, 16> vtparts;
1731 ComputeValueVTs(*TLI, ETy, vtparts);
1732 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1734 EVT elemtype = vtparts[i];
1735 if (vtparts[i].isVector()) {
1736 elems = vtparts[i].getVectorNumElements();
1737 elemtype = vtparts[i].getVectorElementType();
1740 for (unsigned j = 0, je = elems; j != je; ++j) {
1741 unsigned sz = elemtype.getSizeInBits();
1742 if (elemtype.isInteger() && (sz < 32))
1744 O << "\t.reg .b" << sz << " ";
1745 printParamName(I, paramIndex, O);
1761 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1763 const Function *F = MF.getFunction();
1764 emitFunctionParamList(F, O);
1767 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1768 const MachineFunction &MF) {
1769 SmallString<128> Str;
1770 raw_svector_ostream O(Str);
1772 // Map the global virtual register number to a register class specific
1773 // virtual register number starting from 1 with that class.
1774 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1775 //unsigned numRegClasses = TRI->getNumRegClasses();
1777 // Emit the Fake Stack Object
1778 const MachineFrameInfo *MFI = MF.getFrameInfo();
1779 int NumBytes = (int) MFI->getStackSize();
1781 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1782 << getFunctionNumber() << "[" << NumBytes << "];\n";
1783 if (nvptxSubtarget.is64Bit()) {
1784 O << "\t.reg .b64 \t%SP;\n";
1785 O << "\t.reg .b64 \t%SPL;\n";
1787 O << "\t.reg .b32 \t%SP;\n";
1788 O << "\t.reg .b32 \t%SPL;\n";
1792 // Go through all virtual registers to establish the mapping between the
1794 // register number and the per class virtual register number.
1795 // We use the per class virtual register number in the ptx output.
1796 unsigned int numVRs = MRI->getNumVirtRegs();
1797 for (unsigned i = 0; i < numVRs; i++) {
1798 unsigned int vr = TRI->index2VirtReg(i);
1799 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1800 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1801 int n = regmap.size();
1802 regmap.insert(std::make_pair(vr, n + 1));
1805 // Emit register declarations
1806 // @TODO: Extract out the real register usage
1807 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1808 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1809 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1810 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1811 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1812 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1813 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1815 // Emit declaration of the virtual registers or 'physical' registers for
1816 // each register class
1817 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1818 const TargetRegisterClass *RC = TRI->getRegClass(i);
1819 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1820 std::string rcname = getNVPTXRegClassName(RC);
1821 std::string rcStr = getNVPTXRegClassStr(RC);
1822 int n = regmap.size();
1824 // Only declare those registers that may be used.
1826 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1831 OutStreamer.EmitRawText(O.str());
1834 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1835 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1837 unsigned int numHex;
1840 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1843 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1844 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1847 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1849 llvm_unreachable("unsupported fp type");
1851 APInt API = APF.bitcastToAPInt();
1852 std::string hexstr(utohexstr(API.getZExtValue()));
1854 if (hexstr.length() < numHex)
1855 O << std::string(numHex - hexstr.length(), '0');
1856 O << utohexstr(API.getZExtValue());
1859 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1860 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1861 O << CI->getValue();
1864 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1865 printFPConstant(CFP, O);
1868 if (isa<ConstantPointerNull>(CPV)) {
1872 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1873 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1874 bool IsNonGenericPointer = false;
1875 if (PTy && PTy->getAddressSpace() != 0) {
1876 IsNonGenericPointer = true;
1878 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1880 O << *getSymbol(GVar);
1883 O << *getSymbol(GVar);
1887 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1888 const Value *v = Cexpr->stripPointerCasts();
1889 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1890 bool IsNonGenericPointer = false;
1891 if (PTy && PTy->getAddressSpace() != 0) {
1892 IsNonGenericPointer = true;
1894 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1895 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1897 O << *getSymbol(GVar);
1900 O << *getSymbol(GVar);
1904 O << *LowerConstant(CPV, *this);
1908 llvm_unreachable("Not scalar type found in printScalarConstant()");
1911 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1912 AggBuffer *aggBuffer) {
1914 const DataLayout *TD = TM.getDataLayout();
1916 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1917 int s = TD->getTypeAllocSize(CPV->getType());
1920 aggBuffer->addZeros(s);
1925 switch (CPV->getType()->getTypeID()) {
1927 case Type::IntegerTyID: {
1928 const Type *ETy = CPV->getType();
1929 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1931 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1933 aggBuffer->addBytes(ptr, 1, Bytes);
1934 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1935 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1936 ptr = (unsigned char *)&int16;
1937 aggBuffer->addBytes(ptr, 2, Bytes);
1938 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1939 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1940 int int32 = (int)(constInt->getZExtValue());
1941 ptr = (unsigned char *)&int32;
1942 aggBuffer->addBytes(ptr, 4, Bytes);
1944 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1945 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1946 ConstantFoldConstantExpression(Cexpr, TD))) {
1947 int int32 = (int)(constInt->getZExtValue());
1948 ptr = (unsigned char *)&int32;
1949 aggBuffer->addBytes(ptr, 4, Bytes);
1952 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1953 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1954 aggBuffer->addSymbol(v);
1955 aggBuffer->addZeros(4);
1959 llvm_unreachable("unsupported integer const type");
1960 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1961 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1962 long long int64 = (long long)(constInt->getZExtValue());
1963 ptr = (unsigned char *)&int64;
1964 aggBuffer->addBytes(ptr, 8, Bytes);
1966 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1967 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1968 ConstantFoldConstantExpression(Cexpr, TD))) {
1969 long long int64 = (long long)(constInt->getZExtValue());
1970 ptr = (unsigned char *)&int64;
1971 aggBuffer->addBytes(ptr, 8, Bytes);
1974 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1975 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1976 aggBuffer->addSymbol(v);
1977 aggBuffer->addZeros(8);
1981 llvm_unreachable("unsupported integer const type");
1983 llvm_unreachable("unsupported integer const type");
1986 case Type::FloatTyID:
1987 case Type::DoubleTyID: {
1988 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1989 const Type *Ty = CFP->getType();
1990 if (Ty == Type::getFloatTy(CPV->getContext())) {
1991 float float32 = (float) CFP->getValueAPF().convertToFloat();
1992 ptr = (unsigned char *)&float32;
1993 aggBuffer->addBytes(ptr, 4, Bytes);
1994 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1995 double float64 = CFP->getValueAPF().convertToDouble();
1996 ptr = (unsigned char *)&float64;
1997 aggBuffer->addBytes(ptr, 8, Bytes);
1999 llvm_unreachable("unsupported fp const type");
2003 case Type::PointerTyID: {
2004 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2005 aggBuffer->addSymbol(GVar);
2006 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2007 const Value *v = Cexpr->stripPointerCasts();
2008 aggBuffer->addSymbol(v);
2010 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2011 aggBuffer->addZeros(s);
2015 case Type::ArrayTyID:
2016 case Type::VectorTyID:
2017 case Type::StructTyID: {
2018 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2019 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
2020 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2021 bufferAggregateConstant(CPV, aggBuffer);
2022 if (Bytes > ElementSize)
2023 aggBuffer->addZeros(Bytes - ElementSize);
2024 } else if (isa<ConstantAggregateZero>(CPV))
2025 aggBuffer->addZeros(Bytes);
2027 llvm_unreachable("Unexpected Constant type");
2032 llvm_unreachable("unsupported type");
2036 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2037 AggBuffer *aggBuffer) {
2038 const DataLayout *TD = TM.getDataLayout();
2042 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2043 if (CPV->getNumOperands())
2044 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2045 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2049 if (const ConstantDataSequential *CDS =
2050 dyn_cast<ConstantDataSequential>(CPV)) {
2051 if (CDS->getNumElements())
2052 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2053 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2058 if (isa<ConstantStruct>(CPV)) {
2059 if (CPV->getNumOperands()) {
2060 StructType *ST = cast<StructType>(CPV->getType());
2061 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2063 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2064 TD->getTypeAllocSize(ST) -
2065 TD->getStructLayout(ST)->getElementOffset(i);
2067 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2068 TD->getStructLayout(ST)->getElementOffset(i);
2069 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2074 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2077 // buildTypeNameMap - Run through symbol table looking for type names.
2080 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2082 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2084 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2085 !PI->second.compare("struct._image2d_t") ||
2086 !PI->second.compare("struct._image3d_t")))
2093 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2094 switch (MI.getOpcode()) {
2097 case NVPTX::CallArgBeginInst:
2098 case NVPTX::CallArgEndInst0:
2099 case NVPTX::CallArgEndInst1:
2100 case NVPTX::CallArgF32:
2101 case NVPTX::CallArgF64:
2102 case NVPTX::CallArgI16:
2103 case NVPTX::CallArgI32:
2104 case NVPTX::CallArgI32imm:
2105 case NVPTX::CallArgI64:
2106 case NVPTX::CallArgParam:
2107 case NVPTX::CallVoidInst:
2108 case NVPTX::CallVoidInstReg:
2109 case NVPTX::Callseq_End:
2110 case NVPTX::CallVoidInstReg64:
2111 case NVPTX::DeclareParamInst:
2112 case NVPTX::DeclareRetMemInst:
2113 case NVPTX::DeclareRetRegInst:
2114 case NVPTX::DeclareRetScalarInst:
2115 case NVPTX::DeclareScalarParamInst:
2116 case NVPTX::DeclareScalarRegInst:
2117 case NVPTX::StoreParamF32:
2118 case NVPTX::StoreParamF64:
2119 case NVPTX::StoreParamI16:
2120 case NVPTX::StoreParamI32:
2121 case NVPTX::StoreParamI64:
2122 case NVPTX::StoreParamI8:
2123 case NVPTX::StoreRetvalF32:
2124 case NVPTX::StoreRetvalF64:
2125 case NVPTX::StoreRetvalI16:
2126 case NVPTX::StoreRetvalI32:
2127 case NVPTX::StoreRetvalI64:
2128 case NVPTX::StoreRetvalI8:
2129 case NVPTX::LastCallArgF32:
2130 case NVPTX::LastCallArgF64:
2131 case NVPTX::LastCallArgI16:
2132 case NVPTX::LastCallArgI32:
2133 case NVPTX::LastCallArgI32imm:
2134 case NVPTX::LastCallArgI64:
2135 case NVPTX::LastCallArgParam:
2136 case NVPTX::LoadParamMemF32:
2137 case NVPTX::LoadParamMemF64:
2138 case NVPTX::LoadParamMemI16:
2139 case NVPTX::LoadParamMemI32:
2140 case NVPTX::LoadParamMemI64:
2141 case NVPTX::LoadParamMemI8:
2142 case NVPTX::PrototypeInst:
2143 case NVPTX::DBG_VALUE:
2149 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2151 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2152 unsigned AsmVariant,
2153 const char *ExtraCode, raw_ostream &O) {
2154 if (ExtraCode && ExtraCode[0]) {
2155 if (ExtraCode[1] != 0)
2156 return true; // Unknown modifier.
2158 switch (ExtraCode[0]) {
2160 // See if this is a generic print operand
2161 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2167 printOperand(MI, OpNo, O);
2172 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2173 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2174 const char *ExtraCode, raw_ostream &O) {
2175 if (ExtraCode && ExtraCode[0])
2176 return true; // Unknown modifier
2179 printMemOperand(MI, OpNo, O);
2185 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2186 raw_ostream &O, const char *Modifier) {
2187 const MachineOperand &MO = MI->getOperand(opNum);
2188 switch (MO.getType()) {
2189 case MachineOperand::MO_Register:
2190 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2191 if (MO.getReg() == NVPTX::VRDepot)
2192 O << DEPOTNAME << getFunctionNumber();
2194 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2196 emitVirtualRegister(MO.getReg(), O);
2200 case MachineOperand::MO_Immediate:
2203 else if (strstr(Modifier, "vec") == Modifier)
2204 printVecModifiedImmediate(MO, Modifier, O);
2207 "Don't know how to handle modifier on immediate operand");
2210 case MachineOperand::MO_FPImmediate:
2211 printFPConstant(MO.getFPImm(), O);
2214 case MachineOperand::MO_GlobalAddress:
2215 O << *getSymbol(MO.getGlobal());
2218 case MachineOperand::MO_MachineBasicBlock:
2219 O << *MO.getMBB()->getSymbol();
2223 llvm_unreachable("Operand type not supported.");
2227 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2228 raw_ostream &O, const char *Modifier) {
2229 printOperand(MI, opNum, O);
2231 if (Modifier && !strcmp(Modifier, "add")) {
2233 printOperand(MI, opNum + 1, O);
2235 if (MI->getOperand(opNum + 1).isImm() &&
2236 MI->getOperand(opNum + 1).getImm() == 0)
2237 return; // don't print ',0' or '+0'
2239 printOperand(MI, opNum + 1, O);
2244 // Force static initialization.
2245 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2246 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2247 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2250 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2251 std::stringstream temp;
2252 LineReader *reader = this->getReader(filename.str());
2254 temp << filename.str();
2258 temp << reader->readLine(line);
2260 this->OutStreamer.EmitRawText(Twine(temp.str()));
2263 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2265 reader = new LineReader(filename);
2268 if (reader->fileName() != filename) {
2270 reader = new LineReader(filename);
2276 std::string LineReader::readLine(unsigned lineNum) {
2277 if (lineNum < theCurLine) {
2279 fstr.seekg(0, std::ios::beg);
2281 while (theCurLine < lineNum) {
2282 fstr.getline(buff, 500);
2288 // Force static initialization.
2289 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2290 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2291 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);