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 "NVPTXMCExpr.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 bool RegAllocNilUsed = true;
52 #define DEPOTNAME "__local_depot"
55 EmitLineNumbers("nvptx-emit-line-numbers",
56 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 namespace llvm { bool InterleaveSrcInPtx = false; }
61 static cl::opt<bool, true>
62 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
63 cl::desc("NVPTX Specific: Emit source line in ptx file"),
64 cl::location(llvm::InterleaveSrcInPtx));
67 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
69 void DiscoverDependentGlobals(const Value *V,
70 DenseSet<const GlobalVariable *> &Globals) {
71 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
74 if (const User *U = dyn_cast<User>(V)) {
75 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
76 DiscoverDependentGlobals(U->getOperand(i), Globals);
82 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
83 /// instances to be emitted, but only after any dependents have been added
85 void VisitGlobalVariableForEmission(
86 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
87 DenseSet<const GlobalVariable *> &Visited,
88 DenseSet<const GlobalVariable *> &Visiting) {
89 // Have we already visited this one?
90 if (Visited.count(GV))
93 // Do we have a circular dependency?
94 if (Visiting.count(GV))
95 report_fatal_error("Circular dependency found in global variable set");
97 // Start visiting this global
100 // Make sure we visit all dependents first
101 DenseSet<const GlobalVariable *> Others;
102 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
103 DiscoverDependentGlobals(GV->getOperand(i), Others);
105 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
108 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
110 // Now we can visit ourself
117 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
118 // cannot just link to the existing version.
119 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
121 using namespace nvptx;
122 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
123 MCContext &Ctx = AP.OutContext;
125 if (CV->isNullValue() || isa<UndefValue>(CV))
126 return MCConstantExpr::Create(0, Ctx);
128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
129 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
131 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
132 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
134 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
135 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
137 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
139 llvm_unreachable("Unknown constant value to lower!");
141 switch (CE->getOpcode()) {
143 // If the code isn't optimized, there may be outstanding folding
144 // opportunities. Attempt to fold the expression using DataLayout as a
145 // last resort before giving up.
146 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
148 return LowerConstant(C, AP);
150 // Otherwise report the problem to the user.
153 raw_string_ostream OS(S);
154 OS << "Unsupported expression in static initializer: ";
155 WriteAsOperand(OS, CE, /*PrintType=*/ false,
156 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
157 report_fatal_error(OS.str());
159 case Instruction::GetElementPtr: {
160 const DataLayout &TD = *AP.TM.getDataLayout();
161 // Generate a symbolic expression for the byte address
162 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
163 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
165 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
169 int64_t Offset = OffsetAI.getSExtValue();
170 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
174 case Instruction::Trunc:
175 // We emit the value and depend on the assembler to truncate the generated
176 // expression properly. This is important for differences between
177 // blockaddress labels. Since the two labels are in the same function, it
178 // is reasonable to treat their delta as a 32-bit value.
180 case Instruction::BitCast:
181 return LowerConstant(CE->getOperand(0), AP);
183 case Instruction::IntToPtr: {
184 const DataLayout &TD = *AP.TM.getDataLayout();
185 // Handle casts to pointers by changing them into casts to the appropriate
186 // integer type. This promotes constant folding and simplifies this code.
187 Constant *Op = CE->getOperand(0);
188 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
190 return LowerConstant(Op, AP);
193 case Instruction::PtrToInt: {
194 const DataLayout &TD = *AP.TM.getDataLayout();
195 // Support only foldable casts to/from pointers that can be eliminated by
196 // changing the pointer to the appropriately sized integer type.
197 Constant *Op = CE->getOperand(0);
198 Type *Ty = CE->getType();
200 const MCExpr *OpExpr = LowerConstant(Op, AP);
202 // We can emit the pointer value into this slot if the slot is an
203 // integer slot equal to the size of the pointer.
204 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
207 // Otherwise the pointer is smaller than the resultant integer, mask off
208 // the high bits so we are sure to get a proper truncation if the input is
210 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
211 const MCExpr *MaskExpr =
212 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
213 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
216 // The MC library also has a right-shift operator, but it isn't consistently
217 // signed or unsigned between different targets.
218 case Instruction::Add:
219 case Instruction::Sub:
220 case Instruction::Mul:
221 case Instruction::SDiv:
222 case Instruction::SRem:
223 case Instruction::Shl:
224 case Instruction::And:
225 case Instruction::Or:
226 case Instruction::Xor: {
227 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
228 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
229 switch (CE->getOpcode()) {
231 llvm_unreachable("Unknown binary operator constant cast expr");
232 case Instruction::Add:
233 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
234 case Instruction::Sub:
235 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
236 case Instruction::Mul:
237 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
238 case Instruction::SDiv:
239 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
240 case Instruction::SRem:
241 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
242 case Instruction::Shl:
243 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
244 case Instruction::And:
245 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
246 case Instruction::Or:
247 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
248 case Instruction::Xor:
249 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
255 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
256 if (!EmitLineNumbers)
261 DebugLoc curLoc = MI.getDebugLoc();
263 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
266 if (prevDebugLoc == curLoc)
269 prevDebugLoc = curLoc;
271 if (curLoc.isUnknown())
274 const MachineFunction *MF = MI.getParent()->getParent();
275 //const TargetMachine &TM = MF->getTarget();
277 const LLVMContext &ctx = MF->getFunction()->getContext();
278 DIScope Scope(curLoc.getScope(ctx));
280 assert((!Scope || Scope.isScope()) &&
281 "Scope of a DebugLoc should be null or a DIScope.");
285 StringRef fileName(Scope.getFilename());
286 StringRef dirName(Scope.getDirectory());
287 SmallString<128> FullPathName = dirName;
288 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
289 sys::path::append(FullPathName, fileName);
290 fileName = FullPathName.str();
293 if (filenameMap.find(fileName.str()) == filenameMap.end())
296 // Emit the line from the source file.
297 if (llvm::InterleaveSrcInPtx)
298 this->emitSrcInText(fileName.str(), curLoc.getLine());
300 std::stringstream temp;
301 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
302 << " " << curLoc.getCol();
303 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
306 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
307 SmallString<128> Str;
308 raw_svector_ostream OS(Str);
309 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
310 emitLineNumberAsDotLoc(*MI);
313 lowerToMCInst(MI, Inst);
314 OutStreamer.EmitInstruction(Inst);
317 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
318 OutMI.setOpcode(MI->getOpcode());
320 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
321 const MachineOperand &MO = MI->getOperand(i);
324 if (lowerOperand(MO, MCOp))
325 OutMI.addOperand(MCOp);
329 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
331 switch (MO.getType()) {
332 default: llvm_unreachable("unknown operand type");
333 case MachineOperand::MO_Register:
334 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
336 case MachineOperand::MO_Immediate:
337 MCOp = MCOperand::CreateImm(MO.getImm());
339 case MachineOperand::MO_MachineBasicBlock:
340 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
341 MO.getMBB()->getSymbol(), OutContext));
343 case MachineOperand::MO_ExternalSymbol:
344 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
346 case MachineOperand::MO_GlobalAddress:
347 MCOp = GetSymbolRef(MO, Mang->getSymbol(MO.getGlobal()));
349 case MachineOperand::MO_FPImmediate: {
350 const ConstantFP *Cnt = MO.getFPImm();
351 APFloat Val = Cnt->getValueAPF();
353 switch (Cnt->getType()->getTypeID()) {
354 default: report_fatal_error("Unsupported FP type"); break;
355 case Type::FloatTyID:
356 MCOp = MCOperand::CreateExpr(
357 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
359 case Type::DoubleTyID:
360 MCOp = MCOperand::CreateExpr(
361 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
370 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
371 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
372 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
374 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
375 unsigned RegNum = RegMap[Reg];
377 // Encode the register class in the upper 4 bits
378 // Must be kept in sync with NVPTXInstPrinter::printRegName
380 if (RC == &NVPTX::Int1RegsRegClass) {
382 } else if (RC == &NVPTX::Int16RegsRegClass) {
384 } else if (RC == &NVPTX::Int32RegsRegClass) {
386 } else if (RC == &NVPTX::Int64RegsRegClass) {
388 } else if (RC == &NVPTX::Float32RegsRegClass) {
390 } else if (RC == &NVPTX::Float64RegsRegClass) {
393 report_fatal_error("Bad register class");
396 // Insert the vreg number
397 Ret |= (RegNum & 0x0FFFFFFF);
400 // Some special-use registers are actually physical registers.
401 // Encode this as the register class ID of 0 and the real register ID.
402 return Reg & 0x0FFFFFFF;
406 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
407 const MCSymbol *Symbol) {
409 switch (MO.getTargetFlags()) {
411 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
416 return MCOperand::CreateExpr(Expr);
419 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
420 const DataLayout *TD = TM.getDataLayout();
421 const TargetLowering *TLI = TM.getTargetLowering();
423 Type *Ty = F->getReturnType();
425 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
427 if (Ty->getTypeID() == Type::VoidTyID)
433 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
435 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
436 size = ITy->getBitWidth();
440 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
441 size = Ty->getPrimitiveSizeInBits();
444 O << ".param .b" << size << " func_retval0";
445 } else if (isa<PointerType>(Ty)) {
446 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
449 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
450 SmallVector<EVT, 16> vtparts;
451 ComputeValueVTs(*TLI, Ty, vtparts);
452 unsigned totalsz = 0;
453 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
455 EVT elemtype = vtparts[i];
456 if (vtparts[i].isVector()) {
457 elems = vtparts[i].getVectorNumElements();
458 elemtype = vtparts[i].getVectorElementType();
460 for (unsigned j = 0, je = elems; j != je; ++j) {
461 unsigned sz = elemtype.getSizeInBits();
462 if (elemtype.isInteger() && (sz < 8))
467 unsigned retAlignment = 0;
468 if (!llvm::getAlign(*F, 0, retAlignment))
469 retAlignment = TD->getABITypeAlignment(Ty);
470 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
473 assert(false && "Unknown return type");
476 SmallVector<EVT, 16> vtparts;
477 ComputeValueVTs(*TLI, Ty, vtparts);
479 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
481 EVT elemtype = vtparts[i];
482 if (vtparts[i].isVector()) {
483 elems = vtparts[i].getVectorNumElements();
484 elemtype = vtparts[i].getVectorElementType();
487 for (unsigned j = 0, je = elems; j != je; ++j) {
488 unsigned sz = elemtype.getSizeInBits();
489 if (elemtype.isInteger() && (sz < 32))
491 O << ".reg .b" << sz << " func_retval" << idx;
504 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
506 const Function *F = MF.getFunction();
507 printReturnValStr(F, O);
510 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
511 SmallString<128> Str;
512 raw_svector_ostream O(Str);
514 if (!GlobalsEmitted) {
515 emitGlobals(*MF->getFunction()->getParent());
516 GlobalsEmitted = true;
520 MRI = &MF->getRegInfo();
521 F = MF->getFunction();
522 emitLinkageDirective(F, O);
523 if (llvm::isKernelFunction(*F))
527 printReturnValStr(*MF, O);
532 emitFunctionParamList(*MF, O);
534 if (llvm::isKernelFunction(*F))
535 emitKernelFunctionDirectives(*F, O);
537 OutStreamer.EmitRawText(O.str());
539 prevDebugLoc = DebugLoc();
542 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
544 OutStreamer.EmitRawText(StringRef("{\n"));
545 setAndEmitFunctionVirtualRegisters(*MF);
547 SmallString<128> Str;
548 raw_svector_ostream O(Str);
549 emitDemotedVars(MF->getFunction(), O);
550 OutStreamer.EmitRawText(O.str());
553 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
554 OutStreamer.EmitRawText(StringRef("}\n"));
558 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
559 raw_ostream &O) const {
560 // If the NVVM IR has some of reqntid* specified, then output
561 // the reqntid directive, and set the unspecified ones to 1.
562 // If none of reqntid* is specified, don't output reqntid directive.
563 unsigned reqntidx, reqntidy, reqntidz;
564 bool specified = false;
565 if (llvm::getReqNTIDx(F, reqntidx) == false)
569 if (llvm::getReqNTIDy(F, reqntidy) == false)
573 if (llvm::getReqNTIDz(F, reqntidz) == false)
579 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
582 // If the NVVM IR has some of maxntid* specified, then output
583 // the maxntid directive, and set the unspecified ones to 1.
584 // If none of maxntid* is specified, don't output maxntid directive.
585 unsigned maxntidx, maxntidy, maxntidz;
587 if (llvm::getMaxNTIDx(F, maxntidx) == false)
591 if (llvm::getMaxNTIDy(F, maxntidy) == false)
595 if (llvm::getMaxNTIDz(F, maxntidz) == false)
601 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
605 if (llvm::getMinCTASm(F, mincta))
606 O << ".minnctapersm " << mincta << "\n";
609 void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
611 const TargetRegisterClass *RC = MRI->getRegClass(vr);
613 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
614 unsigned mapped_vr = regmap[vr];
617 O << getNVPTXRegClassStr(RC) << mapped_vr;
620 report_fatal_error("Bad register!");
623 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
625 getVirtualRegisterName(vr, isVec, O);
628 void NVPTXAsmPrinter::printVecModifiedImmediate(
629 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
630 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
631 int Imm = (int) MO.getImm();
632 if (0 == strcmp(Modifier, "vecelem"))
633 O << "_" << vecelem[Imm];
634 else if (0 == strcmp(Modifier, "vecv4comm1")) {
635 if ((Imm < 0) || (Imm > 3))
637 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
638 if ((Imm < 4) || (Imm > 7))
640 } else if (0 == strcmp(Modifier, "vecv4pos")) {
643 O << "_" << vecelem[Imm % 4];
644 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
645 if ((Imm < 0) || (Imm > 1))
647 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
648 if ((Imm < 2) || (Imm > 3))
650 } else if (0 == strcmp(Modifier, "vecv2pos")) {
653 O << "_" << vecelem[Imm % 2];
655 llvm_unreachable("Unknown Modifier on immediate operand");
660 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
662 emitLinkageDirective(F, O);
663 if (llvm::isKernelFunction(*F))
667 printReturnValStr(F, O);
668 O << *Mang->getSymbol(F) << "\n";
669 emitFunctionParamList(F, O);
673 static bool usedInGlobalVarDef(const Constant *C) {
677 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
678 if (GV->getName().str() == "llvm.used")
683 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
685 const Constant *C = dyn_cast<Constant>(*ui);
686 if (usedInGlobalVarDef(C))
692 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
693 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
694 if (othergv->getName().str() == "llvm.used")
698 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
699 if (instr->getParent() && instr->getParent()->getParent()) {
700 const Function *curFunc = instr->getParent()->getParent();
701 if (oneFunc && (curFunc != oneFunc))
709 if (const MDNode *md = dyn_cast<MDNode>(U))
710 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
711 (md->getName().str() == "llvm.dbg.sp")))
714 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
716 if (usedInOneFunc(*ui, oneFunc) == false)
722 /* Find out if a global variable can be demoted to local scope.
723 * Currently, this is valid for CUDA shared variables, which have local
724 * scope and global lifetime. So the conditions to check are :
725 * 1. Is the global variable in shared address space?
726 * 2. Does it have internal linkage?
727 * 3. Is the global variable referenced only in one function?
729 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
730 if (gv->hasInternalLinkage() == false)
732 const PointerType *Pty = gv->getType();
733 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
736 const Function *oneFunc = 0;
738 bool flag = usedInOneFunc(gv, oneFunc);
747 static bool useFuncSeen(const Constant *C,
748 llvm::DenseMap<const Function *, bool> &seenMap) {
749 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
751 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
752 if (useFuncSeen(cu, seenMap))
754 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
755 const BasicBlock *bb = I->getParent();
758 const Function *caller = bb->getParent();
761 if (seenMap.find(caller) != seenMap.end())
768 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
769 llvm::DenseMap<const Function *, bool> seenMap;
770 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
771 const Function *F = FI;
773 if (F->isDeclaration()) {
776 if (F->getIntrinsicID())
778 emitDeclaration(F, O);
781 for (Value::const_use_iterator iter = F->use_begin(),
782 iterEnd = F->use_end();
783 iter != iterEnd; ++iter) {
784 if (const Constant *C = dyn_cast<Constant>(*iter)) {
785 if (usedInGlobalVarDef(C)) {
786 // The use is in the initialization of a global variable
787 // that is a function pointer, so print a declaration
788 // for the original function
789 emitDeclaration(F, O);
792 // Emit a declaration of this function if the function that
793 // uses this constant expr has already been seen.
794 if (useFuncSeen(C, seenMap)) {
795 emitDeclaration(F, O);
800 if (!isa<Instruction>(*iter))
802 const Instruction *instr = cast<Instruction>(*iter);
803 const BasicBlock *bb = instr->getParent();
806 const Function *caller = bb->getParent();
810 // If a caller has already been seen, then the caller is
811 // appearing in the module before the callee. so print out
812 // a declaration for the callee.
813 if (seenMap.find(caller) != seenMap.end()) {
814 emitDeclaration(F, O);
822 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
823 DebugInfoFinder DbgFinder;
824 DbgFinder.processModule(M);
827 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
828 E = DbgFinder.compile_unit_end();
830 DICompileUnit DIUnit(*I);
831 StringRef Filename(DIUnit.getFilename());
832 StringRef Dirname(DIUnit.getDirectory());
833 SmallString<128> FullPathName = Dirname;
834 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
835 sys::path::append(FullPathName, Filename);
836 Filename = FullPathName.str();
838 if (filenameMap.find(Filename.str()) != filenameMap.end())
840 filenameMap[Filename.str()] = i;
841 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
845 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
846 E = DbgFinder.subprogram_end();
849 StringRef Filename(SP.getFilename());
850 StringRef Dirname(SP.getDirectory());
851 SmallString<128> FullPathName = Dirname;
852 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
853 sys::path::append(FullPathName, Filename);
854 Filename = FullPathName.str();
856 if (filenameMap.find(Filename.str()) != filenameMap.end())
858 filenameMap[Filename.str()] = i;
863 bool NVPTXAsmPrinter::doInitialization(Module &M) {
865 SmallString<128> Str1;
866 raw_svector_ostream OS1(Str1);
868 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
869 MMI->AnalyzeModule(M);
871 // We need to call the parent's one explicitly.
872 //bool Result = AsmPrinter::doInitialization(M);
874 // Initialize TargetLoweringObjectFile.
875 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
876 .Initialize(OutContext, TM);
878 Mang = new Mangler(OutContext, &TM);
880 // Emit header before any dwarf directives are emitted below.
882 OutStreamer.EmitRawText(OS1.str());
884 // Already commented out
885 //bool Result = AsmPrinter::doInitialization(M);
887 // Emit module-level inline asm if it exists.
888 if (!M.getModuleInlineAsm().empty()) {
889 OutStreamer.AddComment("Start of file scope inline assembly");
890 OutStreamer.AddBlankLine();
891 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
892 OutStreamer.AddBlankLine();
893 OutStreamer.AddComment("End of file scope inline assembly");
894 OutStreamer.AddBlankLine();
897 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
898 recordAndEmitFilenames(M);
900 GlobalsEmitted = false;
902 return false; // success
905 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
906 SmallString<128> Str2;
907 raw_svector_ostream OS2(Str2);
909 emitDeclarations(M, OS2);
911 // As ptxas does not support forward references of globals, we need to first
912 // sort the list of module-level globals in def-use order. We visit each
913 // global variable in order, and ensure that we emit it *after* its dependent
914 // globals. We use a little extra memory maintaining both a set and a list to
915 // have fast searches while maintaining a strict ordering.
916 SmallVector<const GlobalVariable *, 8> Globals;
917 DenseSet<const GlobalVariable *> GVVisited;
918 DenseSet<const GlobalVariable *> GVVisiting;
920 // Visit each global variable, in order
921 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
923 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
925 assert(GVVisited.size() == M.getGlobalList().size() &&
926 "Missed a global variable");
927 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
929 // Print out module-level global variables in proper order
930 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
931 printModuleLevelGV(Globals[i], OS2);
935 OutStreamer.EmitRawText(OS2.str());
938 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
940 O << "// Generated by LLVM NVPTX Back-End\n";
944 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
945 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
948 O << nvptxSubtarget.getTargetName();
950 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
951 O << ", texmode_independent";
952 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
953 if (!nvptxSubtarget.hasDouble())
954 O << ", map_f64_to_f32";
957 if (MAI->doesSupportDebugInformation())
962 O << ".address_size ";
963 if (nvptxSubtarget.is64Bit())
972 bool NVPTXAsmPrinter::doFinalization(Module &M) {
974 // If we did not emit any functions, then the global declarations have not
976 if (!GlobalsEmitted) {
978 GlobalsEmitted = true;
981 // XXX Temproarily remove global variables so that doFinalization() will not
982 // emit them again (global variables are emitted at beginning).
984 Module::GlobalListType &global_list = M.getGlobalList();
985 int i, n = global_list.size();
986 GlobalVariable **gv_array = new GlobalVariable *[n];
988 // first, back-up GlobalVariable in gv_array
990 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
994 // second, empty global_list
995 while (!global_list.empty())
996 global_list.remove(global_list.begin());
998 // call doFinalization
999 bool ret = AsmPrinter::doFinalization(M);
1001 // now we restore global variables
1002 for (i = 0; i < n; i++)
1003 global_list.insert(global_list.end(), gv_array[i]);
1008 //bool Result = AsmPrinter::doFinalization(M);
1009 // Instead of calling the parents doFinalization, we may
1010 // clone parents doFinalization and customize here.
1011 // Currently, we if NVISA out the EmitGlobals() in
1012 // parent's doFinalization, which is too intrusive.
1014 // Same for the doInitialization.
1018 // This function emits appropriate linkage directives for
1019 // functions and global variables.
1021 // extern function declaration -> .extern
1022 // extern function definition -> .visible
1023 // external global variable with init -> .visible
1024 // external without init -> .extern
1025 // appending -> not allowed, assert.
1027 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1029 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1030 if (V->hasExternalLinkage()) {
1031 if (isa<GlobalVariable>(V)) {
1032 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1034 if (GVar->hasInitializer())
1039 } else if (V->isDeclaration())
1043 } else if (V->hasAppendingLinkage()) {
1045 msg.append("Error: ");
1046 msg.append("Symbol ");
1048 msg.append(V->getName().str());
1049 msg.append("has unsupported appending linkage type");
1050 llvm_unreachable(msg.c_str());
1055 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1057 bool processDemoted) {
1060 if (GVar->hasSection()) {
1061 if (GVar->getSection() == "llvm.metadata")
1065 const DataLayout *TD = TM.getDataLayout();
1067 // GlobalVariables are always constant pointers themselves.
1068 const PointerType *PTy = GVar->getType();
1069 Type *ETy = PTy->getElementType();
1071 if (GVar->hasExternalLinkage()) {
1072 if (GVar->hasInitializer())
1078 if (llvm::isTexture(*GVar)) {
1079 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1083 if (llvm::isSurface(*GVar)) {
1084 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1088 if (GVar->isDeclaration()) {
1089 // (extern) declarations, no definition or initializer
1090 // Currently the only known declaration is for an automatic __local
1091 // (.shared) promoted to global.
1092 emitPTXGlobalVariable(GVar, O);
1097 if (llvm::isSampler(*GVar)) {
1098 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1100 const Constant *Initializer = NULL;
1101 if (GVar->hasInitializer())
1102 Initializer = GVar->getInitializer();
1103 const ConstantInt *CI = NULL;
1105 CI = dyn_cast<ConstantInt>(Initializer);
1107 unsigned sample = CI->getZExtValue();
1112 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1114 O << "addr_mode_" << i << " = ";
1120 O << "clamp_to_border";
1123 O << "clamp_to_edge";
1134 O << "filter_mode = ";
1135 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1143 assert(0 && "Anisotropic filtering is not supported");
1148 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1149 O << ", force_unnormalized_coords = 1";
1158 if (GVar->hasPrivateLinkage()) {
1160 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1163 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1164 if (!strncmp(GVar->getName().data(), "filename", 8))
1166 if (GVar->use_empty())
1170 const Function *demotedFunc = 0;
1171 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1172 O << "// " << GVar->getName().str() << " has been demoted\n";
1173 if (localDecls.find(demotedFunc) != localDecls.end())
1174 localDecls[demotedFunc].push_back(GVar);
1176 std::vector<const GlobalVariable *> temp;
1177 temp.push_back(GVar);
1178 localDecls[demotedFunc] = temp;
1184 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1185 if (GVar->getAlignment() == 0)
1186 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1188 O << " .align " << GVar->getAlignment();
1190 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1192 // Special case: ABI requires that we use .u8 for predicates
1193 if (ETy->isIntegerTy(1))
1196 O << getPTXFundamentalTypeStr(ETy, false);
1198 O << *Mang->getSymbol(GVar);
1200 // Ptx allows variable initilization only for constant and global state
1202 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1203 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1204 GVar->hasInitializer()) {
1205 const Constant *Initializer = GVar->getInitializer();
1206 if (!Initializer->isNullValue()) {
1208 printScalarConstant(Initializer, O);
1212 unsigned int ElementSize = 0;
1214 // Although PTX has direct support for struct type and array type and
1215 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1216 // targets that support these high level field accesses. Structs, arrays
1217 // and vectors are lowered into arrays of bytes.
1218 switch (ETy->getTypeID()) {
1219 case Type::StructTyID:
1220 case Type::ArrayTyID:
1221 case Type::VectorTyID:
1222 ElementSize = TD->getTypeStoreSize(ETy);
1223 // Ptx allows variable initilization only for constant and
1224 // global state spaces.
1225 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1226 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1227 GVar->hasInitializer()) {
1228 const Constant *Initializer = GVar->getInitializer();
1229 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1230 AggBuffer aggBuffer(ElementSize, O, *this);
1231 bufferAggregateConstant(Initializer, &aggBuffer);
1232 if (aggBuffer.numSymbols) {
1233 if (nvptxSubtarget.is64Bit()) {
1234 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1235 O << ElementSize / 8;
1237 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1238 O << ElementSize / 4;
1242 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1250 O << " .b8 " << *Mang->getSymbol(GVar);
1258 O << " .b8 " << *Mang->getSymbol(GVar);
1267 assert(0 && "type not supported yet");
1274 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1275 if (localDecls.find(f) == localDecls.end())
1278 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1280 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1281 O << "\t// demoted variable\n\t";
1282 printModuleLevelGV(gvars[i], O, true);
1286 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1287 raw_ostream &O) const {
1288 switch (AddressSpace) {
1289 case llvm::ADDRESS_SPACE_LOCAL:
1292 case llvm::ADDRESS_SPACE_GLOBAL:
1295 case llvm::ADDRESS_SPACE_CONST:
1298 case llvm::ADDRESS_SPACE_SHARED:
1302 report_fatal_error("Bad address space found while emitting PTX");
1308 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1309 switch (Ty->getTypeID()) {
1311 llvm_unreachable("unexpected type");
1313 case Type::IntegerTyID: {
1314 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1317 else if (NumBits <= 64) {
1318 std::string name = "u";
1319 return name + utostr(NumBits);
1321 llvm_unreachable("Integer too large");
1326 case Type::FloatTyID:
1328 case Type::DoubleTyID:
1330 case Type::PointerTyID:
1331 if (nvptxSubtarget.is64Bit())
1341 llvm_unreachable("unexpected type");
1345 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1348 const DataLayout *TD = TM.getDataLayout();
1350 // GlobalVariables are always constant pointers themselves.
1351 const PointerType *PTy = GVar->getType();
1352 Type *ETy = PTy->getElementType();
1355 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1356 if (GVar->getAlignment() == 0)
1357 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1359 O << " .align " << GVar->getAlignment();
1361 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1363 O << getPTXFundamentalTypeStr(ETy);
1365 O << *Mang->getSymbol(GVar);
1369 int64_t ElementSize = 0;
1371 // Although PTX has direct support for struct type and array type and LLVM IR
1372 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1373 // support these high level field accesses. Structs and arrays are lowered
1374 // into arrays of bytes.
1375 switch (ETy->getTypeID()) {
1376 case Type::StructTyID:
1377 case Type::ArrayTyID:
1378 case Type::VectorTyID:
1379 ElementSize = TD->getTypeStoreSize(ETy);
1380 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1382 O << itostr(ElementSize);
1387 assert(0 && "type not supported yet");
1392 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1393 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1394 return TD->getPrefTypeAlignment(Ty);
1396 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1398 return getOpenCLAlignment(TD, ATy->getElementType());
1400 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1402 Type *ETy = VTy->getElementType();
1403 unsigned int numE = VTy->getNumElements();
1404 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1408 return numE * alignE;
1411 const StructType *STy = dyn_cast<StructType>(Ty);
1413 unsigned int alignStruct = 1;
1414 // Go through each element of the struct and find the
1415 // largest alignment.
1416 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1417 Type *ETy = STy->getElementType(i);
1418 unsigned int align = getOpenCLAlignment(TD, ETy);
1419 if (align > alignStruct)
1420 alignStruct = align;
1425 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1427 return TD->getPointerPrefAlignment();
1428 return TD->getPrefTypeAlignment(Ty);
1431 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1432 int paramIndex, raw_ostream &O) {
1433 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1434 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1435 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1437 std::string argName = I->getName();
1438 const char *p = argName.c_str();
1449 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1450 Function::const_arg_iterator I, E;
1453 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1454 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1455 O << *CurrentFnSym << "_param_" << paramIndex;
1459 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1460 if (i == paramIndex) {
1461 printParamName(I, paramIndex, O);
1465 llvm_unreachable("paramIndex out of bound");
1468 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1469 const DataLayout *TD = TM.getDataLayout();
1470 const AttributeSet &PAL = F->getAttributes();
1471 const TargetLowering *TLI = TM.getTargetLowering();
1472 Function::const_arg_iterator I, E;
1473 unsigned paramIndex = 0;
1475 bool isKernelFunc = llvm::isKernelFunction(*F);
1476 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1477 MVT thePointerTy = TLI->getPointerTy();
1481 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1482 Type *Ty = I->getType();
1489 // Handle image/sampler parameters
1490 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1491 if (llvm::isImage(*I)) {
1492 std::string sname = I->getName();
1493 if (llvm::isImageWriteOnly(*I))
1494 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1496 else // Default image is read_only
1497 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1499 } else // Should be llvm::isSampler(*I)
1500 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1505 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1506 if (Ty->isVectorTy()) {
1507 // Just print .param .b8 .align <a> .param[size];
1508 // <a> = PAL.getparamalignment
1509 // size = typeallocsize of element type
1510 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1512 align = TD->getABITypeAlignment(Ty);
1514 unsigned sz = TD->getTypeAllocSize(Ty);
1515 O << "\t.param .align " << align << " .b8 ";
1516 printParamName(I, paramIndex, O);
1517 O << "[" << sz << "]";
1522 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1525 // Special handling for pointer arguments to kernel
1526 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1528 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1529 Type *ETy = PTy->getElementType();
1530 int addrSpace = PTy->getAddressSpace();
1531 switch (addrSpace) {
1535 case llvm::ADDRESS_SPACE_CONST:
1536 O << ".ptr .const ";
1538 case llvm::ADDRESS_SPACE_SHARED:
1539 O << ".ptr .shared ";
1541 case llvm::ADDRESS_SPACE_GLOBAL:
1542 O << ".ptr .global ";
1545 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1547 printParamName(I, paramIndex, O);
1551 // non-pointer scalar to kernel func
1553 // Special case: predicate operands become .u8 types
1554 if (Ty->isIntegerTy(1))
1557 O << getPTXFundamentalTypeStr(Ty);
1559 printParamName(I, paramIndex, O);
1562 // Non-kernel function, just print .param .b<size> for ABI
1563 // and .reg .b<size> for non ABY
1565 if (isa<IntegerType>(Ty)) {
1566 sz = cast<IntegerType>(Ty)->getBitWidth();
1569 } else if (isa<PointerType>(Ty))
1570 sz = thePointerTy.getSizeInBits();
1572 sz = Ty->getPrimitiveSizeInBits();
1574 O << "\t.param .b" << sz << " ";
1576 O << "\t.reg .b" << sz << " ";
1577 printParamName(I, paramIndex, O);
1581 // param has byVal attribute. So should be a pointer
1582 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1583 assert(PTy && "Param with byval attribute should be a pointer type");
1584 Type *ETy = PTy->getElementType();
1586 if (isABI || isKernelFunc) {
1587 // Just print .param .b8 .align <a> .param[size];
1588 // <a> = PAL.getparamalignment
1589 // size = typeallocsize of element type
1590 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1592 align = TD->getABITypeAlignment(ETy);
1594 unsigned sz = TD->getTypeAllocSize(ETy);
1595 O << "\t.param .align " << align << " .b8 ";
1596 printParamName(I, paramIndex, O);
1597 O << "[" << sz << "]";
1600 // Split the ETy into constituent parts and
1601 // print .param .b<size> <name> for each part.
1602 // Further, if a part is vector, print the above for
1603 // each vector element.
1604 SmallVector<EVT, 16> vtparts;
1605 ComputeValueVTs(*TLI, ETy, vtparts);
1606 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1608 EVT elemtype = vtparts[i];
1609 if (vtparts[i].isVector()) {
1610 elems = vtparts[i].getVectorNumElements();
1611 elemtype = vtparts[i].getVectorElementType();
1614 for (unsigned j = 0, je = elems; j != je; ++j) {
1615 unsigned sz = elemtype.getSizeInBits();
1616 if (elemtype.isInteger() && (sz < 32))
1618 O << "\t.reg .b" << sz << " ";
1619 printParamName(I, paramIndex, O);
1635 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1637 const Function *F = MF.getFunction();
1638 emitFunctionParamList(F, O);
1641 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1642 const MachineFunction &MF) {
1643 SmallString<128> Str;
1644 raw_svector_ostream O(Str);
1646 // Map the global virtual register number to a register class specific
1647 // virtual register number starting from 1 with that class.
1648 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1649 //unsigned numRegClasses = TRI->getNumRegClasses();
1651 // Emit the Fake Stack Object
1652 const MachineFrameInfo *MFI = MF.getFrameInfo();
1653 int NumBytes = (int) MFI->getStackSize();
1655 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1656 << getFunctionNumber() << "[" << NumBytes << "];\n";
1657 if (nvptxSubtarget.is64Bit()) {
1658 O << "\t.reg .b64 \t%SP;\n";
1659 O << "\t.reg .b64 \t%SPL;\n";
1661 O << "\t.reg .b32 \t%SP;\n";
1662 O << "\t.reg .b32 \t%SPL;\n";
1666 // Go through all virtual registers to establish the mapping between the
1668 // register number and the per class virtual register number.
1669 // We use the per class virtual register number in the ptx output.
1670 unsigned int numVRs = MRI->getNumVirtRegs();
1671 for (unsigned i = 0; i < numVRs; i++) {
1672 unsigned int vr = TRI->index2VirtReg(i);
1673 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1674 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1675 int n = regmap.size();
1676 regmap.insert(std::make_pair(vr, n + 1));
1679 // Emit register declarations
1680 // @TODO: Extract out the real register usage
1681 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1682 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1683 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1684 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1685 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1686 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1687 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1689 // Emit declaration of the virtual registers or 'physical' registers for
1690 // each register class
1691 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1692 const TargetRegisterClass *RC = TRI->getRegClass(i);
1693 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1694 std::string rcname = getNVPTXRegClassName(RC);
1695 std::string rcStr = getNVPTXRegClassStr(RC);
1696 int n = regmap.size();
1698 // Only declare those registers that may be used.
1700 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1705 OutStreamer.EmitRawText(O.str());
1708 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1709 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1711 unsigned int numHex;
1714 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1717 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1718 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1721 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1723 llvm_unreachable("unsupported fp type");
1725 APInt API = APF.bitcastToAPInt();
1726 std::string hexstr(utohexstr(API.getZExtValue()));
1728 if (hexstr.length() < numHex)
1729 O << std::string(numHex - hexstr.length(), '0');
1730 O << utohexstr(API.getZExtValue());
1733 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1734 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1735 O << CI->getValue();
1738 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1739 printFPConstant(CFP, O);
1742 if (isa<ConstantPointerNull>(CPV)) {
1746 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1747 O << *Mang->getSymbol(GVar);
1750 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1751 const Value *v = Cexpr->stripPointerCasts();
1752 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1753 O << *Mang->getSymbol(GVar);
1756 O << *LowerConstant(CPV, *this);
1760 llvm_unreachable("Not scalar type found in printScalarConstant()");
1763 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1764 AggBuffer *aggBuffer) {
1766 const DataLayout *TD = TM.getDataLayout();
1768 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1769 int s = TD->getTypeAllocSize(CPV->getType());
1772 aggBuffer->addZeros(s);
1777 switch (CPV->getType()->getTypeID()) {
1779 case Type::IntegerTyID: {
1780 const Type *ETy = CPV->getType();
1781 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1783 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1785 aggBuffer->addBytes(ptr, 1, Bytes);
1786 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1787 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1788 ptr = (unsigned char *)&int16;
1789 aggBuffer->addBytes(ptr, 2, Bytes);
1790 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1791 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1792 int int32 = (int)(constInt->getZExtValue());
1793 ptr = (unsigned char *)&int32;
1794 aggBuffer->addBytes(ptr, 4, Bytes);
1796 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1797 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1798 ConstantFoldConstantExpression(Cexpr, TD))) {
1799 int int32 = (int)(constInt->getZExtValue());
1800 ptr = (unsigned char *)&int32;
1801 aggBuffer->addBytes(ptr, 4, Bytes);
1804 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1805 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1806 aggBuffer->addSymbol(v);
1807 aggBuffer->addZeros(4);
1811 llvm_unreachable("unsupported integer const type");
1812 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1813 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1814 long long int64 = (long long)(constInt->getZExtValue());
1815 ptr = (unsigned char *)&int64;
1816 aggBuffer->addBytes(ptr, 8, Bytes);
1818 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1819 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1820 ConstantFoldConstantExpression(Cexpr, TD))) {
1821 long long int64 = (long long)(constInt->getZExtValue());
1822 ptr = (unsigned char *)&int64;
1823 aggBuffer->addBytes(ptr, 8, Bytes);
1826 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1827 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1828 aggBuffer->addSymbol(v);
1829 aggBuffer->addZeros(8);
1833 llvm_unreachable("unsupported integer const type");
1835 llvm_unreachable("unsupported integer const type");
1838 case Type::FloatTyID:
1839 case Type::DoubleTyID: {
1840 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1841 const Type *Ty = CFP->getType();
1842 if (Ty == Type::getFloatTy(CPV->getContext())) {
1843 float float32 = (float) CFP->getValueAPF().convertToFloat();
1844 ptr = (unsigned char *)&float32;
1845 aggBuffer->addBytes(ptr, 4, Bytes);
1846 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1847 double float64 = CFP->getValueAPF().convertToDouble();
1848 ptr = (unsigned char *)&float64;
1849 aggBuffer->addBytes(ptr, 8, Bytes);
1851 llvm_unreachable("unsupported fp const type");
1855 case Type::PointerTyID: {
1856 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1857 aggBuffer->addSymbol(GVar);
1858 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1859 const Value *v = Cexpr->stripPointerCasts();
1860 aggBuffer->addSymbol(v);
1862 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1863 aggBuffer->addZeros(s);
1867 case Type::ArrayTyID:
1868 case Type::VectorTyID:
1869 case Type::StructTyID: {
1870 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1871 isa<ConstantStruct>(CPV)) {
1872 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1873 bufferAggregateConstant(CPV, aggBuffer);
1874 if (Bytes > ElementSize)
1875 aggBuffer->addZeros(Bytes - ElementSize);
1876 } else if (isa<ConstantAggregateZero>(CPV))
1877 aggBuffer->addZeros(Bytes);
1879 llvm_unreachable("Unexpected Constant type");
1884 llvm_unreachable("unsupported type");
1888 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1889 AggBuffer *aggBuffer) {
1890 const DataLayout *TD = TM.getDataLayout();
1894 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1895 if (CPV->getNumOperands())
1896 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1897 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1901 if (const ConstantDataSequential *CDS =
1902 dyn_cast<ConstantDataSequential>(CPV)) {
1903 if (CDS->getNumElements())
1904 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1905 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1910 if (isa<ConstantStruct>(CPV)) {
1911 if (CPV->getNumOperands()) {
1912 StructType *ST = cast<StructType>(CPV->getType());
1913 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1915 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1916 TD->getTypeAllocSize(ST) -
1917 TD->getStructLayout(ST)->getElementOffset(i);
1919 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1920 TD->getStructLayout(ST)->getElementOffset(i);
1921 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1926 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1929 // buildTypeNameMap - Run through symbol table looking for type names.
1932 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1934 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1936 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1937 !PI->second.compare("struct._image2d_t") ||
1938 !PI->second.compare("struct._image3d_t")))
1945 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1946 switch (MI.getOpcode()) {
1949 case NVPTX::CallArgBeginInst:
1950 case NVPTX::CallArgEndInst0:
1951 case NVPTX::CallArgEndInst1:
1952 case NVPTX::CallArgF32:
1953 case NVPTX::CallArgF64:
1954 case NVPTX::CallArgI16:
1955 case NVPTX::CallArgI32:
1956 case NVPTX::CallArgI32imm:
1957 case NVPTX::CallArgI64:
1958 case NVPTX::CallArgParam:
1959 case NVPTX::CallVoidInst:
1960 case NVPTX::CallVoidInstReg:
1961 case NVPTX::Callseq_End:
1962 case NVPTX::CallVoidInstReg64:
1963 case NVPTX::DeclareParamInst:
1964 case NVPTX::DeclareRetMemInst:
1965 case NVPTX::DeclareRetRegInst:
1966 case NVPTX::DeclareRetScalarInst:
1967 case NVPTX::DeclareScalarParamInst:
1968 case NVPTX::DeclareScalarRegInst:
1969 case NVPTX::StoreParamF32:
1970 case NVPTX::StoreParamF64:
1971 case NVPTX::StoreParamI16:
1972 case NVPTX::StoreParamI32:
1973 case NVPTX::StoreParamI64:
1974 case NVPTX::StoreParamI8:
1975 case NVPTX::StoreRetvalF32:
1976 case NVPTX::StoreRetvalF64:
1977 case NVPTX::StoreRetvalI16:
1978 case NVPTX::StoreRetvalI32:
1979 case NVPTX::StoreRetvalI64:
1980 case NVPTX::StoreRetvalI8:
1981 case NVPTX::LastCallArgF32:
1982 case NVPTX::LastCallArgF64:
1983 case NVPTX::LastCallArgI16:
1984 case NVPTX::LastCallArgI32:
1985 case NVPTX::LastCallArgI32imm:
1986 case NVPTX::LastCallArgI64:
1987 case NVPTX::LastCallArgParam:
1988 case NVPTX::LoadParamMemF32:
1989 case NVPTX::LoadParamMemF64:
1990 case NVPTX::LoadParamMemI16:
1991 case NVPTX::LoadParamMemI32:
1992 case NVPTX::LoadParamMemI64:
1993 case NVPTX::LoadParamMemI8:
1994 case NVPTX::PrototypeInst:
1995 case NVPTX::DBG_VALUE:
2001 // Force static initialization.
2002 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2003 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2004 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2007 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2008 std::stringstream temp;
2009 LineReader *reader = this->getReader(filename.str());
2011 temp << filename.str();
2015 temp << reader->readLine(line);
2017 this->OutStreamer.EmitRawText(Twine(temp.str()));
2020 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2021 if (reader == NULL) {
2022 reader = new LineReader(filename);
2025 if (reader->fileName() != filename) {
2027 reader = new LineReader(filename);
2033 std::string LineReader::readLine(unsigned lineNum) {
2034 if (lineNum < theCurLine) {
2036 fstr.seekg(0, std::ios::beg);
2038 while (theCurLine < lineNum) {
2039 fstr.getline(buff, 500);
2045 // Force static initialization.
2046 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2047 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2048 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);