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(
144 CE, AP.TM.getSubtargetImpl()->getDataLayout()))
146 return LowerConstant(C, AP);
148 // Otherwise report the problem to the user.
151 raw_string_ostream OS(S);
152 OS << "Unsupported expression in static initializer: ";
153 CE->printAsOperand(OS, /*PrintType=*/ false,
154 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
155 report_fatal_error(OS.str());
157 case Instruction::AddrSpaceCast: {
158 // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
159 // handled by the generic() logic in the MCExpr printer
160 PointerType *DstTy = cast<PointerType>(CE->getType());
161 PointerType *SrcTy = cast<PointerType>(CE->getOperand(0)->getType());
162 if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
163 return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
166 raw_string_ostream OS(S);
167 OS << "Unsupported expression in static initializer: ";
168 CE->printAsOperand(OS, /*PrintType=*/ false,
169 !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
170 report_fatal_error(OS.str());
172 case Instruction::GetElementPtr: {
173 const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
174 // Generate a symbolic expression for the byte address
175 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
176 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
178 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
182 int64_t Offset = OffsetAI.getSExtValue();
183 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
187 case Instruction::Trunc:
188 // We emit the value and depend on the assembler to truncate the generated
189 // expression properly. This is important for differences between
190 // blockaddress labels. Since the two labels are in the same function, it
191 // is reasonable to treat their delta as a 32-bit value.
193 case Instruction::BitCast:
194 return LowerConstant(CE->getOperand(0), AP);
196 case Instruction::IntToPtr: {
197 const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
198 // Handle casts to pointers by changing them into casts to the appropriate
199 // integer type. This promotes constant folding and simplifies this code.
200 Constant *Op = CE->getOperand(0);
201 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
203 return LowerConstant(Op, AP);
206 case Instruction::PtrToInt: {
207 const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
208 // Support only foldable casts to/from pointers that can be eliminated by
209 // changing the pointer to the appropriately sized integer type.
210 Constant *Op = CE->getOperand(0);
211 Type *Ty = CE->getType();
213 const MCExpr *OpExpr = LowerConstant(Op, AP);
215 // We can emit the pointer value into this slot if the slot is an
216 // integer slot equal to the size of the pointer.
217 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
220 // Otherwise the pointer is smaller than the resultant integer, mask off
221 // the high bits so we are sure to get a proper truncation if the input is
223 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
224 const MCExpr *MaskExpr =
225 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
226 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
229 // The MC library also has a right-shift operator, but it isn't consistently
230 // signed or unsigned between different targets.
231 case Instruction::Add:
232 case Instruction::Sub:
233 case Instruction::Mul:
234 case Instruction::SDiv:
235 case Instruction::SRem:
236 case Instruction::Shl:
237 case Instruction::And:
238 case Instruction::Or:
239 case Instruction::Xor: {
240 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
241 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
242 switch (CE->getOpcode()) {
244 llvm_unreachable("Unknown binary operator constant cast expr");
245 case Instruction::Add:
246 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
247 case Instruction::Sub:
248 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
249 case Instruction::Mul:
250 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
251 case Instruction::SDiv:
252 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
253 case Instruction::SRem:
254 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
255 case Instruction::Shl:
256 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
257 case Instruction::And:
258 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
259 case Instruction::Or:
260 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
261 case Instruction::Xor:
262 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
268 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
269 if (!EmitLineNumbers)
274 DebugLoc curLoc = MI.getDebugLoc();
276 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
279 if (prevDebugLoc == curLoc)
282 prevDebugLoc = curLoc;
284 if (curLoc.isUnknown())
287 const MachineFunction *MF = MI.getParent()->getParent();
288 //const TargetMachine &TM = MF->getTarget();
290 const LLVMContext &ctx = MF->getFunction()->getContext();
291 DIScope Scope(curLoc.getScope(ctx));
293 assert((!Scope || Scope.isScope()) &&
294 "Scope of a DebugLoc should be null or a DIScope.");
298 StringRef fileName(Scope.getFilename());
299 StringRef dirName(Scope.getDirectory());
300 SmallString<128> FullPathName = dirName;
301 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
302 sys::path::append(FullPathName, fileName);
303 fileName = FullPathName.str();
306 if (filenameMap.find(fileName.str()) == filenameMap.end())
309 // Emit the line from the source file.
311 this->emitSrcInText(fileName.str(), curLoc.getLine());
313 std::stringstream temp;
314 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
315 << " " << curLoc.getCol();
316 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
319 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
320 SmallString<128> Str;
321 raw_svector_ostream OS(Str);
322 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
323 emitLineNumberAsDotLoc(*MI);
326 lowerToMCInst(MI, Inst);
327 EmitToStreamer(OutStreamer, Inst);
330 // Handle symbol backtracking for targets that do not support image handles
331 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
332 unsigned OpNo, MCOperand &MCOp) {
333 const MachineOperand &MO = MI->getOperand(OpNo);
334 const MCInstrDesc &MCID = MI->getDesc();
336 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
337 // This is a texture fetch, so operand 4 is a texref and operand 5 is
339 if (OpNo == 4 && MO.isImm()) {
340 lowerImageHandleSymbol(MO.getImm(), MCOp);
343 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
344 lowerImageHandleSymbol(MO.getImm(), MCOp);
349 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
351 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
353 // For a surface load of vector size N, the Nth operand will be the surfref
354 if (OpNo == VecSize && MO.isImm()) {
355 lowerImageHandleSymbol(MO.getImm(), MCOp);
360 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
361 // This is a surface store, so operand 0 is a surfref
362 if (OpNo == 0 && MO.isImm()) {
363 lowerImageHandleSymbol(MO.getImm(), MCOp);
368 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
369 // This is a query, so operand 1 is a surfref/texref
370 if (OpNo == 1 && MO.isImm()) {
371 lowerImageHandleSymbol(MO.getImm(), MCOp);
381 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
383 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
384 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
385 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
386 const char *Sym = MFI->getImageHandleSymbol(Index);
387 std::string *SymNamePtr =
388 nvTM.getManagedStrPool()->getManagedString(Sym);
389 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
390 StringRef(SymNamePtr->c_str())));
393 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
394 OutMI.setOpcode(MI->getOpcode());
395 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
397 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
398 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
399 const MachineOperand &MO = MI->getOperand(0);
400 OutMI.addOperand(GetSymbolRef(
401 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
405 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
406 const MachineOperand &MO = MI->getOperand(i);
409 if (!ST.hasImageHandles()) {
410 if (lowerImageHandleOperand(MI, i, MCOp)) {
411 OutMI.addOperand(MCOp);
416 if (lowerOperand(MO, MCOp))
417 OutMI.addOperand(MCOp);
421 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
423 switch (MO.getType()) {
424 default: llvm_unreachable("unknown operand type");
425 case MachineOperand::MO_Register:
426 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
428 case MachineOperand::MO_Immediate:
429 MCOp = MCOperand::CreateImm(MO.getImm());
431 case MachineOperand::MO_MachineBasicBlock:
432 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
433 MO.getMBB()->getSymbol(), OutContext));
435 case MachineOperand::MO_ExternalSymbol:
436 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
438 case MachineOperand::MO_GlobalAddress:
439 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
441 case MachineOperand::MO_FPImmediate: {
442 const ConstantFP *Cnt = MO.getFPImm();
443 APFloat Val = Cnt->getValueAPF();
445 switch (Cnt->getType()->getTypeID()) {
446 default: report_fatal_error("Unsupported FP type"); break;
447 case Type::FloatTyID:
448 MCOp = MCOperand::CreateExpr(
449 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
451 case Type::DoubleTyID:
452 MCOp = MCOperand::CreateExpr(
453 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
462 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
463 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
464 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
466 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
467 unsigned RegNum = RegMap[Reg];
469 // Encode the register class in the upper 4 bits
470 // Must be kept in sync with NVPTXInstPrinter::printRegName
472 if (RC == &NVPTX::Int1RegsRegClass) {
474 } else if (RC == &NVPTX::Int16RegsRegClass) {
476 } else if (RC == &NVPTX::Int32RegsRegClass) {
478 } else if (RC == &NVPTX::Int64RegsRegClass) {
480 } else if (RC == &NVPTX::Float32RegsRegClass) {
482 } else if (RC == &NVPTX::Float64RegsRegClass) {
485 report_fatal_error("Bad register class");
488 // Insert the vreg number
489 Ret |= (RegNum & 0x0FFFFFFF);
492 // Some special-use registers are actually physical registers.
493 // Encode this as the register class ID of 0 and the real register ID.
494 return Reg & 0x0FFFFFFF;
498 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
500 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
502 return MCOperand::CreateExpr(Expr);
505 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
506 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
507 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
509 Type *Ty = F->getReturnType();
511 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
513 if (Ty->getTypeID() == Type::VoidTyID)
519 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
521 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
522 size = ITy->getBitWidth();
526 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
527 size = Ty->getPrimitiveSizeInBits();
530 O << ".param .b" << size << " func_retval0";
531 } else if (isa<PointerType>(Ty)) {
532 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
535 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
536 unsigned totalsz = TD->getTypeAllocSize(Ty);
537 unsigned retAlignment = 0;
538 if (!llvm::getAlign(*F, 0, retAlignment))
539 retAlignment = TD->getABITypeAlignment(Ty);
540 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
543 assert(false && "Unknown return type");
546 SmallVector<EVT, 16> vtparts;
547 ComputeValueVTs(*TLI, Ty, vtparts);
549 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
551 EVT elemtype = vtparts[i];
552 if (vtparts[i].isVector()) {
553 elems = vtparts[i].getVectorNumElements();
554 elemtype = vtparts[i].getVectorElementType();
557 for (unsigned j = 0, je = elems; j != je; ++j) {
558 unsigned sz = elemtype.getSizeInBits();
559 if (elemtype.isInteger() && (sz < 32))
561 O << ".reg .b" << sz << " func_retval" << idx;
574 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
576 const Function *F = MF.getFunction();
577 printReturnValStr(F, O);
580 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
581 SmallString<128> Str;
582 raw_svector_ostream O(Str);
584 if (!GlobalsEmitted) {
585 emitGlobals(*MF->getFunction()->getParent());
586 GlobalsEmitted = true;
590 MRI = &MF->getRegInfo();
591 F = MF->getFunction();
592 emitLinkageDirective(F, O);
593 if (llvm::isKernelFunction(*F))
597 printReturnValStr(*MF, O);
602 emitFunctionParamList(*MF, O);
604 if (llvm::isKernelFunction(*F))
605 emitKernelFunctionDirectives(*F, O);
607 OutStreamer.EmitRawText(O.str());
609 prevDebugLoc = DebugLoc();
612 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
614 OutStreamer.EmitRawText(StringRef("{\n"));
615 setAndEmitFunctionVirtualRegisters(*MF);
617 SmallString<128> Str;
618 raw_svector_ostream O(Str);
619 emitDemotedVars(MF->getFunction(), O);
620 OutStreamer.EmitRawText(O.str());
623 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
624 OutStreamer.EmitRawText(StringRef("}\n"));
628 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
629 unsigned RegNo = MI->getOperand(0).getReg();
630 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
631 if (TRI->isVirtualRegister(RegNo)) {
632 OutStreamer.AddComment(Twine("implicit-def: ") +
633 getVirtualRegisterName(RegNo));
635 OutStreamer.AddComment(
636 Twine("implicit-def: ") +
637 TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
639 OutStreamer.AddBlankLine();
642 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
643 raw_ostream &O) const {
644 // If the NVVM IR has some of reqntid* specified, then output
645 // the reqntid directive, and set the unspecified ones to 1.
646 // If none of reqntid* is specified, don't output reqntid directive.
647 unsigned reqntidx, reqntidy, reqntidz;
648 bool specified = false;
649 if (llvm::getReqNTIDx(F, reqntidx) == false)
653 if (llvm::getReqNTIDy(F, reqntidy) == false)
657 if (llvm::getReqNTIDz(F, reqntidz) == false)
663 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
666 // If the NVVM IR has some of maxntid* specified, then output
667 // the maxntid directive, and set the unspecified ones to 1.
668 // If none of maxntid* is specified, don't output maxntid directive.
669 unsigned maxntidx, maxntidy, maxntidz;
671 if (llvm::getMaxNTIDx(F, maxntidx) == false)
675 if (llvm::getMaxNTIDy(F, maxntidy) == false)
679 if (llvm::getMaxNTIDz(F, maxntidz) == false)
685 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
689 if (llvm::getMinCTASm(F, mincta))
690 O << ".minnctapersm " << mincta << "\n";
694 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
695 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
698 raw_string_ostream NameStr(Name);
700 VRegRCMap::const_iterator I = VRegMapping.find(RC);
701 assert(I != VRegMapping.end() && "Bad register class");
702 const DenseMap<unsigned, unsigned> &RegMap = I->second;
704 VRegMap::const_iterator VI = RegMap.find(Reg);
705 assert(VI != RegMap.end() && "Bad virtual register");
706 unsigned MappedVR = VI->second;
708 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
714 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
716 O << getVirtualRegisterName(vr);
719 void NVPTXAsmPrinter::printVecModifiedImmediate(
720 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
721 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
722 int Imm = (int) MO.getImm();
723 if (0 == strcmp(Modifier, "vecelem"))
724 O << "_" << vecelem[Imm];
725 else if (0 == strcmp(Modifier, "vecv4comm1")) {
726 if ((Imm < 0) || (Imm > 3))
728 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
729 if ((Imm < 4) || (Imm > 7))
731 } else if (0 == strcmp(Modifier, "vecv4pos")) {
734 O << "_" << vecelem[Imm % 4];
735 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
736 if ((Imm < 0) || (Imm > 1))
738 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
739 if ((Imm < 2) || (Imm > 3))
741 } else if (0 == strcmp(Modifier, "vecv2pos")) {
744 O << "_" << vecelem[Imm % 2];
746 llvm_unreachable("Unknown Modifier on immediate operand");
751 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
753 emitLinkageDirective(F, O);
754 if (llvm::isKernelFunction(*F))
758 printReturnValStr(F, O);
759 O << *getSymbol(F) << "\n";
760 emitFunctionParamList(F, O);
764 static bool usedInGlobalVarDef(const Constant *C) {
768 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
769 if (GV->getName().str() == "llvm.used")
774 for (const User *U : C->users())
775 if (const Constant *C = dyn_cast<Constant>(U))
776 if (usedInGlobalVarDef(C))
782 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
783 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
784 if (othergv->getName().str() == "llvm.used")
788 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
789 if (instr->getParent() && instr->getParent()->getParent()) {
790 const Function *curFunc = instr->getParent()->getParent();
791 if (oneFunc && (curFunc != oneFunc))
799 if (const MDNode *md = dyn_cast<MDNode>(U))
800 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
801 (md->getName().str() == "llvm.dbg.sp")))
804 for (const User *UU : U->users())
805 if (usedInOneFunc(UU, oneFunc) == false)
811 /* Find out if a global variable can be demoted to local scope.
812 * Currently, this is valid for CUDA shared variables, which have local
813 * scope and global lifetime. So the conditions to check are :
814 * 1. Is the global variable in shared address space?
815 * 2. Does it have internal linkage?
816 * 3. Is the global variable referenced only in one function?
818 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
819 if (gv->hasInternalLinkage() == false)
821 const PointerType *Pty = gv->getType();
822 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
825 const Function *oneFunc = nullptr;
827 bool flag = usedInOneFunc(gv, oneFunc);
836 static bool useFuncSeen(const Constant *C,
837 llvm::DenseMap<const Function *, bool> &seenMap) {
838 for (const User *U : C->users()) {
839 if (const Constant *cu = dyn_cast<Constant>(U)) {
840 if (useFuncSeen(cu, seenMap))
842 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
843 const BasicBlock *bb = I->getParent();
846 const Function *caller = bb->getParent();
849 if (seenMap.find(caller) != seenMap.end())
856 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
857 llvm::DenseMap<const Function *, bool> seenMap;
858 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
859 const Function *F = FI;
861 if (F->isDeclaration()) {
864 if (F->getIntrinsicID())
866 emitDeclaration(F, O);
869 for (const User *U : F->users()) {
870 if (const Constant *C = dyn_cast<Constant>(U)) {
871 if (usedInGlobalVarDef(C)) {
872 // The use is in the initialization of a global variable
873 // that is a function pointer, so print a declaration
874 // for the original function
875 emitDeclaration(F, O);
878 // Emit a declaration of this function if the function that
879 // uses this constant expr has already been seen.
880 if (useFuncSeen(C, seenMap)) {
881 emitDeclaration(F, O);
886 if (!isa<Instruction>(U))
888 const Instruction *instr = cast<Instruction>(U);
889 const BasicBlock *bb = instr->getParent();
892 const Function *caller = bb->getParent();
896 // If a caller has already been seen, then the caller is
897 // appearing in the module before the callee. so print out
898 // a declaration for the callee.
899 if (seenMap.find(caller) != seenMap.end()) {
900 emitDeclaration(F, O);
908 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
909 DebugInfoFinder DbgFinder;
910 DbgFinder.processModule(M);
913 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
914 StringRef Filename(DIUnit.getFilename());
915 StringRef Dirname(DIUnit.getDirectory());
916 SmallString<128> FullPathName = Dirname;
917 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
918 sys::path::append(FullPathName, Filename);
919 Filename = FullPathName.str();
921 if (filenameMap.find(Filename.str()) != filenameMap.end())
923 filenameMap[Filename.str()] = i;
924 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
928 for (DISubprogram SP : DbgFinder.subprograms()) {
929 StringRef Filename(SP.getFilename());
930 StringRef Dirname(SP.getDirectory());
931 SmallString<128> FullPathName = Dirname;
932 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
933 sys::path::append(FullPathName, Filename);
934 Filename = FullPathName.str();
936 if (filenameMap.find(Filename.str()) != filenameMap.end())
938 filenameMap[Filename.str()] = i;
943 bool NVPTXAsmPrinter::doInitialization(Module &M) {
945 SmallString<128> Str1;
946 raw_svector_ostream OS1(Str1);
948 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
949 MMI->AnalyzeModule(M);
951 // We need to call the parent's one explicitly.
952 //bool Result = AsmPrinter::doInitialization(M);
954 // Initialize TargetLoweringObjectFile.
955 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
956 .Initialize(OutContext, TM);
958 Mang = new Mangler(TM.getSubtargetImpl()->getDataLayout());
960 // Emit header before any dwarf directives are emitted below.
962 OutStreamer.EmitRawText(OS1.str());
964 // Already commented out
965 //bool Result = AsmPrinter::doInitialization(M);
967 // Emit module-level inline asm if it exists.
968 if (!M.getModuleInlineAsm().empty()) {
969 OutStreamer.AddComment("Start of file scope inline assembly");
970 OutStreamer.AddBlankLine();
971 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
972 OutStreamer.AddBlankLine();
973 OutStreamer.AddComment("End of file scope inline assembly");
974 OutStreamer.AddBlankLine();
977 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
978 recordAndEmitFilenames(M);
980 GlobalsEmitted = false;
982 return false; // success
985 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
986 SmallString<128> Str2;
987 raw_svector_ostream OS2(Str2);
989 emitDeclarations(M, OS2);
991 // As ptxas does not support forward references of globals, we need to first
992 // sort the list of module-level globals in def-use order. We visit each
993 // global variable in order, and ensure that we emit it *after* its dependent
994 // globals. We use a little extra memory maintaining both a set and a list to
995 // have fast searches while maintaining a strict ordering.
996 SmallVector<const GlobalVariable *, 8> Globals;
997 DenseSet<const GlobalVariable *> GVVisited;
998 DenseSet<const GlobalVariable *> GVVisiting;
1000 // Visit each global variable, in order
1001 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1003 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
1005 assert(GVVisited.size() == M.getGlobalList().size() &&
1006 "Missed a global variable");
1007 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1009 // Print out module-level global variables in proper order
1010 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1011 printModuleLevelGV(Globals[i], OS2);
1015 OutStreamer.EmitRawText(OS2.str());
1018 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1020 O << "// Generated by LLVM NVPTX Back-End\n";
1024 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1025 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1028 O << nvptxSubtarget.getTargetName();
1030 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1031 O << ", texmode_independent";
1032 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1033 if (!nvptxSubtarget.hasDouble())
1034 O << ", map_f64_to_f32";
1037 if (MAI->doesSupportDebugInformation())
1042 O << ".address_size ";
1043 if (nvptxSubtarget.is64Bit())
1052 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1054 // If we did not emit any functions, then the global declarations have not
1055 // yet been emitted.
1056 if (!GlobalsEmitted) {
1058 GlobalsEmitted = true;
1061 // XXX Temproarily remove global variables so that doFinalization() will not
1062 // emit them again (global variables are emitted at beginning).
1064 Module::GlobalListType &global_list = M.getGlobalList();
1065 int i, n = global_list.size();
1066 GlobalVariable **gv_array = new GlobalVariable *[n];
1068 // first, back-up GlobalVariable in gv_array
1070 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1072 gv_array[i++] = &*I;
1074 // second, empty global_list
1075 while (!global_list.empty())
1076 global_list.remove(global_list.begin());
1078 // call doFinalization
1079 bool ret = AsmPrinter::doFinalization(M);
1081 // now we restore global variables
1082 for (i = 0; i < n; i++)
1083 global_list.insert(global_list.end(), gv_array[i]);
1085 clearAnnotationCache(&M);
1090 //bool Result = AsmPrinter::doFinalization(M);
1091 // Instead of calling the parents doFinalization, we may
1092 // clone parents doFinalization and customize here.
1093 // Currently, we if NVISA out the EmitGlobals() in
1094 // parent's doFinalization, which is too intrusive.
1096 // Same for the doInitialization.
1100 // This function emits appropriate linkage directives for
1101 // functions and global variables.
1103 // extern function declaration -> .extern
1104 // extern function definition -> .visible
1105 // external global variable with init -> .visible
1106 // external without init -> .extern
1107 // appending -> not allowed, assert.
1108 // for any linkage other than
1109 // internal, private, linker_private,
1110 // linker_private_weak, linker_private_weak_def_auto,
1111 // we emit -> .weak.
1113 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1115 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1116 if (V->hasExternalLinkage()) {
1117 if (isa<GlobalVariable>(V)) {
1118 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1120 if (GVar->hasInitializer())
1125 } else if (V->isDeclaration())
1129 } else if (V->hasAppendingLinkage()) {
1131 msg.append("Error: ");
1132 msg.append("Symbol ");
1134 msg.append(V->getName().str());
1135 msg.append("has unsupported appending linkage type");
1136 llvm_unreachable(msg.c_str());
1137 } else if (!V->hasInternalLinkage() &&
1138 !V->hasPrivateLinkage()) {
1144 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1146 bool processDemoted) {
1149 if (GVar->hasSection()) {
1150 if (GVar->getSection() == StringRef("llvm.metadata"))
1154 // Skip LLVM intrinsic global variables
1155 if (GVar->getName().startswith("llvm.") ||
1156 GVar->getName().startswith("nvvm."))
1159 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1161 // GlobalVariables are always constant pointers themselves.
1162 const PointerType *PTy = GVar->getType();
1163 Type *ETy = PTy->getElementType();
1165 if (GVar->hasExternalLinkage()) {
1166 if (GVar->hasInitializer())
1170 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1171 GVar->hasAvailableExternallyLinkage() ||
1172 GVar->hasCommonLinkage()) {
1176 if (llvm::isTexture(*GVar)) {
1177 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1181 if (llvm::isSurface(*GVar)) {
1182 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1186 if (GVar->isDeclaration()) {
1187 // (extern) declarations, no definition or initializer
1188 // Currently the only known declaration is for an automatic __local
1189 // (.shared) promoted to global.
1190 emitPTXGlobalVariable(GVar, O);
1195 if (llvm::isSampler(*GVar)) {
1196 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1198 const Constant *Initializer = nullptr;
1199 if (GVar->hasInitializer())
1200 Initializer = GVar->getInitializer();
1201 const ConstantInt *CI = nullptr;
1203 CI = dyn_cast<ConstantInt>(Initializer);
1205 unsigned sample = CI->getZExtValue();
1210 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1212 O << "addr_mode_" << i << " = ";
1218 O << "clamp_to_border";
1221 O << "clamp_to_edge";
1232 O << "filter_mode = ";
1233 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1241 llvm_unreachable("Anisotropic filtering is not supported");
1246 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1247 O << ", force_unnormalized_coords = 1";
1256 if (GVar->hasPrivateLinkage()) {
1258 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1261 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1262 if (!strncmp(GVar->getName().data(), "filename", 8))
1264 if (GVar->use_empty())
1268 const Function *demotedFunc = nullptr;
1269 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1270 O << "// " << GVar->getName().str() << " has been demoted\n";
1271 if (localDecls.find(demotedFunc) != localDecls.end())
1272 localDecls[demotedFunc].push_back(GVar);
1274 std::vector<const GlobalVariable *> temp;
1275 temp.push_back(GVar);
1276 localDecls[demotedFunc] = temp;
1282 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1284 if (isManaged(*GVar)) {
1285 O << " .attribute(.managed)";
1288 if (GVar->getAlignment() == 0)
1289 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1291 O << " .align " << GVar->getAlignment();
1293 if (ETy->isSingleValueType()) {
1295 // Special case: ABI requires that we use .u8 for predicates
1296 if (ETy->isIntegerTy(1))
1299 O << getPTXFundamentalTypeStr(ETy, false);
1301 O << *getSymbol(GVar);
1303 // Ptx allows variable initilization only for constant and global state
1305 if (GVar->hasInitializer()) {
1306 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1307 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1308 const Constant *Initializer = GVar->getInitializer();
1309 // 'undef' is treated as there is no value spefied.
1310 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1312 printScalarConstant(Initializer, O);
1315 // The frontend adds zero-initializer to variables that don't have an
1316 // initial value, so skip warning for this case.
1317 if (!GVar->getInitializer()->isNullValue()) {
1318 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1319 "' is not allowed in addrspace(" +
1320 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1321 report_fatal_error(warnMsg.c_str());
1326 unsigned int ElementSize = 0;
1328 // Although PTX has direct support for struct type and array type and
1329 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1330 // targets that support these high level field accesses. Structs, arrays
1331 // and vectors are lowered into arrays of bytes.
1332 switch (ETy->getTypeID()) {
1333 case Type::StructTyID:
1334 case Type::ArrayTyID:
1335 case Type::VectorTyID:
1336 ElementSize = TD->getTypeStoreSize(ETy);
1337 // Ptx allows variable initilization only for constant and
1338 // global state spaces.
1339 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1340 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1341 GVar->hasInitializer()) {
1342 const Constant *Initializer = GVar->getInitializer();
1343 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1344 AggBuffer aggBuffer(ElementSize, O, *this);
1345 bufferAggregateConstant(Initializer, &aggBuffer);
1346 if (aggBuffer.numSymbols) {
1347 if (nvptxSubtarget.is64Bit()) {
1348 O << " .u64 " << *getSymbol(GVar) << "[";
1349 O << ElementSize / 8;
1351 O << " .u32 " << *getSymbol(GVar) << "[";
1352 O << ElementSize / 4;
1356 O << " .b8 " << *getSymbol(GVar) << "[";
1364 O << " .b8 " << *getSymbol(GVar);
1372 O << " .b8 " << *getSymbol(GVar);
1381 llvm_unreachable("type not supported yet");
1388 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1389 if (localDecls.find(f) == localDecls.end())
1392 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1394 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1395 O << "\t// demoted variable\n\t";
1396 printModuleLevelGV(gvars[i], O, true);
1400 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1401 raw_ostream &O) const {
1402 switch (AddressSpace) {
1403 case llvm::ADDRESS_SPACE_LOCAL:
1406 case llvm::ADDRESS_SPACE_GLOBAL:
1409 case llvm::ADDRESS_SPACE_CONST:
1412 case llvm::ADDRESS_SPACE_SHARED:
1416 report_fatal_error("Bad address space found while emitting PTX");
1422 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1423 switch (Ty->getTypeID()) {
1425 llvm_unreachable("unexpected type");
1427 case Type::IntegerTyID: {
1428 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1431 else if (NumBits <= 64) {
1432 std::string name = "u";
1433 return name + utostr(NumBits);
1435 llvm_unreachable("Integer too large");
1440 case Type::FloatTyID:
1442 case Type::DoubleTyID:
1444 case Type::PointerTyID:
1445 if (nvptxSubtarget.is64Bit())
1455 llvm_unreachable("unexpected type");
1459 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1462 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1464 // GlobalVariables are always constant pointers themselves.
1465 const PointerType *PTy = GVar->getType();
1466 Type *ETy = PTy->getElementType();
1469 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1470 if (GVar->getAlignment() == 0)
1471 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1473 O << " .align " << GVar->getAlignment();
1475 if (ETy->isSingleValueType()) {
1477 O << getPTXFundamentalTypeStr(ETy);
1479 O << *getSymbol(GVar);
1483 int64_t ElementSize = 0;
1485 // Although PTX has direct support for struct type and array type and LLVM IR
1486 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1487 // support these high level field accesses. Structs and arrays are lowered
1488 // into arrays of bytes.
1489 switch (ETy->getTypeID()) {
1490 case Type::StructTyID:
1491 case Type::ArrayTyID:
1492 case Type::VectorTyID:
1493 ElementSize = TD->getTypeStoreSize(ETy);
1494 O << " .b8 " << *getSymbol(GVar) << "[";
1496 O << itostr(ElementSize);
1501 llvm_unreachable("type not supported yet");
1506 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1507 if (Ty->isSingleValueType())
1508 return TD->getPrefTypeAlignment(Ty);
1510 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1512 return getOpenCLAlignment(TD, ATy->getElementType());
1514 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1516 Type *ETy = VTy->getElementType();
1517 unsigned int numE = VTy->getNumElements();
1518 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1522 return numE * alignE;
1525 const StructType *STy = dyn_cast<StructType>(Ty);
1527 unsigned int alignStruct = 1;
1528 // Go through each element of the struct and find the
1529 // largest alignment.
1530 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1531 Type *ETy = STy->getElementType(i);
1532 unsigned int align = getOpenCLAlignment(TD, ETy);
1533 if (align > alignStruct)
1534 alignStruct = align;
1539 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1541 return TD->getPointerPrefAlignment();
1542 return TD->getPrefTypeAlignment(Ty);
1545 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1546 int paramIndex, raw_ostream &O) {
1547 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1548 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1549 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1551 std::string argName = I->getName();
1552 const char *p = argName.c_str();
1563 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1564 Function::const_arg_iterator I, E;
1567 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1568 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1569 O << *CurrentFnSym << "_param_" << paramIndex;
1573 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1574 if (i == paramIndex) {
1575 printParamName(I, paramIndex, O);
1579 llvm_unreachable("paramIndex out of bound");
1582 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1583 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1584 const AttributeSet &PAL = F->getAttributes();
1585 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1586 Function::const_arg_iterator I, E;
1587 unsigned paramIndex = 0;
1589 bool isKernelFunc = llvm::isKernelFunction(*F);
1590 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1591 MVT thePointerTy = TLI->getPointerTy();
1595 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1596 Type *Ty = I->getType();
1603 // Handle image/sampler parameters
1604 if (isKernelFunction(*F)) {
1605 if (isSampler(*I) || isImage(*I)) {
1607 std::string sname = I->getName();
1608 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1609 if (nvptxSubtarget.hasImageHandles())
1610 O << "\t.param .u64 .ptr .surfref ";
1612 O << "\t.param .surfref ";
1613 O << *CurrentFnSym << "_param_" << paramIndex;
1615 else { // Default image is read_only
1616 if (nvptxSubtarget.hasImageHandles())
1617 O << "\t.param .u64 .ptr .texref ";
1619 O << "\t.param .texref ";
1620 O << *CurrentFnSym << "_param_" << paramIndex;
1623 if (nvptxSubtarget.hasImageHandles())
1624 O << "\t.param .u64 .ptr .samplerref ";
1626 O << "\t.param .samplerref ";
1627 O << *CurrentFnSym << "_param_" << paramIndex;
1633 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1634 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1635 // Just print .param .align <a> .b8 .param[size];
1636 // <a> = PAL.getparamalignment
1637 // size = typeallocsize of element type
1638 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1640 align = TD->getABITypeAlignment(Ty);
1642 unsigned sz = TD->getTypeAllocSize(Ty);
1643 O << "\t.param .align " << align << " .b8 ";
1644 printParamName(I, paramIndex, O);
1645 O << "[" << sz << "]";
1650 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1653 // Special handling for pointer arguments to kernel
1654 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1656 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1657 Type *ETy = PTy->getElementType();
1658 int addrSpace = PTy->getAddressSpace();
1659 switch (addrSpace) {
1663 case llvm::ADDRESS_SPACE_CONST:
1664 O << ".ptr .const ";
1666 case llvm::ADDRESS_SPACE_SHARED:
1667 O << ".ptr .shared ";
1669 case llvm::ADDRESS_SPACE_GLOBAL:
1670 O << ".ptr .global ";
1673 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1675 printParamName(I, paramIndex, O);
1679 // non-pointer scalar to kernel func
1681 // Special case: predicate operands become .u8 types
1682 if (Ty->isIntegerTy(1))
1685 O << getPTXFundamentalTypeStr(Ty);
1687 printParamName(I, paramIndex, O);
1690 // Non-kernel function, just print .param .b<size> for ABI
1691 // and .reg .b<size> for non-ABI
1693 if (isa<IntegerType>(Ty)) {
1694 sz = cast<IntegerType>(Ty)->getBitWidth();
1697 } else if (isa<PointerType>(Ty))
1698 sz = thePointerTy.getSizeInBits();
1700 sz = Ty->getPrimitiveSizeInBits();
1702 O << "\t.param .b" << sz << " ";
1704 O << "\t.reg .b" << sz << " ";
1705 printParamName(I, paramIndex, O);
1709 // param has byVal attribute. So should be a pointer
1710 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1711 assert(PTy && "Param with byval attribute should be a pointer type");
1712 Type *ETy = PTy->getElementType();
1714 if (isABI || isKernelFunc) {
1715 // Just print .param .align <a> .b8 .param[size];
1716 // <a> = PAL.getparamalignment
1717 // size = typeallocsize of element type
1718 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1720 align = TD->getABITypeAlignment(ETy);
1722 unsigned sz = TD->getTypeAllocSize(ETy);
1723 O << "\t.param .align " << align << " .b8 ";
1724 printParamName(I, paramIndex, O);
1725 O << "[" << sz << "]";
1728 // Split the ETy into constituent parts and
1729 // print .param .b<size> <name> for each part.
1730 // Further, if a part is vector, print the above for
1731 // each vector element.
1732 SmallVector<EVT, 16> vtparts;
1733 ComputeValueVTs(*TLI, ETy, vtparts);
1734 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1736 EVT elemtype = vtparts[i];
1737 if (vtparts[i].isVector()) {
1738 elems = vtparts[i].getVectorNumElements();
1739 elemtype = vtparts[i].getVectorElementType();
1742 for (unsigned j = 0, je = elems; j != je; ++j) {
1743 unsigned sz = elemtype.getSizeInBits();
1744 if (elemtype.isInteger() && (sz < 32))
1746 O << "\t.reg .b" << sz << " ";
1747 printParamName(I, paramIndex, O);
1763 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1765 const Function *F = MF.getFunction();
1766 emitFunctionParamList(F, O);
1769 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1770 const MachineFunction &MF) {
1771 SmallString<128> Str;
1772 raw_svector_ostream O(Str);
1774 // Map the global virtual register number to a register class specific
1775 // virtual register number starting from 1 with that class.
1776 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1777 //unsigned numRegClasses = TRI->getNumRegClasses();
1779 // Emit the Fake Stack Object
1780 const MachineFrameInfo *MFI = MF.getFrameInfo();
1781 int NumBytes = (int) MFI->getStackSize();
1783 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1784 << getFunctionNumber() << "[" << NumBytes << "];\n";
1785 if (nvptxSubtarget.is64Bit()) {
1786 O << "\t.reg .b64 \t%SP;\n";
1787 O << "\t.reg .b64 \t%SPL;\n";
1789 O << "\t.reg .b32 \t%SP;\n";
1790 O << "\t.reg .b32 \t%SPL;\n";
1794 // Go through all virtual registers to establish the mapping between the
1796 // register number and the per class virtual register number.
1797 // We use the per class virtual register number in the ptx output.
1798 unsigned int numVRs = MRI->getNumVirtRegs();
1799 for (unsigned i = 0; i < numVRs; i++) {
1800 unsigned int vr = TRI->index2VirtReg(i);
1801 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1802 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1803 int n = regmap.size();
1804 regmap.insert(std::make_pair(vr, n + 1));
1807 // Emit register declarations
1808 // @TODO: Extract out the real register usage
1809 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1810 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1811 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1812 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1813 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1814 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1815 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1817 // Emit declaration of the virtual registers or 'physical' registers for
1818 // each register class
1819 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1820 const TargetRegisterClass *RC = TRI->getRegClass(i);
1821 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1822 std::string rcname = getNVPTXRegClassName(RC);
1823 std::string rcStr = getNVPTXRegClassStr(RC);
1824 int n = regmap.size();
1826 // Only declare those registers that may be used.
1828 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1833 OutStreamer.EmitRawText(O.str());
1836 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1837 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1839 unsigned int numHex;
1842 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1845 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1846 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1849 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1851 llvm_unreachable("unsupported fp type");
1853 APInt API = APF.bitcastToAPInt();
1854 std::string hexstr(utohexstr(API.getZExtValue()));
1856 if (hexstr.length() < numHex)
1857 O << std::string(numHex - hexstr.length(), '0');
1858 O << utohexstr(API.getZExtValue());
1861 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1862 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1863 O << CI->getValue();
1866 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1867 printFPConstant(CFP, O);
1870 if (isa<ConstantPointerNull>(CPV)) {
1874 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1875 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1876 bool IsNonGenericPointer = false;
1877 if (PTy && PTy->getAddressSpace() != 0) {
1878 IsNonGenericPointer = true;
1880 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1882 O << *getSymbol(GVar);
1885 O << *getSymbol(GVar);
1889 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1890 const Value *v = Cexpr->stripPointerCasts();
1891 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1892 bool IsNonGenericPointer = false;
1893 if (PTy && PTy->getAddressSpace() != 0) {
1894 IsNonGenericPointer = true;
1896 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1897 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1899 O << *getSymbol(GVar);
1902 O << *getSymbol(GVar);
1906 O << *LowerConstant(CPV, *this);
1910 llvm_unreachable("Not scalar type found in printScalarConstant()");
1913 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1914 AggBuffer *aggBuffer) {
1916 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1918 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1919 int s = TD->getTypeAllocSize(CPV->getType());
1922 aggBuffer->addZeros(s);
1927 switch (CPV->getType()->getTypeID()) {
1929 case Type::IntegerTyID: {
1930 const Type *ETy = CPV->getType();
1931 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1933 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1935 aggBuffer->addBytes(ptr, 1, Bytes);
1936 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1937 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1938 ptr = (unsigned char *)&int16;
1939 aggBuffer->addBytes(ptr, 2, Bytes);
1940 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1941 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1942 int int32 = (int)(constInt->getZExtValue());
1943 ptr = (unsigned char *)&int32;
1944 aggBuffer->addBytes(ptr, 4, Bytes);
1946 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1947 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1948 ConstantFoldConstantExpression(Cexpr, TD))) {
1949 int int32 = (int)(constInt->getZExtValue());
1950 ptr = (unsigned char *)&int32;
1951 aggBuffer->addBytes(ptr, 4, Bytes);
1954 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1955 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1956 aggBuffer->addSymbol(v);
1957 aggBuffer->addZeros(4);
1961 llvm_unreachable("unsupported integer const type");
1962 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1963 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1964 long long int64 = (long long)(constInt->getZExtValue());
1965 ptr = (unsigned char *)&int64;
1966 aggBuffer->addBytes(ptr, 8, Bytes);
1968 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1969 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1970 ConstantFoldConstantExpression(Cexpr, TD))) {
1971 long long int64 = (long long)(constInt->getZExtValue());
1972 ptr = (unsigned char *)&int64;
1973 aggBuffer->addBytes(ptr, 8, Bytes);
1976 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1977 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1978 aggBuffer->addSymbol(v);
1979 aggBuffer->addZeros(8);
1983 llvm_unreachable("unsupported integer const type");
1985 llvm_unreachable("unsupported integer const type");
1988 case Type::FloatTyID:
1989 case Type::DoubleTyID: {
1990 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1991 const Type *Ty = CFP->getType();
1992 if (Ty == Type::getFloatTy(CPV->getContext())) {
1993 float float32 = (float) CFP->getValueAPF().convertToFloat();
1994 ptr = (unsigned char *)&float32;
1995 aggBuffer->addBytes(ptr, 4, Bytes);
1996 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1997 double float64 = CFP->getValueAPF().convertToDouble();
1998 ptr = (unsigned char *)&float64;
1999 aggBuffer->addBytes(ptr, 8, Bytes);
2001 llvm_unreachable("unsupported fp const type");
2005 case Type::PointerTyID: {
2006 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
2007 aggBuffer->addSymbol(GVar);
2008 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2009 const Value *v = Cexpr->stripPointerCasts();
2010 aggBuffer->addSymbol(v);
2012 unsigned int s = TD->getTypeAllocSize(CPV->getType());
2013 aggBuffer->addZeros(s);
2017 case Type::ArrayTyID:
2018 case Type::VectorTyID:
2019 case Type::StructTyID: {
2020 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2021 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
2022 int ElementSize = TD->getTypeAllocSize(CPV->getType());
2023 bufferAggregateConstant(CPV, aggBuffer);
2024 if (Bytes > ElementSize)
2025 aggBuffer->addZeros(Bytes - ElementSize);
2026 } else if (isa<ConstantAggregateZero>(CPV))
2027 aggBuffer->addZeros(Bytes);
2029 llvm_unreachable("Unexpected Constant type");
2034 llvm_unreachable("unsupported type");
2038 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2039 AggBuffer *aggBuffer) {
2040 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
2044 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2045 if (CPV->getNumOperands())
2046 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2047 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2051 if (const ConstantDataSequential *CDS =
2052 dyn_cast<ConstantDataSequential>(CPV)) {
2053 if (CDS->getNumElements())
2054 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2055 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2060 if (isa<ConstantStruct>(CPV)) {
2061 if (CPV->getNumOperands()) {
2062 StructType *ST = cast<StructType>(CPV->getType());
2063 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2065 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2066 TD->getTypeAllocSize(ST) -
2067 TD->getStructLayout(ST)->getElementOffset(i);
2069 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2070 TD->getStructLayout(ST)->getElementOffset(i);
2071 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2076 llvm_unreachable("unsupported constant type in printAggregateConstant()");
2079 // buildTypeNameMap - Run through symbol table looking for type names.
2082 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2084 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2086 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2087 !PI->second.compare("struct._image2d_t") ||
2088 !PI->second.compare("struct._image3d_t")))
2095 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2096 switch (MI.getOpcode()) {
2099 case NVPTX::CallArgBeginInst:
2100 case NVPTX::CallArgEndInst0:
2101 case NVPTX::CallArgEndInst1:
2102 case NVPTX::CallArgF32:
2103 case NVPTX::CallArgF64:
2104 case NVPTX::CallArgI16:
2105 case NVPTX::CallArgI32:
2106 case NVPTX::CallArgI32imm:
2107 case NVPTX::CallArgI64:
2108 case NVPTX::CallArgParam:
2109 case NVPTX::CallVoidInst:
2110 case NVPTX::CallVoidInstReg:
2111 case NVPTX::Callseq_End:
2112 case NVPTX::CallVoidInstReg64:
2113 case NVPTX::DeclareParamInst:
2114 case NVPTX::DeclareRetMemInst:
2115 case NVPTX::DeclareRetRegInst:
2116 case NVPTX::DeclareRetScalarInst:
2117 case NVPTX::DeclareScalarParamInst:
2118 case NVPTX::DeclareScalarRegInst:
2119 case NVPTX::StoreParamF32:
2120 case NVPTX::StoreParamF64:
2121 case NVPTX::StoreParamI16:
2122 case NVPTX::StoreParamI32:
2123 case NVPTX::StoreParamI64:
2124 case NVPTX::StoreParamI8:
2125 case NVPTX::StoreRetvalF32:
2126 case NVPTX::StoreRetvalF64:
2127 case NVPTX::StoreRetvalI16:
2128 case NVPTX::StoreRetvalI32:
2129 case NVPTX::StoreRetvalI64:
2130 case NVPTX::StoreRetvalI8:
2131 case NVPTX::LastCallArgF32:
2132 case NVPTX::LastCallArgF64:
2133 case NVPTX::LastCallArgI16:
2134 case NVPTX::LastCallArgI32:
2135 case NVPTX::LastCallArgI32imm:
2136 case NVPTX::LastCallArgI64:
2137 case NVPTX::LastCallArgParam:
2138 case NVPTX::LoadParamMemF32:
2139 case NVPTX::LoadParamMemF64:
2140 case NVPTX::LoadParamMemI16:
2141 case NVPTX::LoadParamMemI32:
2142 case NVPTX::LoadParamMemI64:
2143 case NVPTX::LoadParamMemI8:
2144 case NVPTX::PrototypeInst:
2145 case NVPTX::DBG_VALUE:
2151 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2153 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2154 unsigned AsmVariant,
2155 const char *ExtraCode, raw_ostream &O) {
2156 if (ExtraCode && ExtraCode[0]) {
2157 if (ExtraCode[1] != 0)
2158 return true; // Unknown modifier.
2160 switch (ExtraCode[0]) {
2162 // See if this is a generic print operand
2163 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2169 printOperand(MI, OpNo, O);
2174 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2175 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2176 const char *ExtraCode, raw_ostream &O) {
2177 if (ExtraCode && ExtraCode[0])
2178 return true; // Unknown modifier
2181 printMemOperand(MI, OpNo, O);
2187 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2188 raw_ostream &O, const char *Modifier) {
2189 const MachineOperand &MO = MI->getOperand(opNum);
2190 switch (MO.getType()) {
2191 case MachineOperand::MO_Register:
2192 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2193 if (MO.getReg() == NVPTX::VRDepot)
2194 O << DEPOTNAME << getFunctionNumber();
2196 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2198 emitVirtualRegister(MO.getReg(), O);
2202 case MachineOperand::MO_Immediate:
2205 else if (strstr(Modifier, "vec") == Modifier)
2206 printVecModifiedImmediate(MO, Modifier, O);
2209 "Don't know how to handle modifier on immediate operand");
2212 case MachineOperand::MO_FPImmediate:
2213 printFPConstant(MO.getFPImm(), O);
2216 case MachineOperand::MO_GlobalAddress:
2217 O << *getSymbol(MO.getGlobal());
2220 case MachineOperand::MO_MachineBasicBlock:
2221 O << *MO.getMBB()->getSymbol();
2225 llvm_unreachable("Operand type not supported.");
2229 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2230 raw_ostream &O, const char *Modifier) {
2231 printOperand(MI, opNum, O);
2233 if (Modifier && !strcmp(Modifier, "add")) {
2235 printOperand(MI, opNum + 1, O);
2237 if (MI->getOperand(opNum + 1).isImm() &&
2238 MI->getOperand(opNum + 1).getImm() == 0)
2239 return; // don't print ',0' or '+0'
2241 printOperand(MI, opNum + 1, O);
2246 // Force static initialization.
2247 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2248 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2249 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2252 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2253 std::stringstream temp;
2254 LineReader *reader = this->getReader(filename.str());
2256 temp << filename.str();
2260 temp << reader->readLine(line);
2262 this->OutStreamer.EmitRawText(Twine(temp.str()));
2265 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2267 reader = new LineReader(filename);
2270 if (reader->fileName() != filename) {
2272 reader = new LineReader(filename);
2278 std::string LineReader::readLine(unsigned lineNum) {
2279 if (lineNum < theCurLine) {
2281 fstr.seekg(0, std::ios::beg);
2283 while (theCurLine < lineNum) {
2284 fstr.getline(buff, 500);
2290 // Force static initialization.
2291 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2292 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2293 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);