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.isUnknown() && curLoc.isUnknown())
124 if (prevDebugLoc == curLoc)
127 prevDebugLoc = curLoc;
129 if (curLoc.isUnknown())
132 const MachineFunction *MF = MI.getParent()->getParent();
133 //const TargetMachine &TM = MF->getTarget();
135 const LLVMContext &ctx = MF->getFunction()->getContext();
136 DIScope Scope(curLoc.getScope(ctx));
138 assert((!Scope || Scope.isScope()) &&
139 "Scope of a DebugLoc should be null or a DIScope.");
143 StringRef fileName(Scope.getFilename());
144 StringRef dirName(Scope.getDirectory());
145 SmallString<128> FullPathName = dirName;
146 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
147 sys::path::append(FullPathName, fileName);
148 fileName = FullPathName.str();
151 if (filenameMap.find(fileName.str()) == filenameMap.end())
154 // Emit the line from the source file.
156 this->emitSrcInText(fileName.str(), curLoc.getLine());
158 std::stringstream temp;
159 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
160 << " " << curLoc.getCol();
161 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
164 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
165 SmallString<128> Str;
166 raw_svector_ostream OS(Str);
167 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA)
168 emitLineNumberAsDotLoc(*MI);
171 lowerToMCInst(MI, Inst);
172 EmitToStreamer(OutStreamer, Inst);
175 // Handle symbol backtracking for targets that do not support image handles
176 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
177 unsigned OpNo, MCOperand &MCOp) {
178 const MachineOperand &MO = MI->getOperand(OpNo);
179 const MCInstrDesc &MCID = MI->getDesc();
181 if (MCID.TSFlags & NVPTXII::IsTexFlag) {
182 // This is a texture fetch, so operand 4 is a texref and operand 5 is
184 if (OpNo == 4 && MO.isImm()) {
185 lowerImageHandleSymbol(MO.getImm(), MCOp);
188 if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
189 lowerImageHandleSymbol(MO.getImm(), MCOp);
194 } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
196 1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
198 // For a surface load of vector size N, the Nth operand will be the surfref
199 if (OpNo == VecSize && MO.isImm()) {
200 lowerImageHandleSymbol(MO.getImm(), MCOp);
205 } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
206 // This is a surface store, so operand 0 is a surfref
207 if (OpNo == 0 && MO.isImm()) {
208 lowerImageHandleSymbol(MO.getImm(), MCOp);
213 } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
214 // This is a query, so operand 1 is a surfref/texref
215 if (OpNo == 1 && MO.isImm()) {
216 lowerImageHandleSymbol(MO.getImm(), MCOp);
226 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
228 TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
229 NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
230 const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
231 const char *Sym = MFI->getImageHandleSymbol(Index);
232 std::string *SymNamePtr =
233 nvTM.getManagedStrPool()->getManagedString(Sym);
234 MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
235 StringRef(SymNamePtr->c_str())));
238 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
239 OutMI.setOpcode(MI->getOpcode());
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 (!nvptxSubtarget->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.getDataLayout();
350 const TargetLowering *TLI = nvptxSubtarget->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()
377 } else if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
378 unsigned totalsz = TD->getTypeAllocSize(Ty);
379 unsigned retAlignment = 0;
380 if (!llvm::getAlign(*F, 0, retAlignment))
381 retAlignment = TD->getABITypeAlignment(Ty);
382 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
385 llvm_unreachable("Unknown return type");
387 SmallVector<EVT, 16> vtparts;
388 ComputeValueVTs(*TLI, Ty, vtparts);
390 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
392 EVT elemtype = vtparts[i];
393 if (vtparts[i].isVector()) {
394 elems = vtparts[i].getVectorNumElements();
395 elemtype = vtparts[i].getVectorElementType();
398 for (unsigned j = 0, je = elems; j != je; ++j) {
399 unsigned sz = elemtype.getSizeInBits();
400 if (elemtype.isInteger() && (sz < 32))
402 O << ".reg .b" << sz << " func_retval" << idx;
415 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
417 const Function *F = MF.getFunction();
418 printReturnValStr(F, O);
421 // Return true if MBB is the header of a loop marked with
422 // llvm.loop.unroll.disable.
423 // TODO: consider "#pragma unroll 1" which is equivalent to "#pragma nounroll".
424 bool NVPTXAsmPrinter::isLoopHeaderOfNoUnroll(
425 const MachineBasicBlock &MBB) const {
426 MachineLoopInfo &LI = getAnalysis<MachineLoopInfo>();
427 // TODO: isLoopHeader() should take "const MachineBasicBlock *".
428 // We insert .pragma "nounroll" only to the loop header.
429 if (!LI.isLoopHeader(const_cast<MachineBasicBlock *>(&MBB)))
432 // llvm.loop.unroll.disable is marked on the back edges of a loop. Therefore,
433 // we iterate through each back edge of the loop with header MBB, and check
434 // whether its metadata contains llvm.loop.unroll.disable.
435 for (auto I = MBB.pred_begin(); I != MBB.pred_end(); ++I) {
436 const MachineBasicBlock *PMBB = *I;
437 if (LI.getLoopFor(PMBB) != LI.getLoopFor(&MBB)) {
438 // Edges from other loops to MBB are not back edges.
441 if (const BasicBlock *PBB = PMBB->getBasicBlock()) {
442 if (MDNode *LoopID = PBB->getTerminator()->getMetadata("llvm.loop")) {
443 if (GetUnrollMetadata(LoopID, "llvm.loop.unroll.disable"))
451 void NVPTXAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const {
452 AsmPrinter::EmitBasicBlockStart(MBB);
453 if (isLoopHeaderOfNoUnroll(MBB))
454 OutStreamer.EmitRawText(StringRef("\t.pragma \"nounroll\";\n"));
457 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
458 SmallString<128> Str;
459 raw_svector_ostream O(Str);
461 if (!GlobalsEmitted) {
462 emitGlobals(*MF->getFunction()->getParent());
463 GlobalsEmitted = true;
467 MRI = &MF->getRegInfo();
468 F = MF->getFunction();
469 emitLinkageDirective(F, O);
470 if (llvm::isKernelFunction(*F))
474 printReturnValStr(*MF, O);
479 emitFunctionParamList(*MF, O);
481 if (llvm::isKernelFunction(*F))
482 emitKernelFunctionDirectives(*F, O);
484 OutStreamer.EmitRawText(O.str());
486 prevDebugLoc = DebugLoc();
489 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
491 OutStreamer.EmitRawText(StringRef("{\n"));
492 setAndEmitFunctionVirtualRegisters(*MF);
494 SmallString<128> Str;
495 raw_svector_ostream O(Str);
496 emitDemotedVars(MF->getFunction(), O);
497 OutStreamer.EmitRawText(O.str());
500 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
501 OutStreamer.EmitRawText(StringRef("}\n"));
505 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
506 unsigned RegNo = MI->getOperand(0).getReg();
507 if (TargetRegisterInfo::isVirtualRegister(RegNo)) {
508 OutStreamer.AddComment(Twine("implicit-def: ") +
509 getVirtualRegisterName(RegNo));
511 OutStreamer.AddComment(Twine("implicit-def: ") +
512 nvptxSubtarget->getRegisterInfo()->getName(RegNo));
514 OutStreamer.AddBlankLine();
517 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
518 raw_ostream &O) const {
519 // If the NVVM IR has some of reqntid* specified, then output
520 // the reqntid directive, and set the unspecified ones to 1.
521 // If none of reqntid* is specified, don't output reqntid directive.
522 unsigned reqntidx, reqntidy, reqntidz;
523 bool specified = false;
524 if (!llvm::getReqNTIDx(F, reqntidx))
528 if (!llvm::getReqNTIDy(F, reqntidy))
532 if (!llvm::getReqNTIDz(F, reqntidz))
538 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
541 // If the NVVM IR has some of maxntid* specified, then output
542 // the maxntid directive, and set the unspecified ones to 1.
543 // If none of maxntid* is specified, don't output maxntid directive.
544 unsigned maxntidx, maxntidy, maxntidz;
546 if (!llvm::getMaxNTIDx(F, maxntidx))
550 if (!llvm::getMaxNTIDy(F, maxntidy))
554 if (!llvm::getMaxNTIDz(F, maxntidz))
560 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
564 if (llvm::getMinCTASm(F, mincta))
565 O << ".minnctapersm " << mincta << "\n";
569 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
570 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
573 raw_string_ostream NameStr(Name);
575 VRegRCMap::const_iterator I = VRegMapping.find(RC);
576 assert(I != VRegMapping.end() && "Bad register class");
577 const DenseMap<unsigned, unsigned> &RegMap = I->second;
579 VRegMap::const_iterator VI = RegMap.find(Reg);
580 assert(VI != RegMap.end() && "Bad virtual register");
581 unsigned MappedVR = VI->second;
583 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
589 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
591 O << getVirtualRegisterName(vr);
594 void NVPTXAsmPrinter::printVecModifiedImmediate(
595 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
596 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
597 int Imm = (int) MO.getImm();
598 if (0 == strcmp(Modifier, "vecelem"))
599 O << "_" << vecelem[Imm];
600 else if (0 == strcmp(Modifier, "vecv4comm1")) {
601 if ((Imm < 0) || (Imm > 3))
603 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
604 if ((Imm < 4) || (Imm > 7))
606 } else if (0 == strcmp(Modifier, "vecv4pos")) {
609 O << "_" << vecelem[Imm % 4];
610 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
611 if ((Imm < 0) || (Imm > 1))
613 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
614 if ((Imm < 2) || (Imm > 3))
616 } else if (0 == strcmp(Modifier, "vecv2pos")) {
619 O << "_" << vecelem[Imm % 2];
621 llvm_unreachable("Unknown Modifier on immediate operand");
626 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
628 emitLinkageDirective(F, O);
629 if (llvm::isKernelFunction(*F))
633 printReturnValStr(F, O);
634 O << *getSymbol(F) << "\n";
635 emitFunctionParamList(F, O);
639 static bool usedInGlobalVarDef(const Constant *C) {
643 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
644 if (GV->getName().str() == "llvm.used")
649 for (const User *U : C->users())
650 if (const Constant *C = dyn_cast<Constant>(U))
651 if (usedInGlobalVarDef(C))
657 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
658 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
659 if (othergv->getName().str() == "llvm.used")
663 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
664 if (instr->getParent() && instr->getParent()->getParent()) {
665 const Function *curFunc = instr->getParent()->getParent();
666 if (oneFunc && (curFunc != oneFunc))
674 for (const User *UU : U->users())
675 if (!usedInOneFunc(UU, oneFunc))
681 /* Find out if a global variable can be demoted to local scope.
682 * Currently, this is valid for CUDA shared variables, which have local
683 * scope and global lifetime. So the conditions to check are :
684 * 1. Is the global variable in shared address space?
685 * 2. Does it have internal linkage?
686 * 3. Is the global variable referenced only in one function?
688 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
689 if (!gv->hasInternalLinkage())
691 const PointerType *Pty = gv->getType();
692 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
695 const Function *oneFunc = nullptr;
697 bool flag = usedInOneFunc(gv, oneFunc);
706 static bool useFuncSeen(const Constant *C,
707 llvm::DenseMap<const Function *, bool> &seenMap) {
708 for (const User *U : C->users()) {
709 if (const Constant *cu = dyn_cast<Constant>(U)) {
710 if (useFuncSeen(cu, seenMap))
712 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
713 const BasicBlock *bb = I->getParent();
716 const Function *caller = bb->getParent();
719 if (seenMap.find(caller) != seenMap.end())
726 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
727 llvm::DenseMap<const Function *, bool> seenMap;
728 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
729 const Function *F = FI;
731 if (F->isDeclaration()) {
734 if (F->getIntrinsicID())
736 emitDeclaration(F, O);
739 for (const User *U : F->users()) {
740 if (const Constant *C = dyn_cast<Constant>(U)) {
741 if (usedInGlobalVarDef(C)) {
742 // The use is in the initialization of a global variable
743 // that is a function pointer, so print a declaration
744 // for the original function
745 emitDeclaration(F, O);
748 // Emit a declaration of this function if the function that
749 // uses this constant expr has already been seen.
750 if (useFuncSeen(C, seenMap)) {
751 emitDeclaration(F, O);
756 if (!isa<Instruction>(U))
758 const Instruction *instr = cast<Instruction>(U);
759 const BasicBlock *bb = instr->getParent();
762 const Function *caller = bb->getParent();
766 // If a caller has already been seen, then the caller is
767 // appearing in the module before the callee. so print out
768 // a declaration for the callee.
769 if (seenMap.find(caller) != seenMap.end()) {
770 emitDeclaration(F, O);
778 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
779 DebugInfoFinder DbgFinder;
780 DbgFinder.processModule(M);
783 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
784 StringRef Filename(DIUnit.getFilename());
785 StringRef Dirname(DIUnit.getDirectory());
786 SmallString<128> FullPathName = Dirname;
787 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
788 sys::path::append(FullPathName, Filename);
789 Filename = FullPathName.str();
791 if (filenameMap.find(Filename.str()) != filenameMap.end())
793 filenameMap[Filename.str()] = i;
794 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
798 for (DISubprogram SP : DbgFinder.subprograms()) {
799 StringRef Filename(SP.getFilename());
800 StringRef Dirname(SP.getDirectory());
801 SmallString<128> FullPathName = Dirname;
802 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
803 sys::path::append(FullPathName, Filename);
804 Filename = FullPathName.str();
806 if (filenameMap.find(Filename.str()) != filenameMap.end())
808 filenameMap[Filename.str()] = i;
813 bool NVPTXAsmPrinter::doInitialization(Module &M) {
814 // Construct a default subtarget off of the TargetMachine defaults. The
815 // rest of NVPTX isn't friendly to change subtargets per function and
816 // so the default TargetMachine will have all of the options.
817 StringRef TT = TM.getTargetTriple();
818 StringRef CPU = TM.getTargetCPU();
819 StringRef FS = TM.getTargetFeatureString();
820 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
821 const NVPTXSubtarget STI(TT, CPU, FS, NTM);
823 SmallString<128> Str1;
824 raw_svector_ostream OS1(Str1);
826 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
827 MMI->AnalyzeModule(M);
829 // We need to call the parent's one explicitly.
830 //bool Result = AsmPrinter::doInitialization(M);
832 // Initialize TargetLoweringObjectFile.
833 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
834 .Initialize(OutContext, TM);
836 Mang = new Mangler(TM.getDataLayout());
838 // Emit header before any dwarf directives are emitted below.
839 emitHeader(M, OS1, STI);
840 OutStreamer.EmitRawText(OS1.str());
842 // Already commented out
843 //bool Result = AsmPrinter::doInitialization(M);
845 // Emit module-level inline asm if it exists.
846 if (!M.getModuleInlineAsm().empty()) {
847 OutStreamer.AddComment("Start of file scope inline assembly");
848 OutStreamer.AddBlankLine();
849 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
850 OutStreamer.AddBlankLine();
851 OutStreamer.AddComment("End of file scope inline assembly");
852 OutStreamer.AddBlankLine();
855 // If we're not NVCL we're CUDA, go ahead and emit filenames.
856 if (Triple(TM.getTargetTriple()).getOS() != Triple::NVCL)
857 recordAndEmitFilenames(M);
859 GlobalsEmitted = false;
861 return false; // success
864 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
865 SmallString<128> Str2;
866 raw_svector_ostream OS2(Str2);
868 emitDeclarations(M, OS2);
870 // As ptxas does not support forward references of globals, we need to first
871 // sort the list of module-level globals in def-use order. We visit each
872 // global variable in order, and ensure that we emit it *after* its dependent
873 // globals. We use a little extra memory maintaining both a set and a list to
874 // have fast searches while maintaining a strict ordering.
875 SmallVector<const GlobalVariable *, 8> Globals;
876 DenseSet<const GlobalVariable *> GVVisited;
877 DenseSet<const GlobalVariable *> GVVisiting;
879 // Visit each global variable, in order
880 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
882 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
884 assert(GVVisited.size() == M.getGlobalList().size() &&
885 "Missed a global variable");
886 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
888 // Print out module-level global variables in proper order
889 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
890 printModuleLevelGV(Globals[i], OS2);
894 OutStreamer.EmitRawText(OS2.str());
897 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
898 const NVPTXSubtarget &STI) {
900 O << "// Generated by LLVM NVPTX Back-End\n";
904 unsigned PTXVersion = STI.getPTXVersion();
905 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
908 O << STI.getTargetName();
910 const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
911 if (NTM.getDrvInterface() == NVPTX::NVCL)
912 O << ", texmode_independent";
914 if (!STI.hasDouble())
915 O << ", map_f64_to_f32";
918 if (MAI->doesSupportDebugInformation())
923 O << ".address_size ";
933 bool NVPTXAsmPrinter::doFinalization(Module &M) {
934 // If we did not emit any functions, then the global declarations have not
936 if (!GlobalsEmitted) {
938 GlobalsEmitted = true;
941 // XXX Temproarily remove global variables so that doFinalization() will not
942 // emit them again (global variables are emitted at beginning).
944 Module::GlobalListType &global_list = M.getGlobalList();
945 int i, n = global_list.size();
946 GlobalVariable **gv_array = new GlobalVariable *[n];
948 // first, back-up GlobalVariable in gv_array
950 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
954 // second, empty global_list
955 while (!global_list.empty())
956 global_list.remove(global_list.begin());
958 // call doFinalization
959 bool ret = AsmPrinter::doFinalization(M);
961 // now we restore global variables
962 for (i = 0; i < n; i++)
963 global_list.insert(global_list.end(), gv_array[i]);
965 clearAnnotationCache(&M);
970 //bool Result = AsmPrinter::doFinalization(M);
971 // Instead of calling the parents doFinalization, we may
972 // clone parents doFinalization and customize here.
973 // Currently, we if NVISA out the EmitGlobals() in
974 // parent's doFinalization, which is too intrusive.
976 // Same for the doInitialization.
980 // This function emits appropriate linkage directives for
981 // functions and global variables.
983 // extern function declaration -> .extern
984 // extern function definition -> .visible
985 // external global variable with init -> .visible
986 // external without init -> .extern
987 // appending -> not allowed, assert.
988 // for any linkage other than
989 // internal, private, linker_private,
990 // linker_private_weak, linker_private_weak_def_auto,
993 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
995 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
996 if (V->hasExternalLinkage()) {
997 if (isa<GlobalVariable>(V)) {
998 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1000 if (GVar->hasInitializer())
1005 } else if (V->isDeclaration())
1009 } else if (V->hasAppendingLinkage()) {
1011 msg.append("Error: ");
1012 msg.append("Symbol ");
1014 msg.append(V->getName().str());
1015 msg.append("has unsupported appending linkage type");
1016 llvm_unreachable(msg.c_str());
1017 } else if (!V->hasInternalLinkage() &&
1018 !V->hasPrivateLinkage()) {
1024 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1026 bool processDemoted) {
1029 if (GVar->hasSection()) {
1030 if (GVar->getSection() == StringRef("llvm.metadata"))
1034 // Skip LLVM intrinsic global variables
1035 if (GVar->getName().startswith("llvm.") ||
1036 GVar->getName().startswith("nvvm."))
1039 const DataLayout *TD = TM.getDataLayout();
1041 // GlobalVariables are always constant pointers themselves.
1042 const PointerType *PTy = GVar->getType();
1043 Type *ETy = PTy->getElementType();
1045 if (GVar->hasExternalLinkage()) {
1046 if (GVar->hasInitializer())
1050 } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1051 GVar->hasAvailableExternallyLinkage() ||
1052 GVar->hasCommonLinkage()) {
1056 if (llvm::isTexture(*GVar)) {
1057 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1061 if (llvm::isSurface(*GVar)) {
1062 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1066 if (GVar->isDeclaration()) {
1067 // (extern) declarations, no definition or initializer
1068 // Currently the only known declaration is for an automatic __local
1069 // (.shared) promoted to global.
1070 emitPTXGlobalVariable(GVar, O);
1075 if (llvm::isSampler(*GVar)) {
1076 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1078 const Constant *Initializer = nullptr;
1079 if (GVar->hasInitializer())
1080 Initializer = GVar->getInitializer();
1081 const ConstantInt *CI = nullptr;
1083 CI = dyn_cast<ConstantInt>(Initializer);
1085 unsigned sample = CI->getZExtValue();
1090 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1092 O << "addr_mode_" << i << " = ";
1098 O << "clamp_to_border";
1101 O << "clamp_to_edge";
1112 O << "filter_mode = ";
1113 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1121 llvm_unreachable("Anisotropic filtering is not supported");
1126 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1127 O << ", force_unnormalized_coords = 1";
1136 if (GVar->hasPrivateLinkage()) {
1138 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1141 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1142 if (!strncmp(GVar->getName().data(), "filename", 8))
1144 if (GVar->use_empty())
1148 const Function *demotedFunc = nullptr;
1149 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1150 O << "// " << GVar->getName().str() << " has been demoted\n";
1151 if (localDecls.find(demotedFunc) != localDecls.end())
1152 localDecls[demotedFunc].push_back(GVar);
1154 std::vector<const GlobalVariable *> temp;
1155 temp.push_back(GVar);
1156 localDecls[demotedFunc] = temp;
1162 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1164 if (isManaged(*GVar)) {
1165 O << " .attribute(.managed)";
1168 if (GVar->getAlignment() == 0)
1169 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1171 O << " .align " << GVar->getAlignment();
1173 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1175 // Special case: ABI requires that we use .u8 for predicates
1176 if (ETy->isIntegerTy(1))
1179 O << getPTXFundamentalTypeStr(ETy, false);
1181 O << *getSymbol(GVar);
1183 // Ptx allows variable initilization only for constant and global state
1185 if (GVar->hasInitializer()) {
1186 if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1187 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1188 const Constant *Initializer = GVar->getInitializer();
1189 // 'undef' is treated as there is no value spefied.
1190 if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1192 printScalarConstant(Initializer, O);
1195 // The frontend adds zero-initializer to variables that don't have an
1196 // initial value, so skip warning for this case.
1197 if (!GVar->getInitializer()->isNullValue()) {
1198 std::string warnMsg = "initial value of '" + GVar->getName().str() +
1199 "' is not allowed in addrspace(" +
1200 llvm::utostr_32(PTy->getAddressSpace()) + ")";
1201 report_fatal_error(warnMsg.c_str());
1206 unsigned int ElementSize = 0;
1208 // Although PTX has direct support for struct type and array type and
1209 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1210 // targets that support these high level field accesses. Structs, arrays
1211 // and vectors are lowered into arrays of bytes.
1212 switch (ETy->getTypeID()) {
1213 case Type::StructTyID:
1214 case Type::ArrayTyID:
1215 case Type::VectorTyID:
1216 ElementSize = TD->getTypeStoreSize(ETy);
1217 // Ptx allows variable initilization only for constant and
1218 // global state spaces.
1219 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1220 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1221 GVar->hasInitializer()) {
1222 const Constant *Initializer = GVar->getInitializer();
1223 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1224 AggBuffer aggBuffer(ElementSize, O, *this);
1225 bufferAggregateConstant(Initializer, &aggBuffer);
1226 if (aggBuffer.numSymbols) {
1227 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1228 O << " .u64 " << *getSymbol(GVar) << "[";
1229 O << ElementSize / 8;
1231 O << " .u32 " << *getSymbol(GVar) << "[";
1232 O << ElementSize / 4;
1236 O << " .b8 " << *getSymbol(GVar) << "[";
1244 O << " .b8 " << *getSymbol(GVar);
1252 O << " .b8 " << *getSymbol(GVar);
1261 llvm_unreachable("type not supported yet");
1268 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1269 if (localDecls.find(f) == localDecls.end())
1272 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1274 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1275 O << "\t// demoted variable\n\t";
1276 printModuleLevelGV(gvars[i], O, true);
1280 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1281 raw_ostream &O) const {
1282 switch (AddressSpace) {
1283 case llvm::ADDRESS_SPACE_LOCAL:
1286 case llvm::ADDRESS_SPACE_GLOBAL:
1289 case llvm::ADDRESS_SPACE_CONST:
1292 case llvm::ADDRESS_SPACE_SHARED:
1296 report_fatal_error("Bad address space found while emitting PTX");
1302 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1303 switch (Ty->getTypeID()) {
1305 llvm_unreachable("unexpected type");
1307 case Type::IntegerTyID: {
1308 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1311 else if (NumBits <= 64) {
1312 std::string name = "u";
1313 return name + utostr(NumBits);
1315 llvm_unreachable("Integer too large");
1320 case Type::FloatTyID:
1322 case Type::DoubleTyID:
1324 case Type::PointerTyID:
1325 if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1335 llvm_unreachable("unexpected type");
1339 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1342 const DataLayout *TD = TM.getDataLayout();
1344 // GlobalVariables are always constant pointers themselves.
1345 const PointerType *PTy = GVar->getType();
1346 Type *ETy = PTy->getElementType();
1349 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1350 if (GVar->getAlignment() == 0)
1351 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1353 O << " .align " << GVar->getAlignment();
1355 if (ETy->isFloatingPointTy() || ETy->isIntegerTy() || ETy->isPointerTy()) {
1357 O << getPTXFundamentalTypeStr(ETy);
1359 O << *getSymbol(GVar);
1363 int64_t ElementSize = 0;
1365 // Although PTX has direct support for struct type and array type and LLVM IR
1366 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1367 // support these high level field accesses. Structs and arrays are lowered
1368 // into arrays of bytes.
1369 switch (ETy->getTypeID()) {
1370 case Type::StructTyID:
1371 case Type::ArrayTyID:
1372 case Type::VectorTyID:
1373 ElementSize = TD->getTypeStoreSize(ETy);
1374 O << " .b8 " << *getSymbol(GVar) << "[";
1376 O << itostr(ElementSize);
1381 llvm_unreachable("type not supported yet");
1386 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1387 if (Ty->isSingleValueType())
1388 return TD->getPrefTypeAlignment(Ty);
1390 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1392 return getOpenCLAlignment(TD, ATy->getElementType());
1394 const StructType *STy = dyn_cast<StructType>(Ty);
1396 unsigned int alignStruct = 1;
1397 // Go through each element of the struct and find the
1398 // largest alignment.
1399 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1400 Type *ETy = STy->getElementType(i);
1401 unsigned int align = getOpenCLAlignment(TD, ETy);
1402 if (align > alignStruct)
1403 alignStruct = align;
1408 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1410 return TD->getPointerPrefAlignment();
1411 return TD->getPrefTypeAlignment(Ty);
1414 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1415 int paramIndex, raw_ostream &O) {
1416 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1419 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1420 O << *CurrentFnSym << "_param_" << paramIndex;
1423 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1424 const DataLayout *TD = TM.getDataLayout();
1425 const AttributeSet &PAL = F->getAttributes();
1426 const TargetLowering *TLI = nvptxSubtarget->getTargetLowering();
1427 Function::const_arg_iterator I, E;
1428 unsigned paramIndex = 0;
1430 bool isKernelFunc = llvm::isKernelFunction(*F);
1431 bool isABI = (nvptxSubtarget->getSmVersion() >= 20);
1432 MVT thePointerTy = TLI->getPointerTy();
1436 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1437 Type *Ty = I->getType();
1444 // Handle image/sampler parameters
1445 if (isKernelFunction(*F)) {
1446 if (isSampler(*I) || isImage(*I)) {
1448 std::string sname = I->getName();
1449 if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1450 if (nvptxSubtarget->hasImageHandles())
1451 O << "\t.param .u64 .ptr .surfref ";
1453 O << "\t.param .surfref ";
1454 O << *CurrentFnSym << "_param_" << paramIndex;
1456 else { // Default image is read_only
1457 if (nvptxSubtarget->hasImageHandles())
1458 O << "\t.param .u64 .ptr .texref ";
1460 O << "\t.param .texref ";
1461 O << *CurrentFnSym << "_param_" << paramIndex;
1464 if (nvptxSubtarget->hasImageHandles())
1465 O << "\t.param .u64 .ptr .samplerref ";
1467 O << "\t.param .samplerref ";
1468 O << *CurrentFnSym << "_param_" << paramIndex;
1474 if (!PAL.hasAttribute(paramIndex + 1, Attribute::ByVal)) {
1475 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1476 // Just print .param .align <a> .b8 .param[size];
1477 // <a> = PAL.getparamalignment
1478 // size = typeallocsize of element type
1479 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1481 align = TD->getABITypeAlignment(Ty);
1483 unsigned sz = TD->getTypeAllocSize(Ty);
1484 O << "\t.param .align " << align << " .b8 ";
1485 printParamName(I, paramIndex, O);
1486 O << "[" << sz << "]";
1491 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1494 // Special handling for pointer arguments to kernel
1495 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1497 if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1499 Type *ETy = PTy->getElementType();
1500 int addrSpace = PTy->getAddressSpace();
1501 switch (addrSpace) {
1505 case llvm::ADDRESS_SPACE_CONST:
1506 O << ".ptr .const ";
1508 case llvm::ADDRESS_SPACE_SHARED:
1509 O << ".ptr .shared ";
1511 case llvm::ADDRESS_SPACE_GLOBAL:
1512 O << ".ptr .global ";
1515 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1517 printParamName(I, paramIndex, O);
1521 // non-pointer scalar to kernel func
1523 // Special case: predicate operands become .u8 types
1524 if (Ty->isIntegerTy(1))
1527 O << getPTXFundamentalTypeStr(Ty);
1529 printParamName(I, paramIndex, O);
1532 // Non-kernel function, just print .param .b<size> for ABI
1533 // and .reg .b<size> for non-ABI
1535 if (isa<IntegerType>(Ty)) {
1536 sz = cast<IntegerType>(Ty)->getBitWidth();
1539 } else if (isa<PointerType>(Ty))
1540 sz = thePointerTy.getSizeInBits();
1542 sz = Ty->getPrimitiveSizeInBits();
1544 O << "\t.param .b" << sz << " ";
1546 O << "\t.reg .b" << sz << " ";
1547 printParamName(I, paramIndex, O);
1551 // param has byVal attribute. So should be a pointer
1552 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1553 assert(PTy && "Param with byval attribute should be a pointer type");
1554 Type *ETy = PTy->getElementType();
1556 if (isABI || isKernelFunc) {
1557 // Just print .param .align <a> .b8 .param[size];
1558 // <a> = PAL.getparamalignment
1559 // size = typeallocsize of element type
1560 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1562 align = TD->getABITypeAlignment(ETy);
1564 unsigned sz = TD->getTypeAllocSize(ETy);
1565 O << "\t.param .align " << align << " .b8 ";
1566 printParamName(I, paramIndex, O);
1567 O << "[" << sz << "]";
1570 // Split the ETy into constituent parts and
1571 // print .param .b<size> <name> for each part.
1572 // Further, if a part is vector, print the above for
1573 // each vector element.
1574 SmallVector<EVT, 16> vtparts;
1575 ComputeValueVTs(*TLI, ETy, vtparts);
1576 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1578 EVT elemtype = vtparts[i];
1579 if (vtparts[i].isVector()) {
1580 elems = vtparts[i].getVectorNumElements();
1581 elemtype = vtparts[i].getVectorElementType();
1584 for (unsigned j = 0, je = elems; j != je; ++j) {
1585 unsigned sz = elemtype.getSizeInBits();
1586 if (elemtype.isInteger() && (sz < 32))
1588 O << "\t.reg .b" << sz << " ";
1589 printParamName(I, paramIndex, O);
1605 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1607 const Function *F = MF.getFunction();
1608 emitFunctionParamList(F, O);
1611 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1612 const MachineFunction &MF) {
1613 SmallString<128> Str;
1614 raw_svector_ostream O(Str);
1616 // Map the global virtual register number to a register class specific
1617 // virtual register number starting from 1 with that class.
1618 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1619 //unsigned numRegClasses = TRI->getNumRegClasses();
1621 // Emit the Fake Stack Object
1622 const MachineFrameInfo *MFI = MF.getFrameInfo();
1623 int NumBytes = (int) MFI->getStackSize();
1625 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1626 << getFunctionNumber() << "[" << NumBytes << "];\n";
1627 if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1628 O << "\t.reg .b64 \t%SP;\n";
1629 O << "\t.reg .b64 \t%SPL;\n";
1631 O << "\t.reg .b32 \t%SP;\n";
1632 O << "\t.reg .b32 \t%SPL;\n";
1636 // Go through all virtual registers to establish the mapping between the
1638 // register number and the per class virtual register number.
1639 // We use the per class virtual register number in the ptx output.
1640 unsigned int numVRs = MRI->getNumVirtRegs();
1641 for (unsigned i = 0; i < numVRs; i++) {
1642 unsigned int vr = TRI->index2VirtReg(i);
1643 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1644 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1645 int n = regmap.size();
1646 regmap.insert(std::make_pair(vr, n + 1));
1649 // Emit register declarations
1650 // @TODO: Extract out the real register usage
1651 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1652 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1653 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1654 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1655 // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1656 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1657 // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1659 // Emit declaration of the virtual registers or 'physical' registers for
1660 // each register class
1661 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1662 const TargetRegisterClass *RC = TRI->getRegClass(i);
1663 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1664 std::string rcname = getNVPTXRegClassName(RC);
1665 std::string rcStr = getNVPTXRegClassStr(RC);
1666 int n = regmap.size();
1668 // Only declare those registers that may be used.
1670 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1675 OutStreamer.EmitRawText(O.str());
1678 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1679 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1681 unsigned int numHex;
1684 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1687 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1688 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1691 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1693 llvm_unreachable("unsupported fp type");
1695 APInt API = APF.bitcastToAPInt();
1696 std::string hexstr(utohexstr(API.getZExtValue()));
1698 if (hexstr.length() < numHex)
1699 O << std::string(numHex - hexstr.length(), '0');
1700 O << utohexstr(API.getZExtValue());
1703 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1704 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1705 O << CI->getValue();
1708 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1709 printFPConstant(CFP, O);
1712 if (isa<ConstantPointerNull>(CPV)) {
1716 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1717 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1718 bool IsNonGenericPointer = false;
1719 if (PTy && PTy->getAddressSpace() != 0) {
1720 IsNonGenericPointer = true;
1722 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1724 O << *getSymbol(GVar);
1727 O << *getSymbol(GVar);
1731 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1732 const Value *v = Cexpr->stripPointerCasts();
1733 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1734 bool IsNonGenericPointer = false;
1735 if (PTy && PTy->getAddressSpace() != 0) {
1736 IsNonGenericPointer = true;
1738 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1739 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1741 O << *getSymbol(GVar);
1744 O << *getSymbol(GVar);
1748 O << *lowerConstant(CPV);
1752 llvm_unreachable("Not scalar type found in printScalarConstant()");
1755 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1756 AggBuffer *aggBuffer) {
1758 const DataLayout *TD = TM.getDataLayout();
1760 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1761 int s = TD->getTypeAllocSize(CPV->getType());
1764 aggBuffer->addZeros(s);
1769 switch (CPV->getType()->getTypeID()) {
1771 case Type::IntegerTyID: {
1772 const Type *ETy = CPV->getType();
1773 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1775 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1777 aggBuffer->addBytes(ptr, 1, Bytes);
1778 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1779 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1780 ptr = (unsigned char *)&int16;
1781 aggBuffer->addBytes(ptr, 2, Bytes);
1782 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1783 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1784 int int32 = (int)(constInt->getZExtValue());
1785 ptr = (unsigned char *)&int32;
1786 aggBuffer->addBytes(ptr, 4, Bytes);
1788 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1789 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1790 ConstantFoldConstantExpression(Cexpr, *TD))) {
1791 int int32 = (int)(constInt->getZExtValue());
1792 ptr = (unsigned char *)&int32;
1793 aggBuffer->addBytes(ptr, 4, Bytes);
1796 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1797 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1798 aggBuffer->addSymbol(v);
1799 aggBuffer->addZeros(4);
1803 llvm_unreachable("unsupported integer const type");
1804 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1805 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1806 long long int64 = (long long)(constInt->getZExtValue());
1807 ptr = (unsigned char *)&int64;
1808 aggBuffer->addBytes(ptr, 8, Bytes);
1810 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1811 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1812 ConstantFoldConstantExpression(Cexpr, *TD))) {
1813 long long int64 = (long long)(constInt->getZExtValue());
1814 ptr = (unsigned char *)&int64;
1815 aggBuffer->addBytes(ptr, 8, Bytes);
1818 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1819 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1820 aggBuffer->addSymbol(v);
1821 aggBuffer->addZeros(8);
1825 llvm_unreachable("unsupported integer const type");
1827 llvm_unreachable("unsupported integer const type");
1830 case Type::FloatTyID:
1831 case Type::DoubleTyID: {
1832 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1833 const Type *Ty = CFP->getType();
1834 if (Ty == Type::getFloatTy(CPV->getContext())) {
1835 float float32 = (float) CFP->getValueAPF().convertToFloat();
1836 ptr = (unsigned char *)&float32;
1837 aggBuffer->addBytes(ptr, 4, Bytes);
1838 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1839 double float64 = CFP->getValueAPF().convertToDouble();
1840 ptr = (unsigned char *)&float64;
1841 aggBuffer->addBytes(ptr, 8, Bytes);
1843 llvm_unreachable("unsupported fp const type");
1847 case Type::PointerTyID: {
1848 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1849 aggBuffer->addSymbol(GVar);
1850 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1851 const Value *v = Cexpr->stripPointerCasts();
1852 aggBuffer->addSymbol(v);
1854 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1855 aggBuffer->addZeros(s);
1859 case Type::ArrayTyID:
1860 case Type::VectorTyID:
1861 case Type::StructTyID: {
1862 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1863 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1864 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1865 bufferAggregateConstant(CPV, aggBuffer);
1866 if (Bytes > ElementSize)
1867 aggBuffer->addZeros(Bytes - ElementSize);
1868 } else if (isa<ConstantAggregateZero>(CPV))
1869 aggBuffer->addZeros(Bytes);
1871 llvm_unreachable("Unexpected Constant type");
1876 llvm_unreachable("unsupported type");
1880 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1881 AggBuffer *aggBuffer) {
1882 const DataLayout *TD = TM.getDataLayout();
1886 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1887 if (CPV->getNumOperands())
1888 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1889 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1893 if (const ConstantDataSequential *CDS =
1894 dyn_cast<ConstantDataSequential>(CPV)) {
1895 if (CDS->getNumElements())
1896 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1897 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1902 if (isa<ConstantStruct>(CPV)) {
1903 if (CPV->getNumOperands()) {
1904 StructType *ST = cast<StructType>(CPV->getType());
1905 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1907 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1908 TD->getTypeAllocSize(ST) -
1909 TD->getStructLayout(ST)->getElementOffset(i);
1911 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1912 TD->getStructLayout(ST)->getElementOffset(i);
1913 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1918 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1921 // buildTypeNameMap - Run through symbol table looking for type names.
1924 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1926 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1928 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1929 !PI->second.compare("struct._image2d_t") ||
1930 !PI->second.compare("struct._image3d_t")))
1937 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1938 switch (MI.getOpcode()) {
1941 case NVPTX::CallArgBeginInst:
1942 case NVPTX::CallArgEndInst0:
1943 case NVPTX::CallArgEndInst1:
1944 case NVPTX::CallArgF32:
1945 case NVPTX::CallArgF64:
1946 case NVPTX::CallArgI16:
1947 case NVPTX::CallArgI32:
1948 case NVPTX::CallArgI32imm:
1949 case NVPTX::CallArgI64:
1950 case NVPTX::CallArgParam:
1951 case NVPTX::CallVoidInst:
1952 case NVPTX::CallVoidInstReg:
1953 case NVPTX::Callseq_End:
1954 case NVPTX::CallVoidInstReg64:
1955 case NVPTX::DeclareParamInst:
1956 case NVPTX::DeclareRetMemInst:
1957 case NVPTX::DeclareRetRegInst:
1958 case NVPTX::DeclareRetScalarInst:
1959 case NVPTX::DeclareScalarParamInst:
1960 case NVPTX::DeclareScalarRegInst:
1961 case NVPTX::StoreParamF32:
1962 case NVPTX::StoreParamF64:
1963 case NVPTX::StoreParamI16:
1964 case NVPTX::StoreParamI32:
1965 case NVPTX::StoreParamI64:
1966 case NVPTX::StoreParamI8:
1967 case NVPTX::StoreRetvalF32:
1968 case NVPTX::StoreRetvalF64:
1969 case NVPTX::StoreRetvalI16:
1970 case NVPTX::StoreRetvalI32:
1971 case NVPTX::StoreRetvalI64:
1972 case NVPTX::StoreRetvalI8:
1973 case NVPTX::LastCallArgF32:
1974 case NVPTX::LastCallArgF64:
1975 case NVPTX::LastCallArgI16:
1976 case NVPTX::LastCallArgI32:
1977 case NVPTX::LastCallArgI32imm:
1978 case NVPTX::LastCallArgI64:
1979 case NVPTX::LastCallArgParam:
1980 case NVPTX::LoadParamMemF32:
1981 case NVPTX::LoadParamMemF64:
1982 case NVPTX::LoadParamMemI16:
1983 case NVPTX::LoadParamMemI32:
1984 case NVPTX::LoadParamMemI64:
1985 case NVPTX::LoadParamMemI8:
1986 case NVPTX::PrototypeInst:
1987 case NVPTX::DBG_VALUE:
1993 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1995 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1996 unsigned AsmVariant,
1997 const char *ExtraCode, raw_ostream &O) {
1998 if (ExtraCode && ExtraCode[0]) {
1999 if (ExtraCode[1] != 0)
2000 return true; // Unknown modifier.
2002 switch (ExtraCode[0]) {
2004 // See if this is a generic print operand
2005 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2011 printOperand(MI, OpNo, O);
2016 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2017 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2018 const char *ExtraCode, raw_ostream &O) {
2019 if (ExtraCode && ExtraCode[0])
2020 return true; // Unknown modifier
2023 printMemOperand(MI, OpNo, O);
2029 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2030 raw_ostream &O, const char *Modifier) {
2031 const MachineOperand &MO = MI->getOperand(opNum);
2032 switch (MO.getType()) {
2033 case MachineOperand::MO_Register:
2034 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2035 if (MO.getReg() == NVPTX::VRDepot)
2036 O << DEPOTNAME << getFunctionNumber();
2038 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2040 emitVirtualRegister(MO.getReg(), O);
2044 case MachineOperand::MO_Immediate:
2047 else if (strstr(Modifier, "vec") == Modifier)
2048 printVecModifiedImmediate(MO, Modifier, O);
2051 "Don't know how to handle modifier on immediate operand");
2054 case MachineOperand::MO_FPImmediate:
2055 printFPConstant(MO.getFPImm(), O);
2058 case MachineOperand::MO_GlobalAddress:
2059 O << *getSymbol(MO.getGlobal());
2062 case MachineOperand::MO_MachineBasicBlock:
2063 O << *MO.getMBB()->getSymbol();
2067 llvm_unreachable("Operand type not supported.");
2071 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2072 raw_ostream &O, const char *Modifier) {
2073 printOperand(MI, opNum, O);
2075 if (Modifier && !strcmp(Modifier, "add")) {
2077 printOperand(MI, opNum + 1, O);
2079 if (MI->getOperand(opNum + 1).isImm() &&
2080 MI->getOperand(opNum + 1).getImm() == 0)
2081 return; // don't print ',0' or '+0'
2083 printOperand(MI, opNum + 1, O);
2087 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2088 std::stringstream temp;
2089 LineReader *reader = this->getReader(filename.str());
2091 temp << filename.str();
2095 temp << reader->readLine(line);
2097 this->OutStreamer.EmitRawText(Twine(temp.str()));
2100 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2102 reader = new LineReader(filename);
2105 if (reader->fileName() != filename) {
2107 reader = new LineReader(filename);
2113 std::string LineReader::readLine(unsigned lineNum) {
2114 if (lineNum < theCurLine) {
2116 fstr.seekg(0, std::ios::beg);
2118 while (theCurLine < lineNum) {
2119 fstr.getline(buff, 500);
2125 // Force static initialization.
2126 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2127 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2128 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);