1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMachineFunctionInfo.h"
21 #include "NVPTXMCExpr.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TimeValue.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
51 #define DEPOTNAME "__local_depot"
54 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
55 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
60 cl::desc("NVPTX Specific: Emit source line in ptx file"),
64 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
66 void DiscoverDependentGlobals(const Value *V,
67 DenseSet<const GlobalVariable *> &Globals) {
68 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
71 if (const User *U = dyn_cast<User>(V)) {
72 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
73 DiscoverDependentGlobals(U->getOperand(i), Globals);
79 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
80 /// instances to be emitted, but only after any dependents have been added
82 void VisitGlobalVariableForEmission(
83 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
84 DenseSet<const GlobalVariable *> &Visited,
85 DenseSet<const GlobalVariable *> &Visiting) {
86 // Have we already visited this one?
87 if (Visited.count(GV))
90 // Do we have a circular dependency?
91 if (!Visiting.insert(GV).second)
92 report_fatal_error("Circular dependency found in global variable set");
94 // Make sure we visit all dependents first
95 DenseSet<const GlobalVariable *> Others;
96 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
97 DiscoverDependentGlobals(GV->getOperand(i), Others);
99 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
102 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
104 // Now we can visit ourself
111 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
112 if (!EmitLineNumbers)
117 DebugLoc curLoc = MI.getDebugLoc();
119 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
122 if (prevDebugLoc == curLoc)
125 prevDebugLoc = curLoc;
127 if (curLoc.isUnknown())
130 const MachineFunction *MF = MI.getParent()->getParent();
131 //const TargetMachine &TM = MF->getTarget();
133 const LLVMContext &ctx = MF->getFunction()->getContext();
134 DIScope Scope(curLoc.getScope(ctx));
136 assert((!Scope || Scope.isScope()) &&
137 "Scope of a DebugLoc should be null or a DIScope.");
141 StringRef fileName(Scope.getFilename());
142 StringRef dirName(Scope.getDirectory());
143 SmallString<128> FullPathName = dirName;
144 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
145 sys::path::append(FullPathName, fileName);
146 fileName = FullPathName.str();
149 if (filenameMap.find(fileName.str()) == filenameMap.end())
152 // Emit the line from the source file.
154 this->emitSrcInText(fileName.str(), curLoc.getLine());
156 std::stringstream temp;
157 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
158 << " " << curLoc.getCol();
159 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
162 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
163 SmallString<128> Str;
164 raw_svector_ostream OS(Str);
165 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
166 emitLineNumberAsDotLoc(*MI);
169 lowerToMCInst(MI, Inst);
170 EmitToStreamer(OutStreamer, Inst);
173 // Handle symbol backtracking for targets that do not support image handles
174 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
175 unsigned OpNo, MCOperand &MCOp) {
176 const MachineOperand &MO = MI->getOperand(OpNo);
177 const MCInstrDesc &MCID = MI->getDesc();
179 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
180 // This is a texture fetch, so operand 4 is a texref and operand 5 is
182 if (OpNo == 4 && MO.isImm()) {
183 lowerImageHandleSymbol(MO.getImm(), MCOp);
186 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
187 lowerImageHandleSymbol(MO.getImm(), MCOp);
192 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
194 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
196 // For a surface load of vector size N, the Nth operand will be the surfref
197 if (OpNo == VecSize && MO.isImm()) {
198 lowerImageHandleSymbol(MO.getImm(), MCOp);
203 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
204 // This is a surface store, so operand 0 is a surfref
205 if (OpNo == 0 && MO.isImm()) {
206 lowerImageHandleSymbol(MO.getImm(), MCOp);
211 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
212 // This is a query, so operand 1 is a surfref/texref
213 if (OpNo == 1 && MO.isImm()) {
214 lowerImageHandleSymbol(MO.getImm(), MCOp);
224 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
226 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
227 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
228 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
229 const char *Sym = MFI->getImageHandleSymbol(Index);
230 std::string *SymNamePtr =
231 nvTM.getManagedStrPool()->getManagedString(Sym);
232 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
233 StringRef(SymNamePtr->c_str())));
236 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
237 OutMI.setOpcode(MI->getOpcode());
238 const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
240 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
241 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
242 const MachineOperand &MO = MI->getOperand(0);
243 OutMI.addOperand(GetSymbolRef(
244 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
248 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
249 const MachineOperand &MO = MI->getOperand(i);
252 if (!ST.hasImageHandles()) {
253 if (lowerImageHandleOperand(MI, i, MCOp)) {
254 OutMI.addOperand(MCOp);
259 if (lowerOperand(MO, MCOp))
260 OutMI.addOperand(MCOp);
264 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
266 switch (MO.getType()) {
267 default: llvm_unreachable("unknown operand type");
268 case MachineOperand::MO_Register:
269 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
271 case MachineOperand::MO_Immediate:
272 MCOp = MCOperand::CreateImm(MO.getImm());
274 case MachineOperand::MO_MachineBasicBlock:
275 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
276 MO.getMBB()->getSymbol(), OutContext));
278 case MachineOperand::MO_ExternalSymbol:
279 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
281 case MachineOperand::MO_GlobalAddress:
282 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
284 case MachineOperand::MO_FPImmediate: {
285 const ConstantFP *Cnt = MO.getFPImm();
286 APFloat Val = Cnt->getValueAPF();
288 switch (Cnt->getType()->getTypeID()) {
289 default: report_fatal_error("Unsupported FP type"); break;
290 case Type::FloatTyID:
291 MCOp = MCOperand::CreateExpr(
292 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
294 case Type::DoubleTyID:
295 MCOp = MCOperand::CreateExpr(
296 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
305 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
306 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
307 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
309 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
310 unsigned RegNum = RegMap[Reg];
312 // Encode the register class in the upper 4 bits
313 // Must be kept in sync with NVPTXInstPrinter::printRegName
315 if (RC == &NVPTX::Int1RegsRegClass) {
317 } else if (RC == &NVPTX::Int16RegsRegClass) {
319 } else if (RC == &NVPTX::Int32RegsRegClass) {
321 } else if (RC == &NVPTX::Int64RegsRegClass) {
323 } else if (RC == &NVPTX::Float32RegsRegClass) {
325 } else if (RC == &NVPTX::Float64RegsRegClass) {
328 report_fatal_error("Bad register class");
331 // Insert the vreg number
332 Ret |= (RegNum & 0x0FFFFFFF);
335 // Some special-use registers are actually physical registers.
336 // Encode this as the register class ID of 0 and the real register ID.
337 return Reg & 0x0FFFFFFF;
341 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
343 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
345 return MCOperand::CreateExpr(Expr);
348 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
349 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
350 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
352 Type *Ty = F->getReturnType();
354 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
356 if (Ty->getTypeID() == Type::VoidTyID)
362 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
364 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
365 size = ITy->getBitWidth();
369 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
370 size = Ty->getPrimitiveSizeInBits();
373 O << ".param .b" << size << " func_retval0";
374 } else if (isa<PointerType>(Ty)) {
375 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
378 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
379 unsigned totalsz = TD->getTypeAllocSize(Ty);
380 unsigned retAlignment = 0;
381 if (!llvm::getAlign(*F, 0, retAlignment))
382 retAlignment = TD->getABITypeAlignment(Ty);
383 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
386 assert(false && "Unknown return type");
389 SmallVector<EVT, 16> vtparts;
390 ComputeValueVTs(*TLI, Ty, vtparts);
392 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
394 EVT elemtype = vtparts[i];
395 if (vtparts[i].isVector()) {
396 elems = vtparts[i].getVectorNumElements();
397 elemtype = vtparts[i].getVectorElementType();
400 for (unsigned j = 0, je = elems; j != je; ++j) {
401 unsigned sz = elemtype.getSizeInBits();
402 if (elemtype.isInteger() && (sz < 32))
404 O << ".reg .b" << sz << " func_retval" << idx;
417 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
419 const Function *F = MF.getFunction();
420 printReturnValStr(F, O);
423 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
424 SmallString<128> Str;
425 raw_svector_ostream O(Str);
427 if (!GlobalsEmitted) {
428 emitGlobals(*MF->getFunction()->getParent());
429 GlobalsEmitted = true;
433 MRI = &MF->getRegInfo();
434 F = MF->getFunction();
435 emitLinkageDirective(F, O);
436 if (llvm::isKernelFunction(*F))
440 printReturnValStr(*MF, O);
445 emitFunctionParamList(*MF, O);
447 if (llvm::isKernelFunction(*F))
448 emitKernelFunctionDirectives(*F, O);
450 OutStreamer.EmitRawText(O.str());
452 prevDebugLoc = DebugLoc();
455 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
457 OutStreamer.EmitRawText(StringRef("{\n"));
458 setAndEmitFunctionVirtualRegisters(*MF);
460 SmallString<128> Str;
461 raw_svector_ostream O(Str);
462 emitDemotedVars(MF->getFunction(), O);
463 OutStreamer.EmitRawText(O.str());
466 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
467 OutStreamer.EmitRawText(StringRef("}\n"));
471 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
472 unsigned RegNo = MI->getOperand(0).getReg();
473 const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
474 if (TRI->isVirtualRegister(RegNo)) {
475 OutStreamer.AddComment(Twine("implicit-def: ") +
476 getVirtualRegisterName(RegNo));
478 OutStreamer.AddComment(
479 Twine("implicit-def: ") +
480 TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
482 OutStreamer.AddBlankLine();
485 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
486 raw_ostream &O) const {
487 // If the NVVM IR has some of reqntid* specified, then output
488 // the reqntid directive, and set the unspecified ones to 1.
489 // If none of reqntid* is specified, don't output reqntid directive.
490 unsigned reqntidx, reqntidy, reqntidz;
491 bool specified = false;
492 if (llvm::getReqNTIDx(F, reqntidx) == false)
496 if (llvm::getReqNTIDy(F, reqntidy) == false)
500 if (llvm::getReqNTIDz(F, reqntidz) == false)
506 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
509 // If the NVVM IR has some of maxntid* specified, then output
510 // the maxntid directive, and set the unspecified ones to 1.
511 // If none of maxntid* is specified, don't output maxntid directive.
512 unsigned maxntidx, maxntidy, maxntidz;
514 if (llvm::getMaxNTIDx(F, maxntidx) == false)
518 if (llvm::getMaxNTIDy(F, maxntidy) == false)
522 if (llvm::getMaxNTIDz(F, maxntidz) == false)
528 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
532 if (llvm::getMinCTASm(F, mincta))
533 O << ".minnctapersm " << mincta << "\n";
537 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
538 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
541 raw_string_ostream NameStr(Name);
543 VRegRCMap::const_iterator I = VRegMapping.find(RC);
544 assert(I != VRegMapping.end() && "Bad register class");
545 const DenseMap<unsigned, unsigned> &RegMap = I->second;
547 VRegMap::const_iterator VI = RegMap.find(Reg);
548 assert(VI != RegMap.end() && "Bad virtual register");
549 unsigned MappedVR = VI->second;
551 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
557 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
559 O << getVirtualRegisterName(vr);
562 void NVPTXAsmPrinter::printVecModifiedImmediate(
563 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
564 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
565 int Imm = (int) MO.getImm();
566 if (0 == strcmp(Modifier, "vecelem"))
567 O << "_" << vecelem[Imm];
568 else if (0 == strcmp(Modifier, "vecv4comm1")) {
569 if ((Imm < 0) || (Imm > 3))
571 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
572 if ((Imm < 4) || (Imm > 7))
574 } else if (0 == strcmp(Modifier, "vecv4pos")) {
577 O << "_" << vecelem[Imm % 4];
578 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
579 if ((Imm < 0) || (Imm > 1))
581 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
582 if ((Imm < 2) || (Imm > 3))
584 } else if (0 == strcmp(Modifier, "vecv2pos")) {
587 O << "_" << vecelem[Imm % 2];
589 llvm_unreachable("Unknown Modifier on immediate operand");
594 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
596 emitLinkageDirective(F, O);
597 if (llvm::isKernelFunction(*F))
601 printReturnValStr(F, O);
602 O << *getSymbol(F) << "\n";
603 emitFunctionParamList(F, O);
607 static bool usedInGlobalVarDef(const Constant *C) {
611 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
612 if (GV->getName().str() == "llvm.used")
617 for (const User *U : C->users())
618 if (const Constant *C = dyn_cast<Constant>(U))
619 if (usedInGlobalVarDef(C))
625 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
626 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
627 if (othergv->getName().str() == "llvm.used")
631 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
632 if (instr->getParent() && instr->getParent()->getParent()) {
633 const Function *curFunc = instr->getParent()->getParent();
634 if (oneFunc && (curFunc != oneFunc))
642 for (const User *UU : U->users())
643 if (usedInOneFunc(UU, oneFunc) == false)
649 /* Find out if a global variable can be demoted to local scope.
650 * Currently, this is valid for CUDA shared variables, which have local
651 * scope and global lifetime. So the conditions to check are :
652 * 1. Is the global variable in shared address space?
653 * 2. Does it have internal linkage?
654 * 3. Is the global variable referenced only in one function?
656 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
657 if (gv->hasInternalLinkage() == false)
659 const PointerType *Pty = gv->getType();
660 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
663 const Function *oneFunc = nullptr;
665 bool flag = usedInOneFunc(gv, oneFunc);
674 static bool useFuncSeen(const Constant *C,
675 llvm::DenseMap<const Function *, bool> &seenMap) {
676 for (const User *U : C->users()) {
677 if (const Constant *cu = dyn_cast<Constant>(U)) {
678 if (useFuncSeen(cu, seenMap))
680 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
681 const BasicBlock *bb = I->getParent();
684 const Function *caller = bb->getParent();
687 if (seenMap.find(caller) != seenMap.end())
694 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
695 llvm::DenseMap<const Function *, bool> seenMap;
696 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
697 const Function *F = FI;
699 if (F->isDeclaration()) {
702 if (F->getIntrinsicID())
704 emitDeclaration(F, O);
707 for (const User *U : F->users()) {
708 if (const Constant *C = dyn_cast<Constant>(U)) {
709 if (usedInGlobalVarDef(C)) {
710 // The use is in the initialization of a global variable
711 // that is a function pointer, so print a declaration
712 // for the original function
713 emitDeclaration(F, O);
716 // Emit a declaration of this function if the function that
717 // uses this constant expr has already been seen.
718 if (useFuncSeen(C, seenMap)) {
719 emitDeclaration(F, O);
724 if (!isa<Instruction>(U))
726 const Instruction *instr = cast<Instruction>(U);
727 const BasicBlock *bb = instr->getParent();
730 const Function *caller = bb->getParent();
734 // If a caller has already been seen, then the caller is
735 // appearing in the module before the callee. so print out
736 // a declaration for the callee.
737 if (seenMap.find(caller) != seenMap.end()) {
738 emitDeclaration(F, O);
746 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
747 DebugInfoFinder DbgFinder;
748 DbgFinder.processModule(M);
751 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
752 StringRef Filename(DIUnit.getFilename());
753 StringRef Dirname(DIUnit.getDirectory());
754 SmallString<128> FullPathName = Dirname;
755 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
756 sys::path::append(FullPathName, Filename);
757 Filename = FullPathName.str();
759 if (filenameMap.find(Filename.str()) != filenameMap.end())
761 filenameMap[Filename.str()] = i;
762 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
766 for (DISubprogram SP : DbgFinder.subprograms()) {
767 StringRef Filename(SP.getFilename());
768 StringRef Dirname(SP.getDirectory());
769 SmallString<128> FullPathName = Dirname;
770 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
771 sys::path::append(FullPathName, Filename);
772 Filename = FullPathName.str();
774 if (filenameMap.find(Filename.str()) != filenameMap.end())
776 filenameMap[Filename.str()] = i;
781 bool NVPTXAsmPrinter::doInitialization(Module &M) {
783 SmallString<128> Str1;
784 raw_svector_ostream OS1(Str1);
786 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
787 MMI->AnalyzeModule(M);
789 // We need to call the parent's one explicitly.
790 //bool Result = AsmPrinter::doInitialization(M);
792 // Initialize TargetLoweringObjectFile.
793 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
794 .Initialize(OutContext, TM);
796 Mang = new Mangler(TM.getSubtargetImpl()->getDataLayout());
798 // Emit header before any dwarf directives are emitted below.
800 OutStreamer.EmitRawText(OS1.str());
802 // Already commented out
803 //bool Result = AsmPrinter::doInitialization(M);
805 // Emit module-level inline asm if it exists.
806 if (!M.getModuleInlineAsm().empty()) {
807 OutStreamer.AddComment("Start of file scope inline assembly");
808 OutStreamer.AddBlankLine();
809 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
810 OutStreamer.AddBlankLine();
811 OutStreamer.AddComment("End of file scope inline assembly");
812 OutStreamer.AddBlankLine();
815 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
816 recordAndEmitFilenames(M);
818 GlobalsEmitted = false;
820 return false; // success
823 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
824 SmallString<128> Str2;
825 raw_svector_ostream OS2(Str2);
827 emitDeclarations(M, OS2);
829 // As ptxas does not support forward references of globals, we need to first
830 // sort the list of module-level globals in def-use order. We visit each
831 // global variable in order, and ensure that we emit it *after* its dependent
832 // globals. We use a little extra memory maintaining both a set and a list to
833 // have fast searches while maintaining a strict ordering.
834 SmallVector<const GlobalVariable *, 8> Globals;
835 DenseSet<const GlobalVariable *> GVVisited;
836 DenseSet<const GlobalVariable *> GVVisiting;
838 // Visit each global variable, in order
839 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
841 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
843 assert(GVVisited.size() == M.getGlobalList().size() &&
844 "Missed a global variable");
845 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
847 // Print out module-level global variables in proper order
848 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
849 printModuleLevelGV(Globals[i], OS2);
853 OutStreamer.EmitRawText(OS2.str());
856 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
858 O << "// Generated by LLVM NVPTX Back-End\n";
862 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
863 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
866 O << nvptxSubtarget.getTargetName();
868 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
869 O << ", texmode_independent";
870 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
871 if (!nvptxSubtarget.hasDouble())
872 O << ", map_f64_to_f32";
875 if (MAI->doesSupportDebugInformation())
880 O << ".address_size ";
881 if (nvptxSubtarget.is64Bit())
890 bool NVPTXAsmPrinter::doFinalization(Module &M) {
892 // If we did not emit any functions, then the global declarations have not
894 if (!GlobalsEmitted) {
896 GlobalsEmitted = true;
899 // XXX Temproarily remove global variables so that doFinalization() will not
900 // emit them again (global variables are emitted at beginning).
902 Module::GlobalListType &global_list = M.getGlobalList();
903 int i, n = global_list.size();
904 GlobalVariable **gv_array = new GlobalVariable *[n];
906 // first, back-up GlobalVariable in gv_array
908 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
912 // second, empty global_list
913 while (!global_list.empty())
914 global_list.remove(global_list.begin());
916 // call doFinalization
917 bool ret = AsmPrinter::doFinalization(M);
919 // now we restore global variables
920 for (i = 0; i < n; i++)
921 global_list.insert(global_list.end(), gv_array[i]);
923 clearAnnotationCache(&M);
928 //bool Result = AsmPrinter::doFinalization(M);
929 // Instead of calling the parents doFinalization, we may
930 // clone parents doFinalization and customize here.
931 // Currently, we if NVISA out the EmitGlobals() in
932 // parent's doFinalization, which is too intrusive.
934 // Same for the doInitialization.
938 // This function emits appropriate linkage directives for
939 // functions and global variables.
941 // extern function declaration -> .extern
942 // extern function definition -> .visible
943 // external global variable with init -> .visible
944 // external without init -> .extern
945 // appending -> not allowed, assert.
946 // for any linkage other than
947 // internal, private, linker_private,
948 // linker_private_weak, linker_private_weak_def_auto,
951 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
953 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
954 if (V->hasExternalLinkage()) {
955 if (isa<GlobalVariable>(V)) {
956 const GlobalVariable *GVar = cast<GlobalVariable>(V);
958 if (GVar->hasInitializer())
963 } else if (V->isDeclaration())
967 } else if (V->hasAppendingLinkage()) {
969 msg.append("Error: ");
970 msg.append("Symbol ");
972 msg.append(V->getName().str());
973 msg.append("has unsupported appending linkage type");
974 llvm_unreachable(msg.c_str());
975 } else if (!V->hasInternalLinkage() &&
976 !V->hasPrivateLinkage()) {
982 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
984 bool processDemoted) {
987 if (GVar->hasSection()) {
988 if (GVar->getSection() == StringRef("llvm.metadata"))
992 // Skip LLVM intrinsic global variables
993 if (GVar->getName().startswith("llvm.") ||
994 GVar->getName().startswith("nvvm."))
997 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
999 // GlobalVariables are always constant pointers themselves.
1000 const PointerType *PTy = GVar->getType();
1001 Type *ETy = PTy->getElementType();
1003 if (GVar->hasExternalLinkage()) {
1004 if (GVar->hasInitializer())
1008 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1009 GVar->hasAvailableExternallyLinkage() ||
1010 GVar->hasCommonLinkage()) {
1014 if (llvm::isTexture(*GVar)) {
1015 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1019 if (llvm::isSurface(*GVar)) {
1020 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1024 if (GVar->isDeclaration()) {
1025 // (extern) declarations, no definition or initializer
1026 // Currently the only known declaration is for an automatic __local
1027 // (.shared) promoted to global.
1028 emitPTXGlobalVariable(GVar, O);
1033 if (llvm::isSampler(*GVar)) {
1034 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1036 const Constant *Initializer = nullptr;
1037 if (GVar->hasInitializer())
1038 Initializer = GVar->getInitializer();
1039 const ConstantInt *CI = nullptr;
1041 CI = dyn_cast<ConstantInt>(Initializer);
1043 unsigned sample = CI->getZExtValue();
1048 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1050 O << "addr_mode_" << i << " = ";
1056 O << "clamp_to_border";
1059 O << "clamp_to_edge";
1070 O << "filter_mode = ";
1071 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1079 llvm_unreachable("Anisotropic filtering is not supported");
1084 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1085 O << ", force_unnormalized_coords = 1";
1094 if (GVar->hasPrivateLinkage()) {
1096 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1099 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1100 if (!strncmp(GVar->getName().data(), "filename", 8))
1102 if (GVar->use_empty())
1106 const Function *demotedFunc = nullptr;
1107 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1108 O << "// " << GVar->getName().str() << " has been demoted\n";
1109 if (localDecls.find(demotedFunc) != localDecls.end())
1110 localDecls[demotedFunc].push_back(GVar);
1112 std::vector<const GlobalVariable *> temp;
1113 temp.push_back(GVar);
1114 localDecls[demotedFunc] = temp;
1120 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1122 if (isManaged(*GVar)) {
1123 O << " .attribute(.managed)";
1126 if (GVar->getAlignment() == 0)
1127 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1129 O << " .align " << GVar->getAlignment();
1131 if (ETy->isSingleValueType()) {
1133 // Special case: ABI requires that we use .u8 for predicates
1134 if (ETy->isIntegerTy(1))
1137 O << getPTXFundamentalTypeStr(ETy, false);
1139 O << *getSymbol(GVar);
1141 // Ptx allows variable initilization only for constant and global state
1143 if (GVar->hasInitializer()) {
1144 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1145 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1146 const Constant *Initializer = GVar->getInitializer();
1147 // 'undef' is treated as there is no value spefied.
1148 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1150 printScalarConstant(Initializer, O);
1153 // The frontend adds zero-initializer to variables that don't have an
1154 // initial value, so skip warning for this case.
1155 if (!GVar->getInitializer()->isNullValue()) {
1156 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1157 "' is not allowed in addrspace(" +
1158 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1159 report_fatal_error(warnMsg.c_str());
1164 unsigned int ElementSize = 0;
1166 // Although PTX has direct support for struct type and array type and
1167 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1168 // targets that support these high level field accesses. Structs, arrays
1169 // and vectors are lowered into arrays of bytes.
1170 switch (ETy->getTypeID()) {
1171 case Type::StructTyID:
1172 case Type::ArrayTyID:
1173 case Type::VectorTyID:
1174 ElementSize = TD->getTypeStoreSize(ETy);
1175 // Ptx allows variable initilization only for constant and
1176 // global state spaces.
1177 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1178 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1179 GVar->hasInitializer()) {
1180 const Constant *Initializer = GVar->getInitializer();
1181 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1182 AggBuffer aggBuffer(ElementSize, O, *this);
1183 bufferAggregateConstant(Initializer, &aggBuffer);
1184 if (aggBuffer.numSymbols) {
1185 if (nvptxSubtarget.is64Bit()) {
1186 O << " .u64 " << *getSymbol(GVar) << "[";
1187 O << ElementSize / 8;
1189 O << " .u32 " << *getSymbol(GVar) << "[";
1190 O << ElementSize / 4;
1194 O << " .b8 " << *getSymbol(GVar) << "[";
1202 O << " .b8 " << *getSymbol(GVar);
1210 O << " .b8 " << *getSymbol(GVar);
1219 llvm_unreachable("type not supported yet");
1226 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1227 if (localDecls.find(f) == localDecls.end())
1230 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1232 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1233 O << "\t// demoted variable\n\t";
1234 printModuleLevelGV(gvars[i], O, true);
1238 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1239 raw_ostream &O) const {
1240 switch (AddressSpace) {
1241 case llvm::ADDRESS_SPACE_LOCAL:
1244 case llvm::ADDRESS_SPACE_GLOBAL:
1247 case llvm::ADDRESS_SPACE_CONST:
1250 case llvm::ADDRESS_SPACE_SHARED:
1254 report_fatal_error("Bad address space found while emitting PTX");
1260 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1261 switch (Ty->getTypeID()) {
1263 llvm_unreachable("unexpected type");
1265 case Type::IntegerTyID: {
1266 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1269 else if (NumBits <= 64) {
1270 std::string name = "u";
1271 return name + utostr(NumBits);
1273 llvm_unreachable("Integer too large");
1278 case Type::FloatTyID:
1280 case Type::DoubleTyID:
1282 case Type::PointerTyID:
1283 if (nvptxSubtarget.is64Bit())
1293 llvm_unreachable("unexpected type");
1297 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1300 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1302 // GlobalVariables are always constant pointers themselves.
1303 const PointerType *PTy = GVar->getType();
1304 Type *ETy = PTy->getElementType();
1307 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1308 if (GVar->getAlignment() == 0)
1309 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1311 O << " .align " << GVar->getAlignment();
1313 if (ETy->isSingleValueType()) {
1315 O << getPTXFundamentalTypeStr(ETy);
1317 O << *getSymbol(GVar);
1321 int64_t ElementSize = 0;
1323 // Although PTX has direct support for struct type and array type and LLVM IR
1324 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1325 // support these high level field accesses. Structs and arrays are lowered
1326 // into arrays of bytes.
1327 switch (ETy->getTypeID()) {
1328 case Type::StructTyID:
1329 case Type::ArrayTyID:
1330 case Type::VectorTyID:
1331 ElementSize = TD->getTypeStoreSize(ETy);
1332 O << " .b8 " << *getSymbol(GVar) << "[";
1334 O << itostr(ElementSize);
1339 llvm_unreachable("type not supported yet");
1344 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1345 if (Ty->isSingleValueType())
1346 return TD->getPrefTypeAlignment(Ty);
1348 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1350 return getOpenCLAlignment(TD, ATy->getElementType());
1352 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1354 Type *ETy = VTy->getElementType();
1355 unsigned int numE = VTy->getNumElements();
1356 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1360 return numE * alignE;
1363 const StructType *STy = dyn_cast<StructType>(Ty);
1365 unsigned int alignStruct = 1;
1366 // Go through each element of the struct and find the
1367 // largest alignment.
1368 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1369 Type *ETy = STy->getElementType(i);
1370 unsigned int align = getOpenCLAlignment(TD, ETy);
1371 if (align > alignStruct)
1372 alignStruct = align;
1377 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1379 return TD->getPointerPrefAlignment();
1380 return TD->getPrefTypeAlignment(Ty);
1383 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1384 int paramIndex, raw_ostream &O) {
1385 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1386 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1387 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1389 std::string argName = I->getName();
1390 const char *p = argName.c_str();
1401 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1402 Function::const_arg_iterator I, E;
1405 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1406 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1407 O << *CurrentFnSym << "_param_" << paramIndex;
1411 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1412 if (i == paramIndex) {
1413 printParamName(I, paramIndex, O);
1417 llvm_unreachable("paramIndex out of bound");
1420 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1421 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1422 const AttributeSet &PAL = F->getAttributes();
1423 const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1424 Function::const_arg_iterator I, E;
1425 unsigned paramIndex = 0;
1427 bool isKernelFunc = llvm::isKernelFunction(*F);
1428 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1429 MVT thePointerTy = TLI->getPointerTy();
1433 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1434 Type *Ty = I->getType();
1441 // Handle image/sampler parameters
1442 if (isKernelFunction(*F)) {
1443 if (isSampler(*I) || isImage(*I)) {
1445 std::string sname = I->getName();
1446 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1447 if (nvptxSubtarget.hasImageHandles())
1448 O << "\t.param .u64 .ptr .surfref ";
1450 O << "\t.param .surfref ";
1451 O << *CurrentFnSym << "_param_" << paramIndex;
1453 else { // Default image is read_only
1454 if (nvptxSubtarget.hasImageHandles())
1455 O << "\t.param .u64 .ptr .texref ";
1457 O << "\t.param .texref ";
1458 O << *CurrentFnSym << "_param_" << paramIndex;
1461 if (nvptxSubtarget.hasImageHandles())
1462 O << "\t.param .u64 .ptr .samplerref ";
1464 O << "\t.param .samplerref ";
1465 O << *CurrentFnSym << "_param_" << paramIndex;
1471 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1472 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1473 // Just print .param .align <a> .b8 .param[size];
1474 // <a> = PAL.getparamalignment
1475 // size = typeallocsize of element type
1476 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1478 align = TD->getABITypeAlignment(Ty);
1480 unsigned sz = TD->getTypeAllocSize(Ty);
1481 O << "\t.param .align " << align << " .b8 ";
1482 printParamName(I, paramIndex, O);
1483 O << "[" << sz << "]";
1488 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1491 // Special handling for pointer arguments to kernel
1492 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1494 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1495 Type *ETy = PTy->getElementType();
1496 int addrSpace = PTy->getAddressSpace();
1497 switch (addrSpace) {
1501 case llvm::ADDRESS_SPACE_CONST:
1502 O << ".ptr .const ";
1504 case llvm::ADDRESS_SPACE_SHARED:
1505 O << ".ptr .shared ";
1507 case llvm::ADDRESS_SPACE_GLOBAL:
1508 O << ".ptr .global ";
1511 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1513 printParamName(I, paramIndex, O);
1517 // non-pointer scalar to kernel func
1519 // Special case: predicate operands become .u8 types
1520 if (Ty->isIntegerTy(1))
1523 O << getPTXFundamentalTypeStr(Ty);
1525 printParamName(I, paramIndex, O);
1528 // Non-kernel function, just print .param .b<size> for ABI
1529 // and .reg .b<size> for non-ABI
1531 if (isa<IntegerType>(Ty)) {
1532 sz = cast<IntegerType>(Ty)->getBitWidth();
1535 } else if (isa<PointerType>(Ty))
1536 sz = thePointerTy.getSizeInBits();
1538 sz = Ty->getPrimitiveSizeInBits();
1540 O << "\t.param .b" << sz << " ";
1542 O << "\t.reg .b" << sz << " ";
1543 printParamName(I, paramIndex, O);
1547 // param has byVal attribute. So should be a pointer
1548 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1549 assert(PTy && "Param with byval attribute should be a pointer type");
1550 Type *ETy = PTy->getElementType();
1552 if (isABI || isKernelFunc) {
1553 // Just print .param .align <a> .b8 .param[size];
1554 // <a> = PAL.getparamalignment
1555 // size = typeallocsize of element type
1556 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1558 align = TD->getABITypeAlignment(ETy);
1560 unsigned sz = TD->getTypeAllocSize(ETy);
1561 O << "\t.param .align " << align << " .b8 ";
1562 printParamName(I, paramIndex, O);
1563 O << "[" << sz << "]";
1566 // Split the ETy into constituent parts and
1567 // print .param .b<size> <name> for each part.
1568 // Further, if a part is vector, print the above for
1569 // each vector element.
1570 SmallVector<EVT, 16> vtparts;
1571 ComputeValueVTs(*TLI, ETy, vtparts);
1572 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1574 EVT elemtype = vtparts[i];
1575 if (vtparts[i].isVector()) {
1576 elems = vtparts[i].getVectorNumElements();
1577 elemtype = vtparts[i].getVectorElementType();
1580 for (unsigned j = 0, je = elems; j != je; ++j) {
1581 unsigned sz = elemtype.getSizeInBits();
1582 if (elemtype.isInteger() && (sz < 32))
1584 O << "\t.reg .b" << sz << " ";
1585 printParamName(I, paramIndex, O);
1601 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1603 const Function *F = MF.getFunction();
1604 emitFunctionParamList(F, O);
1607 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1608 const MachineFunction &MF) {
1609 SmallString<128> Str;
1610 raw_svector_ostream O(Str);
1612 // Map the global virtual register number to a register class specific
1613 // virtual register number starting from 1 with that class.
1614 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1615 //unsigned numRegClasses = TRI->getNumRegClasses();
1617 // Emit the Fake Stack Object
1618 const MachineFrameInfo *MFI = MF.getFrameInfo();
1619 int NumBytes = (int) MFI->getStackSize();
1621 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1622 << getFunctionNumber() << "[" << NumBytes << "];\n";
1623 if (nvptxSubtarget.is64Bit()) {
1624 O << "\t.reg .b64 \t%SP;\n";
1625 O << "\t.reg .b64 \t%SPL;\n";
1627 O << "\t.reg .b32 \t%SP;\n";
1628 O << "\t.reg .b32 \t%SPL;\n";
1632 // Go through all virtual registers to establish the mapping between the
1634 // register number and the per class virtual register number.
1635 // We use the per class virtual register number in the ptx output.
1636 unsigned int numVRs = MRI->getNumVirtRegs();
1637 for (unsigned i = 0; i < numVRs; i++) {
1638 unsigned int vr = TRI->index2VirtReg(i);
1639 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1640 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1641 int n = regmap.size();
1642 regmap.insert(std::make_pair(vr, n + 1));
1645 // Emit register declarations
1646 // @TODO: Extract out the real register usage
1647 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1648 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1649 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1650 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1651 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1652 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1653 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1655 // Emit declaration of the virtual registers or 'physical' registers for
1656 // each register class
1657 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1658 const TargetRegisterClass *RC = TRI->getRegClass(i);
1659 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1660 std::string rcname = getNVPTXRegClassName(RC);
1661 std::string rcStr = getNVPTXRegClassStr(RC);
1662 int n = regmap.size();
1664 // Only declare those registers that may be used.
1666 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1671 OutStreamer.EmitRawText(O.str());
1674 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1675 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1677 unsigned int numHex;
1680 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1683 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1684 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1687 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1689 llvm_unreachable("unsupported fp type");
1691 APInt API = APF.bitcastToAPInt();
1692 std::string hexstr(utohexstr(API.getZExtValue()));
1694 if (hexstr.length() < numHex)
1695 O << std::string(numHex - hexstr.length(), '0');
1696 O << utohexstr(API.getZExtValue());
1699 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1700 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1701 O << CI->getValue();
1704 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1705 printFPConstant(CFP, O);
1708 if (isa<ConstantPointerNull>(CPV)) {
1712 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1713 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1714 bool IsNonGenericPointer = false;
1715 if (PTy && PTy->getAddressSpace() != 0) {
1716 IsNonGenericPointer = true;
1718 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1720 O << *getSymbol(GVar);
1723 O << *getSymbol(GVar);
1727 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1728 const Value *v = Cexpr->stripPointerCasts();
1729 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1730 bool IsNonGenericPointer = false;
1731 if (PTy && PTy->getAddressSpace() != 0) {
1732 IsNonGenericPointer = true;
1734 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1735 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1737 O << *getSymbol(GVar);
1740 O << *getSymbol(GVar);
1744 O << *lowerConstant(CPV);
1748 llvm_unreachable("Not scalar type found in printScalarConstant()");
1751 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1752 AggBuffer *aggBuffer) {
1754 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1756 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1757 int s = TD->getTypeAllocSize(CPV->getType());
1760 aggBuffer->addZeros(s);
1765 switch (CPV->getType()->getTypeID()) {
1767 case Type::IntegerTyID: {
1768 const Type *ETy = CPV->getType();
1769 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1771 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1773 aggBuffer->addBytes(ptr, 1, Bytes);
1774 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1775 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1776 ptr = (unsigned char *)&int16;
1777 aggBuffer->addBytes(ptr, 2, Bytes);
1778 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1779 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1780 int int32 = (int)(constInt->getZExtValue());
1781 ptr = (unsigned char *)&int32;
1782 aggBuffer->addBytes(ptr, 4, Bytes);
1784 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1785 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1786 ConstantFoldConstantExpression(Cexpr, TD))) {
1787 int int32 = (int)(constInt->getZExtValue());
1788 ptr = (unsigned char *)&int32;
1789 aggBuffer->addBytes(ptr, 4, Bytes);
1792 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1793 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1794 aggBuffer->addSymbol(v);
1795 aggBuffer->addZeros(4);
1799 llvm_unreachable("unsupported integer const type");
1800 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1801 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1802 long long int64 = (long long)(constInt->getZExtValue());
1803 ptr = (unsigned char *)&int64;
1804 aggBuffer->addBytes(ptr, 8, Bytes);
1806 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1807 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1808 ConstantFoldConstantExpression(Cexpr, TD))) {
1809 long long int64 = (long long)(constInt->getZExtValue());
1810 ptr = (unsigned char *)&int64;
1811 aggBuffer->addBytes(ptr, 8, Bytes);
1814 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1815 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1816 aggBuffer->addSymbol(v);
1817 aggBuffer->addZeros(8);
1821 llvm_unreachable("unsupported integer const type");
1823 llvm_unreachable("unsupported integer const type");
1826 case Type::FloatTyID:
1827 case Type::DoubleTyID: {
1828 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1829 const Type *Ty = CFP->getType();
1830 if (Ty == Type::getFloatTy(CPV->getContext())) {
1831 float float32 = (float) CFP->getValueAPF().convertToFloat();
1832 ptr = (unsigned char *)&float32;
1833 aggBuffer->addBytes(ptr, 4, Bytes);
1834 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1835 double float64 = CFP->getValueAPF().convertToDouble();
1836 ptr = (unsigned char *)&float64;
1837 aggBuffer->addBytes(ptr, 8, Bytes);
1839 llvm_unreachable("unsupported fp const type");
1843 case Type::PointerTyID: {
1844 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1845 aggBuffer->addSymbol(GVar);
1846 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1847 const Value *v = Cexpr->stripPointerCasts();
1848 aggBuffer->addSymbol(v);
1850 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1851 aggBuffer->addZeros(s);
1855 case Type::ArrayTyID:
1856 case Type::VectorTyID:
1857 case Type::StructTyID: {
1858 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1859 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1860 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1861 bufferAggregateConstant(CPV, aggBuffer);
1862 if (Bytes > ElementSize)
1863 aggBuffer->addZeros(Bytes - ElementSize);
1864 } else if (isa<ConstantAggregateZero>(CPV))
1865 aggBuffer->addZeros(Bytes);
1867 llvm_unreachable("Unexpected Constant type");
1872 llvm_unreachable("unsupported type");
1876 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1877 AggBuffer *aggBuffer) {
1878 const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1882 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1883 if (CPV->getNumOperands())
1884 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1885 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1889 if (const ConstantDataSequential *CDS =
1890 dyn_cast<ConstantDataSequential>(CPV)) {
1891 if (CDS->getNumElements())
1892 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1893 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1898 if (isa<ConstantStruct>(CPV)) {
1899 if (CPV->getNumOperands()) {
1900 StructType *ST = cast<StructType>(CPV->getType());
1901 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1903 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1904 TD->getTypeAllocSize(ST) -
1905 TD->getStructLayout(ST)->getElementOffset(i);
1907 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1908 TD->getStructLayout(ST)->getElementOffset(i);
1909 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1914 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1917 // buildTypeNameMap - Run through symbol table looking for type names.
1920 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1922 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1924 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1925 !PI->second.compare("struct._image2d_t") ||
1926 !PI->second.compare("struct._image3d_t")))
1933 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1934 switch (MI.getOpcode()) {
1937 case NVPTX::CallArgBeginInst:
1938 case NVPTX::CallArgEndInst0:
1939 case NVPTX::CallArgEndInst1:
1940 case NVPTX::CallArgF32:
1941 case NVPTX::CallArgF64:
1942 case NVPTX::CallArgI16:
1943 case NVPTX::CallArgI32:
1944 case NVPTX::CallArgI32imm:
1945 case NVPTX::CallArgI64:
1946 case NVPTX::CallArgParam:
1947 case NVPTX::CallVoidInst:
1948 case NVPTX::CallVoidInstReg:
1949 case NVPTX::Callseq_End:
1950 case NVPTX::CallVoidInstReg64:
1951 case NVPTX::DeclareParamInst:
1952 case NVPTX::DeclareRetMemInst:
1953 case NVPTX::DeclareRetRegInst:
1954 case NVPTX::DeclareRetScalarInst:
1955 case NVPTX::DeclareScalarParamInst:
1956 case NVPTX::DeclareScalarRegInst:
1957 case NVPTX::StoreParamF32:
1958 case NVPTX::StoreParamF64:
1959 case NVPTX::StoreParamI16:
1960 case NVPTX::StoreParamI32:
1961 case NVPTX::StoreParamI64:
1962 case NVPTX::StoreParamI8:
1963 case NVPTX::StoreRetvalF32:
1964 case NVPTX::StoreRetvalF64:
1965 case NVPTX::StoreRetvalI16:
1966 case NVPTX::StoreRetvalI32:
1967 case NVPTX::StoreRetvalI64:
1968 case NVPTX::StoreRetvalI8:
1969 case NVPTX::LastCallArgF32:
1970 case NVPTX::LastCallArgF64:
1971 case NVPTX::LastCallArgI16:
1972 case NVPTX::LastCallArgI32:
1973 case NVPTX::LastCallArgI32imm:
1974 case NVPTX::LastCallArgI64:
1975 case NVPTX::LastCallArgParam:
1976 case NVPTX::LoadParamMemF32:
1977 case NVPTX::LoadParamMemF64:
1978 case NVPTX::LoadParamMemI16:
1979 case NVPTX::LoadParamMemI32:
1980 case NVPTX::LoadParamMemI64:
1981 case NVPTX::LoadParamMemI8:
1982 case NVPTX::PrototypeInst:
1983 case NVPTX::DBG_VALUE:
1989 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1991 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1992 unsigned AsmVariant,
1993 const char *ExtraCode, raw_ostream &O) {
1994 if (ExtraCode && ExtraCode[0]) {
1995 if (ExtraCode[1] != 0)
1996 return true; // Unknown modifier.
1998 switch (ExtraCode[0]) {
2000 // See if this is a generic print operand
2001 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2007 printOperand(MI, OpNo, O);
2012 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2013 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2014 const char *ExtraCode, raw_ostream &O) {
2015 if (ExtraCode && ExtraCode[0])
2016 return true; // Unknown modifier
2019 printMemOperand(MI, OpNo, O);
2025 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2026 raw_ostream &O, const char *Modifier) {
2027 const MachineOperand &MO = MI->getOperand(opNum);
2028 switch (MO.getType()) {
2029 case MachineOperand::MO_Register:
2030 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2031 if (MO.getReg() == NVPTX::VRDepot)
2032 O << DEPOTNAME << getFunctionNumber();
2034 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2036 emitVirtualRegister(MO.getReg(), O);
2040 case MachineOperand::MO_Immediate:
2043 else if (strstr(Modifier, "vec") == Modifier)
2044 printVecModifiedImmediate(MO, Modifier, O);
2047 "Don't know how to handle modifier on immediate operand");
2050 case MachineOperand::MO_FPImmediate:
2051 printFPConstant(MO.getFPImm(), O);
2054 case MachineOperand::MO_GlobalAddress:
2055 O << *getSymbol(MO.getGlobal());
2058 case MachineOperand::MO_MachineBasicBlock:
2059 O << *MO.getMBB()->getSymbol();
2063 llvm_unreachable("Operand type not supported.");
2067 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2068 raw_ostream &O, const char *Modifier) {
2069 printOperand(MI, opNum, O);
2071 if (Modifier && !strcmp(Modifier, "add")) {
2073 printOperand(MI, opNum + 1, O);
2075 if (MI->getOperand(opNum + 1).isImm() &&
2076 MI->getOperand(opNum + 1).getImm() == 0)
2077 return; // don't print ',0' or '+0'
2079 printOperand(MI, opNum + 1, O);
2084 // Force static initialization.
2085 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2086 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2087 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2090 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2091 std::stringstream temp;
2092 LineReader *reader = this->getReader(filename.str());
2094 temp << filename.str();
2098 temp << reader->readLine(line);
2100 this->OutStreamer.EmitRawText(Twine(temp.str()));
2103 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2105 reader = new LineReader(filename);
2108 if (reader->fileName() != filename) {
2110 reader = new LineReader(filename);
2116 std::string LineReader::readLine(unsigned lineNum) {
2117 if (lineNum < theCurLine) {
2119 fstr.seekg(0, std::ios::beg);
2121 while (theCurLine < lineNum) {
2122 fstr.getline(buff, 500);
2128 // Force static initialization.
2129 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2130 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2131 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);