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);
470 CurrentFnSym->print(O, MAI);
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 getSymbol(F)->print(O, MAI);
629 emitFunctionParamList(F, O);
633 static bool usedInGlobalVarDef(const Constant *C) {
637 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
638 if (GV->getName() == "llvm.used")
643 for (const User *U : C->users())
644 if (const Constant *C = dyn_cast<Constant>(U))
645 if (usedInGlobalVarDef(C))
651 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
652 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
653 if (othergv->getName() == "llvm.used")
657 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
658 if (instr->getParent() && instr->getParent()->getParent()) {
659 const Function *curFunc = instr->getParent()->getParent();
660 if (oneFunc && (curFunc != oneFunc))
668 for (const User *UU : U->users())
669 if (!usedInOneFunc(UU, oneFunc))
675 /* Find out if a global variable can be demoted to local scope.
676 * Currently, this is valid for CUDA shared variables, which have local
677 * scope and global lifetime. So the conditions to check are :
678 * 1. Is the global variable in shared address space?
679 * 2. Does it have internal linkage?
680 * 3. Is the global variable referenced only in one function?
682 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
683 if (!gv->hasInternalLinkage())
685 const PointerType *Pty = gv->getType();
686 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
689 const Function *oneFunc = nullptr;
691 bool flag = usedInOneFunc(gv, oneFunc);
700 static bool useFuncSeen(const Constant *C,
701 llvm::DenseMap<const Function *, bool> &seenMap) {
702 for (const User *U : C->users()) {
703 if (const Constant *cu = dyn_cast<Constant>(U)) {
704 if (useFuncSeen(cu, seenMap))
706 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
707 const BasicBlock *bb = I->getParent();
710 const Function *caller = bb->getParent();
713 if (seenMap.find(caller) != seenMap.end())
720 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
721 llvm::DenseMap<const Function *, bool> seenMap;
722 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
723 const Function *F = FI;
725 if (F->isDeclaration()) {
728 if (F->getIntrinsicID())
730 emitDeclaration(F, O);
733 for (const User *U : F->users()) {
734 if (const Constant *C = dyn_cast<Constant>(U)) {
735 if (usedInGlobalVarDef(C)) {
736 // The use is in the initialization of a global variable
737 // that is a function pointer, so print a declaration
738 // for the original function
739 emitDeclaration(F, O);
742 // Emit a declaration of this function if the function that
743 // uses this constant expr has already been seen.
744 if (useFuncSeen(C, seenMap)) {
745 emitDeclaration(F, O);
750 if (!isa<Instruction>(U))
752 const Instruction *instr = cast<Instruction>(U);
753 const BasicBlock *bb = instr->getParent();
756 const Function *caller = bb->getParent();
760 // If a caller has already been seen, then the caller is
761 // appearing in the module before the callee. so print out
762 // a declaration for the callee.
763 if (seenMap.find(caller) != seenMap.end()) {
764 emitDeclaration(F, O);
772 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
773 DebugInfoFinder DbgFinder;
774 DbgFinder.processModule(M);
777 for (const DICompileUnit *DIUnit : DbgFinder.compile_units()) {
778 StringRef Filename = DIUnit->getFilename();
779 StringRef Dirname = DIUnit->getDirectory();
780 SmallString<128> FullPathName = Dirname;
781 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
782 sys::path::append(FullPathName, Filename);
783 Filename = FullPathName;
785 if (filenameMap.find(Filename) != filenameMap.end())
787 filenameMap[Filename] = i;
788 OutStreamer->EmitDwarfFileDirective(i, "", Filename);
792 for (DISubprogram *SP : DbgFinder.subprograms()) {
793 StringRef Filename = SP->getFilename();
794 StringRef Dirname = SP->getDirectory();
795 SmallString<128> FullPathName = Dirname;
796 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
797 sys::path::append(FullPathName, Filename);
798 Filename = FullPathName;
800 if (filenameMap.find(Filename) != filenameMap.end())
802 filenameMap[Filename] = i;
807 bool NVPTXAsmPrinter::doInitialization(Module &M) {
808 // Construct a default subtarget off of the TargetMachine defaults. The
809 // rest of NVPTX isn't friendly to change subtargets per function and
810 // so the default TargetMachine will have all of the options.
811 StringRef TT = TM.getTargetTriple();
812 StringRef CPU = TM.getTargetCPU();
813 StringRef FS = TM.getTargetFeatureString();
814 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
815 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
817 SmallString<128> Str1;
818 raw_svector_ostream OS1(Str1);
820 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
821 MMI->AnalyzeModule(M);
823 // We need to call the parent's one explicitly.
824 //bool Result = AsmPrinter::doInitialization(M);
826 // Initialize TargetLoweringObjectFile.
827 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
828 .Initialize(OutContext, TM);
830 Mang = new Mangler(TM.getDataLayout());
832 // Emit header before any dwarf directives are emitted below.
833 emitHeader(M, OS1, STI);
834 OutStreamer->EmitRawText(OS1.str());
836 // Already commented out
837 //bool Result = AsmPrinter::doInitialization(M);
839 // Emit module-level inline asm if it exists.
840 if (!M.getModuleInlineAsm().empty()) {
841 OutStreamer->AddComment("Start of file scope inline assembly");
842 OutStreamer->AddBlankLine();
843 OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
844 OutStreamer->AddBlankLine();
845 OutStreamer->AddComment("End of file scope inline assembly");
846 OutStreamer->AddBlankLine();
849 // If we're not NVCL we're CUDA, go ahead and emit filenames.
850 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
851 recordAndEmitFilenames(M);
853 GlobalsEmitted = false;
855 return false; // success
858 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
859 SmallString<128> Str2;
860 raw_svector_ostream OS2(Str2);
862 emitDeclarations(M, OS2);
864 // As ptxas does not support forward references of globals, we need to first
865 // sort the list of module-level globals in def-use order. We visit each
866 // global variable in order, and ensure that we emit it *after* its dependent
867 // globals. We use a little extra memory maintaining both a set and a list to
868 // have fast searches while maintaining a strict ordering.
869 SmallVector<const GlobalVariable *, 8> Globals;
870 DenseSet<const GlobalVariable *> GVVisited;
871 DenseSet<const GlobalVariable *> GVVisiting;
873 // Visit each global variable, in order
874 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
876 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
878 assert(GVVisited.size() == M.getGlobalList().size() &&
879 "Missed a global variable");
880 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
882 // Print out module-level global variables in proper order
883 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
884 printModuleLevelGV(Globals[i], OS2);
888 OutStreamer->EmitRawText(OS2.str());
891 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
892 const NVPTXSubtarget &STI) {
894 O << "// Generated by LLVM NVPTX Back-End\n";
898 unsigned PTXVersion = STI.getPTXVersion();
899 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
902 O << STI.getTargetName();
904 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
905 if (NTM.getDrvInterface() == NVPTX::NVCL)
906 O << ", texmode_independent";
908 if (!STI.hasDouble())
909 O << ", map_f64_to_f32";
912 if (MAI->doesSupportDebugInformation())
917 O << ".address_size ";
927 bool NVPTXAsmPrinter::doFinalization(Module &M) {
928 // If we did not emit any functions, then the global declarations have not
930 if (!GlobalsEmitted) {
932 GlobalsEmitted = true;
935 // XXX Temproarily remove global variables so that doFinalization() will not
936 // emit them again (global variables are emitted at beginning).
938 Module::GlobalListType &global_list = M.getGlobalList();
939 int i, n = global_list.size();
940 GlobalVariable **gv_array = new GlobalVariable *[n];
942 // first, back-up GlobalVariable in gv_array
944 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
948 // second, empty global_list
949 while (!global_list.empty())
950 global_list.remove(global_list.begin());
952 // call doFinalization
953 bool ret = AsmPrinter::doFinalization(M);
955 // now we restore global variables
956 for (i = 0; i < n; i++)
957 global_list.insert(global_list.end(), gv_array[i]);
959 clearAnnotationCache(&M);
964 //bool Result = AsmPrinter::doFinalization(M);
965 // Instead of calling the parents doFinalization, we may
966 // clone parents doFinalization and customize here.
967 // Currently, we if NVISA out the EmitGlobals() in
968 // parent's doFinalization, which is too intrusive.
970 // Same for the doInitialization.
974 // This function emits appropriate linkage directives for
975 // functions and global variables.
977 // extern function declaration -> .extern
978 // extern function definition -> .visible
979 // external global variable with init -> .visible
980 // external without init -> .extern
981 // appending -> not allowed, assert.
982 // for any linkage other than
983 // internal, private, linker_private,
984 // linker_private_weak, linker_private_weak_def_auto,
987 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
989 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
990 if (V->hasExternalLinkage()) {
991 if (isa<GlobalVariable>(V)) {
992 const GlobalVariable *GVar = cast<GlobalVariable>(V);
994 if (GVar->hasInitializer())
999 } else if (V->isDeclaration())
1003 } else if (V->hasAppendingLinkage()) {
1005 msg.append("Error: ");
1006 msg.append("Symbol ");
1008 msg.append(V->getName());
1009 msg.append("has unsupported appending linkage type");
1010 llvm_unreachable(msg.c_str());
1011 } else if (!V->hasInternalLinkage() &&
1012 !V->hasPrivateLinkage()) {
1018 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1020 bool processDemoted) {
1023 if (GVar->hasSection()) {
1024 if (GVar->getSection() == StringRef("llvm.metadata"))
1028 // Skip LLVM intrinsic global variables
1029 if (GVar->getName().startswith("llvm.") ||
1030 GVar->getName().startswith("nvvm."))
1033 const DataLayout *TD = TM.getDataLayout();
1035 // GlobalVariables are always constant pointers themselves.
1036 const PointerType *PTy = GVar->getType();
1037 Type *ETy = PTy->getElementType();
1039 if (GVar->hasExternalLinkage()) {
1040 if (GVar->hasInitializer())
1044 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1045 GVar->hasAvailableExternallyLinkage() ||
1046 GVar->hasCommonLinkage()) {
1050 if (llvm::isTexture(*GVar)) {
1051 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1055 if (llvm::isSurface(*GVar)) {
1056 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1060 if (GVar->isDeclaration()) {
1061 // (extern) declarations, no definition or initializer
1062 // Currently the only known declaration is for an automatic __local
1063 // (.shared) promoted to global.
1064 emitPTXGlobalVariable(GVar, O);
1069 if (llvm::isSampler(*GVar)) {
1070 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1072 const Constant *Initializer = nullptr;
1073 if (GVar->hasInitializer())
1074 Initializer = GVar->getInitializer();
1075 const ConstantInt *CI = nullptr;
1077 CI = dyn_cast<ConstantInt>(Initializer);
1079 unsigned sample = CI->getZExtValue();
1084 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1086 O << "addr_mode_" << i << " = ";
1092 O << "clamp_to_border";
1095 O << "clamp_to_edge";
1106 O << "filter_mode = ";
1107 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1115 llvm_unreachable("Anisotropic filtering is not supported");
1120 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1121 O << ", force_unnormalized_coords = 1";
1130 if (GVar->hasPrivateLinkage()) {
1132 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1135 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1136 if (!strncmp(GVar->getName().data(), "filename", 8))
1138 if (GVar->use_empty())
1142 const Function *demotedFunc = nullptr;
1143 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1144 O << "// " << GVar->getName() << " has been demoted\n";
1145 if (localDecls.find(demotedFunc) != localDecls.end())
1146 localDecls[demotedFunc].push_back(GVar);
1148 std::vector<const GlobalVariable *> temp;
1149 temp.push_back(GVar);
1150 localDecls[demotedFunc] = temp;
1156 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1158 if (isManaged(*GVar)) {
1159 O << " .attribute(.managed)";
1162 if (GVar->getAlignment() == 0)
1163 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1165 O << " .align " << GVar->getAlignment();
1167 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1169 // Special case: ABI requires that we use .u8 for predicates
1170 if (ETy->isIntegerTy(1))
1173 O << getPTXFundamentalTypeStr(ETy, false);
1175 getSymbol(GVar)->print(O, MAI);
1177 // Ptx allows variable initilization only for constant and global state
1179 if (GVar->hasInitializer()) {
1180 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1181 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1182 const Constant *Initializer = GVar->getInitializer();
1183 // 'undef' is treated as there is no value specified.
1184 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1186 printScalarConstant(Initializer, O);
1189 // The frontend adds zero-initializer to variables that don't have an
1190 // initial value, so skip warning for this case.
1191 if (!GVar->getInitializer()->isNullValue()) {
1192 report_fatal_error("initial value of '" + GVar->getName() +
1193 "' is not allowed in addrspace(" +
1194 Twine(PTy->getAddressSpace()) + ")");
1199 unsigned int ElementSize = 0;
1201 // Although PTX has direct support for struct type and array type and
1202 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1203 // targets that support these high level field accesses. Structs, arrays
1204 // and vectors are lowered into arrays of bytes.
1205 switch (ETy->getTypeID()) {
1206 case Type::StructTyID:
1207 case Type::ArrayTyID:
1208 case Type::VectorTyID:
1209 ElementSize = TD->getTypeStoreSize(ETy);
1210 // Ptx allows variable initilization only for constant and
1211 // global state spaces.
1212 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1213 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1214 GVar->hasInitializer()) {
1215 const Constant *Initializer = GVar->getInitializer();
1216 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1217 AggBuffer aggBuffer(ElementSize, O, *this);
1218 bufferAggregateConstant(Initializer, &aggBuffer);
1219 if (aggBuffer.numSymbols) {
1220 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1222 getSymbol(GVar)->print(O, MAI);
1224 O << ElementSize / 8;
1227 getSymbol(GVar)->print(O, MAI);
1229 O << ElementSize / 4;
1234 getSymbol(GVar)->print(O, MAI);
1244 getSymbol(GVar)->print(O, MAI);
1253 getSymbol(GVar)->print(O, MAI);
1262 llvm_unreachable("type not supported yet");
1269 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1270 if (localDecls.find(f) == localDecls.end())
1273 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1275 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1276 O << "\t// demoted variable\n\t";
1277 printModuleLevelGV(gvars[i], O, true);
1281 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1282 raw_ostream &O) const {
1283 switch (AddressSpace) {
1284 case llvm::ADDRESS_SPACE_LOCAL:
1287 case llvm::ADDRESS_SPACE_GLOBAL:
1290 case llvm::ADDRESS_SPACE_CONST:
1293 case llvm::ADDRESS_SPACE_SHARED:
1297 report_fatal_error("Bad address space found while emitting PTX");
1303 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1304 switch (Ty->getTypeID()) {
1306 llvm_unreachable("unexpected type");
1308 case Type::IntegerTyID: {
1309 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1312 else if (NumBits <= 64) {
1313 std::string name = "u";
1314 return name + utostr(NumBits);
1316 llvm_unreachable("Integer too large");
1321 case Type::FloatTyID:
1323 case Type::DoubleTyID:
1325 case Type::PointerTyID:
1326 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1336 llvm_unreachable("unexpected type");
1340 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1343 const DataLayout *TD = TM.getDataLayout();
1345 // GlobalVariables are always constant pointers themselves.
1346 const PointerType *PTy = GVar->getType();
1347 Type *ETy = PTy->getElementType();
1350 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1351 if (GVar->getAlignment() == 0)
1352 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1354 O << " .align " << GVar->getAlignment();
1356 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1358 O << getPTXFundamentalTypeStr(ETy);
1360 getSymbol(GVar)->print(O, MAI);
1364 int64_t ElementSize = 0;
1366 // Although PTX has direct support for struct type and array type and LLVM IR
1367 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1368 // support these high level field accesses. Structs and arrays are lowered
1369 // into arrays of bytes.
1370 switch (ETy->getTypeID()) {
1371 case Type::StructTyID:
1372 case Type::ArrayTyID:
1373 case Type::VectorTyID:
1374 ElementSize = TD->getTypeStoreSize(ETy);
1376 getSymbol(GVar)->print(O, MAI);
1384 llvm_unreachable("type not supported yet");
1389 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1390 if (Ty->isSingleValueType())
1391 return TD->getPrefTypeAlignment(Ty);
1393 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1395 return getOpenCLAlignment(TD, ATy->getElementType());
1397 const StructType *STy = dyn_cast<StructType>(Ty);
1399 unsigned int alignStruct = 1;
1400 // Go through each element of the struct and find the
1401 // largest alignment.
1402 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1403 Type *ETy = STy->getElementType(i);
1404 unsigned int align = getOpenCLAlignment(TD, ETy);
1405 if (align > alignStruct)
1406 alignStruct = align;
1411 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1413 return TD->getPointerPrefAlignment();
1414 return TD->getPrefTypeAlignment(Ty);
1417 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1418 int paramIndex, raw_ostream &O) {
1419 getSymbol(I->getParent())->print(O, MAI);
1420 O << "_param_" << paramIndex;
1423 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1424 CurrentFnSym->print(O, MAI);
1425 O << "_param_" << paramIndex;
1428 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1429 const DataLayout *TD = TM.getDataLayout();
1430 const AttributeSet &PAL = F->getAttributes();
1431 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
1432 Function::const_arg_iterator I, E;
1433 unsigned paramIndex = 0;
1435 bool isKernelFunc = llvm::isKernelFunction(*F);
1436 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
1437 MVT thePointerTy = TLI->getPointerTy();
1441 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1442 Type *Ty = I->getType();
1449 // Handle image/sampler parameters
1450 if (isKernelFunction(*F)) {
1451 if (isSampler(*I) || isImage(*I)) {
1453 std::string sname = I->getName();
1454 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1455 if (nvptxSubtarget->hasImageHandles())
1456 O << "\t.param .u64 .ptr .surfref ";
1458 O << "\t.param .surfref ";
1459 CurrentFnSym->print(O, MAI);
1460 O << "_param_" << paramIndex;
1462 else { // Default image is read_only
1463 if (nvptxSubtarget->hasImageHandles())
1464 O << "\t.param .u64 .ptr .texref ";
1466 O << "\t.param .texref ";
1467 CurrentFnSym->print(O, MAI);
1468 O << "_param_" << paramIndex;
1471 if (nvptxSubtarget->hasImageHandles())
1472 O << "\t.param .u64 .ptr .samplerref ";
1474 O << "\t.param .samplerref ";
1475 CurrentFnSym->print(O, MAI);
1476 O << "_param_" << paramIndex;
1482 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
1483 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1484 // Just print .param .align <a> .b8 .param[size];
1485 // <a> = PAL.getparamalignment
1486 // size = typeallocsize of element type
1487 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1489 align = TD->getABITypeAlignment(Ty);
1491 unsigned sz = TD->getTypeAllocSize(Ty);
1492 O << "\t.param .align " << align << " .b8 ";
1493 printParamName(I, paramIndex, O);
1494 O << "[" << sz << "]";
1499 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1502 // Special handling for pointer arguments to kernel
1503 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1505 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1507 Type *ETy = PTy->getElementType();
1508 int addrSpace = PTy->getAddressSpace();
1509 switch (addrSpace) {
1513 case llvm::ADDRESS_SPACE_CONST:
1514 O << ".ptr .const ";
1516 case llvm::ADDRESS_SPACE_SHARED:
1517 O << ".ptr .shared ";
1519 case llvm::ADDRESS_SPACE_GLOBAL:
1520 O << ".ptr .global ";
1523 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1525 printParamName(I, paramIndex, O);
1529 // non-pointer scalar to kernel func
1531 // Special case: predicate operands become .u8 types
1532 if (Ty->isIntegerTy(1))
1535 O << getPTXFundamentalTypeStr(Ty);
1537 printParamName(I, paramIndex, O);
1540 // Non-kernel function, just print .param .b<size> for ABI
1541 // and .reg .b<size> for non-ABI
1543 if (isa<IntegerType>(Ty)) {
1544 sz = cast<IntegerType>(Ty)->getBitWidth();
1547 } else if (isa<PointerType>(Ty))
1548 sz = thePointerTy.getSizeInBits();
1550 sz = Ty->getPrimitiveSizeInBits();
1552 O << "\t.param .b" << sz << " ";
1554 O << "\t.reg .b" << sz << " ";
1555 printParamName(I, paramIndex, O);
1559 // param has byVal attribute. So should be a pointer
1560 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1561 assert(PTy && "Param with byval attribute should be a pointer type");
1562 Type *ETy = PTy->getElementType();
1564 if (isABI || isKernelFunc) {
1565 // Just print .param .align <a> .b8 .param[size];
1566 // <a> = PAL.getparamalignment
1567 // size = typeallocsize of element type
1568 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1570 align = TD->getABITypeAlignment(ETy);
1572 unsigned sz = TD->getTypeAllocSize(ETy);
1573 O << "\t.param .align " << align << " .b8 ";
1574 printParamName(I, paramIndex, O);
1575 O << "[" << sz << "]";
1578 // Split the ETy into constituent parts and
1579 // print .param .b<size> <name> for each part.
1580 // Further, if a part is vector, print the above for
1581 // each vector element.
1582 SmallVector<EVT, 16> vtparts;
1583 ComputeValueVTs(*TLI, ETy, vtparts);
1584 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1586 EVT elemtype = vtparts[i];
1587 if (vtparts[i].isVector()) {
1588 elems = vtparts[i].getVectorNumElements();
1589 elemtype = vtparts[i].getVectorElementType();
1592 for (unsigned j = 0, je = elems; j != je; ++j) {
1593 unsigned sz = elemtype.getSizeInBits();
1594 if (elemtype.isInteger() && (sz < 32))
1596 O << "\t.reg .b" << sz << " ";
1597 printParamName(I, paramIndex, O);
1613 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1615 const Function *F = MF.getFunction();
1616 emitFunctionParamList(F, O);
1619 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1620 const MachineFunction &MF) {
1621 SmallString<128> Str;
1622 raw_svector_ostream O(Str);
1624 // Map the global virtual register number to a register class specific
1625 // virtual register number starting from 1 with that class.
1626 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1627 //unsigned numRegClasses = TRI->getNumRegClasses();
1629 // Emit the Fake Stack Object
1630 const MachineFrameInfo *MFI = MF.getFrameInfo();
1631 int NumBytes = (int) MFI->getStackSize();
1633 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1634 << getFunctionNumber() << "[" << NumBytes << "];\n";
1635 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1636 O << "\t.reg .b64 \t%SP;\n";
1637 O << "\t.reg .b64 \t%SPL;\n";
1639 O << "\t.reg .b32 \t%SP;\n";
1640 O << "\t.reg .b32 \t%SPL;\n";
1644 // Go through all virtual registers to establish the mapping between the
1646 // register number and the per class virtual register number.
1647 // We use the per class virtual register number in the ptx output.
1648 unsigned int numVRs = MRI->getNumVirtRegs();
1649 for (unsigned i = 0; i < numVRs; i++) {
1650 unsigned int vr = TRI->index2VirtReg(i);
1651 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1652 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1653 int n = regmap.size();
1654 regmap.insert(std::make_pair(vr, n + 1));
1657 // Emit register declarations
1658 // @TODO: Extract out the real register usage
1659 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1660 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1661 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1662 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1663 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1664 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1665 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1667 // Emit declaration of the virtual registers or 'physical' registers for
1668 // each register class
1669 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1670 const TargetRegisterClass *RC = TRI->getRegClass(i);
1671 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1672 std::string rcname = getNVPTXRegClassName(RC);
1673 std::string rcStr = getNVPTXRegClassStr(RC);
1674 int n = regmap.size();
1676 // Only declare those registers that may be used.
1678 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1683 OutStreamer->EmitRawText(O.str());
1686 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1687 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1689 unsigned int numHex;
1692 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1695 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1696 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1699 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1701 llvm_unreachable("unsupported fp type");
1703 APInt API = APF.bitcastToAPInt();
1704 std::string hexstr(utohexstr(API.getZExtValue()));
1706 if (hexstr.length() < numHex)
1707 O << std::string(numHex - hexstr.length(), '0');
1708 O << utohexstr(API.getZExtValue());
1711 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1712 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1713 O << CI->getValue();
1716 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1717 printFPConstant(CFP, O);
1720 if (isa<ConstantPointerNull>(CPV)) {
1724 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1725 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1726 bool IsNonGenericPointer = false;
1727 if (PTy && PTy->getAddressSpace() != 0) {
1728 IsNonGenericPointer = true;
1730 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1732 getSymbol(GVar)->print(O, MAI);
1735 getSymbol(GVar)->print(O, MAI);
1739 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1740 const Value *v = Cexpr->stripPointerCasts();
1741 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1742 bool IsNonGenericPointer = false;
1743 if (PTy && PTy->getAddressSpace() != 0) {
1744 IsNonGenericPointer = true;
1746 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1747 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1749 getSymbol(GVar)->print(O, MAI);
1752 getSymbol(GVar)->print(O, MAI);
1756 lowerConstant(CPV)->print(O, MAI);
1760 llvm_unreachable("Not scalar type found in printScalarConstant()");
1763 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1764 AggBuffer *aggBuffer) {
1766 const DataLayout *TD = TM.getDataLayout();
1768 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1769 int s = TD->getTypeAllocSize(CPV->getType());
1772 aggBuffer->addZeros(s);
1777 switch (CPV->getType()->getTypeID()) {
1779 case Type::IntegerTyID: {
1780 const Type *ETy = CPV->getType();
1781 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1782 unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
1784 aggBuffer->addBytes(ptr, 1, Bytes);
1785 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1786 short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
1787 ptr = (unsigned char *)&int16;
1788 aggBuffer->addBytes(ptr, 2, Bytes);
1789 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1790 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1791 int int32 = (int)(constInt->getZExtValue());
1792 ptr = (unsigned char *)&int32;
1793 aggBuffer->addBytes(ptr, 4, Bytes);
1795 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1796 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1797 ConstantFoldConstantExpression(Cexpr, *TD))) {
1798 int int32 = (int)(constInt->getZExtValue());
1799 ptr = (unsigned char *)&int32;
1800 aggBuffer->addBytes(ptr, 4, Bytes);
1803 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1804 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1805 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1806 aggBuffer->addZeros(4);
1810 llvm_unreachable("unsupported integer const type");
1811 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1812 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1813 long long int64 = (long long)(constInt->getZExtValue());
1814 ptr = (unsigned char *)&int64;
1815 aggBuffer->addBytes(ptr, 8, Bytes);
1817 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1818 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1819 ConstantFoldConstantExpression(Cexpr, *TD))) {
1820 long long int64 = (long long)(constInt->getZExtValue());
1821 ptr = (unsigned char *)&int64;
1822 aggBuffer->addBytes(ptr, 8, Bytes);
1825 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1826 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1827 aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1828 aggBuffer->addZeros(8);
1832 llvm_unreachable("unsupported integer const type");
1834 llvm_unreachable("unsupported integer const type");
1837 case Type::FloatTyID:
1838 case Type::DoubleTyID: {
1839 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1840 const Type *Ty = CFP->getType();
1841 if (Ty == Type::getFloatTy(CPV->getContext())) {
1842 float float32 = (float) CFP->getValueAPF().convertToFloat();
1843 ptr = (unsigned char *)&float32;
1844 aggBuffer->addBytes(ptr, 4, Bytes);
1845 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1846 double float64 = CFP->getValueAPF().convertToDouble();
1847 ptr = (unsigned char *)&float64;
1848 aggBuffer->addBytes(ptr, 8, Bytes);
1850 llvm_unreachable("unsupported fp const type");
1854 case Type::PointerTyID: {
1855 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1856 aggBuffer->addSymbol(GVar, GVar);
1857 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1858 const Value *v = Cexpr->stripPointerCasts();
1859 aggBuffer->addSymbol(v, Cexpr);
1861 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1862 aggBuffer->addZeros(s);
1866 case Type::ArrayTyID:
1867 case Type::VectorTyID:
1868 case Type::StructTyID: {
1869 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1870 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1871 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1872 bufferAggregateConstant(CPV, aggBuffer);
1873 if (Bytes > ElementSize)
1874 aggBuffer->addZeros(Bytes - ElementSize);
1875 } else if (isa<ConstantAggregateZero>(CPV))
1876 aggBuffer->addZeros(Bytes);
1878 llvm_unreachable("Unexpected Constant type");
1883 llvm_unreachable("unsupported type");
1887 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1888 AggBuffer *aggBuffer) {
1889 const DataLayout *TD = TM.getDataLayout();
1893 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1894 if (CPV->getNumOperands())
1895 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1896 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1900 if (const ConstantDataSequential *CDS =
1901 dyn_cast<ConstantDataSequential>(CPV)) {
1902 if (CDS->getNumElements())
1903 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1904 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1909 if (isa<ConstantStruct>(CPV)) {
1910 if (CPV->getNumOperands()) {
1911 StructType *ST = cast<StructType>(CPV->getType());
1912 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1914 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1915 TD->getTypeAllocSize(ST) -
1916 TD->getStructLayout(ST)->getElementOffset(i);
1918 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1919 TD->getStructLayout(ST)->getElementOffset(i);
1920 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1925 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1928 // buildTypeNameMap - Run through symbol table looking for type names.
1931 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1933 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1935 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1936 !PI->second.compare("struct._image2d_t") ||
1937 !PI->second.compare("struct._image3d_t")))
1944 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1945 switch (MI.getOpcode()) {
1948 case NVPTX::CallArgBeginInst:
1949 case NVPTX::CallArgEndInst0:
1950 case NVPTX::CallArgEndInst1:
1951 case NVPTX::CallArgF32:
1952 case NVPTX::CallArgF64:
1953 case NVPTX::CallArgI16:
1954 case NVPTX::CallArgI32:
1955 case NVPTX::CallArgI32imm:
1956 case NVPTX::CallArgI64:
1957 case NVPTX::CallArgParam:
1958 case NVPTX::CallVoidInst:
1959 case NVPTX::CallVoidInstReg:
1960 case NVPTX::Callseq_End:
1961 case NVPTX::CallVoidInstReg64:
1962 case NVPTX::DeclareParamInst:
1963 case NVPTX::DeclareRetMemInst:
1964 case NVPTX::DeclareRetRegInst:
1965 case NVPTX::DeclareRetScalarInst:
1966 case NVPTX::DeclareScalarParamInst:
1967 case NVPTX::DeclareScalarRegInst:
1968 case NVPTX::StoreParamF32:
1969 case NVPTX::StoreParamF64:
1970 case NVPTX::StoreParamI16:
1971 case NVPTX::StoreParamI32:
1972 case NVPTX::StoreParamI64:
1973 case NVPTX::StoreParamI8:
1974 case NVPTX::StoreRetvalF32:
1975 case NVPTX::StoreRetvalF64:
1976 case NVPTX::StoreRetvalI16:
1977 case NVPTX::StoreRetvalI32:
1978 case NVPTX::StoreRetvalI64:
1979 case NVPTX::StoreRetvalI8:
1980 case NVPTX::LastCallArgF32:
1981 case NVPTX::LastCallArgF64:
1982 case NVPTX::LastCallArgI16:
1983 case NVPTX::LastCallArgI32:
1984 case NVPTX::LastCallArgI32imm:
1985 case NVPTX::LastCallArgI64:
1986 case NVPTX::LastCallArgParam:
1987 case NVPTX::LoadParamMemF32:
1988 case NVPTX::LoadParamMemF64:
1989 case NVPTX::LoadParamMemI16:
1990 case NVPTX::LoadParamMemI32:
1991 case NVPTX::LoadParamMemI64:
1992 case NVPTX::LoadParamMemI8:
1993 case NVPTX::PrototypeInst:
1994 case NVPTX::DBG_VALUE:
2000 /// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
2001 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
2002 /// expressions that are representable in PTX and create
2003 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
2005 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2006 MCContext &Ctx = OutContext;
2008 if (CV->isNullValue() || isa<UndefValue>(CV))
2009 return MCConstantExpr::create(0, Ctx);
2011 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2012 return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2014 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2015 const MCSymbolRefExpr *Expr =
2016 MCSymbolRefExpr::create(getSymbol(GV), Ctx);
2017 if (ProcessingGeneric) {
2018 return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
2024 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2026 llvm_unreachable("Unknown constant value to lower!");
2029 switch (CE->getOpcode()) {
2031 // If the code isn't optimized, there may be outstanding folding
2032 // opportunities. Attempt to fold the expression using DataLayout as a
2033 // last resort before giving up.
2034 if (Constant *C = ConstantFoldConstantExpression(CE, *TM.getDataLayout()))
2036 return lowerConstantForGV(C, ProcessingGeneric);
2038 // Otherwise report the problem to the user.
2041 raw_string_ostream OS(S);
2042 OS << "Unsupported expression in static initializer: ";
2043 CE->printAsOperand(OS, /*PrintType=*/false,
2044 !MF ? nullptr : MF->getFunction()->getParent());
2045 report_fatal_error(OS.str());
2048 case Instruction::AddrSpaceCast: {
2049 // Strip the addrspacecast and pass along the operand
2050 PointerType *DstTy = cast<PointerType>(CE->getType());
2051 if (DstTy->getAddressSpace() == 0) {
2052 return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2055 raw_string_ostream OS(S);
2056 OS << "Unsupported expression in static initializer: ";
2057 CE->printAsOperand(OS, /*PrintType=*/ false,
2058 !MF ? 0 : MF->getFunction()->getParent());
2059 report_fatal_error(OS.str());
2062 case Instruction::GetElementPtr: {
2063 const DataLayout &DL = *TM.getDataLayout();
2065 // Generate a symbolic expression for the byte address
2066 APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2067 cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2069 const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2074 int64_t Offset = OffsetAI.getSExtValue();
2075 return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2079 case Instruction::Trunc:
2080 // We emit the value and depend on the assembler to truncate the generated
2081 // expression properly. This is important for differences between
2082 // blockaddress labels. Since the two labels are in the same function, it
2083 // is reasonable to treat their delta as a 32-bit value.
2085 case Instruction::BitCast:
2086 return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2088 case Instruction::IntToPtr: {
2089 const DataLayout &DL = *TM.getDataLayout();
2091 // Handle casts to pointers by changing them into casts to the appropriate
2092 // integer type. This promotes constant folding and simplifies this code.
2093 Constant *Op = CE->getOperand(0);
2094 Op = ConstantExpr::getIntegerCast(Op, DL.getIntPtrType(CV->getType()),
2096 return lowerConstantForGV(Op, ProcessingGeneric);
2099 case Instruction::PtrToInt: {
2100 const DataLayout &DL = *TM.getDataLayout();
2102 // Support only foldable casts to/from pointers that can be eliminated by
2103 // changing the pointer to the appropriately sized integer type.
2104 Constant *Op = CE->getOperand(0);
2105 Type *Ty = CE->getType();
2107 const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2109 // We can emit the pointer value into this slot if the slot is an
2110 // integer slot equal to the size of the pointer.
2111 if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2114 // Otherwise the pointer is smaller than the resultant integer, mask off
2115 // the high bits so we are sure to get a proper truncation if the input is
2117 unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2118 const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2119 return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2122 // The MC library also has a right-shift operator, but it isn't consistently
2123 // signed or unsigned between different targets.
2124 case Instruction::Add: {
2125 const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2126 const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2127 switch (CE->getOpcode()) {
2128 default: llvm_unreachable("Unknown binary operator constant cast expr");
2129 case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2135 // Copy of MCExpr::print customized for NVPTX
2136 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2137 switch (Expr.getKind()) {
2138 case MCExpr::Target:
2139 return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
2140 case MCExpr::Constant:
2141 OS << cast<MCConstantExpr>(Expr).getValue();
2144 case MCExpr::SymbolRef: {
2145 const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2146 const MCSymbol &Sym = SRE.getSymbol();
2151 case MCExpr::Unary: {
2152 const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2153 switch (UE.getOpcode()) {
2154 case MCUnaryExpr::LNot: OS << '!'; break;
2155 case MCUnaryExpr::Minus: OS << '-'; break;
2156 case MCUnaryExpr::Not: OS << '~'; break;
2157 case MCUnaryExpr::Plus: OS << '+'; break;
2159 printMCExpr(*UE.getSubExpr(), OS);
2163 case MCExpr::Binary: {
2164 const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2166 // Only print parens around the LHS if it is non-trivial.
2167 if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2168 isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2169 printMCExpr(*BE.getLHS(), OS);
2172 printMCExpr(*BE.getLHS(), OS);
2176 switch (BE.getOpcode()) {
2177 case MCBinaryExpr::Add:
2178 // Print "X-42" instead of "X+-42".
2179 if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2180 if (RHSC->getValue() < 0) {
2181 OS << RHSC->getValue();
2188 default: llvm_unreachable("Unhandled binary operator");
2191 // Only print parens around the LHS if it is non-trivial.
2192 if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2193 printMCExpr(*BE.getRHS(), OS);
2196 printMCExpr(*BE.getRHS(), OS);
2203 llvm_unreachable("Invalid expression kind!");
2206 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2208 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2209 unsigned AsmVariant,
2210 const char *ExtraCode, raw_ostream &O) {
2211 if (ExtraCode && ExtraCode[0]) {
2212 if (ExtraCode[1] != 0)
2213 return true; // Unknown modifier.
2215 switch (ExtraCode[0]) {
2217 // See if this is a generic print operand
2218 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2224 printOperand(MI, OpNo, O);
2229 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2230 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2231 const char *ExtraCode, raw_ostream &O) {
2232 if (ExtraCode && ExtraCode[0])
2233 return true; // Unknown modifier
2236 printMemOperand(MI, OpNo, O);
2242 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2243 raw_ostream &O, const char *Modifier) {
2244 const MachineOperand &MO = MI->getOperand(opNum);
2245 switch (MO.getType()) {
2246 case MachineOperand::MO_Register:
2247 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2248 if (MO.getReg() == NVPTX::VRDepot)
2249 O << DEPOTNAME << getFunctionNumber();
2251 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2253 emitVirtualRegister(MO.getReg(), O);
2257 case MachineOperand::MO_Immediate:
2260 else if (strstr(Modifier, "vec") == Modifier)
2261 printVecModifiedImmediate(MO, Modifier, O);
2264 "Don't know how to handle modifier on immediate operand");
2267 case MachineOperand::MO_FPImmediate:
2268 printFPConstant(MO.getFPImm(), O);
2271 case MachineOperand::MO_GlobalAddress:
2272 getSymbol(MO.getGlobal())->print(O, MAI);
2275 case MachineOperand::MO_MachineBasicBlock:
2276 MO.getMBB()->getSymbol()->print(O, MAI);
2280 llvm_unreachable("Operand type not supported.");
2284 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2285 raw_ostream &O, const char *Modifier) {
2286 printOperand(MI, opNum, O);
2288 if (Modifier && !strcmp(Modifier, "add")) {
2290 printOperand(MI, opNum + 1, O);
2292 if (MI->getOperand(opNum + 1).isImm() &&
2293 MI->getOperand(opNum + 1).getImm() == 0)
2294 return; // don't print ',0' or '+0'
2296 printOperand(MI, opNum + 1, O);
2300 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2301 std::stringstream temp;
2302 LineReader *reader = this->getReader(filename);
2304 temp << filename.str();
2308 temp << reader->readLine(line);
2310 this->OutStreamer->EmitRawText(temp.str());
2313 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2315 reader = new LineReader(filename);
2318 if (reader->fileName() != filename) {
2320 reader = new LineReader(filename);
2326 std::string LineReader::readLine(unsigned lineNum) {
2327 if (lineNum < theCurLine) {
2329 fstr.seekg(0, std::ios::beg);
2331 while (theCurLine < lineNum) {
2332 fstr.getline(buff, 500);
2338 // Force static initialization.
2339 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2340 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2341 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);