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/MCStreamer.h"
41 #include "llvm/MC/MCSymbol.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/FormattedStream.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TimeValue.h"
48 #include "llvm/Target/TargetLoweringObjectFile.h"
49 #include "llvm/Transforms/Utils/UnrollLoop.h"
53 #define DEPOTNAME "__local_depot"
56 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
57 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
61 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
62 cl::desc("NVPTX Specific: Emit source line in ptx file"),
66 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
68 void DiscoverDependentGlobals(const Value *V,
69 DenseSet<const GlobalVariable *> &Globals) {
70 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
73 if (const User *U = dyn_cast<User>(V)) {
74 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
75 DiscoverDependentGlobals(U->getOperand(i), Globals);
81 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
82 /// instances to be emitted, but only after any dependents have been added
84 void VisitGlobalVariableForEmission(
85 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
86 DenseSet<const GlobalVariable *> &Visited,
87 DenseSet<const GlobalVariable *> &Visiting) {
88 // Have we already visited this one?
89 if (Visited.count(GV))
92 // Do we have a circular dependency?
93 if (!Visiting.insert(GV).second)
94 report_fatal_error("Circular dependency found in global variable set");
96 // Make sure we visit all dependents first
97 DenseSet<const GlobalVariable *> Others;
98 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
99 DiscoverDependentGlobals(GV->getOperand(i), Others);
101 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
104 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
106 // Now we can visit ourself
113 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
114 if (!EmitLineNumbers)
119 DebugLoc curLoc = MI.getDebugLoc();
121 if (!prevDebugLoc && !curLoc)
124 if (prevDebugLoc == curLoc)
127 prevDebugLoc = curLoc;
132 DIScope Scope(curLoc.getScope());
134 assert((!Scope || Scope.isScope()) &&
135 "Scope of a DebugLoc should be null or a DIScope.");
139 StringRef fileName(Scope.getFilename());
140 StringRef dirName(Scope.getDirectory());
141 SmallString<128> FullPathName = dirName;
142 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
143 sys::path::append(FullPathName, fileName);
144 fileName = FullPathName;
147 if (filenameMap.find(fileName) == filenameMap.end())
150 // Emit the line from the source file.
152 this->emitSrcInText(fileName, curLoc.getLine());
154 std::stringstream temp;
155 temp << "\t.loc " << filenameMap[fileName] << " " << curLoc.getLine()
156 << " " << curLoc.getCol();
157 OutStreamer.EmitRawText(temp.str());
160 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
161 SmallString<128> Str;
162 raw_svector_ostream OS(Str);
163 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
164 emitLineNumberAsDotLoc(*MI);
167 lowerToMCInst(MI, Inst);
168 EmitToStreamer(OutStreamer, Inst);
171 // Handle symbol backtracking for targets that do not support image handles
172 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
173 unsigned OpNo, MCOperand &MCOp) {
174 const MachineOperand &MO = MI->getOperand(OpNo);
175 const MCInstrDesc &MCID = MI->getDesc();
177 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
178 // This is a texture fetch, so operand 4 is a texref and operand 5 is
180 if (OpNo == 4 && MO.isImm()) {
181 lowerImageHandleSymbol(MO.getImm(), MCOp);
184 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
185 lowerImageHandleSymbol(MO.getImm(), MCOp);
190 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
192 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
194 // For a surface load of vector size N, the Nth operand will be the surfref
195 if (OpNo == VecSize && MO.isImm()) {
196 lowerImageHandleSymbol(MO.getImm(), MCOp);
201 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
202 // This is a surface store, so operand 0 is a surfref
203 if (OpNo == 0 && MO.isImm()) {
204 lowerImageHandleSymbol(MO.getImm(), MCOp);
209 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
210 // This is a query, so operand 1 is a surfref/texref
211 if (OpNo == 1 && MO.isImm()) {
212 lowerImageHandleSymbol(MO.getImm(), MCOp);
222 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
224 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
225 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
226 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
227 const char *Sym = MFI->getImageHandleSymbol(Index);
228 std::string *SymNamePtr =
229 nvTM.getManagedStrPool()->getManagedString(Sym);
230 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
231 StringRef(SymNamePtr->c_str())));
234 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
235 OutMI.setOpcode(MI->getOpcode());
236 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
237 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
238 const MachineOperand &MO = MI->getOperand(0);
239 OutMI.addOperand(GetSymbolRef(
240 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
244 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
245 const MachineOperand &MO = MI->getOperand(i);
248 if (!nvptxSubtarget->hasImageHandles()) {
249 if (lowerImageHandleOperand(MI, i, MCOp)) {
250 OutMI.addOperand(MCOp);
255 if (lowerOperand(MO, MCOp))
256 OutMI.addOperand(MCOp);
260 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
262 switch (MO.getType()) {
263 default: llvm_unreachable("unknown operand type");
264 case MachineOperand::MO_Register:
265 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
267 case MachineOperand::MO_Immediate:
268 MCOp = MCOperand::CreateImm(MO.getImm());
270 case MachineOperand::MO_MachineBasicBlock:
271 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
272 MO.getMBB()->getSymbol(), OutContext));
274 case MachineOperand::MO_ExternalSymbol:
275 MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
277 case MachineOperand::MO_GlobalAddress:
278 MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
280 case MachineOperand::MO_FPImmediate: {
281 const ConstantFP *Cnt = MO.getFPImm();
282 APFloat Val = Cnt->getValueAPF();
284 switch (Cnt->getType()->getTypeID()) {
285 default: report_fatal_error("Unsupported FP type"); break;
286 case Type::FloatTyID:
287 MCOp = MCOperand::CreateExpr(
288 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
290 case Type::DoubleTyID:
291 MCOp = MCOperand::CreateExpr(
292 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
301 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
302 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
303 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
305 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
306 unsigned RegNum = RegMap[Reg];
308 // Encode the register class in the upper 4 bits
309 // Must be kept in sync with NVPTXInstPrinter::printRegName
311 if (RC == &NVPTX::Int1RegsRegClass) {
313 } else if (RC == &NVPTX::Int16RegsRegClass) {
315 } else if (RC == &NVPTX::Int32RegsRegClass) {
317 } else if (RC == &NVPTX::Int64RegsRegClass) {
319 } else if (RC == &NVPTX::Float32RegsRegClass) {
321 } else if (RC == &NVPTX::Float64RegsRegClass) {
324 report_fatal_error("Bad register class");
327 // Insert the vreg number
328 Ret |= (RegNum & 0x0FFFFFFF);
331 // Some special-use registers are actually physical registers.
332 // Encode this as the register class ID of 0 and the real register ID.
333 return Reg & 0x0FFFFFFF;
337 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
339 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
341 return MCOperand::CreateExpr(Expr);
344 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
345 const DataLayout *TD = TM.getDataLayout();
346 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
348 Type *Ty = F->getReturnType();
350 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
352 if (Ty->getTypeID() == Type::VoidTyID)
358 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
360 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
361 size = ITy->getBitWidth();
365 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
366 size = Ty->getPrimitiveSizeInBits();
369 O << ".param .b" << size << " func_retval0";
370 } else if (isa<PointerType>(Ty)) {
371 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
373 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
374 unsigned totalsz = TD->getTypeAllocSize(Ty);
375 unsigned retAlignment = 0;
376 if (!llvm::getAlign(*F, 0, retAlignment))
377 retAlignment = TD->getABITypeAlignment(Ty);
378 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
381 llvm_unreachable("Unknown return type");
383 SmallVector<EVT, 16> vtparts;
384 ComputeValueVTs(*TLI, Ty, vtparts);
386 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
388 EVT elemtype = vtparts[i];
389 if (vtparts[i].isVector()) {
390 elems = vtparts[i].getVectorNumElements();
391 elemtype = vtparts[i].getVectorElementType();
394 for (unsigned j = 0, je = elems; j != je; ++j) {
395 unsigned sz = elemtype.getSizeInBits();
396 if (elemtype.isInteger() && (sz < 32))
398 O << ".reg .b" << sz << " func_retval" << idx;
411 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
413 const Function *F = MF.getFunction();
414 printReturnValStr(F, O);
417 // Return true if MBB is the header of a loop marked with
418 // llvm.loop.unroll.disable.
419 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
420 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
421 const MachineBasicBlock &MBB) const {
422 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
423 // TODO: isLoopHeader() should take "const MachineBasicBlock *".
424 // We insert .pragma "nounroll" only to the loop header.
425 if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
428 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
429 // we iterate through each back edge of the loop with header MBB, and check
430 // whether its metadata contains llvm.loop.unroll.disable.
431 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
432 const MachineBasicBlock *PMBB = *I;
433 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
434 // Edges from other loops to MBB are not back edges.
437 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
438 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
439 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
447 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
448 AsmPrinter::EmitBasicBlockStart(MBB);
449 if (isLoopHeaderOfNoUnroll(MBB))
450 OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
453 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
454 SmallString<128> Str;
455 raw_svector_ostream O(Str);
457 if (!GlobalsEmitted) {
458 emitGlobals(*MF->getFunction()->getParent());
459 GlobalsEmitted = true;
463 MRI = &MF->getRegInfo();
464 F = MF->getFunction();
465 emitLinkageDirective(F, O);
466 if (llvm::isKernelFunction(*F))
470 printReturnValStr(*MF, O);
475 emitFunctionParamList(*MF, O);
477 if (llvm::isKernelFunction(*F))
478 emitKernelFunctionDirectives(*F, O);
480 OutStreamer.EmitRawText(O.str());
482 prevDebugLoc = DebugLoc();
485 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
487 OutStreamer.EmitRawText(StringRef("{\n"));
488 setAndEmitFunctionVirtualRegisters(*MF);
490 SmallString<128> Str;
491 raw_svector_ostream O(Str);
492 emitDemotedVars(MF->getFunction(), O);
493 OutStreamer.EmitRawText(O.str());
496 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
497 OutStreamer.EmitRawText(StringRef("}\n"));
501 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
502 unsigned RegNo = MI->getOperand(0).getReg();
503 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
504 OutStreamer.AddComment(Twine("implicit-def: ") +
505 getVirtualRegisterName(RegNo));
507 OutStreamer.AddComment(Twine("implicit-def: ") +
508 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
510 OutStreamer.AddBlankLine();
513 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
514 raw_ostream &O) const {
515 // If the NVVM IR has some of reqntid* specified, then output
516 // the reqntid directive, and set the unspecified ones to 1.
517 // If none of reqntid* is specified, don't output reqntid directive.
518 unsigned reqntidx, reqntidy, reqntidz;
519 bool specified = false;
520 if (!llvm::getReqNTIDx(F, reqntidx))
524 if (!llvm::getReqNTIDy(F, reqntidy))
528 if (!llvm::getReqNTIDz(F, reqntidz))
534 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
537 // If the NVVM IR has some of maxntid* specified, then output
538 // the maxntid directive, and set the unspecified ones to 1.
539 // If none of maxntid* is specified, don't output maxntid directive.
540 unsigned maxntidx, maxntidy, maxntidz;
542 if (!llvm::getMaxNTIDx(F, maxntidx))
546 if (!llvm::getMaxNTIDy(F, maxntidy))
550 if (!llvm::getMaxNTIDz(F, maxntidz))
556 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
560 if (llvm::getMinCTASm(F, mincta))
561 O << ".minnctapersm " << mincta << "\n";
565 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
566 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
569 raw_string_ostream NameStr(Name);
571 VRegRCMap::const_iterator I = VRegMapping.find(RC);
572 assert(I != VRegMapping.end() && "Bad register class");
573 const DenseMap<unsigned, unsigned> &RegMap = I->second;
575 VRegMap::const_iterator VI = RegMap.find(Reg);
576 assert(VI != RegMap.end() && "Bad virtual register");
577 unsigned MappedVR = VI->second;
579 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
585 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
587 O << getVirtualRegisterName(vr);
590 void NVPTXAsmPrinter::printVecModifiedImmediate(
591 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
592 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
593 int Imm = (int) MO.getImm();
594 if (0 == strcmp(Modifier, "vecelem"))
595 O << "_" << vecelem[Imm];
596 else if (0 == strcmp(Modifier, "vecv4comm1")) {
597 if ((Imm < 0) || (Imm > 3))
599 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
600 if ((Imm < 4) || (Imm > 7))
602 } else if (0 == strcmp(Modifier, "vecv4pos")) {
605 O << "_" << vecelem[Imm % 4];
606 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
607 if ((Imm < 0) || (Imm > 1))
609 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
610 if ((Imm < 2) || (Imm > 3))
612 } else if (0 == strcmp(Modifier, "vecv2pos")) {
615 O << "_" << vecelem[Imm % 2];
617 llvm_unreachable("Unknown Modifier on immediate operand");
622 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
624 emitLinkageDirective(F, O);
625 if (llvm::isKernelFunction(*F))
629 printReturnValStr(F, O);
630 O << *getSymbol(F) << "\n";
631 emitFunctionParamList(F, O);
635 static bool usedInGlobalVarDef(const Constant *C) {
639 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
640 if (GV->getName() == "llvm.used")
645 for (const User *U : C->users())
646 if (const Constant *C = dyn_cast<Constant>(U))
647 if (usedInGlobalVarDef(C))
653 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
654 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
655 if (othergv->getName() == "llvm.used")
659 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
660 if (instr->getParent() && instr->getParent()->getParent()) {
661 const Function *curFunc = instr->getParent()->getParent();
662 if (oneFunc && (curFunc != oneFunc))
670 for (const User *UU : U->users())
671 if (!usedInOneFunc(UU, oneFunc))
677 /* Find out if a global variable can be demoted to local scope.
678 * Currently, this is valid for CUDA shared variables, which have local
679 * scope and global lifetime. So the conditions to check are :
680 * 1. Is the global variable in shared address space?
681 * 2. Does it have internal linkage?
682 * 3. Is the global variable referenced only in one function?
684 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
685 if (!gv->hasInternalLinkage())
687 const PointerType *Pty = gv->getType();
688 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
691 const Function *oneFunc = nullptr;
693 bool flag = usedInOneFunc(gv, oneFunc);
702 static bool useFuncSeen(const Constant *C,
703 llvm::DenseMap<const Function *, bool> &seenMap) {
704 for (const User *U : C->users()) {
705 if (const Constant *cu = dyn_cast<Constant>(U)) {
706 if (useFuncSeen(cu, seenMap))
708 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
709 const BasicBlock *bb = I->getParent();
712 const Function *caller = bb->getParent();
715 if (seenMap.find(caller) != seenMap.end())
722 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
723 llvm::DenseMap<const Function *, bool> seenMap;
724 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
725 const Function *F = FI;
727 if (F->isDeclaration()) {
730 if (F->getIntrinsicID())
732 emitDeclaration(F, O);
735 for (const User *U : F->users()) {
736 if (const Constant *C = dyn_cast<Constant>(U)) {
737 if (usedInGlobalVarDef(C)) {
738 // The use is in the initialization of a global variable
739 // that is a function pointer, so print a declaration
740 // for the original function
741 emitDeclaration(F, O);
744 // Emit a declaration of this function if the function that
745 // uses this constant expr has already been seen.
746 if (useFuncSeen(C, seenMap)) {
747 emitDeclaration(F, O);
752 if (!isa<Instruction>(U))
754 const Instruction *instr = cast<Instruction>(U);
755 const BasicBlock *bb = instr->getParent();
758 const Function *caller = bb->getParent();
762 // If a caller has already been seen, then the caller is
763 // appearing in the module before the callee. so print out
764 // a declaration for the callee.
765 if (seenMap.find(caller) != seenMap.end()) {
766 emitDeclaration(F, O);
774 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
775 DebugInfoFinder DbgFinder;
776 DbgFinder.processModule(M);
779 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
780 StringRef Filename(DIUnit.getFilename());
781 StringRef Dirname(DIUnit.getDirectory());
782 SmallString<128> FullPathName = Dirname;
783 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
784 sys::path::append(FullPathName, Filename);
785 Filename = FullPathName;
787 if (filenameMap.find(Filename) != filenameMap.end())
789 filenameMap[Filename] = i;
790 OutStreamer.EmitDwarfFileDirective(i, "", Filename);
794 for (DISubprogram SP : DbgFinder.subprograms()) {
795 StringRef Filename(SP.getFilename());
796 StringRef Dirname(SP.getDirectory());
797 SmallString<128> FullPathName = Dirname;
798 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
799 sys::path::append(FullPathName, Filename);
800 Filename = FullPathName;
802 if (filenameMap.find(Filename) != filenameMap.end())
804 filenameMap[Filename] = i;
809 bool NVPTXAsmPrinter::doInitialization(Module &M) {
810 // Construct a default subtarget off of the TargetMachine defaults. The
811 // rest of NVPTX isn't friendly to change subtargets per function and
812 // so the default TargetMachine will have all of the options.
813 StringRef TT = TM.getTargetTriple();
814 StringRef CPU = TM.getTargetCPU();
815 StringRef FS = TM.getTargetFeatureString();
816 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
817 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
819 SmallString<128> Str1;
820 raw_svector_ostream OS1(Str1);
822 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
823 MMI->AnalyzeModule(M);
825 // We need to call the parent's one explicitly.
826 //bool Result = AsmPrinter::doInitialization(M);
828 // Initialize TargetLoweringObjectFile.
829 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
830 .Initialize(OutContext, TM);
832 Mang = new Mangler(TM.getDataLayout());
834 // Emit header before any dwarf directives are emitted below.
835 emitHeader(M, OS1, STI);
836 OutStreamer.EmitRawText(OS1.str());
838 // Already commented out
839 //bool Result = AsmPrinter::doInitialization(M);
841 // Emit module-level inline asm if it exists.
842 if (!M.getModuleInlineAsm().empty()) {
843 OutStreamer.AddComment("Start of file scope inline assembly");
844 OutStreamer.AddBlankLine();
845 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
846 OutStreamer.AddBlankLine();
847 OutStreamer.AddComment("End of file scope inline assembly");
848 OutStreamer.AddBlankLine();
851 // If we're not NVCL we're CUDA, go ahead and emit filenames.
852 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
853 recordAndEmitFilenames(M);
855 GlobalsEmitted = false;
857 return false; // success
860 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
861 SmallString<128> Str2;
862 raw_svector_ostream OS2(Str2);
864 emitDeclarations(M, OS2);
866 // As ptxas does not support forward references of globals, we need to first
867 // sort the list of module-level globals in def-use order. We visit each
868 // global variable in order, and ensure that we emit it *after* its dependent
869 // globals. We use a little extra memory maintaining both a set and a list to
870 // have fast searches while maintaining a strict ordering.
871 SmallVector<const GlobalVariable *, 8> Globals;
872 DenseSet<const GlobalVariable *> GVVisited;
873 DenseSet<const GlobalVariable *> GVVisiting;
875 // Visit each global variable, in order
876 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
878 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
880 assert(GVVisited.size() == M.getGlobalList().size() &&
881 "Missed a global variable");
882 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
884 // Print out module-level global variables in proper order
885 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
886 printModuleLevelGV(Globals[i], OS2);
890 OutStreamer.EmitRawText(OS2.str());
893 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
894 const NVPTXSubtarget &STI) {
896 O << "// Generated by LLVM NVPTX Back-End\n";
900 unsigned PTXVersion = STI.getPTXVersion();
901 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
904 O << STI.getTargetName();
906 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
907 if (NTM.getDrvInterface() == NVPTX::NVCL)
908 O << ", texmode_independent";
910 if (!STI.hasDouble())
911 O << ", map_f64_to_f32";
914 if (MAI->doesSupportDebugInformation())
919 O << ".address_size ";
929 bool NVPTXAsmPrinter::doFinalization(Module &M) {
930 // If we did not emit any functions, then the global declarations have not
932 if (!GlobalsEmitted) {
934 GlobalsEmitted = true;
937 // XXX Temproarily remove global variables so that doFinalization() will not
938 // emit them again (global variables are emitted at beginning).
940 Module::GlobalListType &global_list = M.getGlobalList();
941 int i, n = global_list.size();
942 GlobalVariable **gv_array = new GlobalVariable *[n];
944 // first, back-up GlobalVariable in gv_array
946 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
950 // second, empty global_list
951 while (!global_list.empty())
952 global_list.remove(global_list.begin());
954 // call doFinalization
955 bool ret = AsmPrinter::doFinalization(M);
957 // now we restore global variables
958 for (i = 0; i < n; i++)
959 global_list.insert(global_list.end(), gv_array[i]);
961 clearAnnotationCache(&M);
966 //bool Result = AsmPrinter::doFinalization(M);
967 // Instead of calling the parents doFinalization, we may
968 // clone parents doFinalization and customize here.
969 // Currently, we if NVISA out the EmitGlobals() in
970 // parent's doFinalization, which is too intrusive.
972 // Same for the doInitialization.
976 // This function emits appropriate linkage directives for
977 // functions and global variables.
979 // extern function declaration -> .extern
980 // extern function definition -> .visible
981 // external global variable with init -> .visible
982 // external without init -> .extern
983 // appending -> not allowed, assert.
984 // for any linkage other than
985 // internal, private, linker_private,
986 // linker_private_weak, linker_private_weak_def_auto,
989 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
991 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
992 if (V->hasExternalLinkage()) {
993 if (isa<GlobalVariable>(V)) {
994 const GlobalVariable *GVar = cast<GlobalVariable>(V);
996 if (GVar->hasInitializer())
1001 } else if (V->isDeclaration())
1005 } else if (V->hasAppendingLinkage()) {
1007 msg.append("Error: ");
1008 msg.append("Symbol ");
1010 msg.append(V->getName());
1011 msg.append("has unsupported appending linkage type");
1012 llvm_unreachable(msg.c_str());
1013 } else if (!V->hasInternalLinkage() &&
1014 !V->hasPrivateLinkage()) {
1020 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1022 bool processDemoted) {
1025 if (GVar->hasSection()) {
1026 if (GVar->getSection() == StringRef("llvm.metadata"))
1030 // Skip LLVM intrinsic global variables
1031 if (GVar->getName().startswith("llvm.") ||
1032 GVar->getName().startswith("nvvm."))
1035 const DataLayout *TD = TM.getDataLayout();
1037 // GlobalVariables are always constant pointers themselves.
1038 const PointerType *PTy = GVar->getType();
1039 Type *ETy = PTy->getElementType();
1041 if (GVar->hasExternalLinkage()) {
1042 if (GVar->hasInitializer())
1046 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1047 GVar->hasAvailableExternallyLinkage() ||
1048 GVar->hasCommonLinkage()) {
1052 if (llvm::isTexture(*GVar)) {
1053 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1057 if (llvm::isSurface(*GVar)) {
1058 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1062 if (GVar->isDeclaration()) {
1063 // (extern) declarations, no definition or initializer
1064 // Currently the only known declaration is for an automatic __local
1065 // (.shared) promoted to global.
1066 emitPTXGlobalVariable(GVar, O);
1071 if (llvm::isSampler(*GVar)) {
1072 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1074 const Constant *Initializer = nullptr;
1075 if (GVar->hasInitializer())
1076 Initializer = GVar->getInitializer();
1077 const ConstantInt *CI = nullptr;
1079 CI = dyn_cast<ConstantInt>(Initializer);
1081 unsigned sample = CI->getZExtValue();
1086 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1088 O << "addr_mode_" << i << " = ";
1094 O << "clamp_to_border";
1097 O << "clamp_to_edge";
1108 O << "filter_mode = ";
1109 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1117 llvm_unreachable("Anisotropic filtering is not supported");
1122 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1123 O << ", force_unnormalized_coords = 1";
1132 if (GVar->hasPrivateLinkage()) {
1134 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1137 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1138 if (!strncmp(GVar->getName().data(), "filename", 8))
1140 if (GVar->use_empty())
1144 const Function *demotedFunc = nullptr;
1145 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1146 O << "// " << GVar->getName() << " has been demoted\n";
1147 if (localDecls.find(demotedFunc) != localDecls.end())
1148 localDecls[demotedFunc].push_back(GVar);
1150 std::vector<const GlobalVariable *> temp;
1151 temp.push_back(GVar);
1152 localDecls[demotedFunc] = temp;
1158 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1160 if (isManaged(*GVar)) {
1161 O << " .attribute(.managed)";
1164 if (GVar->getAlignment() == 0)
1165 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1167 O << " .align " << GVar->getAlignment();
1169 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1171 // Special case: ABI requires that we use .u8 for predicates
1172 if (ETy->isIntegerTy(1))
1175 O << getPTXFundamentalTypeStr(ETy, false);
1177 O << *getSymbol(GVar);
1179 // Ptx allows variable initilization only for constant and global state
1181 if (GVar->hasInitializer()) {
1182 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1183 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1184 const Constant *Initializer = GVar->getInitializer();
1185 // 'undef' is treated as there is no value spefied.
1186 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1188 printScalarConstant(Initializer, O);
1191 // The frontend adds zero-initializer to variables that don't have an
1192 // initial value, so skip warning for this case.
1193 if (!GVar->getInitializer()->isNullValue()) {
1194 std::string warnMsg =
1195 ("initial value of '" + GVar->getName() +
1196 "' is not allowed in addrspace(" +
1197 Twine(llvm::utostr_32(PTy->getAddressSpace())) + ")").str();
1198 report_fatal_error(warnMsg.c_str());
1203 unsigned int ElementSize = 0;
1205 // Although PTX has direct support for struct type and array type and
1206 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1207 // targets that support these high level field accesses. Structs, arrays
1208 // and vectors are lowered into arrays of bytes.
1209 switch (ETy->getTypeID()) {
1210 case Type::StructTyID:
1211 case Type::ArrayTyID:
1212 case Type::VectorTyID:
1213 ElementSize = TD->getTypeStoreSize(ETy);
1214 // Ptx allows variable initilization only for constant and
1215 // global state spaces.
1216 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1217 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1218 GVar->hasInitializer()) {
1219 const Constant *Initializer = GVar->getInitializer();
1220 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1221 AggBuffer aggBuffer(ElementSize, O, *this);
1222 bufferAggregateConstant(Initializer, &aggBuffer);
1223 if (aggBuffer.numSymbols) {
1224 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1225 O << " .u64 " << *getSymbol(GVar) << "[";
1226 O << ElementSize / 8;
1228 O << " .u32 " << *getSymbol(GVar) << "[";
1229 O << ElementSize / 4;
1233 O << " .b8 " << *getSymbol(GVar) << "[";
1241 O << " .b8 " << *getSymbol(GVar);
1249 O << " .b8 " << *getSymbol(GVar);
1258 llvm_unreachable("type not supported yet");
1265 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1266 if (localDecls.find(f) == localDecls.end())
1269 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1271 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1272 O << "\t// demoted variable\n\t";
1273 printModuleLevelGV(gvars[i], O, true);
1277 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1278 raw_ostream &O) const {
1279 switch (AddressSpace) {
1280 case llvm::ADDRESS_SPACE_LOCAL:
1283 case llvm::ADDRESS_SPACE_GLOBAL:
1286 case llvm::ADDRESS_SPACE_CONST:
1289 case llvm::ADDRESS_SPACE_SHARED:
1293 report_fatal_error("Bad address space found while emitting PTX");
1299 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1300 switch (Ty->getTypeID()) {
1302 llvm_unreachable("unexpected type");
1304 case Type::IntegerTyID: {
1305 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1308 else if (NumBits <= 64) {
1309 std::string name = "u";
1310 return name + utostr(NumBits);
1312 llvm_unreachable("Integer too large");
1317 case Type::FloatTyID:
1319 case Type::DoubleTyID:
1321 case Type::PointerTyID:
1322 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1332 llvm_unreachable("unexpected type");
1336 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1339 const DataLayout *TD = TM.getDataLayout();
1341 // GlobalVariables are always constant pointers themselves.
1342 const PointerType *PTy = GVar->getType();
1343 Type *ETy = PTy->getElementType();
1346 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1347 if (GVar->getAlignment() == 0)
1348 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1350 O << " .align " << GVar->getAlignment();
1352 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1354 O << getPTXFundamentalTypeStr(ETy);
1356 O << *getSymbol(GVar);
1360 int64_t ElementSize = 0;
1362 // Although PTX has direct support for struct type and array type and LLVM IR
1363 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1364 // support these high level field accesses. Structs and arrays are lowered
1365 // into arrays of bytes.
1366 switch (ETy->getTypeID()) {
1367 case Type::StructTyID:
1368 case Type::ArrayTyID:
1369 case Type::VectorTyID:
1370 ElementSize = TD->getTypeStoreSize(ETy);
1371 O << " .b8 " << *getSymbol(GVar) << "[";
1373 O << itostr(ElementSize);
1378 llvm_unreachable("type not supported yet");
1383 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1384 if (Ty->isSingleValueType())
1385 return TD->getPrefTypeAlignment(Ty);
1387 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1389 return getOpenCLAlignment(TD, ATy->getElementType());
1391 const StructType *STy = dyn_cast<StructType>(Ty);
1393 unsigned int alignStruct = 1;
1394 // Go through each element of the struct and find the
1395 // largest alignment.
1396 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1397 Type *ETy = STy->getElementType(i);
1398 unsigned int align = getOpenCLAlignment(TD, ETy);
1399 if (align > alignStruct)
1400 alignStruct = align;
1405 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1407 return TD->getPointerPrefAlignment();
1408 return TD->getPrefTypeAlignment(Ty);
1411 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1412 int paramIndex, raw_ostream &O) {
1413 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1416 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1417 O << *CurrentFnSym << "_param_" << paramIndex;
1420 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1421 const DataLayout *TD = TM.getDataLayout();
1422 const AttributeSet &PAL = F->getAttributes();
1423 const TargetLowering *TLI = nvptxSubtarget->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)) {
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 (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1496 Type *ETy = PTy->getElementType();
1497 int addrSpace = PTy->getAddressSpace();
1498 switch (addrSpace) {
1502 case llvm::ADDRESS_SPACE_CONST:
1503 O << ".ptr .const ";
1505 case llvm::ADDRESS_SPACE_SHARED:
1506 O << ".ptr .shared ";
1508 case llvm::ADDRESS_SPACE_GLOBAL:
1509 O << ".ptr .global ";
1512 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1514 printParamName(I, paramIndex, O);
1518 // non-pointer scalar to kernel func
1520 // Special case: predicate operands become .u8 types
1521 if (Ty->isIntegerTy(1))
1524 O << getPTXFundamentalTypeStr(Ty);
1526 printParamName(I, paramIndex, O);
1529 // Non-kernel function, just print .param .b<size> for ABI
1530 // and .reg .b<size> for non-ABI
1532 if (isa<IntegerType>(Ty)) {
1533 sz = cast<IntegerType>(Ty)->getBitWidth();
1536 } else if (isa<PointerType>(Ty))
1537 sz = thePointerTy.getSizeInBits();
1539 sz = Ty->getPrimitiveSizeInBits();
1541 O << "\t.param .b" << sz << " ";
1543 O << "\t.reg .b" << sz << " ";
1544 printParamName(I, paramIndex, O);
1548 // param has byVal attribute. So should be a pointer
1549 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1550 assert(PTy && "Param with byval attribute should be a pointer type");
1551 Type *ETy = PTy->getElementType();
1553 if (isABI || isKernelFunc) {
1554 // Just print .param .align <a> .b8 .param[size];
1555 // <a> = PAL.getparamalignment
1556 // size = typeallocsize of element type
1557 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1559 align = TD->getABITypeAlignment(ETy);
1561 unsigned sz = TD->getTypeAllocSize(ETy);
1562 O << "\t.param .align " << align << " .b8 ";
1563 printParamName(I, paramIndex, O);
1564 O << "[" << sz << "]";
1567 // Split the ETy into constituent parts and
1568 // print .param .b<size> <name> for each part.
1569 // Further, if a part is vector, print the above for
1570 // each vector element.
1571 SmallVector<EVT, 16> vtparts;
1572 ComputeValueVTs(*TLI, ETy, vtparts);
1573 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1575 EVT elemtype = vtparts[i];
1576 if (vtparts[i].isVector()) {
1577 elems = vtparts[i].getVectorNumElements();
1578 elemtype = vtparts[i].getVectorElementType();
1581 for (unsigned j = 0, je = elems; j != je; ++j) {
1582 unsigned sz = elemtype.getSizeInBits();
1583 if (elemtype.isInteger() && (sz < 32))
1585 O << "\t.reg .b" << sz << " ";
1586 printParamName(I, paramIndex, O);
1602 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1604 const Function *F = MF.getFunction();
1605 emitFunctionParamList(F, O);
1608 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1609 const MachineFunction &MF) {
1610 SmallString<128> Str;
1611 raw_svector_ostream O(Str);
1613 // Map the global virtual register number to a register class specific
1614 // virtual register number starting from 1 with that class.
1615 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1616 //unsigned numRegClasses = TRI->getNumRegClasses();
1618 // Emit the Fake Stack Object
1619 const MachineFrameInfo *MFI = MF.getFrameInfo();
1620 int NumBytes = (int) MFI->getStackSize();
1622 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1623 << getFunctionNumber() << "[" << NumBytes << "];\n";
1624 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1625 O << "\t.reg .b64 \t%SP;\n";
1626 O << "\t.reg .b64 \t%SPL;\n";
1628 O << "\t.reg .b32 \t%SP;\n";
1629 O << "\t.reg .b32 \t%SPL;\n";
1633 // Go through all virtual registers to establish the mapping between the
1635 // register number and the per class virtual register number.
1636 // We use the per class virtual register number in the ptx output.
1637 unsigned int numVRs = MRI->getNumVirtRegs();
1638 for (unsigned i = 0; i < numVRs; i++) {
1639 unsigned int vr = TRI->index2VirtReg(i);
1640 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1641 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1642 int n = regmap.size();
1643 regmap.insert(std::make_pair(vr, n + 1));
1646 // Emit register declarations
1647 // @TODO: Extract out the real register usage
1648 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1649 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1650 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1651 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1652 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1653 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1654 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1656 // Emit declaration of the virtual registers or 'physical' registers for
1657 // each register class
1658 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1659 const TargetRegisterClass *RC = TRI->getRegClass(i);
1660 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1661 std::string rcname = getNVPTXRegClassName(RC);
1662 std::string rcStr = getNVPTXRegClassStr(RC);
1663 int n = regmap.size();
1665 // Only declare those registers that may be used.
1667 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1672 OutStreamer.EmitRawText(O.str());
1675 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1676 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1678 unsigned int numHex;
1681 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1684 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1685 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1688 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1690 llvm_unreachable("unsupported fp type");
1692 APInt API = APF.bitcastToAPInt();
1693 std::string hexstr(utohexstr(API.getZExtValue()));
1695 if (hexstr.length() < numHex)
1696 O << std::string(numHex - hexstr.length(), '0');
1697 O << utohexstr(API.getZExtValue());
1700 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1701 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1702 O << CI->getValue();
1705 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1706 printFPConstant(CFP, O);
1709 if (isa<ConstantPointerNull>(CPV)) {
1713 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1714 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1715 bool IsNonGenericPointer = false;
1716 if (PTy && PTy->getAddressSpace() != 0) {
1717 IsNonGenericPointer = true;
1719 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1721 O << *getSymbol(GVar);
1724 O << *getSymbol(GVar);
1728 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1729 const Value *v = Cexpr->stripPointerCasts();
1730 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1731 bool IsNonGenericPointer = false;
1732 if (PTy && PTy->getAddressSpace() != 0) {
1733 IsNonGenericPointer = true;
1735 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1736 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1738 O << *getSymbol(GVar);
1741 O << *getSymbol(GVar);
1745 O << *lowerConstant(CPV);
1749 llvm_unreachable("Not scalar type found in printScalarConstant()");
1752 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1753 AggBuffer *aggBuffer) {
1755 const DataLayout *TD = TM.getDataLayout();
1757 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1758 int s = TD->getTypeAllocSize(CPV->getType());
1761 aggBuffer->addZeros(s);
1766 switch (CPV->getType()->getTypeID()) {
1768 case Type::IntegerTyID: {
1769 const Type *ETy = CPV->getType();
1770 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1772 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1774 aggBuffer->addBytes(ptr, 1, Bytes);
1775 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1776 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1777 ptr = (unsigned char *)&int16;
1778 aggBuffer->addBytes(ptr, 2, Bytes);
1779 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1780 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1781 int int32 = (int)(constInt->getZExtValue());
1782 ptr = (unsigned char *)&int32;
1783 aggBuffer->addBytes(ptr, 4, Bytes);
1785 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1786 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1787 ConstantFoldConstantExpression(Cexpr, *TD))) {
1788 int int32 = (int)(constInt->getZExtValue());
1789 ptr = (unsigned char *)&int32;
1790 aggBuffer->addBytes(ptr, 4, Bytes);
1793 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1794 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1795 aggBuffer->addSymbol(v);
1796 aggBuffer->addZeros(4);
1800 llvm_unreachable("unsupported integer const type");
1801 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1802 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1803 long long int64 = (long long)(constInt->getZExtValue());
1804 ptr = (unsigned char *)&int64;
1805 aggBuffer->addBytes(ptr, 8, Bytes);
1807 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1808 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1809 ConstantFoldConstantExpression(Cexpr, *TD))) {
1810 long long int64 = (long long)(constInt->getZExtValue());
1811 ptr = (unsigned char *)&int64;
1812 aggBuffer->addBytes(ptr, 8, Bytes);
1815 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1816 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1817 aggBuffer->addSymbol(v);
1818 aggBuffer->addZeros(8);
1822 llvm_unreachable("unsupported integer const type");
1824 llvm_unreachable("unsupported integer const type");
1827 case Type::FloatTyID:
1828 case Type::DoubleTyID: {
1829 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1830 const Type *Ty = CFP->getType();
1831 if (Ty == Type::getFloatTy(CPV->getContext())) {
1832 float float32 = (float) CFP->getValueAPF().convertToFloat();
1833 ptr = (unsigned char *)&float32;
1834 aggBuffer->addBytes(ptr, 4, Bytes);
1835 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1836 double float64 = CFP->getValueAPF().convertToDouble();
1837 ptr = (unsigned char *)&float64;
1838 aggBuffer->addBytes(ptr, 8, Bytes);
1840 llvm_unreachable("unsupported fp const type");
1844 case Type::PointerTyID: {
1845 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1846 aggBuffer->addSymbol(GVar);
1847 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1848 const Value *v = Cexpr->stripPointerCasts();
1849 aggBuffer->addSymbol(v);
1851 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1852 aggBuffer->addZeros(s);
1856 case Type::ArrayTyID:
1857 case Type::VectorTyID:
1858 case Type::StructTyID: {
1859 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1860 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1861 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1862 bufferAggregateConstant(CPV, aggBuffer);
1863 if (Bytes > ElementSize)
1864 aggBuffer->addZeros(Bytes - ElementSize);
1865 } else if (isa<ConstantAggregateZero>(CPV))
1866 aggBuffer->addZeros(Bytes);
1868 llvm_unreachable("Unexpected Constant type");
1873 llvm_unreachable("unsupported type");
1877 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1878 AggBuffer *aggBuffer) {
1879 const DataLayout *TD = TM.getDataLayout();
1883 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1884 if (CPV->getNumOperands())
1885 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1886 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1890 if (const ConstantDataSequential *CDS =
1891 dyn_cast<ConstantDataSequential>(CPV)) {
1892 if (CDS->getNumElements())
1893 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1894 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1899 if (isa<ConstantStruct>(CPV)) {
1900 if (CPV->getNumOperands()) {
1901 StructType *ST = cast<StructType>(CPV->getType());
1902 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1904 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1905 TD->getTypeAllocSize(ST) -
1906 TD->getStructLayout(ST)->getElementOffset(i);
1908 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1909 TD->getStructLayout(ST)->getElementOffset(i);
1910 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1915 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1918 // buildTypeNameMap - Run through symbol table looking for type names.
1921 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1923 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1925 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1926 !PI->second.compare("struct._image2d_t") ||
1927 !PI->second.compare("struct._image3d_t")))
1934 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1935 switch (MI.getOpcode()) {
1938 case NVPTX::CallArgBeginInst:
1939 case NVPTX::CallArgEndInst0:
1940 case NVPTX::CallArgEndInst1:
1941 case NVPTX::CallArgF32:
1942 case NVPTX::CallArgF64:
1943 case NVPTX::CallArgI16:
1944 case NVPTX::CallArgI32:
1945 case NVPTX::CallArgI32imm:
1946 case NVPTX::CallArgI64:
1947 case NVPTX::CallArgParam:
1948 case NVPTX::CallVoidInst:
1949 case NVPTX::CallVoidInstReg:
1950 case NVPTX::Callseq_End:
1951 case NVPTX::CallVoidInstReg64:
1952 case NVPTX::DeclareParamInst:
1953 case NVPTX::DeclareRetMemInst:
1954 case NVPTX::DeclareRetRegInst:
1955 case NVPTX::DeclareRetScalarInst:
1956 case NVPTX::DeclareScalarParamInst:
1957 case NVPTX::DeclareScalarRegInst:
1958 case NVPTX::StoreParamF32:
1959 case NVPTX::StoreParamF64:
1960 case NVPTX::StoreParamI16:
1961 case NVPTX::StoreParamI32:
1962 case NVPTX::StoreParamI64:
1963 case NVPTX::StoreParamI8:
1964 case NVPTX::StoreRetvalF32:
1965 case NVPTX::StoreRetvalF64:
1966 case NVPTX::StoreRetvalI16:
1967 case NVPTX::StoreRetvalI32:
1968 case NVPTX::StoreRetvalI64:
1969 case NVPTX::StoreRetvalI8:
1970 case NVPTX::LastCallArgF32:
1971 case NVPTX::LastCallArgF64:
1972 case NVPTX::LastCallArgI16:
1973 case NVPTX::LastCallArgI32:
1974 case NVPTX::LastCallArgI32imm:
1975 case NVPTX::LastCallArgI64:
1976 case NVPTX::LastCallArgParam:
1977 case NVPTX::LoadParamMemF32:
1978 case NVPTX::LoadParamMemF64:
1979 case NVPTX::LoadParamMemI16:
1980 case NVPTX::LoadParamMemI32:
1981 case NVPTX::LoadParamMemI64:
1982 case NVPTX::LoadParamMemI8:
1983 case NVPTX::PrototypeInst:
1984 case NVPTX::DBG_VALUE:
1990 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1992 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1993 unsigned AsmVariant,
1994 const char *ExtraCode, raw_ostream &O) {
1995 if (ExtraCode && ExtraCode[0]) {
1996 if (ExtraCode[1] != 0)
1997 return true; // Unknown modifier.
1999 switch (ExtraCode[0]) {
2001 // See if this is a generic print operand
2002 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2008 printOperand(MI, OpNo, O);
2013 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2014 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2015 const char *ExtraCode, raw_ostream &O) {
2016 if (ExtraCode && ExtraCode[0])
2017 return true; // Unknown modifier
2020 printMemOperand(MI, OpNo, O);
2026 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2027 raw_ostream &O, const char *Modifier) {
2028 const MachineOperand &MO = MI->getOperand(opNum);
2029 switch (MO.getType()) {
2030 case MachineOperand::MO_Register:
2031 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2032 if (MO.getReg() == NVPTX::VRDepot)
2033 O << DEPOTNAME << getFunctionNumber();
2035 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2037 emitVirtualRegister(MO.getReg(), O);
2041 case MachineOperand::MO_Immediate:
2044 else if (strstr(Modifier, "vec") == Modifier)
2045 printVecModifiedImmediate(MO, Modifier, O);
2048 "Don't know how to handle modifier on immediate operand");
2051 case MachineOperand::MO_FPImmediate:
2052 printFPConstant(MO.getFPImm(), O);
2055 case MachineOperand::MO_GlobalAddress:
2056 O << *getSymbol(MO.getGlobal());
2059 case MachineOperand::MO_MachineBasicBlock:
2060 O << *MO.getMBB()->getSymbol();
2064 llvm_unreachable("Operand type not supported.");
2068 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2069 raw_ostream &O, const char *Modifier) {
2070 printOperand(MI, opNum, O);
2072 if (Modifier && !strcmp(Modifier, "add")) {
2074 printOperand(MI, opNum + 1, O);
2076 if (MI->getOperand(opNum + 1).isImm() &&
2077 MI->getOperand(opNum + 1).getImm() == 0)
2078 return; // don't print ',0' or '+0'
2080 printOperand(MI, opNum + 1, O);
2084 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2085 std::stringstream temp;
2086 LineReader *reader = this->getReader(filename);
2088 temp << filename.str();
2092 temp << reader->readLine(line);
2094 this->OutStreamer.EmitRawText(temp.str());
2097 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2099 reader = new LineReader(filename);
2102 if (reader->fileName() != filename) {
2104 reader = new LineReader(filename);
2110 std::string LineReader::readLine(unsigned lineNum) {
2111 if (lineNum < theCurLine) {
2113 fstr.seekg(0, std::ios::beg);
2115 while (theCurLine < lineNum) {
2116 fstr.getline(buff, 500);
2122 // Force static initialization.
2123 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2124 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2125 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);