1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMCExpr.h"
21 #include "NVPTXRegisterInfo.h"
22 #include "NVPTXTargetMachine.h"
23 #include "NVPTXUtilities.h"
24 #include "cl_common_defines.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Analysis/ConstantFolding.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/IR/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Mangler.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/MC/MCStreamer.h"
39 #include "llvm/MC/MCSymbol.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/TargetRegistry.h"
45 #include "llvm/Support/TimeValue.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
50 #define DEPOTNAME "__local_depot"
53 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
54 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
58 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
59 cl::desc("NVPTX Specific: Emit source line in ptx file"),
63 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
65 void DiscoverDependentGlobals(const Value *V,
66 DenseSet<const GlobalVariable *> &Globals) {
67 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
70 if (const User *U = dyn_cast<User>(V)) {
71 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
72 DiscoverDependentGlobals(U->getOperand(i), Globals);
78 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
79 /// instances to be emitted, but only after any dependents have been added
81 void VisitGlobalVariableForEmission(
82 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
83 DenseSet<const GlobalVariable *> &Visited,
84 DenseSet<const GlobalVariable *> &Visiting) {
85 // Have we already visited this one?
86 if (Visited.count(GV))
89 // Do we have a circular dependency?
90 if (Visiting.count(GV))
91 report_fatal_error("Circular dependency found in global variable set");
93 // Start visiting this global
96 // Make sure we visit all dependents first
97 DenseSet<const GlobalVariable *> Others;
98 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
99 DiscoverDependentGlobals(GV->getOperand(i), Others);
101 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
104 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
106 // Now we can visit ourself
113 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
114 // cannot just link to the existing version.
115 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
117 using namespace nvptx;
118 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
119 MCContext &Ctx = AP.OutContext;
121 if (CV->isNullValue() || isa<UndefValue>(CV))
122 return MCConstantExpr::Create(0, Ctx);
124 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
125 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
127 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
128 return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
130 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
131 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
133 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
135 llvm_unreachable("Unknown constant value to lower!");
137 switch (CE->getOpcode()) {
139 // If the code isn't optimized, there may be outstanding folding
140 // opportunities. Attempt to fold the expression using DataLayout as a
141 // last resort before giving up.
142 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
144 return LowerConstant(C, AP);
146 // Otherwise report the problem to the user.
149 raw_string_ostream OS(S);
150 OS << "Unsupported expression in static initializer: ";
151 CE->printAsOperand(OS, /*PrintType=*/ false,
152 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
153 report_fatal_error(OS.str());
155 case Instruction::AddrSpaceCast: {
156 // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
157 // handled by the generic() logic in the MCExpr printer
158 PointerType *DstTy = cast<PointerType>(CE->getType());
159 PointerType *SrcTy = cast<PointerType>(CE->getOperand(0)->getType());
160 if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
161 return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
164 raw_string_ostream OS(S);
165 OS << "Unsupported expression in static initializer: ";
166 CE->printAsOperand(OS, /*PrintType=*/ false,
167 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
168 report_fatal_error(OS.str());
170 case Instruction::GetElementPtr: {
171 const DataLayout &TD = *AP.TM.getDataLayout();
172 // Generate a symbolic expression for the byte address
173 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
174 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
176 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
180 int64_t Offset = OffsetAI.getSExtValue();
181 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
185 case Instruction::Trunc:
186 // We emit the value and depend on the assembler to truncate the generated
187 // expression properly. This is important for differences between
188 // blockaddress labels. Since the two labels are in the same function, it
189 // is reasonable to treat their delta as a 32-bit value.
191 case Instruction::BitCast:
192 return LowerConstant(CE->getOperand(0), AP);
194 case Instruction::IntToPtr: {
195 const DataLayout &TD = *AP.TM.getDataLayout();
196 // Handle casts to pointers by changing them into casts to the appropriate
197 // integer type. This promotes constant folding and simplifies this code.
198 Constant *Op = CE->getOperand(0);
199 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
201 return LowerConstant(Op, AP);
204 case Instruction::PtrToInt: {
205 const DataLayout &TD = *AP.TM.getDataLayout();
206 // Support only foldable casts to/from pointers that can be eliminated by
207 // changing the pointer to the appropriately sized integer type.
208 Constant *Op = CE->getOperand(0);
209 Type *Ty = CE->getType();
211 const MCExpr *OpExpr = LowerConstant(Op, AP);
213 // We can emit the pointer value into this slot if the slot is an
214 // integer slot equal to the size of the pointer.
215 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
218 // Otherwise the pointer is smaller than the resultant integer, mask off
219 // the high bits so we are sure to get a proper truncation if the input is
221 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
222 const MCExpr *MaskExpr =
223 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
224 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
227 // The MC library also has a right-shift operator, but it isn't consistently
228 // signed or unsigned between different targets.
229 case Instruction::Add:
230 case Instruction::Sub:
231 case Instruction::Mul:
232 case Instruction::SDiv:
233 case Instruction::SRem:
234 case Instruction::Shl:
235 case Instruction::And:
236 case Instruction::Or:
237 case Instruction::Xor: {
238 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
239 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
240 switch (CE->getOpcode()) {
242 llvm_unreachable("Unknown binary operator constant cast expr");
243 case Instruction::Add:
244 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
245 case Instruction::Sub:
246 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
247 case Instruction::Mul:
248 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
249 case Instruction::SDiv:
250 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
251 case Instruction::SRem:
252 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
253 case Instruction::Shl:
254 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
255 case Instruction::And:
256 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
257 case Instruction::Or:
258 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
259 case Instruction::Xor:
260 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
266 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
267 if (!EmitLineNumbers)
272 DebugLoc curLoc = MI.getDebugLoc();
274 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
277 if (prevDebugLoc == curLoc)
280 prevDebugLoc = curLoc;
282 if (curLoc.isUnknown())
285 const MachineFunction *MF = MI.getParent()->getParent();
286 //const TargetMachine &TM = MF->getTarget();
288 const LLVMContext &ctx = MF->getFunction()->getContext();
289 DIScope Scope(curLoc.getScope(ctx));
291 assert((!Scope || Scope.isScope()) &&
292 "Scope of a DebugLoc should be null or a DIScope.");
296 StringRef fileName(Scope.getFilename());
297 StringRef dirName(Scope.getDirectory());
298 SmallString<128> FullPathName = dirName;
299 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
300 sys::path::append(FullPathName, fileName);
301 fileName = FullPathName.str();
304 if (filenameMap.find(fileName.str()) == filenameMap.end())
307 // Emit the line from the source file.
309 this->emitSrcInText(fileName.str(), curLoc.getLine());
311 std::stringstream temp;
312 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
313 << " " << curLoc.getCol();
314 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
317 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
318 SmallString<128> Str;
319 raw_svector_ostream OS(Str);
320 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
321 emitLineNumberAsDotLoc(*MI);
324 lowerToMCInst(MI, Inst);
325 EmitToStreamer(OutStreamer, Inst);
328 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
329 OutMI.setOpcode(MI->getOpcode());
331 // Special: Do not mangle symbol operand of CALL_PROTOTYPE
332 if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
333 const MachineOperand &MO = MI->getOperand(0);
334 OutMI.addOperand(GetSymbolRef(MO,
335 OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
339 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
340 const MachineOperand &MO = MI->getOperand(i);
343 if (lowerOperand(MO, MCOp))
344 OutMI.addOperand(MCOp);
348 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
350 switch (MO.getType()) {
351 default: llvm_unreachable("unknown operand type");
352 case MachineOperand::MO_Register:
353 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
355 case MachineOperand::MO_Immediate:
356 MCOp = MCOperand::CreateImm(MO.getImm());
358 case MachineOperand::MO_MachineBasicBlock:
359 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
360 MO.getMBB()->getSymbol(), OutContext));
362 case MachineOperand::MO_ExternalSymbol:
363 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
365 case MachineOperand::MO_GlobalAddress:
366 MCOp = GetSymbolRef(MO, getSymbol(MO.getGlobal()));
368 case MachineOperand::MO_FPImmediate: {
369 const ConstantFP *Cnt = MO.getFPImm();
370 APFloat Val = Cnt->getValueAPF();
372 switch (Cnt->getType()->getTypeID()) {
373 default: report_fatal_error("Unsupported FP type"); break;
374 case Type::FloatTyID:
375 MCOp = MCOperand::CreateExpr(
376 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
378 case Type::DoubleTyID:
379 MCOp = MCOperand::CreateExpr(
380 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
389 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
390 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
391 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
393 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
394 unsigned RegNum = RegMap[Reg];
396 // Encode the register class in the upper 4 bits
397 // Must be kept in sync with NVPTXInstPrinter::printRegName
399 if (RC == &NVPTX::Int1RegsRegClass) {
401 } else if (RC == &NVPTX::Int16RegsRegClass) {
403 } else if (RC == &NVPTX::Int32RegsRegClass) {
405 } else if (RC == &NVPTX::Int64RegsRegClass) {
407 } else if (RC == &NVPTX::Float32RegsRegClass) {
409 } else if (RC == &NVPTX::Float64RegsRegClass) {
412 report_fatal_error("Bad register class");
415 // Insert the vreg number
416 Ret |= (RegNum & 0x0FFFFFFF);
419 // Some special-use registers are actually physical registers.
420 // Encode this as the register class ID of 0 and the real register ID.
421 return Reg & 0x0FFFFFFF;
425 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
426 const MCSymbol *Symbol) {
428 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
430 return MCOperand::CreateExpr(Expr);
433 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
434 const DataLayout *TD = TM.getDataLayout();
435 const TargetLowering *TLI = TM.getTargetLowering();
437 Type *Ty = F->getReturnType();
439 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
441 if (Ty->getTypeID() == Type::VoidTyID)
447 if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
449 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
450 size = ITy->getBitWidth();
454 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
455 size = Ty->getPrimitiveSizeInBits();
458 O << ".param .b" << size << " func_retval0";
459 } else if (isa<PointerType>(Ty)) {
460 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
463 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
464 SmallVector<EVT, 16> vtparts;
465 ComputeValueVTs(*TLI, Ty, vtparts);
466 unsigned totalsz = 0;
467 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
469 EVT elemtype = vtparts[i];
470 if (vtparts[i].isVector()) {
471 elems = vtparts[i].getVectorNumElements();
472 elemtype = vtparts[i].getVectorElementType();
474 for (unsigned j = 0, je = elems; j != je; ++j) {
475 unsigned sz = elemtype.getSizeInBits();
476 if (elemtype.isInteger() && (sz < 8))
481 unsigned retAlignment = 0;
482 if (!llvm::getAlign(*F, 0, retAlignment))
483 retAlignment = TD->getABITypeAlignment(Ty);
484 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
487 assert(false && "Unknown return type");
490 SmallVector<EVT, 16> vtparts;
491 ComputeValueVTs(*TLI, Ty, vtparts);
493 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
495 EVT elemtype = vtparts[i];
496 if (vtparts[i].isVector()) {
497 elems = vtparts[i].getVectorNumElements();
498 elemtype = vtparts[i].getVectorElementType();
501 for (unsigned j = 0, je = elems; j != je; ++j) {
502 unsigned sz = elemtype.getSizeInBits();
503 if (elemtype.isInteger() && (sz < 32))
505 O << ".reg .b" << sz << " func_retval" << idx;
518 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
520 const Function *F = MF.getFunction();
521 printReturnValStr(F, O);
524 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
525 SmallString<128> Str;
526 raw_svector_ostream O(Str);
528 if (!GlobalsEmitted) {
529 emitGlobals(*MF->getFunction()->getParent());
530 GlobalsEmitted = true;
534 MRI = &MF->getRegInfo();
535 F = MF->getFunction();
536 emitLinkageDirective(F, O);
537 if (llvm::isKernelFunction(*F))
541 printReturnValStr(*MF, O);
546 emitFunctionParamList(*MF, O);
548 if (llvm::isKernelFunction(*F))
549 emitKernelFunctionDirectives(*F, O);
551 OutStreamer.EmitRawText(O.str());
553 prevDebugLoc = DebugLoc();
556 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
558 OutStreamer.EmitRawText(StringRef("{\n"));
559 setAndEmitFunctionVirtualRegisters(*MF);
561 SmallString<128> Str;
562 raw_svector_ostream O(Str);
563 emitDemotedVars(MF->getFunction(), O);
564 OutStreamer.EmitRawText(O.str());
567 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
568 OutStreamer.EmitRawText(StringRef("}\n"));
572 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
573 unsigned RegNo = MI->getOperand(0).getReg();
574 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
575 if (TRI->isVirtualRegister(RegNo)) {
576 OutStreamer.AddComment(Twine("implicit-def: ") +
577 getVirtualRegisterName(RegNo));
579 OutStreamer.AddComment(Twine("implicit-def: ") +
580 TM.getRegisterInfo()->getName(RegNo));
582 OutStreamer.AddBlankLine();
585 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
586 raw_ostream &O) const {
587 // If the NVVM IR has some of reqntid* specified, then output
588 // the reqntid directive, and set the unspecified ones to 1.
589 // If none of reqntid* is specified, don't output reqntid directive.
590 unsigned reqntidx, reqntidy, reqntidz;
591 bool specified = false;
592 if (llvm::getReqNTIDx(F, reqntidx) == false)
596 if (llvm::getReqNTIDy(F, reqntidy) == false)
600 if (llvm::getReqNTIDz(F, reqntidz) == false)
606 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
609 // If the NVVM IR has some of maxntid* specified, then output
610 // the maxntid directive, and set the unspecified ones to 1.
611 // If none of maxntid* is specified, don't output maxntid directive.
612 unsigned maxntidx, maxntidy, maxntidz;
614 if (llvm::getMaxNTIDx(F, maxntidx) == false)
618 if (llvm::getMaxNTIDy(F, maxntidy) == false)
622 if (llvm::getMaxNTIDz(F, maxntidz) == false)
628 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
632 if (llvm::getMinCTASm(F, mincta))
633 O << ".minnctapersm " << mincta << "\n";
637 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
638 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
641 raw_string_ostream NameStr(Name);
643 VRegRCMap::const_iterator I = VRegMapping.find(RC);
644 assert(I != VRegMapping.end() && "Bad register class");
645 const DenseMap<unsigned, unsigned> &RegMap = I->second;
647 VRegMap::const_iterator VI = RegMap.find(Reg);
648 assert(VI != RegMap.end() && "Bad virtual register");
649 unsigned MappedVR = VI->second;
651 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
657 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
659 O << getVirtualRegisterName(vr);
662 void NVPTXAsmPrinter::printVecModifiedImmediate(
663 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
664 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
665 int Imm = (int) MO.getImm();
666 if (0 == strcmp(Modifier, "vecelem"))
667 O << "_" << vecelem[Imm];
668 else if (0 == strcmp(Modifier, "vecv4comm1")) {
669 if ((Imm < 0) || (Imm > 3))
671 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
672 if ((Imm < 4) || (Imm > 7))
674 } else if (0 == strcmp(Modifier, "vecv4pos")) {
677 O << "_" << vecelem[Imm % 4];
678 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
679 if ((Imm < 0) || (Imm > 1))
681 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
682 if ((Imm < 2) || (Imm > 3))
684 } else if (0 == strcmp(Modifier, "vecv2pos")) {
687 O << "_" << vecelem[Imm % 2];
689 llvm_unreachable("Unknown Modifier on immediate operand");
694 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
696 emitLinkageDirective(F, O);
697 if (llvm::isKernelFunction(*F))
701 printReturnValStr(F, O);
702 O << *getSymbol(F) << "\n";
703 emitFunctionParamList(F, O);
707 static bool usedInGlobalVarDef(const Constant *C) {
711 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
712 if (GV->getName().str() == "llvm.used")
717 for (const User *U : C->users())
718 if (const Constant *C = dyn_cast<Constant>(U))
719 if (usedInGlobalVarDef(C))
725 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
726 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
727 if (othergv->getName().str() == "llvm.used")
731 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
732 if (instr->getParent() && instr->getParent()->getParent()) {
733 const Function *curFunc = instr->getParent()->getParent();
734 if (oneFunc && (curFunc != oneFunc))
742 if (const MDNode *md = dyn_cast<MDNode>(U))
743 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
744 (md->getName().str() == "llvm.dbg.sp")))
747 for (const User *UU : U->users())
748 if (usedInOneFunc(UU, oneFunc) == false)
754 /* Find out if a global variable can be demoted to local scope.
755 * Currently, this is valid for CUDA shared variables, which have local
756 * scope and global lifetime. So the conditions to check are :
757 * 1. Is the global variable in shared address space?
758 * 2. Does it have internal linkage?
759 * 3. Is the global variable referenced only in one function?
761 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
762 if (gv->hasInternalLinkage() == false)
764 const PointerType *Pty = gv->getType();
765 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
768 const Function *oneFunc = 0;
770 bool flag = usedInOneFunc(gv, oneFunc);
779 static bool useFuncSeen(const Constant *C,
780 llvm::DenseMap<const Function *, bool> &seenMap) {
781 for (const User *U : C->users()) {
782 if (const Constant *cu = dyn_cast<Constant>(U)) {
783 if (useFuncSeen(cu, seenMap))
785 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
786 const BasicBlock *bb = I->getParent();
789 const Function *caller = bb->getParent();
792 if (seenMap.find(caller) != seenMap.end())
799 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
800 llvm::DenseMap<const Function *, bool> seenMap;
801 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
802 const Function *F = FI;
804 if (F->isDeclaration()) {
807 if (F->getIntrinsicID())
809 emitDeclaration(F, O);
812 for (const User *U : F->users()) {
813 if (const Constant *C = dyn_cast<Constant>(U)) {
814 if (usedInGlobalVarDef(C)) {
815 // The use is in the initialization of a global variable
816 // that is a function pointer, so print a declaration
817 // for the original function
818 emitDeclaration(F, O);
821 // Emit a declaration of this function if the function that
822 // uses this constant expr has already been seen.
823 if (useFuncSeen(C, seenMap)) {
824 emitDeclaration(F, O);
829 if (!isa<Instruction>(U))
831 const Instruction *instr = cast<Instruction>(U);
832 const BasicBlock *bb = instr->getParent();
835 const Function *caller = bb->getParent();
839 // If a caller has already been seen, then the caller is
840 // appearing in the module before the callee. so print out
841 // a declaration for the callee.
842 if (seenMap.find(caller) != seenMap.end()) {
843 emitDeclaration(F, O);
851 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
852 DebugInfoFinder DbgFinder;
853 DbgFinder.processModule(M);
856 for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
857 StringRef Filename(DIUnit.getFilename());
858 StringRef Dirname(DIUnit.getDirectory());
859 SmallString<128> FullPathName = Dirname;
860 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
861 sys::path::append(FullPathName, Filename);
862 Filename = FullPathName.str();
864 if (filenameMap.find(Filename.str()) != filenameMap.end())
866 filenameMap[Filename.str()] = i;
867 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
871 for (DISubprogram SP : DbgFinder.subprograms()) {
872 StringRef Filename(SP.getFilename());
873 StringRef Dirname(SP.getDirectory());
874 SmallString<128> FullPathName = Dirname;
875 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
876 sys::path::append(FullPathName, Filename);
877 Filename = FullPathName.str();
879 if (filenameMap.find(Filename.str()) != filenameMap.end())
881 filenameMap[Filename.str()] = i;
886 bool NVPTXAsmPrinter::doInitialization(Module &M) {
888 SmallString<128> Str1;
889 raw_svector_ostream OS1(Str1);
891 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
892 MMI->AnalyzeModule(M);
894 // We need to call the parent's one explicitly.
895 //bool Result = AsmPrinter::doInitialization(M);
897 // Initialize TargetLoweringObjectFile.
898 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
899 .Initialize(OutContext, TM);
901 Mang = new Mangler(TM.getDataLayout());
903 // Emit header before any dwarf directives are emitted below.
905 OutStreamer.EmitRawText(OS1.str());
907 // Already commented out
908 //bool Result = AsmPrinter::doInitialization(M);
910 // Emit module-level inline asm if it exists.
911 if (!M.getModuleInlineAsm().empty()) {
912 OutStreamer.AddComment("Start of file scope inline assembly");
913 OutStreamer.AddBlankLine();
914 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
915 OutStreamer.AddBlankLine();
916 OutStreamer.AddComment("End of file scope inline assembly");
917 OutStreamer.AddBlankLine();
920 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
921 recordAndEmitFilenames(M);
923 GlobalsEmitted = false;
925 return false; // success
928 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
929 SmallString<128> Str2;
930 raw_svector_ostream OS2(Str2);
932 emitDeclarations(M, OS2);
934 // As ptxas does not support forward references of globals, we need to first
935 // sort the list of module-level globals in def-use order. We visit each
936 // global variable in order, and ensure that we emit it *after* its dependent
937 // globals. We use a little extra memory maintaining both a set and a list to
938 // have fast searches while maintaining a strict ordering.
939 SmallVector<const GlobalVariable *, 8> Globals;
940 DenseSet<const GlobalVariable *> GVVisited;
941 DenseSet<const GlobalVariable *> GVVisiting;
943 // Visit each global variable, in order
944 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
946 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
948 assert(GVVisited.size() == M.getGlobalList().size() &&
949 "Missed a global variable");
950 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
952 // Print out module-level global variables in proper order
953 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
954 printModuleLevelGV(Globals[i], OS2);
958 OutStreamer.EmitRawText(OS2.str());
961 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
963 O << "// Generated by LLVM NVPTX Back-End\n";
967 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
968 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
971 O << nvptxSubtarget.getTargetName();
973 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
974 O << ", texmode_independent";
975 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
976 if (!nvptxSubtarget.hasDouble())
977 O << ", map_f64_to_f32";
980 if (MAI->doesSupportDebugInformation())
985 O << ".address_size ";
986 if (nvptxSubtarget.is64Bit())
995 bool NVPTXAsmPrinter::doFinalization(Module &M) {
997 // If we did not emit any functions, then the global declarations have not
999 if (!GlobalsEmitted) {
1001 GlobalsEmitted = true;
1004 // XXX Temproarily remove global variables so that doFinalization() will not
1005 // emit them again (global variables are emitted at beginning).
1007 Module::GlobalListType &global_list = M.getGlobalList();
1008 int i, n = global_list.size();
1009 GlobalVariable **gv_array = new GlobalVariable *[n];
1011 // first, back-up GlobalVariable in gv_array
1013 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1015 gv_array[i++] = &*I;
1017 // second, empty global_list
1018 while (!global_list.empty())
1019 global_list.remove(global_list.begin());
1021 // call doFinalization
1022 bool ret = AsmPrinter::doFinalization(M);
1024 // now we restore global variables
1025 for (i = 0; i < n; i++)
1026 global_list.insert(global_list.end(), gv_array[i]);
1028 clearAnnotationCache(&M);
1033 //bool Result = AsmPrinter::doFinalization(M);
1034 // Instead of calling the parents doFinalization, we may
1035 // clone parents doFinalization and customize here.
1036 // Currently, we if NVISA out the EmitGlobals() in
1037 // parent's doFinalization, which is too intrusive.
1039 // Same for the doInitialization.
1043 // This function emits appropriate linkage directives for
1044 // functions and global variables.
1046 // extern function declaration -> .extern
1047 // extern function definition -> .visible
1048 // external global variable with init -> .visible
1049 // external without init -> .extern
1050 // appending -> not allowed, assert.
1052 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1054 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1055 if (V->hasExternalLinkage()) {
1056 if (isa<GlobalVariable>(V)) {
1057 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1059 if (GVar->hasInitializer())
1064 } else if (V->isDeclaration())
1068 } else if (V->hasAppendingLinkage()) {
1070 msg.append("Error: ");
1071 msg.append("Symbol ");
1073 msg.append(V->getName().str());
1074 msg.append("has unsupported appending linkage type");
1075 llvm_unreachable(msg.c_str());
1080 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1082 bool processDemoted) {
1085 if (GVar->hasSection()) {
1086 if (GVar->getSection() == "llvm.metadata")
1090 const DataLayout *TD = TM.getDataLayout();
1092 // GlobalVariables are always constant pointers themselves.
1093 const PointerType *PTy = GVar->getType();
1094 Type *ETy = PTy->getElementType();
1096 if (GVar->hasExternalLinkage()) {
1097 if (GVar->hasInitializer())
1103 if (llvm::isTexture(*GVar)) {
1104 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1108 if (llvm::isSurface(*GVar)) {
1109 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1113 if (GVar->isDeclaration()) {
1114 // (extern) declarations, no definition or initializer
1115 // Currently the only known declaration is for an automatic __local
1116 // (.shared) promoted to global.
1117 emitPTXGlobalVariable(GVar, O);
1122 if (llvm::isSampler(*GVar)) {
1123 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1125 const Constant *Initializer = NULL;
1126 if (GVar->hasInitializer())
1127 Initializer = GVar->getInitializer();
1128 const ConstantInt *CI = NULL;
1130 CI = dyn_cast<ConstantInt>(Initializer);
1132 unsigned sample = CI->getZExtValue();
1137 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1139 O << "addr_mode_" << i << " = ";
1145 O << "clamp_to_border";
1148 O << "clamp_to_edge";
1159 O << "filter_mode = ";
1160 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1168 assert(0 && "Anisotropic filtering is not supported");
1173 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1174 O << ", force_unnormalized_coords = 1";
1183 if (GVar->hasPrivateLinkage()) {
1185 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1188 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1189 if (!strncmp(GVar->getName().data(), "filename", 8))
1191 if (GVar->use_empty())
1195 const Function *demotedFunc = 0;
1196 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1197 O << "// " << GVar->getName().str() << " has been demoted\n";
1198 if (localDecls.find(demotedFunc) != localDecls.end())
1199 localDecls[demotedFunc].push_back(GVar);
1201 std::vector<const GlobalVariable *> temp;
1202 temp.push_back(GVar);
1203 localDecls[demotedFunc] = temp;
1209 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1210 if (GVar->getAlignment() == 0)
1211 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1213 O << " .align " << GVar->getAlignment();
1215 if (ETy->isSingleValueType()) {
1217 // Special case: ABI requires that we use .u8 for predicates
1218 if (ETy->isIntegerTy(1))
1221 O << getPTXFundamentalTypeStr(ETy, false);
1223 O << *getSymbol(GVar);
1225 // Ptx allows variable initilization only for constant and global state
1227 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1228 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1229 GVar->hasInitializer()) {
1230 const Constant *Initializer = GVar->getInitializer();
1231 if (!Initializer->isNullValue()) {
1233 printScalarConstant(Initializer, O);
1237 unsigned int ElementSize = 0;
1239 // Although PTX has direct support for struct type and array type and
1240 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1241 // targets that support these high level field accesses. Structs, arrays
1242 // and vectors are lowered into arrays of bytes.
1243 switch (ETy->getTypeID()) {
1244 case Type::StructTyID:
1245 case Type::ArrayTyID:
1246 case Type::VectorTyID:
1247 ElementSize = TD->getTypeStoreSize(ETy);
1248 // Ptx allows variable initilization only for constant and
1249 // global state spaces.
1250 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1251 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1252 GVar->hasInitializer()) {
1253 const Constant *Initializer = GVar->getInitializer();
1254 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1255 AggBuffer aggBuffer(ElementSize, O, *this);
1256 bufferAggregateConstant(Initializer, &aggBuffer);
1257 if (aggBuffer.numSymbols) {
1258 if (nvptxSubtarget.is64Bit()) {
1259 O << " .u64 " << *getSymbol(GVar) << "[";
1260 O << ElementSize / 8;
1262 O << " .u32 " << *getSymbol(GVar) << "[";
1263 O << ElementSize / 4;
1267 O << " .b8 " << *getSymbol(GVar) << "[";
1275 O << " .b8 " << *getSymbol(GVar);
1283 O << " .b8 " << *getSymbol(GVar);
1292 assert(0 && "type not supported yet");
1299 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1300 if (localDecls.find(f) == localDecls.end())
1303 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1305 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1306 O << "\t// demoted variable\n\t";
1307 printModuleLevelGV(gvars[i], O, true);
1311 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1312 raw_ostream &O) const {
1313 switch (AddressSpace) {
1314 case llvm::ADDRESS_SPACE_LOCAL:
1317 case llvm::ADDRESS_SPACE_GLOBAL:
1320 case llvm::ADDRESS_SPACE_CONST:
1323 case llvm::ADDRESS_SPACE_SHARED:
1327 report_fatal_error("Bad address space found while emitting PTX");
1333 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1334 switch (Ty->getTypeID()) {
1336 llvm_unreachable("unexpected type");
1338 case Type::IntegerTyID: {
1339 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1342 else if (NumBits <= 64) {
1343 std::string name = "u";
1344 return name + utostr(NumBits);
1346 llvm_unreachable("Integer too large");
1351 case Type::FloatTyID:
1353 case Type::DoubleTyID:
1355 case Type::PointerTyID:
1356 if (nvptxSubtarget.is64Bit())
1366 llvm_unreachable("unexpected type");
1370 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1373 const DataLayout *TD = TM.getDataLayout();
1375 // GlobalVariables are always constant pointers themselves.
1376 const PointerType *PTy = GVar->getType();
1377 Type *ETy = PTy->getElementType();
1380 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1381 if (GVar->getAlignment() == 0)
1382 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1384 O << " .align " << GVar->getAlignment();
1386 if (ETy->isSingleValueType()) {
1388 O << getPTXFundamentalTypeStr(ETy);
1390 O << *getSymbol(GVar);
1394 int64_t ElementSize = 0;
1396 // Although PTX has direct support for struct type and array type and LLVM IR
1397 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1398 // support these high level field accesses. Structs and arrays are lowered
1399 // into arrays of bytes.
1400 switch (ETy->getTypeID()) {
1401 case Type::StructTyID:
1402 case Type::ArrayTyID:
1403 case Type::VectorTyID:
1404 ElementSize = TD->getTypeStoreSize(ETy);
1405 O << " .b8 " << *getSymbol(GVar) << "[";
1407 O << itostr(ElementSize);
1412 assert(0 && "type not supported yet");
1417 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1418 if (Ty->isSingleValueType())
1419 return TD->getPrefTypeAlignment(Ty);
1421 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1423 return getOpenCLAlignment(TD, ATy->getElementType());
1425 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1427 Type *ETy = VTy->getElementType();
1428 unsigned int numE = VTy->getNumElements();
1429 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1433 return numE * alignE;
1436 const StructType *STy = dyn_cast<StructType>(Ty);
1438 unsigned int alignStruct = 1;
1439 // Go through each element of the struct and find the
1440 // largest alignment.
1441 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1442 Type *ETy = STy->getElementType(i);
1443 unsigned int align = getOpenCLAlignment(TD, ETy);
1444 if (align > alignStruct)
1445 alignStruct = align;
1450 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1452 return TD->getPointerPrefAlignment();
1453 return TD->getPrefTypeAlignment(Ty);
1456 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1457 int paramIndex, raw_ostream &O) {
1458 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1459 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1460 O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1462 std::string argName = I->getName();
1463 const char *p = argName.c_str();
1474 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1475 Function::const_arg_iterator I, E;
1478 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1479 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1480 O << *CurrentFnSym << "_param_" << paramIndex;
1484 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1485 if (i == paramIndex) {
1486 printParamName(I, paramIndex, O);
1490 llvm_unreachable("paramIndex out of bound");
1493 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1494 const DataLayout *TD = TM.getDataLayout();
1495 const AttributeSet &PAL = F->getAttributes();
1496 const TargetLowering *TLI = TM.getTargetLowering();
1497 Function::const_arg_iterator I, E;
1498 unsigned paramIndex = 0;
1500 bool isKernelFunc = llvm::isKernelFunction(*F);
1501 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1502 MVT thePointerTy = TLI->getPointerTy();
1506 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1507 Type *Ty = I->getType();
1514 // Handle image/sampler parameters
1515 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1516 if (llvm::isImage(*I)) {
1517 std::string sname = I->getName();
1518 if (llvm::isImageWriteOnly(*I))
1519 O << "\t.param .surfref " << *getSymbol(F) << "_param_"
1521 else // Default image is read_only
1522 O << "\t.param .texref " << *getSymbol(F) << "_param_"
1524 } else // Should be llvm::isSampler(*I)
1525 O << "\t.param .samplerref " << *getSymbol(F) << "_param_"
1530 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1531 if (Ty->isAggregateType() || Ty->isVectorTy()) {
1532 // Just print .param .align <a> .b8 .param[size];
1533 // <a> = PAL.getparamalignment
1534 // size = typeallocsize of element type
1535 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1537 align = TD->getABITypeAlignment(Ty);
1539 unsigned sz = TD->getTypeAllocSize(Ty);
1540 O << "\t.param .align " << align << " .b8 ";
1541 printParamName(I, paramIndex, O);
1542 O << "[" << sz << "]";
1547 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1550 // Special handling for pointer arguments to kernel
1551 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1553 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1554 Type *ETy = PTy->getElementType();
1555 int addrSpace = PTy->getAddressSpace();
1556 switch (addrSpace) {
1560 case llvm::ADDRESS_SPACE_CONST:
1561 O << ".ptr .const ";
1563 case llvm::ADDRESS_SPACE_SHARED:
1564 O << ".ptr .shared ";
1566 case llvm::ADDRESS_SPACE_GLOBAL:
1567 O << ".ptr .global ";
1570 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1572 printParamName(I, paramIndex, O);
1576 // non-pointer scalar to kernel func
1578 // Special case: predicate operands become .u8 types
1579 if (Ty->isIntegerTy(1))
1582 O << getPTXFundamentalTypeStr(Ty);
1584 printParamName(I, paramIndex, O);
1587 // Non-kernel function, just print .param .b<size> for ABI
1588 // and .reg .b<size> for non-ABI
1590 if (isa<IntegerType>(Ty)) {
1591 sz = cast<IntegerType>(Ty)->getBitWidth();
1594 } else if (isa<PointerType>(Ty))
1595 sz = thePointerTy.getSizeInBits();
1597 sz = Ty->getPrimitiveSizeInBits();
1599 O << "\t.param .b" << sz << " ";
1601 O << "\t.reg .b" << sz << " ";
1602 printParamName(I, paramIndex, O);
1606 // param has byVal attribute. So should be a pointer
1607 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1608 assert(PTy && "Param with byval attribute should be a pointer type");
1609 Type *ETy = PTy->getElementType();
1611 if (isABI || isKernelFunc) {
1612 // Just print .param .align <a> .b8 .param[size];
1613 // <a> = PAL.getparamalignment
1614 // size = typeallocsize of element type
1615 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1617 align = TD->getABITypeAlignment(ETy);
1619 unsigned sz = TD->getTypeAllocSize(ETy);
1620 O << "\t.param .align " << align << " .b8 ";
1621 printParamName(I, paramIndex, O);
1622 O << "[" << sz << "]";
1625 // Split the ETy into constituent parts and
1626 // print .param .b<size> <name> for each part.
1627 // Further, if a part is vector, print the above for
1628 // each vector element.
1629 SmallVector<EVT, 16> vtparts;
1630 ComputeValueVTs(*TLI, ETy, vtparts);
1631 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1633 EVT elemtype = vtparts[i];
1634 if (vtparts[i].isVector()) {
1635 elems = vtparts[i].getVectorNumElements();
1636 elemtype = vtparts[i].getVectorElementType();
1639 for (unsigned j = 0, je = elems; j != je; ++j) {
1640 unsigned sz = elemtype.getSizeInBits();
1641 if (elemtype.isInteger() && (sz < 32))
1643 O << "\t.reg .b" << sz << " ";
1644 printParamName(I, paramIndex, O);
1660 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1662 const Function *F = MF.getFunction();
1663 emitFunctionParamList(F, O);
1666 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1667 const MachineFunction &MF) {
1668 SmallString<128> Str;
1669 raw_svector_ostream O(Str);
1671 // Map the global virtual register number to a register class specific
1672 // virtual register number starting from 1 with that class.
1673 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1674 //unsigned numRegClasses = TRI->getNumRegClasses();
1676 // Emit the Fake Stack Object
1677 const MachineFrameInfo *MFI = MF.getFrameInfo();
1678 int NumBytes = (int) MFI->getStackSize();
1680 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1681 << getFunctionNumber() << "[" << NumBytes << "];\n";
1682 if (nvptxSubtarget.is64Bit()) {
1683 O << "\t.reg .b64 \t%SP;\n";
1684 O << "\t.reg .b64 \t%SPL;\n";
1686 O << "\t.reg .b32 \t%SP;\n";
1687 O << "\t.reg .b32 \t%SPL;\n";
1691 // Go through all virtual registers to establish the mapping between the
1693 // register number and the per class virtual register number.
1694 // We use the per class virtual register number in the ptx output.
1695 unsigned int numVRs = MRI->getNumVirtRegs();
1696 for (unsigned i = 0; i < numVRs; i++) {
1697 unsigned int vr = TRI->index2VirtReg(i);
1698 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1699 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1700 int n = regmap.size();
1701 regmap.insert(std::make_pair(vr, n + 1));
1704 // Emit register declarations
1705 // @TODO: Extract out the real register usage
1706 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1707 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1708 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1709 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1710 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1711 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1712 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1714 // Emit declaration of the virtual registers or 'physical' registers for
1715 // each register class
1716 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1717 const TargetRegisterClass *RC = TRI->getRegClass(i);
1718 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1719 std::string rcname = getNVPTXRegClassName(RC);
1720 std::string rcStr = getNVPTXRegClassStr(RC);
1721 int n = regmap.size();
1723 // Only declare those registers that may be used.
1725 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1730 OutStreamer.EmitRawText(O.str());
1733 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1734 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1736 unsigned int numHex;
1739 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1742 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1743 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1746 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1748 llvm_unreachable("unsupported fp type");
1750 APInt API = APF.bitcastToAPInt();
1751 std::string hexstr(utohexstr(API.getZExtValue()));
1753 if (hexstr.length() < numHex)
1754 O << std::string(numHex - hexstr.length(), '0');
1755 O << utohexstr(API.getZExtValue());
1758 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1759 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1760 O << CI->getValue();
1763 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1764 printFPConstant(CFP, O);
1767 if (isa<ConstantPointerNull>(CPV)) {
1771 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1772 PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1773 bool IsNonGenericPointer = false;
1774 if (PTy && PTy->getAddressSpace() != 0) {
1775 IsNonGenericPointer = true;
1777 if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1779 O << *getSymbol(GVar);
1782 O << *getSymbol(GVar);
1786 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1787 const Value *v = Cexpr->stripPointerCasts();
1788 PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1789 bool IsNonGenericPointer = false;
1790 if (PTy && PTy->getAddressSpace() != 0) {
1791 IsNonGenericPointer = true;
1793 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1794 if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1796 O << *getSymbol(GVar);
1799 O << *getSymbol(GVar);
1803 O << *LowerConstant(CPV, *this);
1807 llvm_unreachable("Not scalar type found in printScalarConstant()");
1810 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1811 AggBuffer *aggBuffer) {
1813 const DataLayout *TD = TM.getDataLayout();
1815 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1816 int s = TD->getTypeAllocSize(CPV->getType());
1819 aggBuffer->addZeros(s);
1824 switch (CPV->getType()->getTypeID()) {
1826 case Type::IntegerTyID: {
1827 const Type *ETy = CPV->getType();
1828 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1830 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1832 aggBuffer->addBytes(ptr, 1, Bytes);
1833 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1834 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1835 ptr = (unsigned char *)&int16;
1836 aggBuffer->addBytes(ptr, 2, Bytes);
1837 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1838 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1839 int int32 = (int)(constInt->getZExtValue());
1840 ptr = (unsigned char *)&int32;
1841 aggBuffer->addBytes(ptr, 4, Bytes);
1843 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1844 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1845 ConstantFoldConstantExpression(Cexpr, TD))) {
1846 int int32 = (int)(constInt->getZExtValue());
1847 ptr = (unsigned char *)&int32;
1848 aggBuffer->addBytes(ptr, 4, Bytes);
1851 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1852 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1853 aggBuffer->addSymbol(v);
1854 aggBuffer->addZeros(4);
1858 llvm_unreachable("unsupported integer const type");
1859 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1860 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1861 long long int64 = (long long)(constInt->getZExtValue());
1862 ptr = (unsigned char *)&int64;
1863 aggBuffer->addBytes(ptr, 8, Bytes);
1865 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1866 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1867 ConstantFoldConstantExpression(Cexpr, TD))) {
1868 long long int64 = (long long)(constInt->getZExtValue());
1869 ptr = (unsigned char *)&int64;
1870 aggBuffer->addBytes(ptr, 8, Bytes);
1873 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1874 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1875 aggBuffer->addSymbol(v);
1876 aggBuffer->addZeros(8);
1880 llvm_unreachable("unsupported integer const type");
1882 llvm_unreachable("unsupported integer const type");
1885 case Type::FloatTyID:
1886 case Type::DoubleTyID: {
1887 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1888 const Type *Ty = CFP->getType();
1889 if (Ty == Type::getFloatTy(CPV->getContext())) {
1890 float float32 = (float) CFP->getValueAPF().convertToFloat();
1891 ptr = (unsigned char *)&float32;
1892 aggBuffer->addBytes(ptr, 4, Bytes);
1893 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1894 double float64 = CFP->getValueAPF().convertToDouble();
1895 ptr = (unsigned char *)&float64;
1896 aggBuffer->addBytes(ptr, 8, Bytes);
1898 llvm_unreachable("unsupported fp const type");
1902 case Type::PointerTyID: {
1903 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1904 aggBuffer->addSymbol(GVar);
1905 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1906 const Value *v = Cexpr->stripPointerCasts();
1907 aggBuffer->addSymbol(v);
1909 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1910 aggBuffer->addZeros(s);
1914 case Type::ArrayTyID:
1915 case Type::VectorTyID:
1916 case Type::StructTyID: {
1917 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1918 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1919 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1920 bufferAggregateConstant(CPV, aggBuffer);
1921 if (Bytes > ElementSize)
1922 aggBuffer->addZeros(Bytes - ElementSize);
1923 } else if (isa<ConstantAggregateZero>(CPV))
1924 aggBuffer->addZeros(Bytes);
1926 llvm_unreachable("Unexpected Constant type");
1931 llvm_unreachable("unsupported type");
1935 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1936 AggBuffer *aggBuffer) {
1937 const DataLayout *TD = TM.getDataLayout();
1941 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1942 if (CPV->getNumOperands())
1943 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1944 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1948 if (const ConstantDataSequential *CDS =
1949 dyn_cast<ConstantDataSequential>(CPV)) {
1950 if (CDS->getNumElements())
1951 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1952 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1957 if (isa<ConstantStruct>(CPV)) {
1958 if (CPV->getNumOperands()) {
1959 StructType *ST = cast<StructType>(CPV->getType());
1960 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1962 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1963 TD->getTypeAllocSize(ST) -
1964 TD->getStructLayout(ST)->getElementOffset(i);
1966 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1967 TD->getStructLayout(ST)->getElementOffset(i);
1968 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1973 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1976 // buildTypeNameMap - Run through symbol table looking for type names.
1979 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1981 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1983 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1984 !PI->second.compare("struct._image2d_t") ||
1985 !PI->second.compare("struct._image3d_t")))
1992 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1993 switch (MI.getOpcode()) {
1996 case NVPTX::CallArgBeginInst:
1997 case NVPTX::CallArgEndInst0:
1998 case NVPTX::CallArgEndInst1:
1999 case NVPTX::CallArgF32:
2000 case NVPTX::CallArgF64:
2001 case NVPTX::CallArgI16:
2002 case NVPTX::CallArgI32:
2003 case NVPTX::CallArgI32imm:
2004 case NVPTX::CallArgI64:
2005 case NVPTX::CallArgParam:
2006 case NVPTX::CallVoidInst:
2007 case NVPTX::CallVoidInstReg:
2008 case NVPTX::Callseq_End:
2009 case NVPTX::CallVoidInstReg64:
2010 case NVPTX::DeclareParamInst:
2011 case NVPTX::DeclareRetMemInst:
2012 case NVPTX::DeclareRetRegInst:
2013 case NVPTX::DeclareRetScalarInst:
2014 case NVPTX::DeclareScalarParamInst:
2015 case NVPTX::DeclareScalarRegInst:
2016 case NVPTX::StoreParamF32:
2017 case NVPTX::StoreParamF64:
2018 case NVPTX::StoreParamI16:
2019 case NVPTX::StoreParamI32:
2020 case NVPTX::StoreParamI64:
2021 case NVPTX::StoreParamI8:
2022 case NVPTX::StoreRetvalF32:
2023 case NVPTX::StoreRetvalF64:
2024 case NVPTX::StoreRetvalI16:
2025 case NVPTX::StoreRetvalI32:
2026 case NVPTX::StoreRetvalI64:
2027 case NVPTX::StoreRetvalI8:
2028 case NVPTX::LastCallArgF32:
2029 case NVPTX::LastCallArgF64:
2030 case NVPTX::LastCallArgI16:
2031 case NVPTX::LastCallArgI32:
2032 case NVPTX::LastCallArgI32imm:
2033 case NVPTX::LastCallArgI64:
2034 case NVPTX::LastCallArgParam:
2035 case NVPTX::LoadParamMemF32:
2036 case NVPTX::LoadParamMemF64:
2037 case NVPTX::LoadParamMemI16:
2038 case NVPTX::LoadParamMemI32:
2039 case NVPTX::LoadParamMemI64:
2040 case NVPTX::LoadParamMemI8:
2041 case NVPTX::PrototypeInst:
2042 case NVPTX::DBG_VALUE:
2048 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2050 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2051 unsigned AsmVariant,
2052 const char *ExtraCode, raw_ostream &O) {
2053 if (ExtraCode && ExtraCode[0]) {
2054 if (ExtraCode[1] != 0)
2055 return true; // Unknown modifier.
2057 switch (ExtraCode[0]) {
2059 // See if this is a generic print operand
2060 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2066 printOperand(MI, OpNo, O);
2071 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2072 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2073 const char *ExtraCode, raw_ostream &O) {
2074 if (ExtraCode && ExtraCode[0])
2075 return true; // Unknown modifier
2078 printMemOperand(MI, OpNo, O);
2084 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2085 raw_ostream &O, const char *Modifier) {
2086 const MachineOperand &MO = MI->getOperand(opNum);
2087 switch (MO.getType()) {
2088 case MachineOperand::MO_Register:
2089 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2090 if (MO.getReg() == NVPTX::VRDepot)
2091 O << DEPOTNAME << getFunctionNumber();
2093 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2095 emitVirtualRegister(MO.getReg(), O);
2099 case MachineOperand::MO_Immediate:
2102 else if (strstr(Modifier, "vec") == Modifier)
2103 printVecModifiedImmediate(MO, Modifier, O);
2106 "Don't know how to handle modifier on immediate operand");
2109 case MachineOperand::MO_FPImmediate:
2110 printFPConstant(MO.getFPImm(), O);
2113 case MachineOperand::MO_GlobalAddress:
2114 O << *getSymbol(MO.getGlobal());
2117 case MachineOperand::MO_MachineBasicBlock:
2118 O << *MO.getMBB()->getSymbol();
2122 llvm_unreachable("Operand type not supported.");
2126 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2127 raw_ostream &O, const char *Modifier) {
2128 printOperand(MI, opNum, O);
2130 if (Modifier && !strcmp(Modifier, "add")) {
2132 printOperand(MI, opNum + 1, O);
2134 if (MI->getOperand(opNum + 1).isImm() &&
2135 MI->getOperand(opNum + 1).getImm() == 0)
2136 return; // don't print ',0' or '+0'
2138 printOperand(MI, opNum + 1, O);
2143 // Force static initialization.
2144 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2145 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2146 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2149 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2150 std::stringstream temp;
2151 LineReader *reader = this->getReader(filename.str());
2153 temp << filename.str();
2157 temp << reader->readLine(line);
2159 this->OutStreamer.EmitRawText(Twine(temp.str()));
2162 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2163 if (reader == NULL) {
2164 reader = new LineReader(filename);
2167 if (reader->fileName() != filename) {
2169 reader = new LineReader(filename);
2175 std::string LineReader::readLine(unsigned lineNum) {
2176 if (lineNum < theCurLine) {
2178 fstr.seekg(0, std::ios::beg);
2180 while (theCurLine < lineNum) {
2181 fstr.getline(buff, 500);
2187 // Force static initialization.
2188 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2189 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2190 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);