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 "MCTargetDesc/NVPTXMCAsmInfo.h"
18 #include "NVPTXInstrInfo.h"
19 #include "NVPTXNumRegisters.h"
20 #include "NVPTXRegisterInfo.h"
21 #include "NVPTXTargetMachine.h"
22 #include "NVPTXUtilities.h"
23 #include "cl_common_defines.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TimeValue.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #include "NVPTXGenAsmWriter.inc"
52 bool RegAllocNilUsed = true;
54 #define DEPOTNAME "__local_depot"
57 EmitLineNumbers("nvptx-emit-line-numbers",
58 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
61 namespace llvm { bool InterleaveSrcInPtx = false; }
63 static cl::opt<bool, true>
64 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
65 cl::desc("NVPTX Specific: Emit source line in ptx file"),
66 cl::location(llvm::InterleaveSrcInPtx));
69 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
71 void DiscoverDependentGlobals(const Value *V,
72 DenseSet<const GlobalVariable *> &Globals) {
73 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
76 if (const User *U = dyn_cast<User>(V)) {
77 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
78 DiscoverDependentGlobals(U->getOperand(i), Globals);
84 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
85 /// instances to be emitted, but only after any dependents have been added
87 void VisitGlobalVariableForEmission(
88 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
89 DenseSet<const GlobalVariable *> &Visited,
90 DenseSet<const GlobalVariable *> &Visiting) {
91 // Have we already visited this one?
92 if (Visited.count(GV))
95 // Do we have a circular dependency?
96 if (Visiting.count(GV))
97 report_fatal_error("Circular dependency found in global variable set");
99 // Start visiting this global
102 // Make sure we visit all dependents first
103 DenseSet<const GlobalVariable *> Others;
104 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
105 DiscoverDependentGlobals(GV->getOperand(i), Others);
107 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
110 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
112 // Now we can visit ourself
119 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
120 // cannot just link to the existing version.
121 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
123 using namespace nvptx;
124 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
125 MCContext &Ctx = AP.OutContext;
127 if (CV->isNullValue() || isa<UndefValue>(CV))
128 return MCConstantExpr::Create(0, Ctx);
130 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
131 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
133 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
134 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
136 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
137 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
139 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
141 llvm_unreachable("Unknown constant value to lower!");
143 switch (CE->getOpcode()) {
145 // If the code isn't optimized, there may be outstanding folding
146 // opportunities. Attempt to fold the expression using DataLayout as a
147 // last resort before giving up.
148 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
150 return LowerConstant(C, AP);
152 // Otherwise report the problem to the user.
155 raw_string_ostream OS(S);
156 OS << "Unsupported expression in static initializer: ";
157 WriteAsOperand(OS, CE, /*PrintType=*/ false,
158 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
159 report_fatal_error(OS.str());
161 case Instruction::GetElementPtr: {
162 const DataLayout &TD = *AP.TM.getDataLayout();
163 // Generate a symbolic expression for the byte address
164 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
165 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
167 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
171 int64_t Offset = OffsetAI.getSExtValue();
172 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
176 case Instruction::Trunc:
177 // We emit the value and depend on the assembler to truncate the generated
178 // expression properly. This is important for differences between
179 // blockaddress labels. Since the two labels are in the same function, it
180 // is reasonable to treat their delta as a 32-bit value.
182 case Instruction::BitCast:
183 return LowerConstant(CE->getOperand(0), AP);
185 case Instruction::IntToPtr: {
186 const DataLayout &TD = *AP.TM.getDataLayout();
187 // Handle casts to pointers by changing them into casts to the appropriate
188 // integer type. This promotes constant folding and simplifies this code.
189 Constant *Op = CE->getOperand(0);
190 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
192 return LowerConstant(Op, AP);
195 case Instruction::PtrToInt: {
196 const DataLayout &TD = *AP.TM.getDataLayout();
197 // Support only foldable casts to/from pointers that can be eliminated by
198 // changing the pointer to the appropriately sized integer type.
199 Constant *Op = CE->getOperand(0);
200 Type *Ty = CE->getType();
202 const MCExpr *OpExpr = LowerConstant(Op, AP);
204 // We can emit the pointer value into this slot if the slot is an
205 // integer slot equal to the size of the pointer.
206 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
209 // Otherwise the pointer is smaller than the resultant integer, mask off
210 // the high bits so we are sure to get a proper truncation if the input is
212 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
213 const MCExpr *MaskExpr =
214 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
215 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
218 // The MC library also has a right-shift operator, but it isn't consistently
219 // signed or unsigned between different targets.
220 case Instruction::Add:
221 case Instruction::Sub:
222 case Instruction::Mul:
223 case Instruction::SDiv:
224 case Instruction::SRem:
225 case Instruction::Shl:
226 case Instruction::And:
227 case Instruction::Or:
228 case Instruction::Xor: {
229 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
230 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
231 switch (CE->getOpcode()) {
233 llvm_unreachable("Unknown binary operator constant cast expr");
234 case Instruction::Add:
235 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
236 case Instruction::Sub:
237 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
238 case Instruction::Mul:
239 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
240 case Instruction::SDiv:
241 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
242 case Instruction::SRem:
243 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
244 case Instruction::Shl:
245 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
246 case Instruction::And:
247 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
248 case Instruction::Or:
249 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
250 case Instruction::Xor:
251 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
257 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
258 if (!EmitLineNumbers)
263 DebugLoc curLoc = MI.getDebugLoc();
265 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
268 if (prevDebugLoc == curLoc)
271 prevDebugLoc = curLoc;
273 if (curLoc.isUnknown())
276 const MachineFunction *MF = MI.getParent()->getParent();
277 //const TargetMachine &TM = MF->getTarget();
279 const LLVMContext &ctx = MF->getFunction()->getContext();
280 DIScope Scope(curLoc.getScope(ctx));
282 assert((!Scope || Scope.isScope()) &&
283 "Scope of a DebugLoc should be null or a DIScope.");
287 StringRef fileName(Scope.getFilename());
288 StringRef dirName(Scope.getDirectory());
289 SmallString<128> FullPathName = dirName;
290 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
291 sys::path::append(FullPathName, fileName);
292 fileName = FullPathName.str();
295 if (filenameMap.find(fileName.str()) == filenameMap.end())
298 // Emit the line from the source file.
299 if (llvm::InterleaveSrcInPtx)
300 this->emitSrcInText(fileName.str(), curLoc.getLine());
302 std::stringstream temp;
303 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
304 << " " << curLoc.getCol();
305 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
308 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
309 SmallString<128> Str;
310 raw_svector_ostream OS(Str);
311 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
312 emitLineNumberAsDotLoc(*MI);
313 printInstruction(MI, OS);
314 OutStreamer.EmitRawText(OS.str());
317 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
318 const DataLayout *TD = TM.getDataLayout();
319 const TargetLowering *TLI = TM.getTargetLowering();
321 Type *Ty = F->getReturnType();
323 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
325 if (Ty->getTypeID() == Type::VoidTyID)
331 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
333 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
334 size = ITy->getBitWidth();
338 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
339 size = Ty->getPrimitiveSizeInBits();
342 O << ".param .b" << size << " func_retval0";
343 } else if (isa<PointerType>(Ty)) {
344 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
347 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
348 SmallVector<EVT, 16> vtparts;
349 ComputeValueVTs(*TLI, Ty, vtparts);
350 unsigned totalsz = 0;
351 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
353 EVT elemtype = vtparts[i];
354 if (vtparts[i].isVector()) {
355 elems = vtparts[i].getVectorNumElements();
356 elemtype = vtparts[i].getVectorElementType();
358 for (unsigned j = 0, je = elems; j != je; ++j) {
359 unsigned sz = elemtype.getSizeInBits();
360 if (elemtype.isInteger() && (sz < 8))
365 unsigned retAlignment = 0;
366 if (!llvm::getAlign(*F, 0, retAlignment))
367 retAlignment = TD->getABITypeAlignment(Ty);
368 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
371 assert(false && "Unknown return type");
374 SmallVector<EVT, 16> vtparts;
375 ComputeValueVTs(*TLI, Ty, vtparts);
377 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
379 EVT elemtype = vtparts[i];
380 if (vtparts[i].isVector()) {
381 elems = vtparts[i].getVectorNumElements();
382 elemtype = vtparts[i].getVectorElementType();
385 for (unsigned j = 0, je = elems; j != je; ++j) {
386 unsigned sz = elemtype.getSizeInBits();
387 if (elemtype.isInteger() && (sz < 32))
389 O << ".reg .b" << sz << " func_retval" << idx;
402 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
404 const Function *F = MF.getFunction();
405 printReturnValStr(F, O);
408 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
409 SmallString<128> Str;
410 raw_svector_ostream O(Str);
412 if (!GlobalsEmitted) {
413 emitGlobals(*MF->getFunction()->getParent());
414 GlobalsEmitted = true;
418 MRI = &MF->getRegInfo();
419 F = MF->getFunction();
420 emitLinkageDirective(F, O);
421 if (llvm::isKernelFunction(*F))
425 printReturnValStr(*MF, O);
430 emitFunctionParamList(*MF, O);
432 if (llvm::isKernelFunction(*F))
433 emitKernelFunctionDirectives(*F, O);
435 OutStreamer.EmitRawText(O.str());
437 prevDebugLoc = DebugLoc();
440 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
442 OutStreamer.EmitRawText(StringRef("{\n"));
443 setAndEmitFunctionVirtualRegisters(*MF);
445 SmallString<128> Str;
446 raw_svector_ostream O(Str);
447 emitDemotedVars(MF->getFunction(), O);
448 OutStreamer.EmitRawText(O.str());
451 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
452 OutStreamer.EmitRawText(StringRef("}\n"));
456 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
457 raw_ostream &O) const {
458 // If the NVVM IR has some of reqntid* specified, then output
459 // the reqntid directive, and set the unspecified ones to 1.
460 // If none of reqntid* is specified, don't output reqntid directive.
461 unsigned reqntidx, reqntidy, reqntidz;
462 bool specified = false;
463 if (llvm::getReqNTIDx(F, reqntidx) == false)
467 if (llvm::getReqNTIDy(F, reqntidy) == false)
471 if (llvm::getReqNTIDz(F, reqntidz) == false)
477 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
480 // If the NVVM IR has some of maxntid* specified, then output
481 // the maxntid directive, and set the unspecified ones to 1.
482 // If none of maxntid* is specified, don't output maxntid directive.
483 unsigned maxntidx, maxntidy, maxntidz;
485 if (llvm::getMaxNTIDx(F, maxntidx) == false)
489 if (llvm::getMaxNTIDy(F, maxntidy) == false)
493 if (llvm::getMaxNTIDz(F, maxntidz) == false)
499 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
503 if (llvm::getMinCTASm(F, mincta))
504 O << ".minnctapersm " << mincta << "\n";
507 void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
509 const TargetRegisterClass *RC = MRI->getRegClass(vr);
511 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
512 unsigned mapped_vr = regmap[vr];
515 O << getNVPTXRegClassStr(RC) << mapped_vr;
518 report_fatal_error("Bad register!");
521 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
523 getVirtualRegisterName(vr, isVec, O);
526 void NVPTXAsmPrinter::printVecModifiedImmediate(
527 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
528 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
529 int Imm = (int) MO.getImm();
530 if (0 == strcmp(Modifier, "vecelem"))
531 O << "_" << vecelem[Imm];
532 else if (0 == strcmp(Modifier, "vecv4comm1")) {
533 if ((Imm < 0) || (Imm > 3))
535 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
536 if ((Imm < 4) || (Imm > 7))
538 } else if (0 == strcmp(Modifier, "vecv4pos")) {
541 O << "_" << vecelem[Imm % 4];
542 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
543 if ((Imm < 0) || (Imm > 1))
545 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
546 if ((Imm < 2) || (Imm > 3))
548 } else if (0 == strcmp(Modifier, "vecv2pos")) {
551 O << "_" << vecelem[Imm % 2];
553 llvm_unreachable("Unknown Modifier on immediate operand");
556 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
557 raw_ostream &O, const char *Modifier) {
558 const MachineOperand &MO = MI->getOperand(opNum);
559 switch (MO.getType()) {
560 case MachineOperand::MO_Register:
561 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
562 if (MO.getReg() == NVPTX::VRDepot)
563 O << DEPOTNAME << getFunctionNumber();
565 O << getRegisterName(MO.getReg());
568 emitVirtualRegister(MO.getReg(), false, O);
570 if (strcmp(Modifier, "vecfull") == 0)
571 emitVirtualRegister(MO.getReg(), true, O);
574 "Don't know how to handle the modifier on virtual register.");
579 case MachineOperand::MO_Immediate:
582 else if (strstr(Modifier, "vec") == Modifier)
583 printVecModifiedImmediate(MO, Modifier, O);
586 "Don't know how to handle modifier on immediate operand");
589 case MachineOperand::MO_FPImmediate:
590 printFPConstant(MO.getFPImm(), O);
593 case MachineOperand::MO_GlobalAddress:
594 O << *Mang->getSymbol(MO.getGlobal());
597 case MachineOperand::MO_ExternalSymbol: {
598 const char *symbname = MO.getSymbolName();
599 if (strstr(symbname, ".PARAM") == symbname) {
601 sscanf(symbname + 6, "%u[];", &index);
602 printParamName(index, O);
603 } else if (strstr(symbname, ".HLPPARAM") == symbname) {
605 sscanf(symbname + 9, "%u[];", &index);
606 O << *CurrentFnSym << "_param_" << index << "_offset";
612 case MachineOperand::MO_MachineBasicBlock:
613 O << *MO.getMBB()->getSymbol();
617 llvm_unreachable("Operand type not supported.");
621 void NVPTXAsmPrinter::printImplicitDef(const MachineInstr *MI,
622 raw_ostream &O) const {
624 O << "\t// Implicit def :";
625 //printOperand(MI, 0);
630 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
631 raw_ostream &O, const char *Modifier) {
632 printOperand(MI, opNum, O);
634 if (Modifier && !strcmp(Modifier, "add")) {
636 printOperand(MI, opNum + 1, O);
638 if (MI->getOperand(opNum + 1).isImm() &&
639 MI->getOperand(opNum + 1).getImm() == 0)
640 return; // don't print ',0' or '+0'
642 printOperand(MI, opNum + 1, O);
646 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
647 raw_ostream &O, const char *Modifier) {
649 const MachineOperand &MO = MI->getOperand(opNum);
650 int Imm = (int) MO.getImm();
651 if (!strcmp(Modifier, "volatile")) {
654 } else if (!strcmp(Modifier, "addsp")) {
656 case NVPTX::PTXLdStInstCode::GLOBAL:
659 case NVPTX::PTXLdStInstCode::SHARED:
662 case NVPTX::PTXLdStInstCode::LOCAL:
665 case NVPTX::PTXLdStInstCode::PARAM:
668 case NVPTX::PTXLdStInstCode::CONSTANT:
671 case NVPTX::PTXLdStInstCode::GENERIC:
672 if (!nvptxSubtarget.hasGenericLdSt())
676 llvm_unreachable("Wrong Address Space");
678 } else if (!strcmp(Modifier, "sign")) {
679 if (Imm == NVPTX::PTXLdStInstCode::Signed)
681 else if (Imm == NVPTX::PTXLdStInstCode::Unsigned)
685 } else if (!strcmp(Modifier, "vec")) {
686 if (Imm == NVPTX::PTXLdStInstCode::V2)
688 else if (Imm == NVPTX::PTXLdStInstCode::V4)
691 llvm_unreachable("Unknown Modifier");
693 llvm_unreachable("Empty Modifier");
696 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
698 emitLinkageDirective(F, O);
699 if (llvm::isKernelFunction(*F))
703 printReturnValStr(F, O);
704 O << *Mang->getSymbol(F) << "\n";
705 emitFunctionParamList(F, O);
709 static bool usedInGlobalVarDef(const Constant *C) {
713 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
714 if (GV->getName().str() == "llvm.used")
719 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
721 const Constant *C = dyn_cast<Constant>(*ui);
722 if (usedInGlobalVarDef(C))
728 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
729 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
730 if (othergv->getName().str() == "llvm.used")
734 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
735 if (instr->getParent() && instr->getParent()->getParent()) {
736 const Function *curFunc = instr->getParent()->getParent();
737 if (oneFunc && (curFunc != oneFunc))
745 if (const MDNode *md = dyn_cast<MDNode>(U))
746 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
747 (md->getName().str() == "llvm.dbg.sp")))
750 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
752 if (usedInOneFunc(*ui, oneFunc) == false)
758 /* Find out if a global variable can be demoted to local scope.
759 * Currently, this is valid for CUDA shared variables, which have local
760 * scope and global lifetime. So the conditions to check are :
761 * 1. Is the global variable in shared address space?
762 * 2. Does it have internal linkage?
763 * 3. Is the global variable referenced only in one function?
765 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
766 if (gv->hasInternalLinkage() == false)
768 const PointerType *Pty = gv->getType();
769 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
772 const Function *oneFunc = 0;
774 bool flag = usedInOneFunc(gv, oneFunc);
783 static bool useFuncSeen(const Constant *C,
784 llvm::DenseMap<const Function *, bool> &seenMap) {
785 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
787 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
788 if (useFuncSeen(cu, seenMap))
790 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
791 const BasicBlock *bb = I->getParent();
794 const Function *caller = bb->getParent();
797 if (seenMap.find(caller) != seenMap.end())
804 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
805 llvm::DenseMap<const Function *, bool> seenMap;
806 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
807 const Function *F = FI;
809 if (F->isDeclaration()) {
812 if (F->getIntrinsicID())
814 emitDeclaration(F, O);
817 for (Value::const_use_iterator iter = F->use_begin(),
818 iterEnd = F->use_end();
819 iter != iterEnd; ++iter) {
820 if (const Constant *C = dyn_cast<Constant>(*iter)) {
821 if (usedInGlobalVarDef(C)) {
822 // The use is in the initialization of a global variable
823 // that is a function pointer, so print a declaration
824 // for the original function
825 emitDeclaration(F, O);
828 // Emit a declaration of this function if the function that
829 // uses this constant expr has already been seen.
830 if (useFuncSeen(C, seenMap)) {
831 emitDeclaration(F, O);
836 if (!isa<Instruction>(*iter))
838 const Instruction *instr = cast<Instruction>(*iter);
839 const BasicBlock *bb = instr->getParent();
842 const Function *caller = bb->getParent();
846 // If a caller has already been seen, then the caller is
847 // appearing in the module before the callee. so print out
848 // a declaration for the callee.
849 if (seenMap.find(caller) != seenMap.end()) {
850 emitDeclaration(F, O);
858 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
859 DebugInfoFinder DbgFinder;
860 DbgFinder.processModule(M);
863 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
864 E = DbgFinder.compile_unit_end();
866 DICompileUnit DIUnit(*I);
867 StringRef Filename(DIUnit.getFilename());
868 StringRef Dirname(DIUnit.getDirectory());
869 SmallString<128> FullPathName = Dirname;
870 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
871 sys::path::append(FullPathName, Filename);
872 Filename = FullPathName.str();
874 if (filenameMap.find(Filename.str()) != filenameMap.end())
876 filenameMap[Filename.str()] = i;
877 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
881 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
882 E = DbgFinder.subprogram_end();
885 StringRef Filename(SP.getFilename());
886 StringRef Dirname(SP.getDirectory());
887 SmallString<128> FullPathName = Dirname;
888 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
889 sys::path::append(FullPathName, Filename);
890 Filename = FullPathName.str();
892 if (filenameMap.find(Filename.str()) != filenameMap.end())
894 filenameMap[Filename.str()] = i;
899 bool NVPTXAsmPrinter::doInitialization(Module &M) {
901 SmallString<128> Str1;
902 raw_svector_ostream OS1(Str1);
904 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
905 MMI->AnalyzeModule(M);
907 // We need to call the parent's one explicitly.
908 //bool Result = AsmPrinter::doInitialization(M);
910 // Initialize TargetLoweringObjectFile.
911 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
912 .Initialize(OutContext, TM);
914 Mang = new Mangler(OutContext, &TM);
916 // Emit header before any dwarf directives are emitted below.
918 OutStreamer.EmitRawText(OS1.str());
920 // Already commented out
921 //bool Result = AsmPrinter::doInitialization(M);
923 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
924 recordAndEmitFilenames(M);
926 GlobalsEmitted = false;
928 return false; // success
931 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
932 SmallString<128> Str2;
933 raw_svector_ostream OS2(Str2);
935 emitDeclarations(M, OS2);
937 // As ptxas does not support forward references of globals, we need to first
938 // sort the list of module-level globals in def-use order. We visit each
939 // global variable in order, and ensure that we emit it *after* its dependent
940 // globals. We use a little extra memory maintaining both a set and a list to
941 // have fast searches while maintaining a strict ordering.
942 SmallVector<const GlobalVariable *, 8> Globals;
943 DenseSet<const GlobalVariable *> GVVisited;
944 DenseSet<const GlobalVariable *> GVVisiting;
946 // Visit each global variable, in order
947 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
949 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
951 assert(GVVisited.size() == M.getGlobalList().size() &&
952 "Missed a global variable");
953 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
955 // Print out module-level global variables in proper order
956 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
957 printModuleLevelGV(Globals[i], OS2);
961 OutStreamer.EmitRawText(OS2.str());
964 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
966 O << "// Generated by LLVM NVPTX Back-End\n";
970 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
971 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
974 O << nvptxSubtarget.getTargetName();
976 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
977 O << ", texmode_independent";
978 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
979 if (!nvptxSubtarget.hasDouble())
980 O << ", map_f64_to_f32";
983 if (MAI->doesSupportDebugInformation())
988 O << ".address_size ";
989 if (nvptxSubtarget.is64Bit())
998 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1000 // If we did not emit any functions, then the global declarations have not
1001 // yet been emitted.
1002 if (!GlobalsEmitted) {
1004 GlobalsEmitted = true;
1007 // XXX Temproarily remove global variables so that doFinalization() will not
1008 // emit them again (global variables are emitted at beginning).
1010 Module::GlobalListType &global_list = M.getGlobalList();
1011 int i, n = global_list.size();
1012 GlobalVariable **gv_array = new GlobalVariable *[n];
1014 // first, back-up GlobalVariable in gv_array
1016 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1018 gv_array[i++] = &*I;
1020 // second, empty global_list
1021 while (!global_list.empty())
1022 global_list.remove(global_list.begin());
1024 // call doFinalization
1025 bool ret = AsmPrinter::doFinalization(M);
1027 // now we restore global variables
1028 for (i = 0; i < n; i++)
1029 global_list.insert(global_list.end(), gv_array[i]);
1034 //bool Result = AsmPrinter::doFinalization(M);
1035 // Instead of calling the parents doFinalization, we may
1036 // clone parents doFinalization and customize here.
1037 // Currently, we if NVISA out the EmitGlobals() in
1038 // parent's doFinalization, which is too intrusive.
1040 // Same for the doInitialization.
1044 // This function emits appropriate linkage directives for
1045 // functions and global variables.
1047 // extern function declaration -> .extern
1048 // extern function definition -> .visible
1049 // external global variable with init -> .visible
1050 // external without init -> .extern
1051 // appending -> not allowed, assert.
1053 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1055 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1056 if (V->hasExternalLinkage()) {
1057 if (isa<GlobalVariable>(V)) {
1058 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1060 if (GVar->hasInitializer())
1065 } else if (V->isDeclaration())
1069 } else if (V->hasAppendingLinkage()) {
1071 msg.append("Error: ");
1072 msg.append("Symbol ");
1074 msg.append(V->getName().str());
1075 msg.append("has unsupported appending linkage type");
1076 llvm_unreachable(msg.c_str());
1081 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1083 bool processDemoted) {
1086 if (GVar->hasSection()) {
1087 if (GVar->getSection() == "llvm.metadata")
1091 const DataLayout *TD = TM.getDataLayout();
1093 // GlobalVariables are always constant pointers themselves.
1094 const PointerType *PTy = GVar->getType();
1095 Type *ETy = PTy->getElementType();
1097 if (GVar->hasExternalLinkage()) {
1098 if (GVar->hasInitializer())
1104 if (llvm::isTexture(*GVar)) {
1105 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1109 if (llvm::isSurface(*GVar)) {
1110 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1114 if (GVar->isDeclaration()) {
1115 // (extern) declarations, no definition or initializer
1116 // Currently the only known declaration is for an automatic __local
1117 // (.shared) promoted to global.
1118 emitPTXGlobalVariable(GVar, O);
1123 if (llvm::isSampler(*GVar)) {
1124 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1126 const Constant *Initializer = NULL;
1127 if (GVar->hasInitializer())
1128 Initializer = GVar->getInitializer();
1129 const ConstantInt *CI = NULL;
1131 CI = dyn_cast<ConstantInt>(Initializer);
1133 unsigned sample = CI->getZExtValue();
1138 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1140 O << "addr_mode_" << i << " = ";
1146 O << "clamp_to_border";
1149 O << "clamp_to_edge";
1160 O << "filter_mode = ";
1161 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1169 assert(0 && "Anisotropic filtering is not supported");
1174 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1175 O << ", force_unnormalized_coords = 1";
1184 if (GVar->hasPrivateLinkage()) {
1186 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1189 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1190 if (!strncmp(GVar->getName().data(), "filename", 8))
1192 if (GVar->use_empty())
1196 const Function *demotedFunc = 0;
1197 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1198 O << "// " << GVar->getName().str() << " has been demoted\n";
1199 if (localDecls.find(demotedFunc) != localDecls.end())
1200 localDecls[demotedFunc].push_back(GVar);
1202 std::vector<const GlobalVariable *> temp;
1203 temp.push_back(GVar);
1204 localDecls[demotedFunc] = temp;
1210 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1211 if (GVar->getAlignment() == 0)
1212 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1214 O << " .align " << GVar->getAlignment();
1216 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1218 // Special case: ABI requires that we use .u8 for predicates
1219 if (ETy->isIntegerTy(1))
1222 O << getPTXFundamentalTypeStr(ETy, false);
1224 O << *Mang->getSymbol(GVar);
1226 // Ptx allows variable initilization only for constant and global state
1228 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1229 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1230 GVar->hasInitializer()) {
1231 const Constant *Initializer = GVar->getInitializer();
1232 if (!Initializer->isNullValue()) {
1234 printScalarConstant(Initializer, O);
1238 unsigned int ElementSize = 0;
1240 // Although PTX has direct support for struct type and array type and
1241 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1242 // targets that support these high level field accesses. Structs, arrays
1243 // and vectors are lowered into arrays of bytes.
1244 switch (ETy->getTypeID()) {
1245 case Type::StructTyID:
1246 case Type::ArrayTyID:
1247 case Type::VectorTyID:
1248 ElementSize = TD->getTypeStoreSize(ETy);
1249 // Ptx allows variable initilization only for constant and
1250 // global state spaces.
1251 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1252 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1253 GVar->hasInitializer()) {
1254 const Constant *Initializer = GVar->getInitializer();
1255 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1256 AggBuffer aggBuffer(ElementSize, O, *this);
1257 bufferAggregateConstant(Initializer, &aggBuffer);
1258 if (aggBuffer.numSymbols) {
1259 if (nvptxSubtarget.is64Bit()) {
1260 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1261 O << ElementSize / 8;
1263 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1264 O << ElementSize / 4;
1268 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1276 O << " .b8 " << *Mang->getSymbol(GVar);
1284 O << " .b8 " << *Mang->getSymbol(GVar);
1293 assert(0 && "type not supported yet");
1300 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1301 if (localDecls.find(f) == localDecls.end())
1304 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1306 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1307 O << "\t// demoted variable\n\t";
1308 printModuleLevelGV(gvars[i], O, true);
1312 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1313 raw_ostream &O) const {
1314 switch (AddressSpace) {
1315 case llvm::ADDRESS_SPACE_LOCAL:
1318 case llvm::ADDRESS_SPACE_GLOBAL:
1321 case llvm::ADDRESS_SPACE_CONST:
1324 case llvm::ADDRESS_SPACE_SHARED:
1328 report_fatal_error("Bad address space found while emitting PTX");
1334 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1335 switch (Ty->getTypeID()) {
1337 llvm_unreachable("unexpected type");
1339 case Type::IntegerTyID: {
1340 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1343 else if (NumBits <= 64) {
1344 std::string name = "u";
1345 return name + utostr(NumBits);
1347 llvm_unreachable("Integer too large");
1352 case Type::FloatTyID:
1354 case Type::DoubleTyID:
1356 case Type::PointerTyID:
1357 if (nvptxSubtarget.is64Bit())
1367 llvm_unreachable("unexpected type");
1371 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1374 const DataLayout *TD = TM.getDataLayout();
1376 // GlobalVariables are always constant pointers themselves.
1377 const PointerType *PTy = GVar->getType();
1378 Type *ETy = PTy->getElementType();
1381 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1382 if (GVar->getAlignment() == 0)
1383 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1385 O << " .align " << GVar->getAlignment();
1387 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1389 O << getPTXFundamentalTypeStr(ETy);
1391 O << *Mang->getSymbol(GVar);
1395 int64_t ElementSize = 0;
1397 // Although PTX has direct support for struct type and array type and LLVM IR
1398 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1399 // support these high level field accesses. Structs and arrays are lowered
1400 // into arrays of bytes.
1401 switch (ETy->getTypeID()) {
1402 case Type::StructTyID:
1403 case Type::ArrayTyID:
1404 case Type::VectorTyID:
1405 ElementSize = TD->getTypeStoreSize(ETy);
1406 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1408 O << itostr(ElementSize);
1413 assert(0 && "type not supported yet");
1418 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1419 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1420 return TD->getPrefTypeAlignment(Ty);
1422 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1424 return getOpenCLAlignment(TD, ATy->getElementType());
1426 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1428 Type *ETy = VTy->getElementType();
1429 unsigned int numE = VTy->getNumElements();
1430 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1434 return numE * alignE;
1437 const StructType *STy = dyn_cast<StructType>(Ty);
1439 unsigned int alignStruct = 1;
1440 // Go through each element of the struct and find the
1441 // largest alignment.
1442 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1443 Type *ETy = STy->getElementType(i);
1444 unsigned int align = getOpenCLAlignment(TD, ETy);
1445 if (align > alignStruct)
1446 alignStruct = align;
1451 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1453 return TD->getPointerPrefAlignment();
1454 return TD->getPrefTypeAlignment(Ty);
1457 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1458 int paramIndex, raw_ostream &O) {
1459 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1460 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1461 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1463 std::string argName = I->getName();
1464 const char *p = argName.c_str();
1475 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1476 Function::const_arg_iterator I, E;
1479 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1480 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1481 O << *CurrentFnSym << "_param_" << paramIndex;
1485 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1486 if (i == paramIndex) {
1487 printParamName(I, paramIndex, O);
1491 llvm_unreachable("paramIndex out of bound");
1494 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1495 const DataLayout *TD = TM.getDataLayout();
1496 const AttributeSet &PAL = F->getAttributes();
1497 const TargetLowering *TLI = TM.getTargetLowering();
1498 Function::const_arg_iterator I, E;
1499 unsigned paramIndex = 0;
1501 bool isKernelFunc = llvm::isKernelFunction(*F);
1502 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1503 MVT thePointerTy = TLI->getPointerTy();
1507 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1508 Type *Ty = I->getType();
1515 // Handle image/sampler parameters
1516 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1517 if (llvm::isImage(*I)) {
1518 std::string sname = I->getName();
1519 if (llvm::isImageWriteOnly(*I))
1520 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1522 else // Default image is read_only
1523 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1525 } else // Should be llvm::isSampler(*I)
1526 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1531 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1532 if (Ty->isVectorTy()) {
1533 // Just print .param .b8 .align <a> .param[size];
1534 // <a> = PAL.getparamalignment
1535 // size = typeallocsize of element type
1536 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1538 align = TD->getABITypeAlignment(Ty);
1540 unsigned sz = TD->getTypeAllocSize(Ty);
1541 O << "\t.param .align " << align << " .b8 ";
1542 printParamName(I, paramIndex, O);
1543 O << "[" << sz << "]";
1548 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1551 // Special handling for pointer arguments to kernel
1552 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1554 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1555 Type *ETy = PTy->getElementType();
1556 int addrSpace = PTy->getAddressSpace();
1557 switch (addrSpace) {
1561 case llvm::ADDRESS_SPACE_CONST:
1562 O << ".ptr .const ";
1564 case llvm::ADDRESS_SPACE_SHARED:
1565 O << ".ptr .shared ";
1567 case llvm::ADDRESS_SPACE_GLOBAL:
1568 O << ".ptr .global ";
1571 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1573 printParamName(I, paramIndex, O);
1577 // non-pointer scalar to kernel func
1579 // Special case: predicate operands become .u8 types
1580 if (Ty->isIntegerTy(1))
1583 O << getPTXFundamentalTypeStr(Ty);
1585 printParamName(I, paramIndex, O);
1588 // Non-kernel function, just print .param .b<size> for ABI
1589 // and .reg .b<size> for non ABY
1591 if (isa<IntegerType>(Ty)) {
1592 sz = cast<IntegerType>(Ty)->getBitWidth();
1595 } else if (isa<PointerType>(Ty))
1596 sz = thePointerTy.getSizeInBits();
1598 sz = Ty->getPrimitiveSizeInBits();
1600 O << "\t.param .b" << sz << " ";
1602 O << "\t.reg .b" << sz << " ";
1603 printParamName(I, paramIndex, O);
1607 // param has byVal attribute. So should be a pointer
1608 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1609 assert(PTy && "Param with byval attribute should be a pointer type");
1610 Type *ETy = PTy->getElementType();
1612 if (isABI || isKernelFunc) {
1613 // Just print .param .b8 .align <a> .param[size];
1614 // <a> = PAL.getparamalignment
1615 // size = typeallocsize of element type
1616 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1618 align = TD->getABITypeAlignment(ETy);
1620 unsigned sz = TD->getTypeAllocSize(ETy);
1621 O << "\t.param .align " << align << " .b8 ";
1622 printParamName(I, paramIndex, O);
1623 O << "[" << sz << "]";
1626 // Split the ETy into constituent parts and
1627 // print .param .b<size> <name> for each part.
1628 // Further, if a part is vector, print the above for
1629 // each vector element.
1630 SmallVector<EVT, 16> vtparts;
1631 ComputeValueVTs(*TLI, ETy, vtparts);
1632 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1634 EVT elemtype = vtparts[i];
1635 if (vtparts[i].isVector()) {
1636 elems = vtparts[i].getVectorNumElements();
1637 elemtype = vtparts[i].getVectorElementType();
1640 for (unsigned j = 0, je = elems; j != je; ++j) {
1641 unsigned sz = elemtype.getSizeInBits();
1642 if (elemtype.isInteger() && (sz < 32))
1644 O << "\t.reg .b" << sz << " ";
1645 printParamName(I, paramIndex, O);
1661 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1663 const Function *F = MF.getFunction();
1664 emitFunctionParamList(F, O);
1667 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1668 const MachineFunction &MF) {
1669 SmallString<128> Str;
1670 raw_svector_ostream O(Str);
1672 // Map the global virtual register number to a register class specific
1673 // virtual register number starting from 1 with that class.
1674 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1675 //unsigned numRegClasses = TRI->getNumRegClasses();
1677 // Emit the Fake Stack Object
1678 const MachineFrameInfo *MFI = MF.getFrameInfo();
1679 int NumBytes = (int) MFI->getStackSize();
1681 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1682 << getFunctionNumber() << "[" << NumBytes << "];\n";
1683 if (nvptxSubtarget.is64Bit()) {
1684 O << "\t.reg .b64 \t%SP;\n";
1685 O << "\t.reg .b64 \t%SPL;\n";
1687 O << "\t.reg .b32 \t%SP;\n";
1688 O << "\t.reg .b32 \t%SPL;\n";
1692 // Go through all virtual registers to establish the mapping between the
1694 // register number and the per class virtual register number.
1695 // We use the per class virtual register number in the ptx output.
1696 unsigned int numVRs = MRI->getNumVirtRegs();
1697 for (unsigned i = 0; i < numVRs; i++) {
1698 unsigned int vr = TRI->index2VirtReg(i);
1699 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1700 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1701 int n = regmap.size();
1702 regmap.insert(std::make_pair(vr, n + 1));
1705 // Emit register declarations
1706 // @TODO: Extract out the real register usage
1707 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1708 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1709 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1710 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1711 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1712 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1713 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1715 // Emit declaration of the virtual registers or 'physical' registers for
1716 // each register class
1717 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1718 const TargetRegisterClass *RC = TRI->getRegClass(i);
1719 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1720 std::string rcname = getNVPTXRegClassName(RC);
1721 std::string rcStr = getNVPTXRegClassStr(RC);
1722 int n = regmap.size();
1724 // Only declare those registers that may be used.
1726 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1731 OutStreamer.EmitRawText(O.str());
1734 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1735 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1737 unsigned int numHex;
1740 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1743 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1744 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1747 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1749 llvm_unreachable("unsupported fp type");
1751 APInt API = APF.bitcastToAPInt();
1752 std::string hexstr(utohexstr(API.getZExtValue()));
1754 if (hexstr.length() < numHex)
1755 O << std::string(numHex - hexstr.length(), '0');
1756 O << utohexstr(API.getZExtValue());
1759 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1760 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1761 O << CI->getValue();
1764 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1765 printFPConstant(CFP, O);
1768 if (isa<ConstantPointerNull>(CPV)) {
1772 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1773 O << *Mang->getSymbol(GVar);
1776 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1777 const Value *v = Cexpr->stripPointerCasts();
1778 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1779 O << *Mang->getSymbol(GVar);
1782 O << *LowerConstant(CPV, *this);
1786 llvm_unreachable("Not scalar type found in printScalarConstant()");
1789 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1790 AggBuffer *aggBuffer) {
1792 const DataLayout *TD = TM.getDataLayout();
1794 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1795 int s = TD->getTypeAllocSize(CPV->getType());
1798 aggBuffer->addZeros(s);
1803 switch (CPV->getType()->getTypeID()) {
1805 case Type::IntegerTyID: {
1806 const Type *ETy = CPV->getType();
1807 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1809 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1811 aggBuffer->addBytes(ptr, 1, Bytes);
1812 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1813 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1814 ptr = (unsigned char *)&int16;
1815 aggBuffer->addBytes(ptr, 2, Bytes);
1816 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1817 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1818 int int32 = (int)(constInt->getZExtValue());
1819 ptr = (unsigned char *)&int32;
1820 aggBuffer->addBytes(ptr, 4, Bytes);
1822 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1823 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1824 ConstantFoldConstantExpression(Cexpr, TD))) {
1825 int int32 = (int)(constInt->getZExtValue());
1826 ptr = (unsigned char *)&int32;
1827 aggBuffer->addBytes(ptr, 4, Bytes);
1830 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1831 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1832 aggBuffer->addSymbol(v);
1833 aggBuffer->addZeros(4);
1837 llvm_unreachable("unsupported integer const type");
1838 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1839 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1840 long long int64 = (long long)(constInt->getZExtValue());
1841 ptr = (unsigned char *)&int64;
1842 aggBuffer->addBytes(ptr, 8, Bytes);
1844 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1845 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1846 ConstantFoldConstantExpression(Cexpr, TD))) {
1847 long long int64 = (long long)(constInt->getZExtValue());
1848 ptr = (unsigned char *)&int64;
1849 aggBuffer->addBytes(ptr, 8, Bytes);
1852 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1853 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1854 aggBuffer->addSymbol(v);
1855 aggBuffer->addZeros(8);
1859 llvm_unreachable("unsupported integer const type");
1861 llvm_unreachable("unsupported integer const type");
1864 case Type::FloatTyID:
1865 case Type::DoubleTyID: {
1866 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1867 const Type *Ty = CFP->getType();
1868 if (Ty == Type::getFloatTy(CPV->getContext())) {
1869 float float32 = (float) CFP->getValueAPF().convertToFloat();
1870 ptr = (unsigned char *)&float32;
1871 aggBuffer->addBytes(ptr, 4, Bytes);
1872 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1873 double float64 = CFP->getValueAPF().convertToDouble();
1874 ptr = (unsigned char *)&float64;
1875 aggBuffer->addBytes(ptr, 8, Bytes);
1877 llvm_unreachable("unsupported fp const type");
1881 case Type::PointerTyID: {
1882 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1883 aggBuffer->addSymbol(GVar);
1884 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1885 const Value *v = Cexpr->stripPointerCasts();
1886 aggBuffer->addSymbol(v);
1888 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1889 aggBuffer->addZeros(s);
1893 case Type::ArrayTyID:
1894 case Type::VectorTyID:
1895 case Type::StructTyID: {
1896 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1897 isa<ConstantStruct>(CPV)) {
1898 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1899 bufferAggregateConstant(CPV, aggBuffer);
1900 if (Bytes > ElementSize)
1901 aggBuffer->addZeros(Bytes - ElementSize);
1902 } else if (isa<ConstantAggregateZero>(CPV))
1903 aggBuffer->addZeros(Bytes);
1905 llvm_unreachable("Unexpected Constant type");
1910 llvm_unreachable("unsupported type");
1914 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1915 AggBuffer *aggBuffer) {
1916 const DataLayout *TD = TM.getDataLayout();
1920 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1921 if (CPV->getNumOperands())
1922 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1923 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1927 if (const ConstantDataSequential *CDS =
1928 dyn_cast<ConstantDataSequential>(CPV)) {
1929 if (CDS->getNumElements())
1930 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1931 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1936 if (isa<ConstantStruct>(CPV)) {
1937 if (CPV->getNumOperands()) {
1938 StructType *ST = cast<StructType>(CPV->getType());
1939 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1941 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1942 TD->getTypeAllocSize(ST) -
1943 TD->getStructLayout(ST)->getElementOffset(i);
1945 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1946 TD->getStructLayout(ST)->getElementOffset(i);
1947 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1952 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1955 // buildTypeNameMap - Run through symbol table looking for type names.
1958 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1960 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1962 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1963 !PI->second.compare("struct._image2d_t") ||
1964 !PI->second.compare("struct._image3d_t")))
1970 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1972 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1973 unsigned AsmVariant,
1974 const char *ExtraCode, raw_ostream &O) {
1975 if (ExtraCode && ExtraCode[0]) {
1976 if (ExtraCode[1] != 0)
1977 return true; // Unknown modifier.
1979 switch (ExtraCode[0]) {
1981 // See if this is a generic print operand
1982 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
1988 printOperand(MI, OpNo, O);
1993 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
1994 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
1995 const char *ExtraCode, raw_ostream &O) {
1996 if (ExtraCode && ExtraCode[0])
1997 return true; // Unknown modifier
2000 printMemOperand(MI, OpNo, O);
2006 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2007 switch (MI.getOpcode()) {
2010 case NVPTX::CallArgBeginInst:
2011 case NVPTX::CallArgEndInst0:
2012 case NVPTX::CallArgEndInst1:
2013 case NVPTX::CallArgF32:
2014 case NVPTX::CallArgF64:
2015 case NVPTX::CallArgI16:
2016 case NVPTX::CallArgI32:
2017 case NVPTX::CallArgI32imm:
2018 case NVPTX::CallArgI64:
2019 case NVPTX::CallArgParam:
2020 case NVPTX::CallVoidInst:
2021 case NVPTX::CallVoidInstReg:
2022 case NVPTX::Callseq_End:
2023 case NVPTX::CallVoidInstReg64:
2024 case NVPTX::DeclareParamInst:
2025 case NVPTX::DeclareRetMemInst:
2026 case NVPTX::DeclareRetRegInst:
2027 case NVPTX::DeclareRetScalarInst:
2028 case NVPTX::DeclareScalarParamInst:
2029 case NVPTX::DeclareScalarRegInst:
2030 case NVPTX::StoreParamF32:
2031 case NVPTX::StoreParamF64:
2032 case NVPTX::StoreParamI16:
2033 case NVPTX::StoreParamI32:
2034 case NVPTX::StoreParamI64:
2035 case NVPTX::StoreParamI8:
2036 case NVPTX::StoreParamS32I8:
2037 case NVPTX::StoreParamU32I8:
2038 case NVPTX::StoreParamS32I16:
2039 case NVPTX::StoreParamU32I16:
2040 case NVPTX::StoreRetvalF32:
2041 case NVPTX::StoreRetvalF64:
2042 case NVPTX::StoreRetvalI16:
2043 case NVPTX::StoreRetvalI32:
2044 case NVPTX::StoreRetvalI64:
2045 case NVPTX::StoreRetvalI8:
2046 case NVPTX::LastCallArgF32:
2047 case NVPTX::LastCallArgF64:
2048 case NVPTX::LastCallArgI16:
2049 case NVPTX::LastCallArgI32:
2050 case NVPTX::LastCallArgI32imm:
2051 case NVPTX::LastCallArgI64:
2052 case NVPTX::LastCallArgParam:
2053 case NVPTX::LoadParamMemF32:
2054 case NVPTX::LoadParamMemF64:
2055 case NVPTX::LoadParamMemI16:
2056 case NVPTX::LoadParamMemI32:
2057 case NVPTX::LoadParamMemI64:
2058 case NVPTX::LoadParamMemI8:
2059 case NVPTX::LoadParamRegF32:
2060 case NVPTX::LoadParamRegF64:
2061 case NVPTX::LoadParamRegI16:
2062 case NVPTX::LoadParamRegI32:
2063 case NVPTX::LoadParamRegI64:
2064 case NVPTX::PrototypeInst:
2065 case NVPTX::DBG_VALUE:
2071 // Force static initialization.
2072 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2073 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2074 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2077 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2078 std::stringstream temp;
2079 LineReader *reader = this->getReader(filename.str());
2081 temp << filename.str();
2085 temp << reader->readLine(line);
2087 this->OutStreamer.EmitRawText(Twine(temp.str()));
2090 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2091 if (reader == NULL) {
2092 reader = new LineReader(filename);
2095 if (reader->fileName() != filename) {
2097 reader = new LineReader(filename);
2103 std::string LineReader::readLine(unsigned lineNum) {
2104 if (lineNum < theCurLine) {
2106 fstr.seekg(0, std::ios::beg);
2108 while (theCurLine < lineNum) {
2109 fstr.getline(buff, 500);
2115 // Force static initialization.
2116 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2117 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2118 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);