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 "InstPrinter/NVPTXInstPrinter.h"
24 #include "cl_common_defines.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.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/Mangler.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
51 bool RegAllocNilUsed = true;
53 #define DEPOTNAME "__local_depot"
56 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
57 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
60 namespace llvm { bool InterleaveSrcInPtx = false; }
62 static cl::opt<bool, true>
63 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
64 cl::desc("NVPTX Specific: Emit source line in ptx file"),
65 cl::location(llvm::InterleaveSrcInPtx));
68 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
70 void DiscoverDependentGlobals(const Value *V,
71 DenseSet<const GlobalVariable *> &Globals) {
72 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
75 if (const User *U = dyn_cast<User>(V)) {
76 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
77 DiscoverDependentGlobals(U->getOperand(i), Globals);
83 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
84 /// instances to be emitted, but only after any dependents have been added
86 void VisitGlobalVariableForEmission(
87 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
88 DenseSet<const GlobalVariable *> &Visited,
89 DenseSet<const GlobalVariable *> &Visiting) {
90 // Have we already visited this one?
91 if (Visited.count(GV))
94 // Do we have a circular dependency?
95 if (Visiting.count(GV))
96 report_fatal_error("Circular dependency found in global variable set");
98 // Start visiting this global
101 // Make sure we visit all dependents first
102 DenseSet<const GlobalVariable *> Others;
103 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
104 DiscoverDependentGlobals(GV->getOperand(i), Others);
106 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
109 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
111 // Now we can visit ourself
118 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
119 // cannot just link to the existing version.
120 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
122 using namespace nvptx;
123 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
124 MCContext &Ctx = AP.OutContext;
126 if (CV->isNullValue() || isa<UndefValue>(CV))
127 return MCConstantExpr::Create(0, Ctx);
129 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
130 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
132 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
133 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
135 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
136 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
138 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
140 llvm_unreachable("Unknown constant value to lower!");
142 switch (CE->getOpcode()) {
144 // If the code isn't optimized, there may be outstanding folding
145 // opportunities. Attempt to fold the expression using DataLayout as a
146 // last resort before giving up.
147 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
149 return LowerConstant(C, AP);
151 // Otherwise report the problem to the user.
154 raw_string_ostream OS(S);
155 OS << "Unsupported expression in static initializer: ";
156 WriteAsOperand(OS, CE, /*PrintType=*/ false,
157 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
158 report_fatal_error(OS.str());
160 case Instruction::GetElementPtr: {
161 const DataLayout &TD = *AP.TM.getDataLayout();
162 // Generate a symbolic expression for the byte address
163 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
164 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
166 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
170 int64_t Offset = OffsetAI.getSExtValue();
171 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
175 case Instruction::Trunc:
176 // We emit the value and depend on the assembler to truncate the generated
177 // expression properly. This is important for differences between
178 // blockaddress labels. Since the two labels are in the same function, it
179 // is reasonable to treat their delta as a 32-bit value.
181 case Instruction::BitCast:
182 return LowerConstant(CE->getOperand(0), AP);
184 case Instruction::IntToPtr: {
185 const DataLayout &TD = *AP.TM.getDataLayout();
186 // Handle casts to pointers by changing them into casts to the appropriate
187 // integer type. This promotes constant folding and simplifies this code.
188 Constant *Op = CE->getOperand(0);
189 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
191 return LowerConstant(Op, AP);
194 case Instruction::PtrToInt: {
195 const DataLayout &TD = *AP.TM.getDataLayout();
196 // Support only foldable casts to/from pointers that can be eliminated by
197 // changing the pointer to the appropriately sized integer type.
198 Constant *Op = CE->getOperand(0);
199 Type *Ty = CE->getType();
201 const MCExpr *OpExpr = LowerConstant(Op, AP);
203 // We can emit the pointer value into this slot if the slot is an
204 // integer slot equal to the size of the pointer.
205 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
208 // Otherwise the pointer is smaller than the resultant integer, mask off
209 // the high bits so we are sure to get a proper truncation if the input is
211 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
212 const MCExpr *MaskExpr =
213 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
214 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
217 // The MC library also has a right-shift operator, but it isn't consistently
218 // signed or unsigned between different targets.
219 case Instruction::Add:
220 case Instruction::Sub:
221 case Instruction::Mul:
222 case Instruction::SDiv:
223 case Instruction::SRem:
224 case Instruction::Shl:
225 case Instruction::And:
226 case Instruction::Or:
227 case Instruction::Xor: {
228 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
229 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
230 switch (CE->getOpcode()) {
232 llvm_unreachable("Unknown binary operator constant cast expr");
233 case Instruction::Add:
234 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
235 case Instruction::Sub:
236 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
237 case Instruction::Mul:
238 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
239 case Instruction::SDiv:
240 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
241 case Instruction::SRem:
242 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
243 case Instruction::Shl:
244 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
245 case Instruction::And:
246 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
247 case Instruction::Or:
248 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
249 case Instruction::Xor:
250 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
256 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
257 if (!EmitLineNumbers)
262 DebugLoc curLoc = MI.getDebugLoc();
264 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
267 if (prevDebugLoc == curLoc)
270 prevDebugLoc = curLoc;
272 if (curLoc.isUnknown())
275 const MachineFunction *MF = MI.getParent()->getParent();
276 //const TargetMachine &TM = MF->getTarget();
278 const LLVMContext &ctx = MF->getFunction()->getContext();
279 DIScope Scope(curLoc.getScope(ctx));
281 assert((!Scope || Scope.isScope()) &&
282 "Scope of a DebugLoc should be null or a DIScope.");
286 StringRef fileName(Scope.getFilename());
287 StringRef dirName(Scope.getDirectory());
288 SmallString<128> FullPathName = dirName;
289 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
290 sys::path::append(FullPathName, fileName);
291 fileName = FullPathName.str();
294 if (filenameMap.find(fileName.str()) == filenameMap.end())
297 // Emit the line from the source file.
298 if (llvm::InterleaveSrcInPtx)
299 this->emitSrcInText(fileName.str(), curLoc.getLine());
301 std::stringstream temp;
302 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
303 << " " << curLoc.getCol();
304 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
307 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
308 SmallString<128> Str;
309 raw_svector_ostream OS(Str);
310 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
311 emitLineNumberAsDotLoc(*MI);
314 lowerToMCInst(MI, Inst);
315 OutStreamer.EmitInstruction(Inst);
318 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
319 OutMI.setOpcode(MI->getOpcode());
321 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
322 const MachineOperand &MO = MI->getOperand(i);
325 if (lowerOperand(MO, MCOp))
326 OutMI.addOperand(MCOp);
330 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
332 switch (MO.getType()) {
333 default: llvm_unreachable("unknown operand type");
334 case MachineOperand::MO_Register:
335 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
337 case MachineOperand::MO_Immediate:
338 MCOp = MCOperand::CreateImm(MO.getImm());
340 case MachineOperand::MO_MachineBasicBlock:
341 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
342 MO.getMBB()->getSymbol(), OutContext));
344 case MachineOperand::MO_ExternalSymbol:
345 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
347 case MachineOperand::MO_GlobalAddress:
348 MCOp = GetSymbolRef(MO, Mang->getSymbol(MO.getGlobal()));
350 case MachineOperand::MO_FPImmediate: {
351 const ConstantFP *Cnt = MO.getFPImm();
352 APFloat Val = Cnt->getValueAPF();
354 switch (Cnt->getType()->getTypeID()) {
355 default: report_fatal_error("Unsupported FP type"); break;
356 case Type::FloatTyID:
357 MCOp = MCOperand::CreateExpr(
358 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
360 case Type::DoubleTyID:
361 MCOp = MCOperand::CreateExpr(
362 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
371 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
372 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
373 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
375 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
376 unsigned RegNum = RegMap[Reg];
378 // Encode the register class in the upper 4 bits
379 // Must be kept in sync with NVPTXInstPrinter::printRegName
381 if (RC == &NVPTX::Int1RegsRegClass) {
383 } else if (RC == &NVPTX::Int16RegsRegClass) {
385 } else if (RC == &NVPTX::Int32RegsRegClass) {
387 } else if (RC == &NVPTX::Int64RegsRegClass) {
389 } else if (RC == &NVPTX::Float32RegsRegClass) {
391 } else if (RC == &NVPTX::Float64RegsRegClass) {
394 report_fatal_error("Bad register class");
397 // Insert the vreg number
398 Ret |= (RegNum & 0x0FFFFFFF);
401 // Some special-use registers are actually physical registers.
402 // Encode this as the register class ID of 0 and the real register ID.
403 return Reg & 0x0FFFFFFF;
407 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
408 const MCSymbol *Symbol) {
410 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
412 return MCOperand::CreateExpr(Expr);
415 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
416 const DataLayout *TD = TM.getDataLayout();
417 const TargetLowering *TLI = TM.getTargetLowering();
419 Type *Ty = F->getReturnType();
421 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
423 if (Ty->getTypeID() == Type::VoidTyID)
429 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
431 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
432 size = ITy->getBitWidth();
436 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
437 size = Ty->getPrimitiveSizeInBits();
440 O << ".param .b" << size << " func_retval0";
441 } else if (isa<PointerType>(Ty)) {
442 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
445 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
446 SmallVector<EVT, 16> vtparts;
447 ComputeValueVTs(*TLI, Ty, vtparts);
448 unsigned totalsz = 0;
449 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
451 EVT elemtype = vtparts[i];
452 if (vtparts[i].isVector()) {
453 elems = vtparts[i].getVectorNumElements();
454 elemtype = vtparts[i].getVectorElementType();
456 for (unsigned j = 0, je = elems; j != je; ++j) {
457 unsigned sz = elemtype.getSizeInBits();
458 if (elemtype.isInteger() && (sz < 8))
463 unsigned retAlignment = 0;
464 if (!llvm::getAlign(*F, 0, retAlignment))
465 retAlignment = TD->getABITypeAlignment(Ty);
466 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
469 assert(false && "Unknown return type");
472 SmallVector<EVT, 16> vtparts;
473 ComputeValueVTs(*TLI, Ty, vtparts);
475 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
477 EVT elemtype = vtparts[i];
478 if (vtparts[i].isVector()) {
479 elems = vtparts[i].getVectorNumElements();
480 elemtype = vtparts[i].getVectorElementType();
483 for (unsigned j = 0, je = elems; j != je; ++j) {
484 unsigned sz = elemtype.getSizeInBits();
485 if (elemtype.isInteger() && (sz < 32))
487 O << ".reg .b" << sz << " func_retval" << idx;
500 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
502 const Function *F = MF.getFunction();
503 printReturnValStr(F, O);
506 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
507 SmallString<128> Str;
508 raw_svector_ostream O(Str);
510 if (!GlobalsEmitted) {
511 emitGlobals(*MF->getFunction()->getParent());
512 GlobalsEmitted = true;
516 MRI = &MF->getRegInfo();
517 F = MF->getFunction();
518 emitLinkageDirective(F, O);
519 if (llvm::isKernelFunction(*F))
523 printReturnValStr(*MF, O);
528 emitFunctionParamList(*MF, O);
530 if (llvm::isKernelFunction(*F))
531 emitKernelFunctionDirectives(*F, O);
533 OutStreamer.EmitRawText(O.str());
535 prevDebugLoc = DebugLoc();
538 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
540 OutStreamer.EmitRawText(StringRef("{\n"));
541 setAndEmitFunctionVirtualRegisters(*MF);
543 SmallString<128> Str;
544 raw_svector_ostream O(Str);
545 emitDemotedVars(MF->getFunction(), O);
546 OutStreamer.EmitRawText(O.str());
549 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
550 OutStreamer.EmitRawText(StringRef("}\n"));
554 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
555 unsigned RegNo = MI->getOperand(0).getReg();
556 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
557 if (TRI->isVirtualRegister(RegNo)) {
558 OutStreamer.AddComment(Twine("implicit-def: ") +
559 getVirtualRegisterName(RegNo));
561 OutStreamer.AddComment(Twine("implicit-def: ") +
562 TM.getRegisterInfo()->getName(RegNo));
564 OutStreamer.AddBlankLine();
567 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
568 raw_ostream &O) const {
569 // If the NVVM IR has some of reqntid* specified, then output
570 // the reqntid directive, and set the unspecified ones to 1.
571 // If none of reqntid* is specified, don't output reqntid directive.
572 unsigned reqntidx, reqntidy, reqntidz;
573 bool specified = false;
574 if (llvm::getReqNTIDx(F, reqntidx) == false)
578 if (llvm::getReqNTIDy(F, reqntidy) == false)
582 if (llvm::getReqNTIDz(F, reqntidz) == false)
588 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
591 // If the NVVM IR has some of maxntid* specified, then output
592 // the maxntid directive, and set the unspecified ones to 1.
593 // If none of maxntid* is specified, don't output maxntid directive.
594 unsigned maxntidx, maxntidy, maxntidz;
596 if (llvm::getMaxNTIDx(F, maxntidx) == false)
600 if (llvm::getMaxNTIDy(F, maxntidy) == false)
604 if (llvm::getMaxNTIDz(F, maxntidz) == false)
610 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
614 if (llvm::getMinCTASm(F, mincta))
615 O << ".minnctapersm " << mincta << "\n";
619 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
620 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
623 raw_string_ostream NameStr(Name);
625 VRegRCMap::const_iterator I = VRegMapping.find(RC);
626 assert(I != VRegMapping.end() && "Bad register class");
627 const DenseMap<unsigned, unsigned> &RegMap = I->second;
629 VRegMap::const_iterator VI = RegMap.find(Reg);
630 assert(VI != RegMap.end() && "Bad virtual register");
631 unsigned MappedVR = VI->second;
633 NameStr << getNVPTXRegClassStr(RC) << MappedVR;
639 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
641 O << getVirtualRegisterName(vr);
644 void NVPTXAsmPrinter::printVecModifiedImmediate(
645 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
646 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
647 int Imm = (int) MO.getImm();
648 if (0 == strcmp(Modifier, "vecelem"))
649 O << "_" << vecelem[Imm];
650 else if (0 == strcmp(Modifier, "vecv4comm1")) {
651 if ((Imm < 0) || (Imm > 3))
653 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
654 if ((Imm < 4) || (Imm > 7))
656 } else if (0 == strcmp(Modifier, "vecv4pos")) {
659 O << "_" << vecelem[Imm % 4];
660 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
661 if ((Imm < 0) || (Imm > 1))
663 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
664 if ((Imm < 2) || (Imm > 3))
666 } else if (0 == strcmp(Modifier, "vecv2pos")) {
669 O << "_" << vecelem[Imm % 2];
671 llvm_unreachable("Unknown Modifier on immediate operand");
676 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
678 emitLinkageDirective(F, O);
679 if (llvm::isKernelFunction(*F))
683 printReturnValStr(F, O);
684 O << *Mang->getSymbol(F) << "\n";
685 emitFunctionParamList(F, O);
689 static bool usedInGlobalVarDef(const Constant *C) {
693 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
694 if (GV->getName().str() == "llvm.used")
699 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
701 const Constant *C = dyn_cast<Constant>(*ui);
702 if (usedInGlobalVarDef(C))
708 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
709 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
710 if (othergv->getName().str() == "llvm.used")
714 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
715 if (instr->getParent() && instr->getParent()->getParent()) {
716 const Function *curFunc = instr->getParent()->getParent();
717 if (oneFunc && (curFunc != oneFunc))
725 if (const MDNode *md = dyn_cast<MDNode>(U))
726 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
727 (md->getName().str() == "llvm.dbg.sp")))
730 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
732 if (usedInOneFunc(*ui, oneFunc) == false)
738 /* Find out if a global variable can be demoted to local scope.
739 * Currently, this is valid for CUDA shared variables, which have local
740 * scope and global lifetime. So the conditions to check are :
741 * 1. Is the global variable in shared address space?
742 * 2. Does it have internal linkage?
743 * 3. Is the global variable referenced only in one function?
745 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
746 if (gv->hasInternalLinkage() == false)
748 const PointerType *Pty = gv->getType();
749 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
752 const Function *oneFunc = 0;
754 bool flag = usedInOneFunc(gv, oneFunc);
763 static bool useFuncSeen(const Constant *C,
764 llvm::DenseMap<const Function *, bool> &seenMap) {
765 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
767 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
768 if (useFuncSeen(cu, seenMap))
770 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
771 const BasicBlock *bb = I->getParent();
774 const Function *caller = bb->getParent();
777 if (seenMap.find(caller) != seenMap.end())
784 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
785 llvm::DenseMap<const Function *, bool> seenMap;
786 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
787 const Function *F = FI;
789 if (F->isDeclaration()) {
792 if (F->getIntrinsicID())
794 emitDeclaration(F, O);
797 for (Value::const_use_iterator iter = F->use_begin(),
798 iterEnd = F->use_end();
799 iter != iterEnd; ++iter) {
800 if (const Constant *C = dyn_cast<Constant>(*iter)) {
801 if (usedInGlobalVarDef(C)) {
802 // The use is in the initialization of a global variable
803 // that is a function pointer, so print a declaration
804 // for the original function
805 emitDeclaration(F, O);
808 // Emit a declaration of this function if the function that
809 // uses this constant expr has already been seen.
810 if (useFuncSeen(C, seenMap)) {
811 emitDeclaration(F, O);
816 if (!isa<Instruction>(*iter))
818 const Instruction *instr = cast<Instruction>(*iter);
819 const BasicBlock *bb = instr->getParent();
822 const Function *caller = bb->getParent();
826 // If a caller has already been seen, then the caller is
827 // appearing in the module before the callee. so print out
828 // a declaration for the callee.
829 if (seenMap.find(caller) != seenMap.end()) {
830 emitDeclaration(F, O);
838 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
839 DebugInfoFinder DbgFinder;
840 DbgFinder.processModule(M);
843 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
844 E = DbgFinder.compile_unit_end();
846 DICompileUnit DIUnit(*I);
847 StringRef Filename(DIUnit.getFilename());
848 StringRef Dirname(DIUnit.getDirectory());
849 SmallString<128> FullPathName = Dirname;
850 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
851 sys::path::append(FullPathName, Filename);
852 Filename = FullPathName.str();
854 if (filenameMap.find(Filename.str()) != filenameMap.end())
856 filenameMap[Filename.str()] = i;
857 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
861 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
862 E = DbgFinder.subprogram_end();
865 StringRef Filename(SP.getFilename());
866 StringRef Dirname(SP.getDirectory());
867 SmallString<128> FullPathName = Dirname;
868 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
869 sys::path::append(FullPathName, Filename);
870 Filename = FullPathName.str();
872 if (filenameMap.find(Filename.str()) != filenameMap.end())
874 filenameMap[Filename.str()] = i;
879 bool NVPTXAsmPrinter::doInitialization(Module &M) {
881 SmallString<128> Str1;
882 raw_svector_ostream OS1(Str1);
884 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
885 MMI->AnalyzeModule(M);
887 // We need to call the parent's one explicitly.
888 //bool Result = AsmPrinter::doInitialization(M);
890 // Initialize TargetLoweringObjectFile.
891 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
892 .Initialize(OutContext, TM);
894 Mang = new Mangler(OutContext, &TM);
896 // Emit header before any dwarf directives are emitted below.
898 OutStreamer.EmitRawText(OS1.str());
900 // Already commented out
901 //bool Result = AsmPrinter::doInitialization(M);
903 // Emit module-level inline asm if it exists.
904 if (!M.getModuleInlineAsm().empty()) {
905 OutStreamer.AddComment("Start of file scope inline assembly");
906 OutStreamer.AddBlankLine();
907 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
908 OutStreamer.AddBlankLine();
909 OutStreamer.AddComment("End of file scope inline assembly");
910 OutStreamer.AddBlankLine();
913 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
914 recordAndEmitFilenames(M);
916 GlobalsEmitted = false;
918 return false; // success
921 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
922 SmallString<128> Str2;
923 raw_svector_ostream OS2(Str2);
925 emitDeclarations(M, OS2);
927 // As ptxas does not support forward references of globals, we need to first
928 // sort the list of module-level globals in def-use order. We visit each
929 // global variable in order, and ensure that we emit it *after* its dependent
930 // globals. We use a little extra memory maintaining both a set and a list to
931 // have fast searches while maintaining a strict ordering.
932 SmallVector<const GlobalVariable *, 8> Globals;
933 DenseSet<const GlobalVariable *> GVVisited;
934 DenseSet<const GlobalVariable *> GVVisiting;
936 // Visit each global variable, in order
937 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
939 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
941 assert(GVVisited.size() == M.getGlobalList().size() &&
942 "Missed a global variable");
943 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
945 // Print out module-level global variables in proper order
946 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
947 printModuleLevelGV(Globals[i], OS2);
951 OutStreamer.EmitRawText(OS2.str());
954 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
956 O << "// Generated by LLVM NVPTX Back-End\n";
960 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
961 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
964 O << nvptxSubtarget.getTargetName();
966 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
967 O << ", texmode_independent";
968 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
969 if (!nvptxSubtarget.hasDouble())
970 O << ", map_f64_to_f32";
973 if (MAI->doesSupportDebugInformation())
978 O << ".address_size ";
979 if (nvptxSubtarget.is64Bit())
988 bool NVPTXAsmPrinter::doFinalization(Module &M) {
990 // If we did not emit any functions, then the global declarations have not
992 if (!GlobalsEmitted) {
994 GlobalsEmitted = true;
997 // XXX Temproarily remove global variables so that doFinalization() will not
998 // emit them again (global variables are emitted at beginning).
1000 Module::GlobalListType &global_list = M.getGlobalList();
1001 int i, n = global_list.size();
1002 GlobalVariable **gv_array = new GlobalVariable *[n];
1004 // first, back-up GlobalVariable in gv_array
1006 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1008 gv_array[i++] = &*I;
1010 // second, empty global_list
1011 while (!global_list.empty())
1012 global_list.remove(global_list.begin());
1014 // call doFinalization
1015 bool ret = AsmPrinter::doFinalization(M);
1017 // now we restore global variables
1018 for (i = 0; i < n; i++)
1019 global_list.insert(global_list.end(), gv_array[i]);
1024 //bool Result = AsmPrinter::doFinalization(M);
1025 // Instead of calling the parents doFinalization, we may
1026 // clone parents doFinalization and customize here.
1027 // Currently, we if NVISA out the EmitGlobals() in
1028 // parent's doFinalization, which is too intrusive.
1030 // Same for the doInitialization.
1034 // This function emits appropriate linkage directives for
1035 // functions and global variables.
1037 // extern function declaration -> .extern
1038 // extern function definition -> .visible
1039 // external global variable with init -> .visible
1040 // external without init -> .extern
1041 // appending -> not allowed, assert.
1043 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1045 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1046 if (V->hasExternalLinkage()) {
1047 if (isa<GlobalVariable>(V)) {
1048 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1050 if (GVar->hasInitializer())
1055 } else if (V->isDeclaration())
1059 } else if (V->hasAppendingLinkage()) {
1061 msg.append("Error: ");
1062 msg.append("Symbol ");
1064 msg.append(V->getName().str());
1065 msg.append("has unsupported appending linkage type");
1066 llvm_unreachable(msg.c_str());
1071 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1073 bool processDemoted) {
1076 if (GVar->hasSection()) {
1077 if (GVar->getSection() == "llvm.metadata")
1081 const DataLayout *TD = TM.getDataLayout();
1083 // GlobalVariables are always constant pointers themselves.
1084 const PointerType *PTy = GVar->getType();
1085 Type *ETy = PTy->getElementType();
1087 if (GVar->hasExternalLinkage()) {
1088 if (GVar->hasInitializer())
1094 if (llvm::isTexture(*GVar)) {
1095 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1099 if (llvm::isSurface(*GVar)) {
1100 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1104 if (GVar->isDeclaration()) {
1105 // (extern) declarations, no definition or initializer
1106 // Currently the only known declaration is for an automatic __local
1107 // (.shared) promoted to global.
1108 emitPTXGlobalVariable(GVar, O);
1113 if (llvm::isSampler(*GVar)) {
1114 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1116 const Constant *Initializer = NULL;
1117 if (GVar->hasInitializer())
1118 Initializer = GVar->getInitializer();
1119 const ConstantInt *CI = NULL;
1121 CI = dyn_cast<ConstantInt>(Initializer);
1123 unsigned sample = CI->getZExtValue();
1128 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1130 O << "addr_mode_" << i << " = ";
1136 O << "clamp_to_border";
1139 O << "clamp_to_edge";
1150 O << "filter_mode = ";
1151 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1159 assert(0 && "Anisotropic filtering is not supported");
1164 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1165 O << ", force_unnormalized_coords = 1";
1174 if (GVar->hasPrivateLinkage()) {
1176 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1179 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1180 if (!strncmp(GVar->getName().data(), "filename", 8))
1182 if (GVar->use_empty())
1186 const Function *demotedFunc = 0;
1187 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1188 O << "// " << GVar->getName().str() << " has been demoted\n";
1189 if (localDecls.find(demotedFunc) != localDecls.end())
1190 localDecls[demotedFunc].push_back(GVar);
1192 std::vector<const GlobalVariable *> temp;
1193 temp.push_back(GVar);
1194 localDecls[demotedFunc] = temp;
1200 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1201 if (GVar->getAlignment() == 0)
1202 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1204 O << " .align " << GVar->getAlignment();
1206 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1208 // Special case: ABI requires that we use .u8 for predicates
1209 if (ETy->isIntegerTy(1))
1212 O << getPTXFundamentalTypeStr(ETy, false);
1214 O << *Mang->getSymbol(GVar);
1216 // Ptx allows variable initilization only for constant and global state
1218 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1219 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1220 GVar->hasInitializer()) {
1221 const Constant *Initializer = GVar->getInitializer();
1222 if (!Initializer->isNullValue()) {
1224 printScalarConstant(Initializer, O);
1228 unsigned int ElementSize = 0;
1230 // Although PTX has direct support for struct type and array type and
1231 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1232 // targets that support these high level field accesses. Structs, arrays
1233 // and vectors are lowered into arrays of bytes.
1234 switch (ETy->getTypeID()) {
1235 case Type::StructTyID:
1236 case Type::ArrayTyID:
1237 case Type::VectorTyID:
1238 ElementSize = TD->getTypeStoreSize(ETy);
1239 // Ptx allows variable initilization only for constant and
1240 // global state spaces.
1241 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1242 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1243 GVar->hasInitializer()) {
1244 const Constant *Initializer = GVar->getInitializer();
1245 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1246 AggBuffer aggBuffer(ElementSize, O, *this);
1247 bufferAggregateConstant(Initializer, &aggBuffer);
1248 if (aggBuffer.numSymbols) {
1249 if (nvptxSubtarget.is64Bit()) {
1250 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1251 O << ElementSize / 8;
1253 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1254 O << ElementSize / 4;
1258 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1266 O << " .b8 " << *Mang->getSymbol(GVar);
1274 O << " .b8 " << *Mang->getSymbol(GVar);
1283 assert(0 && "type not supported yet");
1290 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1291 if (localDecls.find(f) == localDecls.end())
1294 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1296 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1297 O << "\t// demoted variable\n\t";
1298 printModuleLevelGV(gvars[i], O, true);
1302 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1303 raw_ostream &O) const {
1304 switch (AddressSpace) {
1305 case llvm::ADDRESS_SPACE_LOCAL:
1308 case llvm::ADDRESS_SPACE_GLOBAL:
1311 case llvm::ADDRESS_SPACE_CONST:
1314 case llvm::ADDRESS_SPACE_SHARED:
1318 report_fatal_error("Bad address space found while emitting PTX");
1324 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1325 switch (Ty->getTypeID()) {
1327 llvm_unreachable("unexpected type");
1329 case Type::IntegerTyID: {
1330 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1333 else if (NumBits <= 64) {
1334 std::string name = "u";
1335 return name + utostr(NumBits);
1337 llvm_unreachable("Integer too large");
1342 case Type::FloatTyID:
1344 case Type::DoubleTyID:
1346 case Type::PointerTyID:
1347 if (nvptxSubtarget.is64Bit())
1357 llvm_unreachable("unexpected type");
1361 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1364 const DataLayout *TD = TM.getDataLayout();
1366 // GlobalVariables are always constant pointers themselves.
1367 const PointerType *PTy = GVar->getType();
1368 Type *ETy = PTy->getElementType();
1371 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1372 if (GVar->getAlignment() == 0)
1373 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1375 O << " .align " << GVar->getAlignment();
1377 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1379 O << getPTXFundamentalTypeStr(ETy);
1381 O << *Mang->getSymbol(GVar);
1385 int64_t ElementSize = 0;
1387 // Although PTX has direct support for struct type and array type and LLVM IR
1388 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1389 // support these high level field accesses. Structs and arrays are lowered
1390 // into arrays of bytes.
1391 switch (ETy->getTypeID()) {
1392 case Type::StructTyID:
1393 case Type::ArrayTyID:
1394 case Type::VectorTyID:
1395 ElementSize = TD->getTypeStoreSize(ETy);
1396 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1398 O << itostr(ElementSize);
1403 assert(0 && "type not supported yet");
1408 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1409 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1410 return TD->getPrefTypeAlignment(Ty);
1412 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1414 return getOpenCLAlignment(TD, ATy->getElementType());
1416 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1418 Type *ETy = VTy->getElementType();
1419 unsigned int numE = VTy->getNumElements();
1420 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1424 return numE * alignE;
1427 const StructType *STy = dyn_cast<StructType>(Ty);
1429 unsigned int alignStruct = 1;
1430 // Go through each element of the struct and find the
1431 // largest alignment.
1432 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1433 Type *ETy = STy->getElementType(i);
1434 unsigned int align = getOpenCLAlignment(TD, ETy);
1435 if (align > alignStruct)
1436 alignStruct = align;
1441 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1443 return TD->getPointerPrefAlignment();
1444 return TD->getPrefTypeAlignment(Ty);
1447 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1448 int paramIndex, raw_ostream &O) {
1449 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1450 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1451 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1453 std::string argName = I->getName();
1454 const char *p = argName.c_str();
1465 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1466 Function::const_arg_iterator I, E;
1469 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1470 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1471 O << *CurrentFnSym << "_param_" << paramIndex;
1475 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1476 if (i == paramIndex) {
1477 printParamName(I, paramIndex, O);
1481 llvm_unreachable("paramIndex out of bound");
1484 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1485 const DataLayout *TD = TM.getDataLayout();
1486 const AttributeSet &PAL = F->getAttributes();
1487 const TargetLowering *TLI = TM.getTargetLowering();
1488 Function::const_arg_iterator I, E;
1489 unsigned paramIndex = 0;
1491 bool isKernelFunc = llvm::isKernelFunction(*F);
1492 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1493 MVT thePointerTy = TLI->getPointerTy();
1497 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1498 Type *Ty = I->getType();
1505 // Handle image/sampler parameters
1506 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1507 if (llvm::isImage(*I)) {
1508 std::string sname = I->getName();
1509 if (llvm::isImageWriteOnly(*I))
1510 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1512 else // Default image is read_only
1513 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1515 } else // Should be llvm::isSampler(*I)
1516 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1521 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1522 if (Ty->isVectorTy()) {
1523 // Just print .param .b8 .align <a> .param[size];
1524 // <a> = PAL.getparamalignment
1525 // size = typeallocsize of element type
1526 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1528 align = TD->getABITypeAlignment(Ty);
1530 unsigned sz = TD->getTypeAllocSize(Ty);
1531 O << "\t.param .align " << align << " .b8 ";
1532 printParamName(I, paramIndex, O);
1533 O << "[" << sz << "]";
1538 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1541 // Special handling for pointer arguments to kernel
1542 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1544 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1545 Type *ETy = PTy->getElementType();
1546 int addrSpace = PTy->getAddressSpace();
1547 switch (addrSpace) {
1551 case llvm::ADDRESS_SPACE_CONST:
1552 O << ".ptr .const ";
1554 case llvm::ADDRESS_SPACE_SHARED:
1555 O << ".ptr .shared ";
1557 case llvm::ADDRESS_SPACE_GLOBAL:
1558 O << ".ptr .global ";
1561 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1563 printParamName(I, paramIndex, O);
1567 // non-pointer scalar to kernel func
1569 // Special case: predicate operands become .u8 types
1570 if (Ty->isIntegerTy(1))
1573 O << getPTXFundamentalTypeStr(Ty);
1575 printParamName(I, paramIndex, O);
1578 // Non-kernel function, just print .param .b<size> for ABI
1579 // and .reg .b<size> for non ABY
1581 if (isa<IntegerType>(Ty)) {
1582 sz = cast<IntegerType>(Ty)->getBitWidth();
1585 } else if (isa<PointerType>(Ty))
1586 sz = thePointerTy.getSizeInBits();
1588 sz = Ty->getPrimitiveSizeInBits();
1590 O << "\t.param .b" << sz << " ";
1592 O << "\t.reg .b" << sz << " ";
1593 printParamName(I, paramIndex, O);
1597 // param has byVal attribute. So should be a pointer
1598 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1599 assert(PTy && "Param with byval attribute should be a pointer type");
1600 Type *ETy = PTy->getElementType();
1602 if (isABI || isKernelFunc) {
1603 // Just print .param .b8 .align <a> .param[size];
1604 // <a> = PAL.getparamalignment
1605 // size = typeallocsize of element type
1606 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1608 align = TD->getABITypeAlignment(ETy);
1610 unsigned sz = TD->getTypeAllocSize(ETy);
1611 O << "\t.param .align " << align << " .b8 ";
1612 printParamName(I, paramIndex, O);
1613 O << "[" << sz << "]";
1616 // Split the ETy into constituent parts and
1617 // print .param .b<size> <name> for each part.
1618 // Further, if a part is vector, print the above for
1619 // each vector element.
1620 SmallVector<EVT, 16> vtparts;
1621 ComputeValueVTs(*TLI, ETy, vtparts);
1622 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1624 EVT elemtype = vtparts[i];
1625 if (vtparts[i].isVector()) {
1626 elems = vtparts[i].getVectorNumElements();
1627 elemtype = vtparts[i].getVectorElementType();
1630 for (unsigned j = 0, je = elems; j != je; ++j) {
1631 unsigned sz = elemtype.getSizeInBits();
1632 if (elemtype.isInteger() && (sz < 32))
1634 O << "\t.reg .b" << sz << " ";
1635 printParamName(I, paramIndex, O);
1651 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1653 const Function *F = MF.getFunction();
1654 emitFunctionParamList(F, O);
1657 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1658 const MachineFunction &MF) {
1659 SmallString<128> Str;
1660 raw_svector_ostream O(Str);
1662 // Map the global virtual register number to a register class specific
1663 // virtual register number starting from 1 with that class.
1664 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1665 //unsigned numRegClasses = TRI->getNumRegClasses();
1667 // Emit the Fake Stack Object
1668 const MachineFrameInfo *MFI = MF.getFrameInfo();
1669 int NumBytes = (int) MFI->getStackSize();
1671 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1672 << getFunctionNumber() << "[" << NumBytes << "];\n";
1673 if (nvptxSubtarget.is64Bit()) {
1674 O << "\t.reg .b64 \t%SP;\n";
1675 O << "\t.reg .b64 \t%SPL;\n";
1677 O << "\t.reg .b32 \t%SP;\n";
1678 O << "\t.reg .b32 \t%SPL;\n";
1682 // Go through all virtual registers to establish the mapping between the
1684 // register number and the per class virtual register number.
1685 // We use the per class virtual register number in the ptx output.
1686 unsigned int numVRs = MRI->getNumVirtRegs();
1687 for (unsigned i = 0; i < numVRs; i++) {
1688 unsigned int vr = TRI->index2VirtReg(i);
1689 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1690 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1691 int n = regmap.size();
1692 regmap.insert(std::make_pair(vr, n + 1));
1695 // Emit register declarations
1696 // @TODO: Extract out the real register usage
1697 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1698 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1699 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1700 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1701 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1702 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1703 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1705 // Emit declaration of the virtual registers or 'physical' registers for
1706 // each register class
1707 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1708 const TargetRegisterClass *RC = TRI->getRegClass(i);
1709 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1710 std::string rcname = getNVPTXRegClassName(RC);
1711 std::string rcStr = getNVPTXRegClassStr(RC);
1712 int n = regmap.size();
1714 // Only declare those registers that may be used.
1716 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1721 OutStreamer.EmitRawText(O.str());
1724 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1725 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1727 unsigned int numHex;
1730 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1733 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1734 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1737 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1739 llvm_unreachable("unsupported fp type");
1741 APInt API = APF.bitcastToAPInt();
1742 std::string hexstr(utohexstr(API.getZExtValue()));
1744 if (hexstr.length() < numHex)
1745 O << std::string(numHex - hexstr.length(), '0');
1746 O << utohexstr(API.getZExtValue());
1749 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1750 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1751 O << CI->getValue();
1754 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1755 printFPConstant(CFP, O);
1758 if (isa<ConstantPointerNull>(CPV)) {
1762 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1763 O << *Mang->getSymbol(GVar);
1766 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1767 const Value *v = Cexpr->stripPointerCasts();
1768 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1769 O << *Mang->getSymbol(GVar);
1772 O << *LowerConstant(CPV, *this);
1776 llvm_unreachable("Not scalar type found in printScalarConstant()");
1779 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1780 AggBuffer *aggBuffer) {
1782 const DataLayout *TD = TM.getDataLayout();
1784 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1785 int s = TD->getTypeAllocSize(CPV->getType());
1788 aggBuffer->addZeros(s);
1793 switch (CPV->getType()->getTypeID()) {
1795 case Type::IntegerTyID: {
1796 const Type *ETy = CPV->getType();
1797 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1799 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1801 aggBuffer->addBytes(ptr, 1, Bytes);
1802 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1803 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1804 ptr = (unsigned char *)&int16;
1805 aggBuffer->addBytes(ptr, 2, Bytes);
1806 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1807 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1808 int int32 = (int)(constInt->getZExtValue());
1809 ptr = (unsigned char *)&int32;
1810 aggBuffer->addBytes(ptr, 4, Bytes);
1812 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1813 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1814 ConstantFoldConstantExpression(Cexpr, TD))) {
1815 int int32 = (int)(constInt->getZExtValue());
1816 ptr = (unsigned char *)&int32;
1817 aggBuffer->addBytes(ptr, 4, Bytes);
1820 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1821 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1822 aggBuffer->addSymbol(v);
1823 aggBuffer->addZeros(4);
1827 llvm_unreachable("unsupported integer const type");
1828 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1829 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1830 long long int64 = (long long)(constInt->getZExtValue());
1831 ptr = (unsigned char *)&int64;
1832 aggBuffer->addBytes(ptr, 8, Bytes);
1834 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1835 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1836 ConstantFoldConstantExpression(Cexpr, TD))) {
1837 long long int64 = (long long)(constInt->getZExtValue());
1838 ptr = (unsigned char *)&int64;
1839 aggBuffer->addBytes(ptr, 8, Bytes);
1842 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1843 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1844 aggBuffer->addSymbol(v);
1845 aggBuffer->addZeros(8);
1849 llvm_unreachable("unsupported integer const type");
1851 llvm_unreachable("unsupported integer const type");
1854 case Type::FloatTyID:
1855 case Type::DoubleTyID: {
1856 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1857 const Type *Ty = CFP->getType();
1858 if (Ty == Type::getFloatTy(CPV->getContext())) {
1859 float float32 = (float) CFP->getValueAPF().convertToFloat();
1860 ptr = (unsigned char *)&float32;
1861 aggBuffer->addBytes(ptr, 4, Bytes);
1862 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1863 double float64 = CFP->getValueAPF().convertToDouble();
1864 ptr = (unsigned char *)&float64;
1865 aggBuffer->addBytes(ptr, 8, Bytes);
1867 llvm_unreachable("unsupported fp const type");
1871 case Type::PointerTyID: {
1872 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1873 aggBuffer->addSymbol(GVar);
1874 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1875 const Value *v = Cexpr->stripPointerCasts();
1876 aggBuffer->addSymbol(v);
1878 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1879 aggBuffer->addZeros(s);
1883 case Type::ArrayTyID:
1884 case Type::VectorTyID:
1885 case Type::StructTyID: {
1886 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1887 isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
1888 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1889 bufferAggregateConstant(CPV, aggBuffer);
1890 if (Bytes > ElementSize)
1891 aggBuffer->addZeros(Bytes - ElementSize);
1892 } else if (isa<ConstantAggregateZero>(CPV))
1893 aggBuffer->addZeros(Bytes);
1895 llvm_unreachable("Unexpected Constant type");
1900 llvm_unreachable("unsupported type");
1904 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1905 AggBuffer *aggBuffer) {
1906 const DataLayout *TD = TM.getDataLayout();
1910 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1911 if (CPV->getNumOperands())
1912 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1913 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1917 if (const ConstantDataSequential *CDS =
1918 dyn_cast<ConstantDataSequential>(CPV)) {
1919 if (CDS->getNumElements())
1920 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1921 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1926 if (isa<ConstantStruct>(CPV)) {
1927 if (CPV->getNumOperands()) {
1928 StructType *ST = cast<StructType>(CPV->getType());
1929 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1931 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1932 TD->getTypeAllocSize(ST) -
1933 TD->getStructLayout(ST)->getElementOffset(i);
1935 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1936 TD->getStructLayout(ST)->getElementOffset(i);
1937 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1942 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1945 // buildTypeNameMap - Run through symbol table looking for type names.
1948 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1950 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1952 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1953 !PI->second.compare("struct._image2d_t") ||
1954 !PI->second.compare("struct._image3d_t")))
1961 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1962 switch (MI.getOpcode()) {
1965 case NVPTX::CallArgBeginInst:
1966 case NVPTX::CallArgEndInst0:
1967 case NVPTX::CallArgEndInst1:
1968 case NVPTX::CallArgF32:
1969 case NVPTX::CallArgF64:
1970 case NVPTX::CallArgI16:
1971 case NVPTX::CallArgI32:
1972 case NVPTX::CallArgI32imm:
1973 case NVPTX::CallArgI64:
1974 case NVPTX::CallArgParam:
1975 case NVPTX::CallVoidInst:
1976 case NVPTX::CallVoidInstReg:
1977 case NVPTX::Callseq_End:
1978 case NVPTX::CallVoidInstReg64:
1979 case NVPTX::DeclareParamInst:
1980 case NVPTX::DeclareRetMemInst:
1981 case NVPTX::DeclareRetRegInst:
1982 case NVPTX::DeclareRetScalarInst:
1983 case NVPTX::DeclareScalarParamInst:
1984 case NVPTX::DeclareScalarRegInst:
1985 case NVPTX::StoreParamF32:
1986 case NVPTX::StoreParamF64:
1987 case NVPTX::StoreParamI16:
1988 case NVPTX::StoreParamI32:
1989 case NVPTX::StoreParamI64:
1990 case NVPTX::StoreParamI8:
1991 case NVPTX::StoreRetvalF32:
1992 case NVPTX::StoreRetvalF64:
1993 case NVPTX::StoreRetvalI16:
1994 case NVPTX::StoreRetvalI32:
1995 case NVPTX::StoreRetvalI64:
1996 case NVPTX::StoreRetvalI8:
1997 case NVPTX::LastCallArgF32:
1998 case NVPTX::LastCallArgF64:
1999 case NVPTX::LastCallArgI16:
2000 case NVPTX::LastCallArgI32:
2001 case NVPTX::LastCallArgI32imm:
2002 case NVPTX::LastCallArgI64:
2003 case NVPTX::LastCallArgParam:
2004 case NVPTX::LoadParamMemF32:
2005 case NVPTX::LoadParamMemF64:
2006 case NVPTX::LoadParamMemI16:
2007 case NVPTX::LoadParamMemI32:
2008 case NVPTX::LoadParamMemI64:
2009 case NVPTX::LoadParamMemI8:
2010 case NVPTX::PrototypeInst:
2011 case NVPTX::DBG_VALUE:
2017 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2019 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2020 unsigned AsmVariant,
2021 const char *ExtraCode, raw_ostream &O) {
2022 if (ExtraCode && ExtraCode[0]) {
2023 if (ExtraCode[1] != 0)
2024 return true; // Unknown modifier.
2026 switch (ExtraCode[0]) {
2028 // See if this is a generic print operand
2029 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2035 printOperand(MI, OpNo, O);
2040 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2041 const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2042 const char *ExtraCode, raw_ostream &O) {
2043 if (ExtraCode && ExtraCode[0])
2044 return true; // Unknown modifier
2047 printMemOperand(MI, OpNo, O);
2053 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2054 raw_ostream &O, const char *Modifier) {
2055 const MachineOperand &MO = MI->getOperand(opNum);
2056 switch (MO.getType()) {
2057 case MachineOperand::MO_Register:
2058 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2059 if (MO.getReg() == NVPTX::VRDepot)
2060 O << DEPOTNAME << getFunctionNumber();
2062 O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2064 emitVirtualRegister(MO.getReg(), O);
2068 case MachineOperand::MO_Immediate:
2071 else if (strstr(Modifier, "vec") == Modifier)
2072 printVecModifiedImmediate(MO, Modifier, O);
2075 "Don't know how to handle modifier on immediate operand");
2078 case MachineOperand::MO_FPImmediate:
2079 printFPConstant(MO.getFPImm(), O);
2082 case MachineOperand::MO_GlobalAddress:
2083 O << *Mang->getSymbol(MO.getGlobal());
2086 case MachineOperand::MO_ExternalSymbol: {
2087 const char *symbname = MO.getSymbolName();
2088 if (strstr(symbname, ".PARAM") == symbname) {
2090 sscanf(symbname + 6, "%u[];", &index);
2091 printParamName(index, O);
2092 } else if (strstr(symbname, ".HLPPARAM") == symbname) {
2094 sscanf(symbname + 9, "%u[];", &index);
2095 O << *CurrentFnSym << "_param_" << index << "_offset";
2101 case MachineOperand::MO_MachineBasicBlock:
2102 O << *MO.getMBB()->getSymbol();
2106 llvm_unreachable("Operand type not supported.");
2110 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2111 raw_ostream &O, const char *Modifier) {
2112 printOperand(MI, opNum, O);
2114 if (Modifier && !strcmp(Modifier, "add")) {
2116 printOperand(MI, opNum + 1, O);
2118 if (MI->getOperand(opNum + 1).isImm() &&
2119 MI->getOperand(opNum + 1).getImm() == 0)
2120 return; // don't print ',0' or '+0'
2122 printOperand(MI, opNum + 1, O);
2127 // Force static initialization.
2128 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2129 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2130 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2133 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2134 std::stringstream temp;
2135 LineReader *reader = this->getReader(filename.str());
2137 temp << filename.str();
2141 temp << reader->readLine(line);
2143 this->OutStreamer.EmitRawText(Twine(temp.str()));
2146 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2147 if (reader == NULL) {
2148 reader = new LineReader(filename);
2151 if (reader->fileName() != filename) {
2153 reader = new LineReader(filename);
2159 std::string LineReader::readLine(unsigned lineNum) {
2160 if (lineNum < theCurLine) {
2162 fstr.seekg(0, std::ios::beg);
2164 while (theCurLine < lineNum) {
2165 fstr.getline(buff, 500);
2171 // Force static initialization.
2172 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2173 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2174 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);