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 "NVPTXMCExpr.h"
21 #include "NVPTXMachineFunctionInfo.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/MachineLoopInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/DebugInfo.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/Mangler.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Operator.h"
40 #include "llvm/MC/MCInst.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/MC/MCSymbol.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/Path.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TimeValue.h"
49 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "llvm/Transforms/Utils/UnrollLoop.h"
54 #define DEPOTNAME "__local_depot"
57 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
58 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
62 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
63 cl::desc("NVPTX Specific: Emit source line in ptx file"),
67 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
69 void DiscoverDependentGlobals(const Value *V,
70 DenseSet<const GlobalVariable *> &Globals) {
71 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
74 if (const User *U = dyn_cast<User>(V)) {
75 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
76 DiscoverDependentGlobals(U->getOperand(i), Globals);
82 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
83 /// instances to be emitted, but only after any dependents have been added
85 void VisitGlobalVariableForEmission(
86 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
87 DenseSet<const GlobalVariable *> &Visited,
88 DenseSet<const GlobalVariable *> &Visiting) {
89 // Have we already visited this one?
90 if (Visited.count(GV))
93 // Do we have a circular dependency?
94 if (!Visiting.insert(GV).second)
95 report_fatal_error("Circular dependency found in global variable set");
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 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
115 if (!EmitLineNumbers)
120 DebugLoc curLoc = MI.getDebugLoc();
122 if (!prevDebugLoc && !curLoc)
125 if (prevDebugLoc == curLoc)
128 prevDebugLoc = curLoc;
133 auto *Scope = cast_or_null<DIScope>(curLoc.getScope());
137 StringRef fileName(Scope->getFilename());
138 StringRef dirName(Scope->getDirectory());
139 SmallString<128> FullPathName = dirName;
140 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
141 sys::path::append(FullPathName, fileName);
142 fileName = FullPathName;
145 if (filenameMap.find(fileName) == filenameMap.end())
148 // Emit the line from the source file.
150 this->emitSrcInText(fileName, curLoc.getLine());
152 std::stringstream temp;
153 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
154 << " " << curLoc.getCol();
155 OutStreamer->EmitRawText(temp.str());
158 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
159 SmallString<128> Str;
160 raw_svector_ostream OS(Str);
161 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
162 emitLineNumberAsDotLoc(*MI);
165 lowerToMCInst(MI, Inst);
166 EmitToStreamer(*OutStreamer, Inst);
169 // Handle symbol backtracking for targets that do not support image handles
170 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
171 unsigned OpNo, MCOperand &MCOp) {
172 const MachineOperand &MO = MI->getOperand(OpNo);
173 const MCInstrDesc &MCID = MI->getDesc();
175 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
176 // This is a texture fetch, so operand 4 is a texref and operand 5 is
178 if (OpNo == 4 && MO.isImm()) {
179 lowerImageHandleSymbol(MO.getImm(), MCOp);
182 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
183 lowerImageHandleSymbol(MO.getImm(), MCOp);
188 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
190 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
192 // For a surface load of vector size N, the Nth operand will be the surfref
193 if (OpNo == VecSize && MO.isImm()) {
194 lowerImageHandleSymbol(MO.getImm(), MCOp);
199 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
200 // This is a surface store, so operand 0 is a surfref
201 if (OpNo == 0 && MO.isImm()) {
202 lowerImageHandleSymbol(MO.getImm(), MCOp);
207 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
208 // This is a query, so operand 1 is a surfref/texref
209 if (OpNo == 1 && MO.isImm()) {
210 lowerImageHandleSymbol(MO.getImm(), MCOp);
220 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
222 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
223 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
224 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
225 const char *Sym = MFI->getImageHandleSymbol(Index);
226 std::string *SymNamePtr =
227 nvTM.getManagedStrPool()->getManagedString(Sym);
228 MCOp = GetSymbolRef(OutContext.getOrCreateSymbol(
229 StringRef(SymNamePtr->c_str())));
232 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
233 OutMI.setOpcode(MI->getOpcode());
234 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
235 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
236 const MachineOperand &MO = MI->getOperand(0);
237 OutMI.addOperand(GetSymbolRef(
238 OutContext.getOrCreateSymbol(Twine(MO.getSymbolName()))));
242 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
243 const MachineOperand &MO = MI->getOperand(i);
246 if (!nvptxSubtarget->hasImageHandles()) {
247 if (lowerImageHandleOperand(MI, i, MCOp)) {
248 OutMI.addOperand(MCOp);
253 if (lowerOperand(MO, MCOp))
254 OutMI.addOperand(MCOp);
258 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
260 switch (MO.getType()) {
261 default: llvm_unreachable("unknown operand type");
262 case MachineOperand::MO_Register:
263 MCOp = MCOperand::createReg(encodeVirtualRegister(MO.getReg()));
265 case MachineOperand::MO_Immediate:
266 MCOp = MCOperand::createImm(MO.getImm());
268 case MachineOperand::MO_MachineBasicBlock:
269 MCOp = MCOperand::createExpr(MCSymbolRefExpr::create(
270 MO.getMBB()->getSymbol(), OutContext));
272 case MachineOperand::MO_ExternalSymbol:
273 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
275 case MachineOperand::MO_GlobalAddress:
276 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
278 case MachineOperand::MO_FPImmediate: {
279 const ConstantFP *Cnt = MO.getFPImm();
280 APFloat Val = Cnt->getValueAPF();
282 switch (Cnt->getType()->getTypeID()) {
283 default: report_fatal_error("Unsupported FP type"); break;
284 case Type::FloatTyID:
285 MCOp = MCOperand::createExpr(
286 NVPTXFloatMCExpr::createConstantFPSingle(Val, OutContext));
288 case Type::DoubleTyID:
289 MCOp = MCOperand::createExpr(
290 NVPTXFloatMCExpr::createConstantFPDouble(Val, OutContext));
299 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
300 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
301 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
303 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
304 unsigned RegNum = RegMap[Reg];
306 // Encode the register class in the upper 4 bits
307 // Must be kept in sync with NVPTXInstPrinter::printRegName
309 if (RC == &NVPTX::Int1RegsRegClass) {
311 } else if (RC == &NVPTX::Int16RegsRegClass) {
313 } else if (RC == &NVPTX::Int32RegsRegClass) {
315 } else if (RC == &NVPTX::Int64RegsRegClass) {
317 } else if (RC == &NVPTX::Float32RegsRegClass) {
319 } else if (RC == &NVPTX::Float64RegsRegClass) {
322 report_fatal_error("Bad register class");
325 // Insert the vreg number
326 Ret |= (RegNum & 0x0FFFFFFF);
329 // Some special-use registers are actually physical registers.
330 // Encode this as the register class ID of 0 and the real register ID.
331 return Reg & 0x0FFFFFFF;
335 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
337 Expr = MCSymbolRefExpr::create(Symbol, MCSymbolRefExpr::VK_None,
339 return MCOperand::createExpr(Expr);
342 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
343 const DataLayout *TD = TM.getDataLayout();
344 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
346 Type *Ty = F->getReturnType();
348 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
350 if (Ty->getTypeID() == Type::VoidTyID)
356 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
358 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
359 size = ITy->getBitWidth();
363 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
364 size = Ty->getPrimitiveSizeInBits();
367 O << ".param .b" << size << " func_retval0";
368 } else if (isa<PointerType>(Ty)) {
369 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
371 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
372 unsigned totalsz = TD->getTypeAllocSize(Ty);
373 unsigned retAlignment = 0;
374 if (!llvm::getAlign(*F, 0, retAlignment))
375 retAlignment = TD->getABITypeAlignment(Ty);
376 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
379 llvm_unreachable("Unknown return type");
381 SmallVector<EVT, 16> vtparts;
382 ComputeValueVTs(*TLI, Ty, vtparts);
384 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
386 EVT elemtype = vtparts[i];
387 if (vtparts[i].isVector()) {
388 elems = vtparts[i].getVectorNumElements();
389 elemtype = vtparts[i].getVectorElementType();
392 for (unsigned j = 0, je = elems; j != je; ++j) {
393 unsigned sz = elemtype.getSizeInBits();
394 if (elemtype.isInteger() && (sz < 32))
396 O << ".reg .b" << sz << " func_retval" << idx;
409 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
411 const Function *F = MF.getFunction();
412 printReturnValStr(F, O);
415 // Return true if MBB is the header of a loop marked with
416 // llvm.loop.unroll.disable.
417 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
418 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
419 const MachineBasicBlock &MBB) const {
420 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
421 // We insert .pragma "nounroll" only to the loop header.
422 if (!LI.isLoopHeader(&MBB))
425 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
426 // we iterate through each back edge of the loop with header MBB, and check
427 // whether its metadata contains llvm.loop.unroll.disable.
428 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
429 const MachineBasicBlock *PMBB = *I;
430 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
431 // Edges from other loops to MBB are not back edges.
434 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
435 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
436 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
444 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
445 AsmPrinter::EmitBasicBlockStart(MBB);
446 if (isLoopHeaderOfNoUnroll(MBB))
447 OutStreamer->EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
450 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
451 SmallString<128> Str;
452 raw_svector_ostream O(Str);
454 if (!GlobalsEmitted) {
455 emitGlobals(*MF->getFunction()->getParent());
456 GlobalsEmitted = true;
460 MRI = &MF->getRegInfo();
461 F = MF->getFunction();
462 emitLinkageDirective(F, O);
463 if (llvm::isKernelFunction(*F))
467 printReturnValStr(*MF, O);
472 emitFunctionParamList(*MF, O);
474 if (llvm::isKernelFunction(*F))
475 emitKernelFunctionDirectives(*F, O);
477 OutStreamer->EmitRawText(O.str());
479 prevDebugLoc = DebugLoc();
482 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
484 OutStreamer->EmitRawText(StringRef("{\n"));
485 setAndEmitFunctionVirtualRegisters(*MF);
487 SmallString<128> Str;
488 raw_svector_ostream O(Str);
489 emitDemotedVars(MF->getFunction(), O);
490 OutStreamer->EmitRawText(O.str());
493 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
494 OutStreamer->EmitRawText(StringRef("}\n"));
498 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
499 unsigned RegNo = MI->getOperand(0).getReg();
500 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
501 OutStreamer->AddComment(Twine("implicit-def: ") +
502 getVirtualRegisterName(RegNo));
504 OutStreamer->AddComment(Twine("implicit-def: ") +
505 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
507 OutStreamer->AddBlankLine();
510 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
511 raw_ostream &O) const {
512 // If the NVVM IR has some of reqntid* specified, then output
513 // the reqntid directive, and set the unspecified ones to 1.
514 // If none of reqntid* is specified, don't output reqntid directive.
515 unsigned reqntidx, reqntidy, reqntidz;
516 bool specified = false;
517 if (!llvm::getReqNTIDx(F, reqntidx))
521 if (!llvm::getReqNTIDy(F, reqntidy))
525 if (!llvm::getReqNTIDz(F, reqntidz))
531 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
534 // If the NVVM IR has some of maxntid* specified, then output
535 // the maxntid directive, and set the unspecified ones to 1.
536 // If none of maxntid* is specified, don't output maxntid directive.
537 unsigned maxntidx, maxntidy, maxntidz;
539 if (!llvm::getMaxNTIDx(F, maxntidx))
543 if (!llvm::getMaxNTIDy(F, maxntidy))
547 if (!llvm::getMaxNTIDz(F, maxntidz))
553 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
557 if (llvm::getMinCTASm(F, mincta))
558 O << ".minnctapersm " << mincta << "\n";
562 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
563 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
566 raw_string_ostream NameStr(Name);
568 VRegRCMap::const_iterator I = VRegMapping.find(RC);
569 assert(I != VRegMapping.end() && "Bad register class");
570 const DenseMap<unsigned, unsigned> &RegMap = I->second;
572 VRegMap::const_iterator VI = RegMap.find(Reg);
573 assert(VI != RegMap.end() && "Bad virtual register");
574 unsigned MappedVR = VI->second;
576 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
582 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
584 O << getVirtualRegisterName(vr);
587 void NVPTXAsmPrinter::printVecModifiedImmediate(
588 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
589 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
590 int Imm = (int) MO.getImm();
591 if (0 == strcmp(Modifier, "vecelem"))
592 O << "_" << vecelem[Imm];
593 else if (0 == strcmp(Modifier, "vecv4comm1")) {
594 if ((Imm < 0) || (Imm > 3))
596 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
597 if ((Imm < 4) || (Imm > 7))
599 } else if (0 == strcmp(Modifier, "vecv4pos")) {
602 O << "_" << vecelem[Imm % 4];
603 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
604 if ((Imm < 0) || (Imm > 1))
606 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
607 if ((Imm < 2) || (Imm > 3))
609 } else if (0 == strcmp(Modifier, "vecv2pos")) {
612 O << "_" << vecelem[Imm % 2];
614 llvm_unreachable("Unknown Modifier on immediate operand");
619 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
621 emitLinkageDirective(F, O);
622 if (llvm::isKernelFunction(*F))
626 printReturnValStr(F, O);
627 O << *getSymbol(F) << "\n";
628 emitFunctionParamList(F, O);
632 static bool usedInGlobalVarDef(const Constant *C) {
636 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
637 if (GV->getName() == "llvm.used")
642 for (const User *U : C->users())
643 if (const Constant *C = dyn_cast<Constant>(U))
644 if (usedInGlobalVarDef(C))
650 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
651 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
652 if (othergv->getName() == "llvm.used")
656 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
657 if (instr->getParent() && instr->getParent()->getParent()) {
658 const Function *curFunc = instr->getParent()->getParent();
659 if (oneFunc && (curFunc != oneFunc))
667 for (const User *UU : U->users())
668 if (!usedInOneFunc(UU, oneFunc))
674 /* Find out if a global variable can be demoted to local scope.
675 * Currently, this is valid for CUDA shared variables, which have local
676 * scope and global lifetime. So the conditions to check are :
677 * 1. Is the global variable in shared address space?
678 * 2. Does it have internal linkage?
679 * 3. Is the global variable referenced only in one function?
681 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
682 if (!gv->hasInternalLinkage())
684 const PointerType *Pty = gv->getType();
685 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
688 const Function *oneFunc = nullptr;
690 bool flag = usedInOneFunc(gv, oneFunc);
699 static bool useFuncSeen(const Constant *C,
700 llvm::DenseMap<const Function *, bool> &seenMap) {
701 for (const User *U : C->users()) {
702 if (const Constant *cu = dyn_cast<Constant>(U)) {
703 if (useFuncSeen(cu, seenMap))
705 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
706 const BasicBlock *bb = I->getParent();
709 const Function *caller = bb->getParent();
712 if (seenMap.find(caller) != seenMap.end())
719 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
720 llvm::DenseMap<const Function *, bool> seenMap;
721 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
722 const Function *F = FI;
724 if (F->isDeclaration()) {
727 if (F->getIntrinsicID())
729 emitDeclaration(F, O);
732 for (const User *U : F->users()) {
733 if (const Constant *C = dyn_cast<Constant>(U)) {
734 if (usedInGlobalVarDef(C)) {
735 // The use is in the initialization of a global variable
736 // that is a function pointer, so print a declaration
737 // for the original function
738 emitDeclaration(F, O);
741 // Emit a declaration of this function if the function that
742 // uses this constant expr has already been seen.
743 if (useFuncSeen(C, seenMap)) {
744 emitDeclaration(F, O);
749 if (!isa<Instruction>(U))
751 const Instruction *instr = cast<Instruction>(U);
752 const BasicBlock *bb = instr->getParent();
755 const Function *caller = bb->getParent();
759 // If a caller has already been seen, then the caller is
760 // appearing in the module before the callee. so print out
761 // a declaration for the callee.
762 if (seenMap.find(caller) != seenMap.end()) {
763 emitDeclaration(F, O);
771 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
772 DebugInfoFinder DbgFinder;
773 DbgFinder.processModule(M);
776 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
777 StringRef Filename = DIUnit->getFilename();
778 StringRef Dirname = DIUnit->getDirectory();
779 SmallString<128> FullPathName = Dirname;
780 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
781 sys::path::append(FullPathName, Filename);
782 Filename = FullPathName;
784 if (filenameMap.find(Filename) != filenameMap.end())
786 filenameMap[Filename] = i;
787 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
791 for (DISubprogram *SP : DbgFinder.subprograms()) {
792 StringRef Filename = SP->getFilename();
793 StringRef Dirname = SP->getDirectory();
794 SmallString<128> FullPathName = Dirname;
795 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
796 sys::path::append(FullPathName, Filename);
797 Filename = FullPathName;
799 if (filenameMap.find(Filename) != filenameMap.end())
801 filenameMap[Filename] = i;
806 bool NVPTXAsmPrinter::doInitialization(Module &M) {
807 // Construct a default subtarget off of the TargetMachine defaults. The
808 // rest of NVPTX isn't friendly to change subtargets per function and
809 // so the default TargetMachine will have all of the options.
810 StringRef TT = TM.getTargetTriple();
811 StringRef CPU = TM.getTargetCPU();
812 StringRef FS = TM.getTargetFeatureString();
813 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
814 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
816 SmallString<128> Str1;
817 raw_svector_ostream OS1(Str1);
819 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
820 MMI->AnalyzeModule(M);
822 // We need to call the parent's one explicitly.
823 //bool Result = AsmPrinter::doInitialization(M);
825 // Initialize TargetLoweringObjectFile.
826 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
827 .Initialize(OutContext, TM);
829 Mang = new Mangler(TM.getDataLayout());
831 // Emit header before any dwarf directives are emitted below.
832 emitHeader(M, OS1, STI);
833 OutStreamer->EmitRawText(OS1.str());
835 // Already commented out
836 //bool Result = AsmPrinter::doInitialization(M);
838 // Emit module-level inline asm if it exists.
839 if (!M.getModuleInlineAsm().empty()) {
840 OutStreamer->AddComment("Start of file scope inline assembly");
841 OutStreamer->AddBlankLine();
842 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
843 OutStreamer->AddBlankLine();
844 OutStreamer->AddComment("End of file scope inline assembly");
845 OutStreamer->AddBlankLine();
848 // If we're not NVCL we're CUDA, go ahead and emit filenames.
849 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
850 recordAndEmitFilenames(M);
852 GlobalsEmitted = false;
854 return false; // success
857 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
858 SmallString<128> Str2;
859 raw_svector_ostream OS2(Str2);
861 emitDeclarations(M, OS2);
863 // As ptxas does not support forward references of globals, we need to first
864 // sort the list of module-level globals in def-use order. We visit each
865 // global variable in order, and ensure that we emit it *after* its dependent
866 // globals. We use a little extra memory maintaining both a set and a list to
867 // have fast searches while maintaining a strict ordering.
868 SmallVector<const GlobalVariable *, 8> Globals;
869 DenseSet<const GlobalVariable *> GVVisited;
870 DenseSet<const GlobalVariable *> GVVisiting;
872 // Visit each global variable, in order
873 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
875 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
877 assert(GVVisited.size() == M.getGlobalList().size() &&
878 "Missed a global variable");
879 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
881 // Print out module-level global variables in proper order
882 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
883 printModuleLevelGV(Globals[i], OS2);
887 OutStreamer->EmitRawText(OS2.str());
890 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
891 const NVPTXSubtarget &STI) {
893 O << "// Generated by LLVM NVPTX Back-End\n";
897 unsigned PTXVersion = STI.getPTXVersion();
898 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
901 O << STI.getTargetName();
903 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
904 if (NTM.getDrvInterface() == NVPTX::NVCL)
905 O << ", texmode_independent";
907 if (!STI.hasDouble())
908 O << ", map_f64_to_f32";
911 if (MAI->doesSupportDebugInformation())
916 O << ".address_size ";
926 bool NVPTXAsmPrinter::doFinalization(Module &M) {
927 // If we did not emit any functions, then the global declarations have not
929 if (!GlobalsEmitted) {
931 GlobalsEmitted = true;
934 // XXX Temproarily remove global variables so that doFinalization() will not
935 // emit them again (global variables are emitted at beginning).
937 Module::GlobalListType &global_list = M.getGlobalList();
938 int i, n = global_list.size();
939 GlobalVariable **gv_array = new GlobalVariable *[n];
941 // first, back-up GlobalVariable in gv_array
943 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
947 // second, empty global_list
948 while (!global_list.empty())
949 global_list.remove(global_list.begin());
951 // call doFinalization
952 bool ret = AsmPrinter::doFinalization(M);
954 // now we restore global variables
955 for (i = 0; i < n; i++)
956 global_list.insert(global_list.end(), gv_array[i]);
958 clearAnnotationCache(&M);
963 //bool Result = AsmPrinter::doFinalization(M);
964 // Instead of calling the parents doFinalization, we may
965 // clone parents doFinalization and customize here.
966 // Currently, we if NVISA out the EmitGlobals() in
967 // parent's doFinalization, which is too intrusive.
969 // Same for the doInitialization.
973 // This function emits appropriate linkage directives for
974 // functions and global variables.
976 // extern function declaration -> .extern
977 // extern function definition -> .visible
978 // external global variable with init -> .visible
979 // external without init -> .extern
980 // appending -> not allowed, assert.
981 // for any linkage other than
982 // internal, private, linker_private,
983 // linker_private_weak, linker_private_weak_def_auto,
986 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
988 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
989 if (V->hasExternalLinkage()) {
990 if (isa<GlobalVariable>(V)) {
991 const GlobalVariable *GVar = cast<GlobalVariable>(V);
993 if (GVar->hasInitializer())
998 } else if (V->isDeclaration())
1002 } else if (V->hasAppendingLinkage()) {
1004 msg.append("Error: ");
1005 msg.append("Symbol ");
1007 msg.append(V->getName());
1008 msg.append("has unsupported appending linkage type");
1009 llvm_unreachable(msg.c_str());
1010 } else if (!V->hasInternalLinkage() &&
1011 !V->hasPrivateLinkage()) {
1017 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1019 bool processDemoted) {
1022 if (GVar->hasSection()) {
1023 if (GVar->getSection() == StringRef("llvm.metadata"))
1027 // Skip LLVM intrinsic global variables
1028 if (GVar->getName().startswith("llvm.") ||
1029 GVar->getName().startswith("nvvm."))
1032 const DataLayout *TD = TM.getDataLayout();
1034 // GlobalVariables are always constant pointers themselves.
1035 const PointerType *PTy = GVar->getType();
1036 Type *ETy = PTy->getElementType();
1038 if (GVar->hasExternalLinkage()) {
1039 if (GVar->hasInitializer())
1043 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1044 GVar->hasAvailableExternallyLinkage() ||
1045 GVar->hasCommonLinkage()) {
1049 if (llvm::isTexture(*GVar)) {
1050 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1054 if (llvm::isSurface(*GVar)) {
1055 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1059 if (GVar->isDeclaration()) {
1060 // (extern) declarations, no definition or initializer
1061 // Currently the only known declaration is for an automatic __local
1062 // (.shared) promoted to global.
1063 emitPTXGlobalVariable(GVar, O);
1068 if (llvm::isSampler(*GVar)) {
1069 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1071 const Constant *Initializer = nullptr;
1072 if (GVar->hasInitializer())
1073 Initializer = GVar->getInitializer();
1074 const ConstantInt *CI = nullptr;
1076 CI = dyn_cast<ConstantInt>(Initializer);
1078 unsigned sample = CI->getZExtValue();
1083 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1085 O << "addr_mode_" << i << " = ";
1091 O << "clamp_to_border";
1094 O << "clamp_to_edge";
1105 O << "filter_mode = ";
1106 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1114 llvm_unreachable("Anisotropic filtering is not supported");
1119 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1120 O << ", force_unnormalized_coords = 1";
1129 if (GVar->hasPrivateLinkage()) {
1131 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1134 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1135 if (!strncmp(GVar->getName().data(), "filename", 8))
1137 if (GVar->use_empty())
1141 const Function *demotedFunc = nullptr;
1142 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1143 O << "// " << GVar->getName() << " has been demoted\n";
1144 if (localDecls.find(demotedFunc) != localDecls.end())
1145 localDecls[demotedFunc].push_back(GVar);
1147 std::vector<const GlobalVariable *> temp;
1148 temp.push_back(GVar);
1149 localDecls[demotedFunc] = temp;
1155 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1157 if (isManaged(*GVar)) {
1158 O << " .attribute(.managed)";
1161 if (GVar->getAlignment() == 0)
1162 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1164 O << " .align " << GVar->getAlignment();
1166 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1168 // Special case: ABI requires that we use .u8 for predicates
1169 if (ETy->isIntegerTy(1))
1172 O << getPTXFundamentalTypeStr(ETy, false);
1174 O << *getSymbol(GVar);
1176 // Ptx allows variable initilization only for constant and global state
1178 if (GVar->hasInitializer()) {
1179 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1180 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1181 const Constant *Initializer = GVar->getInitializer();
1182 // 'undef' is treated as there is no value specified.
1183 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1185 printScalarConstant(Initializer, O);
1188 // The frontend adds zero-initializer to variables that don't have an
1189 // initial value, so skip warning for this case.
1190 if (!GVar->getInitializer()->isNullValue()) {
1191 report_fatal_error("initial value of '" + GVar->getName() +
1192 "' is not allowed in addrspace(" +
1193 Twine(PTy->getAddressSpace()) + ")");
1198 unsigned int ElementSize = 0;
1200 // Although PTX has direct support for struct type and array type and
1201 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1202 // targets that support these high level field accesses. Structs, arrays
1203 // and vectors are lowered into arrays of bytes.
1204 switch (ETy->getTypeID()) {
1205 case Type::StructTyID:
1206 case Type::ArrayTyID:
1207 case Type::VectorTyID:
1208 ElementSize = TD->getTypeStoreSize(ETy);
1209 // Ptx allows variable initilization only for constant and
1210 // global state spaces.
1211 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1212 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1213 GVar->hasInitializer()) {
1214 const Constant *Initializer = GVar->getInitializer();
1215 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1216 AggBuffer aggBuffer(ElementSize, O, *this);
1217 bufferAggregateConstant(Initializer, &aggBuffer);
1218 if (aggBuffer.numSymbols) {
1219 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1220 O << " .u64 " << *getSymbol(GVar) << "[";
1221 O << ElementSize / 8;
1223 O << " .u32 " << *getSymbol(GVar) << "[";
1224 O << ElementSize / 4;
1228 O << " .b8 " << *getSymbol(GVar) << "[";
1236 O << " .b8 " << *getSymbol(GVar);
1244 O << " .b8 " << *getSymbol(GVar);
1253 llvm_unreachable("type not supported yet");
1260 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1261 if (localDecls.find(f) == localDecls.end())
1264 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1266 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1267 O << "\t// demoted variable\n\t";
1268 printModuleLevelGV(gvars[i], O, true);
1272 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1273 raw_ostream &O) const {
1274 switch (AddressSpace) {
1275 case llvm::ADDRESS_SPACE_LOCAL:
1278 case llvm::ADDRESS_SPACE_GLOBAL:
1281 case llvm::ADDRESS_SPACE_CONST:
1284 case llvm::ADDRESS_SPACE_SHARED:
1288 report_fatal_error("Bad address space found while emitting PTX");
1294 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1295 switch (Ty->getTypeID()) {
1297 llvm_unreachable("unexpected type");
1299 case Type::IntegerTyID: {
1300 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1303 else if (NumBits <= 64) {
1304 std::string name = "u";
1305 return name + utostr(NumBits);
1307 llvm_unreachable("Integer too large");
1312 case Type::FloatTyID:
1314 case Type::DoubleTyID:
1316 case Type::PointerTyID:
1317 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1327 llvm_unreachable("unexpected type");
1331 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1334 const DataLayout *TD = TM.getDataLayout();
1336 // GlobalVariables are always constant pointers themselves.
1337 const PointerType *PTy = GVar->getType();
1338 Type *ETy = PTy->getElementType();
1341 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1342 if (GVar->getAlignment() == 0)
1343 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1345 O << " .align " << GVar->getAlignment();
1347 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1349 O << getPTXFundamentalTypeStr(ETy);
1351 O << *getSymbol(GVar);
1355 int64_t ElementSize = 0;
1357 // Although PTX has direct support for struct type and array type and LLVM IR
1358 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1359 // support these high level field accesses. Structs and arrays are lowered
1360 // into arrays of bytes.
1361 switch (ETy->getTypeID()) {
1362 case Type::StructTyID:
1363 case Type::ArrayTyID:
1364 case Type::VectorTyID:
1365 ElementSize = TD->getTypeStoreSize(ETy);
1366 O << " .b8 " << *getSymbol(GVar) << "[";
1373 llvm_unreachable("type not supported yet");
1378 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1379 if (Ty->isSingleValueType())
1380 return TD->getPrefTypeAlignment(Ty);
1382 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1384 return getOpenCLAlignment(TD, ATy->getElementType());
1386 const StructType *STy = dyn_cast<StructType>(Ty);
1388 unsigned int alignStruct = 1;
1389 // Go through each element of the struct and find the
1390 // largest alignment.
1391 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1392 Type *ETy = STy->getElementType(i);
1393 unsigned int align = getOpenCLAlignment(TD, ETy);
1394 if (align > alignStruct)
1395 alignStruct = align;
1400 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1402 return TD->getPointerPrefAlignment();
1403 return TD->getPrefTypeAlignment(Ty);
1406 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1407 int paramIndex, raw_ostream &O) {
1408 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1411 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1412 O << *CurrentFnSym << "_param_" << paramIndex;
1415 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1416 const DataLayout *TD = TM.getDataLayout();
1417 const AttributeSet &PAL = F->getAttributes();
1418 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
1419 Function::const_arg_iterator I, E;
1420 unsigned paramIndex = 0;
1422 bool isKernelFunc = llvm::isKernelFunction(*F);
1423 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
1424 MVT thePointerTy = TLI->getPointerTy();
1428 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1429 Type *Ty = I->getType();
1436 // Handle image/sampler parameters
1437 if (isKernelFunction(*F)) {
1438 if (isSampler(*I) || isImage(*I)) {
1440 std::string sname = I->getName();
1441 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1442 if (nvptxSubtarget->hasImageHandles())
1443 O << "\t.param .u64 .ptr .surfref ";
1445 O << "\t.param .surfref ";
1446 O << *CurrentFnSym << "_param_" << paramIndex;
1448 else { // Default image is read_only
1449 if (nvptxSubtarget->hasImageHandles())
1450 O << "\t.param .u64 .ptr .texref ";
1452 O << "\t.param .texref ";
1453 O << *CurrentFnSym << "_param_" << paramIndex;
1456 if (nvptxSubtarget->hasImageHandles())
1457 O << "\t.param .u64 .ptr .samplerref ";
1459 O << "\t.param .samplerref ";
1460 O << *CurrentFnSym << "_param_" << paramIndex;
1466 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
1467 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1468 // Just print .param .align <a> .b8 .param[size];
1469 // <a> = PAL.getparamalignment
1470 // size = typeallocsize of element type
1471 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1473 align = TD->getABITypeAlignment(Ty);
1475 unsigned sz = TD->getTypeAllocSize(Ty);
1476 O << "\t.param .align " << align << " .b8 ";
1477 printParamName(I, paramIndex, O);
1478 O << "[" << sz << "]";
1483 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1486 // Special handling for pointer arguments to kernel
1487 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1489 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1491 Type *ETy = PTy->getElementType();
1492 int addrSpace = PTy->getAddressSpace();
1493 switch (addrSpace) {
1497 case llvm::ADDRESS_SPACE_CONST:
1498 O << ".ptr .const ";
1500 case llvm::ADDRESS_SPACE_SHARED:
1501 O << ".ptr .shared ";
1503 case llvm::ADDRESS_SPACE_GLOBAL:
1504 O << ".ptr .global ";
1507 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1509 printParamName(I, paramIndex, O);
1513 // non-pointer scalar to kernel func
1515 // Special case: predicate operands become .u8 types
1516 if (Ty->isIntegerTy(1))
1519 O << getPTXFundamentalTypeStr(Ty);
1521 printParamName(I, paramIndex, O);
1524 // Non-kernel function, just print .param .b<size> for ABI
1525 // and .reg .b<size> for non-ABI
1527 if (isa<IntegerType>(Ty)) {
1528 sz = cast<IntegerType>(Ty)->getBitWidth();
1531 } else if (isa<PointerType>(Ty))
1532 sz = thePointerTy.getSizeInBits();
1534 sz = Ty->getPrimitiveSizeInBits();
1536 O << "\t.param .b" << sz << " ";
1538 O << "\t.reg .b" << sz << " ";
1539 printParamName(I, paramIndex, O);
1543 // param has byVal attribute. So should be a pointer
1544 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1545 assert(PTy && "Param with byval attribute should be a pointer type");
1546 Type *ETy = PTy->getElementType();
1548 if (isABI || isKernelFunc) {
1549 // Just print .param .align <a> .b8 .param[size];
1550 // <a> = PAL.getparamalignment
1551 // size = typeallocsize of element type
1552 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1554 align = TD->getABITypeAlignment(ETy);
1556 unsigned sz = TD->getTypeAllocSize(ETy);
1557 O << "\t.param .align " << align << " .b8 ";
1558 printParamName(I, paramIndex, O);
1559 O << "[" << sz << "]";
1562 // Split the ETy into constituent parts and
1563 // print .param .b<size> <name> for each part.
1564 // Further, if a part is vector, print the above for
1565 // each vector element.
1566 SmallVector<EVT, 16> vtparts;
1567 ComputeValueVTs(*TLI, ETy, vtparts);
1568 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1570 EVT elemtype = vtparts[i];
1571 if (vtparts[i].isVector()) {
1572 elems = vtparts[i].getVectorNumElements();
1573 elemtype = vtparts[i].getVectorElementType();
1576 for (unsigned j = 0, je = elems; j != je; ++j) {
1577 unsigned sz = elemtype.getSizeInBits();
1578 if (elemtype.isInteger() && (sz < 32))
1580 O << "\t.reg .b" << sz << " ";
1581 printParamName(I, paramIndex, O);
1597 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1599 const Function *F = MF.getFunction();
1600 emitFunctionParamList(F, O);
1603 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1604 const MachineFunction &MF) {
1605 SmallString<128> Str;
1606 raw_svector_ostream O(Str);
1608 // Map the global virtual register number to a register class specific
1609 // virtual register number starting from 1 with that class.
1610 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1611 //unsigned numRegClasses = TRI->getNumRegClasses();
1613 // Emit the Fake Stack Object
1614 const MachineFrameInfo *MFI = MF.getFrameInfo();
1615 int NumBytes = (int) MFI->getStackSize();
1617 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1618 << getFunctionNumber() << "[" << NumBytes << "];\n";
1619 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1620 O << "\t.reg .b64 \t%SP;\n";
1621 O << "\t.reg .b64 \t%SPL;\n";
1623 O << "\t.reg .b32 \t%SP;\n";
1624 O << "\t.reg .b32 \t%SPL;\n";
1628 // Go through all virtual registers to establish the mapping between the
1630 // register number and the per class virtual register number.
1631 // We use the per class virtual register number in the ptx output.
1632 unsigned int numVRs = MRI->getNumVirtRegs();
1633 for (unsigned i = 0; i < numVRs; i++) {
1634 unsigned int vr = TRI->index2VirtReg(i);
1635 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1636 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1637 int n = regmap.size();
1638 regmap.insert(std::make_pair(vr, n + 1));
1641 // Emit register declarations
1642 // @TODO: Extract out the real register usage
1643 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1644 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1645 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1646 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1647 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1648 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1649 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1651 // Emit declaration of the virtual registers or 'physical' registers for
1652 // each register class
1653 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1654 const TargetRegisterClass *RC = TRI->getRegClass(i);
1655 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1656 std::string rcname = getNVPTXRegClassName(RC);
1657 std::string rcStr = getNVPTXRegClassStr(RC);
1658 int n = regmap.size();
1660 // Only declare those registers that may be used.
1662 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1667 OutStreamer->EmitRawText(O.str());
1670 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1671 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1673 unsigned int numHex;
1676 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1679 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1680 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1683 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1685 llvm_unreachable("unsupported fp type");
1687 APInt API = APF.bitcastToAPInt();
1688 std::string hexstr(utohexstr(API.getZExtValue()));
1690 if (hexstr.length() < numHex)
1691 O << std::string(numHex - hexstr.length(), '0');
1692 O << utohexstr(API.getZExtValue());
1695 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1696 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1697 O << CI->getValue();
1700 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1701 printFPConstant(CFP, O);
1704 if (isa<ConstantPointerNull>(CPV)) {
1708 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1709 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1710 bool IsNonGenericPointer = false;
1711 if (PTy && PTy->getAddressSpace() != 0) {
1712 IsNonGenericPointer = true;
1714 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1716 O << *getSymbol(GVar);
1719 O << *getSymbol(GVar);
1723 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1724 const Value *v = Cexpr->stripPointerCasts();
1725 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1726 bool IsNonGenericPointer = false;
1727 if (PTy && PTy->getAddressSpace() != 0) {
1728 IsNonGenericPointer = true;
1730 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1731 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1733 O << *getSymbol(GVar);
1736 O << *getSymbol(GVar);
1740 O << *lowerConstant(CPV);
1744 llvm_unreachable("Not scalar type found in printScalarConstant()");
1747 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1748 AggBuffer *aggBuffer) {
1750 const DataLayout *TD = TM.getDataLayout();
1752 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1753 int s = TD->getTypeAllocSize(CPV->getType());
1756 aggBuffer->addZeros(s);
1761 switch (CPV->getType()->getTypeID()) {
1763 case Type::IntegerTyID: {
1764 const Type *ETy = CPV->getType();
1765 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1766 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
1768 aggBuffer->addBytes(ptr, 1, Bytes);
1769 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1770 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
1771 ptr = (unsigned char *)&int16;
1772 aggBuffer->addBytes(ptr, 2, Bytes);
1773 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1774 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1775 int int32 = (int)(constInt->getZExtValue());
1776 ptr = (unsigned char *)&int32;
1777 aggBuffer->addBytes(ptr, 4, Bytes);
1779 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1780 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1781 ConstantFoldConstantExpression(Cexpr, *TD))) {
1782 int int32 = (int)(constInt->getZExtValue());
1783 ptr = (unsigned char *)&int32;
1784 aggBuffer->addBytes(ptr, 4, Bytes);
1787 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1788 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1789 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1790 aggBuffer->addZeros(4);
1794 llvm_unreachable("unsupported integer const type");
1795 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1796 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1797 long long int64 = (long long)(constInt->getZExtValue());
1798 ptr = (unsigned char *)&int64;
1799 aggBuffer->addBytes(ptr, 8, Bytes);
1801 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1802 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1803 ConstantFoldConstantExpression(Cexpr, *TD))) {
1804 long long int64 = (long long)(constInt->getZExtValue());
1805 ptr = (unsigned char *)&int64;
1806 aggBuffer->addBytes(ptr, 8, Bytes);
1809 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1810 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1811 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1812 aggBuffer->addZeros(8);
1816 llvm_unreachable("unsupported integer const type");
1818 llvm_unreachable("unsupported integer const type");
1821 case Type::FloatTyID:
1822 case Type::DoubleTyID: {
1823 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1824 const Type *Ty = CFP->getType();
1825 if (Ty == Type::getFloatTy(CPV->getContext())) {
1826 float float32 = (float) CFP->getValueAPF().convertToFloat();
1827 ptr = (unsigned char *)&float32;
1828 aggBuffer->addBytes(ptr, 4, Bytes);
1829 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1830 double float64 = CFP->getValueAPF().convertToDouble();
1831 ptr = (unsigned char *)&float64;
1832 aggBuffer->addBytes(ptr, 8, Bytes);
1834 llvm_unreachable("unsupported fp const type");
1838 case Type::PointerTyID: {
1839 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1840 aggBuffer->addSymbol(GVar, GVar);
1841 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1842 const Value *v = Cexpr->stripPointerCasts();
1843 aggBuffer->addSymbol(v, Cexpr);
1845 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1846 aggBuffer->addZeros(s);
1850 case Type::ArrayTyID:
1851 case Type::VectorTyID:
1852 case Type::StructTyID: {
1853 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1854 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1855 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1856 bufferAggregateConstant(CPV, aggBuffer);
1857 if (Bytes > ElementSize)
1858 aggBuffer->addZeros(Bytes - ElementSize);
1859 } else if (isa<ConstantAggregateZero>(CPV))
1860 aggBuffer->addZeros(Bytes);
1862 llvm_unreachable("Unexpected Constant type");
1867 llvm_unreachable("unsupported type");
1871 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1872 AggBuffer *aggBuffer) {
1873 const DataLayout *TD = TM.getDataLayout();
1877 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1878 if (CPV->getNumOperands())
1879 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1880 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1884 if (const ConstantDataSequential *CDS =
1885 dyn_cast<ConstantDataSequential>(CPV)) {
1886 if (CDS->getNumElements())
1887 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1888 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1893 if (isa<ConstantStruct>(CPV)) {
1894 if (CPV->getNumOperands()) {
1895 StructType *ST = cast<StructType>(CPV->getType());
1896 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1898 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1899 TD->getTypeAllocSize(ST) -
1900 TD->getStructLayout(ST)->getElementOffset(i);
1902 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1903 TD->getStructLayout(ST)->getElementOffset(i);
1904 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1909 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1912 // buildTypeNameMap - Run through symbol table looking for type names.
1915 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1917 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1919 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1920 !PI->second.compare("struct._image2d_t") ||
1921 !PI->second.compare("struct._image3d_t")))
1928 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1929 switch (MI.getOpcode()) {
1932 case NVPTX::CallArgBeginInst:
1933 case NVPTX::CallArgEndInst0:
1934 case NVPTX::CallArgEndInst1:
1935 case NVPTX::CallArgF32:
1936 case NVPTX::CallArgF64:
1937 case NVPTX::CallArgI16:
1938 case NVPTX::CallArgI32:
1939 case NVPTX::CallArgI32imm:
1940 case NVPTX::CallArgI64:
1941 case NVPTX::CallArgParam:
1942 case NVPTX::CallVoidInst:
1943 case NVPTX::CallVoidInstReg:
1944 case NVPTX::Callseq_End:
1945 case NVPTX::CallVoidInstReg64:
1946 case NVPTX::DeclareParamInst:
1947 case NVPTX::DeclareRetMemInst:
1948 case NVPTX::DeclareRetRegInst:
1949 case NVPTX::DeclareRetScalarInst:
1950 case NVPTX::DeclareScalarParamInst:
1951 case NVPTX::DeclareScalarRegInst:
1952 case NVPTX::StoreParamF32:
1953 case NVPTX::StoreParamF64:
1954 case NVPTX::StoreParamI16:
1955 case NVPTX::StoreParamI32:
1956 case NVPTX::StoreParamI64:
1957 case NVPTX::StoreParamI8:
1958 case NVPTX::StoreRetvalF32:
1959 case NVPTX::StoreRetvalF64:
1960 case NVPTX::StoreRetvalI16:
1961 case NVPTX::StoreRetvalI32:
1962 case NVPTX::StoreRetvalI64:
1963 case NVPTX::StoreRetvalI8:
1964 case NVPTX::LastCallArgF32:
1965 case NVPTX::LastCallArgF64:
1966 case NVPTX::LastCallArgI16:
1967 case NVPTX::LastCallArgI32:
1968 case NVPTX::LastCallArgI32imm:
1969 case NVPTX::LastCallArgI64:
1970 case NVPTX::LastCallArgParam:
1971 case NVPTX::LoadParamMemF32:
1972 case NVPTX::LoadParamMemF64:
1973 case NVPTX::LoadParamMemI16:
1974 case NVPTX::LoadParamMemI32:
1975 case NVPTX::LoadParamMemI64:
1976 case NVPTX::LoadParamMemI8:
1977 case NVPTX::PrototypeInst:
1978 case NVPTX::DBG_VALUE:
1984 /// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
1985 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
1986 /// expressions that are representable in PTX and create
1987 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
1989 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
1990 MCContext &Ctx = OutContext;
1992 if (CV->isNullValue() || isa<UndefValue>(CV))
1993 return MCConstantExpr::create(0, Ctx);
1995 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
1996 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
1998 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
1999 const MCSymbolRefExpr *Expr =
2000 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2001 if (ProcessingGeneric) {
2002 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
2008 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2010 llvm_unreachable("Unknown constant value to lower!");
2013 switch (CE->getOpcode()) {
2015 // If the code isn't optimized, there may be outstanding folding
2016 // opportunities. Attempt to fold the expression using DataLayout as a
2017 // last resort before giving up.
2018 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
2020 return lowerConstantForGV(C, ProcessingGeneric);
2022 // Otherwise report the problem to the user.
2025 raw_string_ostream OS(S);
2026 OS << "Unsupported expression in static initializer: ";
2027 CE->printAsOperand(OS, /*PrintType=*/false,
2028 !MF ? nullptr : MF->getFunction()->getParent());
2029 report_fatal_error(OS.str());
2032 case Instruction::AddrSpaceCast: {
2033 // Strip the addrspacecast and pass along the operand
2034 PointerType *DstTy = cast<PointerType>(CE->getType());
2035 if (DstTy->getAddressSpace() == 0) {
2036 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2039 raw_string_ostream OS(S);
2040 OS << "Unsupported expression in static initializer: ";
2041 CE->printAsOperand(OS, /*PrintType=*/ false,
2042 !MF ? 0 : MF->getFunction()->getParent());
2043 report_fatal_error(OS.str());
2046 case Instruction::GetElementPtr: {
2047 const DataLayout &DL = *TM.getDataLayout();
2049 // Generate a symbolic expression for the byte address
2050 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2051 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2053 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2058 int64_t Offset = OffsetAI.getSExtValue();
2059 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2063 case Instruction::Trunc:
2064 // We emit the value and depend on the assembler to truncate the generated
2065 // expression properly. This is important for differences between
2066 // blockaddress labels. Since the two labels are in the same function, it
2067 // is reasonable to treat their delta as a 32-bit value.
2069 case Instruction::BitCast:
2070 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2072 case Instruction::IntToPtr: {
2073 const DataLayout &DL = *TM.getDataLayout();
2075 // Handle casts to pointers by changing them into casts to the appropriate
2076 // integer type. This promotes constant folding and simplifies this code.
2077 Constant *Op = CE->getOperand(0);
2078 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2080 return lowerConstantForGV(Op, ProcessingGeneric);
2083 case Instruction::PtrToInt: {
2084 const DataLayout &DL = *TM.getDataLayout();
2086 // Support only foldable casts to/from pointers that can be eliminated by
2087 // changing the pointer to the appropriately sized integer type.
2088 Constant *Op = CE->getOperand(0);
2089 Type *Ty = CE->getType();
2091 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2093 // We can emit the pointer value into this slot if the slot is an
2094 // integer slot equal to the size of the pointer.
2095 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2098 // Otherwise the pointer is smaller than the resultant integer, mask off
2099 // the high bits so we are sure to get a proper truncation if the input is
2101 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2102 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2103 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2106 // The MC library also has a right-shift operator, but it isn't consistently
2107 // signed or unsigned between different targets.
2108 case Instruction::Add: {
2109 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2110 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2111 switch (CE->getOpcode()) {
2112 default: llvm_unreachable("Unknown binary operator constant cast expr");
2113 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2119 // Copy of MCExpr::print customized for NVPTX
2120 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2121 switch (Expr.getKind()) {
2122 case MCExpr::Target:
2123 return cast<MCTargetExpr>(&Expr)->printImpl(OS);
2124 case MCExpr::Constant:
2125 OS << cast<MCConstantExpr>(Expr).getValue();
2128 case MCExpr::SymbolRef: {
2129 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2130 const MCSymbol &Sym = SRE.getSymbol();
2135 case MCExpr::Unary: {
2136 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2137 switch (UE.getOpcode()) {
2138 case MCUnaryExpr::LNot: OS << '!'; break;
2139 case MCUnaryExpr::Minus: OS << '-'; break;
2140 case MCUnaryExpr::Not: OS << '~'; break;
2141 case MCUnaryExpr::Plus: OS << '+'; break;
2143 printMCExpr(*UE.getSubExpr(), OS);
2147 case MCExpr::Binary: {
2148 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2150 // Only print parens around the LHS if it is non-trivial.
2151 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2152 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2153 printMCExpr(*BE.getLHS(), OS);
2156 printMCExpr(*BE.getLHS(), OS);
2160 switch (BE.getOpcode()) {
2161 case MCBinaryExpr::Add:
2162 // Print "X-42" instead of "X+-42".
2163 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2164 if (RHSC->getValue() < 0) {
2165 OS << RHSC->getValue();
2172 default: llvm_unreachable("Unhandled binary operator");
2175 // Only print parens around the LHS if it is non-trivial.
2176 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2177 printMCExpr(*BE.getRHS(), OS);
2180 printMCExpr(*BE.getRHS(), OS);
2187 llvm_unreachable("Invalid expression kind!");
2190 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2192 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2193 unsigned AsmVariant,
2194 const char *ExtraCode, raw_ostream &O) {
2195 if (ExtraCode && ExtraCode[0]) {
2196 if (ExtraCode[1] != 0)
2197 return true; // Unknown modifier.
2199 switch (ExtraCode[0]) {
2201 // See if this is a generic print operand
2202 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2208 printOperand(MI, OpNo, O);
2213 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2214 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2215 const char *ExtraCode, raw_ostream &O) {
2216 if (ExtraCode && ExtraCode[0])
2217 return true; // Unknown modifier
2220 printMemOperand(MI, OpNo, O);
2226 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2227 raw_ostream &O, const char *Modifier) {
2228 const MachineOperand &MO = MI->getOperand(opNum);
2229 switch (MO.getType()) {
2230 case MachineOperand::MO_Register:
2231 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2232 if (MO.getReg() == NVPTX::VRDepot)
2233 O << DEPOTNAME << getFunctionNumber();
2235 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2237 emitVirtualRegister(MO.getReg(), O);
2241 case MachineOperand::MO_Immediate:
2244 else if (strstr(Modifier, "vec") == Modifier)
2245 printVecModifiedImmediate(MO, Modifier, O);
2248 "Don't know how to handle modifier on immediate operand");
2251 case MachineOperand::MO_FPImmediate:
2252 printFPConstant(MO.getFPImm(), O);
2255 case MachineOperand::MO_GlobalAddress:
2256 O << *getSymbol(MO.getGlobal());
2259 case MachineOperand::MO_MachineBasicBlock:
2260 O << *MO.getMBB()->getSymbol();
2264 llvm_unreachable("Operand type not supported.");
2268 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2269 raw_ostream &O, const char *Modifier) {
2270 printOperand(MI, opNum, O);
2272 if (Modifier && !strcmp(Modifier, "add")) {
2274 printOperand(MI, opNum + 1, O);
2276 if (MI->getOperand(opNum + 1).isImm() &&
2277 MI->getOperand(opNum + 1).getImm() == 0)
2278 return; // don't print ',0' or '+0'
2280 printOperand(MI, opNum + 1, O);
2284 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2285 std::stringstream temp;
2286 LineReader *reader = this->getReader(filename);
2288 temp << filename.str();
2292 temp << reader->readLine(line);
2294 this->OutStreamer->EmitRawText(temp.str());
2297 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2299 reader = new LineReader(filename);
2302 if (reader->fileName() != filename) {
2304 reader = new LineReader(filename);
2310 std::string LineReader::readLine(unsigned lineNum) {
2311 if (lineNum < theCurLine) {
2313 fstr.seekg(0, std::ios::beg);
2315 while (theCurLine < lineNum) {
2316 fstr.getline(buff, 500);
2322 // Force static initialization.
2323 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2324 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2325 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);