1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
18 #include "NVPTXInstrInfo.h"
19 #include "NVPTXMCExpr.h"
20 #include "NVPTXRegisterInfo.h"
21 #include "NVPTXTargetMachine.h"
22 #include "NVPTXUtilities.h"
23 #include "cl_common_defines.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/DebugInfo.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Module.h"
36 #include "llvm/IR/Operator.h"
37 #include "llvm/MC/MCStreamer.h"
38 #include "llvm/MC/MCSymbol.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/FormattedStream.h"
42 #include "llvm/Support/Path.h"
43 #include "llvm/Support/TargetRegistry.h"
44 #include "llvm/Support/TimeValue.h"
45 #include "llvm/Target/Mangler.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
50 bool RegAllocNilUsed = true;
52 #define DEPOTNAME "__local_depot"
55 EmitLineNumbers("nvptx-emit-line-numbers",
56 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
59 namespace llvm { bool InterleaveSrcInPtx = false; }
61 static cl::opt<bool, true>
62 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore,
63 cl::desc("NVPTX Specific: Emit source line in ptx file"),
64 cl::location(llvm::InterleaveSrcInPtx));
67 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
69 void DiscoverDependentGlobals(const Value *V,
70 DenseSet<const GlobalVariable *> &Globals) {
71 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
74 if (const User *U = dyn_cast<User>(V)) {
75 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
76 DiscoverDependentGlobals(U->getOperand(i), Globals);
82 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
83 /// instances to be emitted, but only after any dependents have been added
85 void VisitGlobalVariableForEmission(
86 const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
87 DenseSet<const GlobalVariable *> &Visited,
88 DenseSet<const GlobalVariable *> &Visiting) {
89 // Have we already visited this one?
90 if (Visited.count(GV))
93 // Do we have a circular dependency?
94 if (Visiting.count(GV))
95 report_fatal_error("Circular dependency found in global variable set");
97 // Start visiting this global
100 // Make sure we visit all dependents first
101 DenseSet<const GlobalVariable *> Others;
102 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
103 DiscoverDependentGlobals(GV->getOperand(i), Others);
105 for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
108 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
110 // Now we can visit ourself
117 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
118 // cannot just link to the existing version.
119 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
121 using namespace nvptx;
122 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
123 MCContext &Ctx = AP.OutContext;
125 if (CV->isNullValue() || isa<UndefValue>(CV))
126 return MCConstantExpr::Create(0, Ctx);
128 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
129 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
131 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
132 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
134 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
135 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
137 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
139 llvm_unreachable("Unknown constant value to lower!");
141 switch (CE->getOpcode()) {
143 // If the code isn't optimized, there may be outstanding folding
144 // opportunities. Attempt to fold the expression using DataLayout as a
145 // last resort before giving up.
146 if (Constant *C = ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
148 return LowerConstant(C, AP);
150 // Otherwise report the problem to the user.
153 raw_string_ostream OS(S);
154 OS << "Unsupported expression in static initializer: ";
155 WriteAsOperand(OS, CE, /*PrintType=*/ false,
156 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
157 report_fatal_error(OS.str());
159 case Instruction::GetElementPtr: {
160 const DataLayout &TD = *AP.TM.getDataLayout();
161 // Generate a symbolic expression for the byte address
162 APInt OffsetAI(TD.getPointerSizeInBits(), 0);
163 cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
165 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
169 int64_t Offset = OffsetAI.getSExtValue();
170 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
174 case Instruction::Trunc:
175 // We emit the value and depend on the assembler to truncate the generated
176 // expression properly. This is important for differences between
177 // blockaddress labels. Since the two labels are in the same function, it
178 // is reasonable to treat their delta as a 32-bit value.
180 case Instruction::BitCast:
181 return LowerConstant(CE->getOperand(0), AP);
183 case Instruction::IntToPtr: {
184 const DataLayout &TD = *AP.TM.getDataLayout();
185 // Handle casts to pointers by changing them into casts to the appropriate
186 // integer type. This promotes constant folding and simplifies this code.
187 Constant *Op = CE->getOperand(0);
188 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
190 return LowerConstant(Op, AP);
193 case Instruction::PtrToInt: {
194 const DataLayout &TD = *AP.TM.getDataLayout();
195 // Support only foldable casts to/from pointers that can be eliminated by
196 // changing the pointer to the appropriately sized integer type.
197 Constant *Op = CE->getOperand(0);
198 Type *Ty = CE->getType();
200 const MCExpr *OpExpr = LowerConstant(Op, AP);
202 // We can emit the pointer value into this slot if the slot is an
203 // integer slot equal to the size of the pointer.
204 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
207 // Otherwise the pointer is smaller than the resultant integer, mask off
208 // the high bits so we are sure to get a proper truncation if the input is
210 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
211 const MCExpr *MaskExpr =
212 MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
213 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
216 // The MC library also has a right-shift operator, but it isn't consistently
217 // signed or unsigned between different targets.
218 case Instruction::Add:
219 case Instruction::Sub:
220 case Instruction::Mul:
221 case Instruction::SDiv:
222 case Instruction::SRem:
223 case Instruction::Shl:
224 case Instruction::And:
225 case Instruction::Or:
226 case Instruction::Xor: {
227 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
228 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
229 switch (CE->getOpcode()) {
231 llvm_unreachable("Unknown binary operator constant cast expr");
232 case Instruction::Add:
233 return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
234 case Instruction::Sub:
235 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
236 case Instruction::Mul:
237 return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
238 case Instruction::SDiv:
239 return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
240 case Instruction::SRem:
241 return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
242 case Instruction::Shl:
243 return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
244 case Instruction::And:
245 return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
246 case Instruction::Or:
247 return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
248 case Instruction::Xor:
249 return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
255 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
256 if (!EmitLineNumbers)
261 DebugLoc curLoc = MI.getDebugLoc();
263 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
266 if (prevDebugLoc == curLoc)
269 prevDebugLoc = curLoc;
271 if (curLoc.isUnknown())
274 const MachineFunction *MF = MI.getParent()->getParent();
275 //const TargetMachine &TM = MF->getTarget();
277 const LLVMContext &ctx = MF->getFunction()->getContext();
278 DIScope Scope(curLoc.getScope(ctx));
280 assert((!Scope || Scope.isScope()) &&
281 "Scope of a DebugLoc should be null or a DIScope.");
285 StringRef fileName(Scope.getFilename());
286 StringRef dirName(Scope.getDirectory());
287 SmallString<128> FullPathName = dirName;
288 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
289 sys::path::append(FullPathName, fileName);
290 fileName = FullPathName.str();
293 if (filenameMap.find(fileName.str()) == filenameMap.end())
296 // Emit the line from the source file.
297 if (llvm::InterleaveSrcInPtx)
298 this->emitSrcInText(fileName.str(), curLoc.getLine());
300 std::stringstream temp;
301 temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
302 << " " << curLoc.getCol();
303 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
306 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
307 SmallString<128> Str;
308 raw_svector_ostream OS(Str);
309 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
310 emitLineNumberAsDotLoc(*MI);
313 lowerToMCInst(MI, Inst);
314 OutStreamer.EmitInstruction(Inst);
317 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
318 OutMI.setOpcode(MI->getOpcode());
320 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
321 const MachineOperand &MO = MI->getOperand(i);
324 if (lowerOperand(MO, MCOp))
325 OutMI.addOperand(MCOp);
329 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
331 switch (MO.getType()) {
332 default: llvm_unreachable("unknown operand type");
333 case MachineOperand::MO_Register:
334 MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
336 case MachineOperand::MO_Immediate:
337 MCOp = MCOperand::CreateImm(MO.getImm());
339 case MachineOperand::MO_MachineBasicBlock:
340 MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
341 MO.getMBB()->getSymbol(), OutContext));
343 case MachineOperand::MO_ExternalSymbol:
344 MCOp = GetSymbolRef(MO, GetExternalSymbolSymbol(MO.getSymbolName()));
346 case MachineOperand::MO_GlobalAddress:
347 MCOp = GetSymbolRef(MO, Mang->getSymbol(MO.getGlobal()));
349 case MachineOperand::MO_FPImmediate: {
350 const ConstantFP *Cnt = MO.getFPImm();
351 APFloat Val = Cnt->getValueAPF();
353 switch (Cnt->getType()->getTypeID()) {
354 default: report_fatal_error("Unsupported FP type"); break;
355 case Type::FloatTyID:
356 MCOp = MCOperand::CreateExpr(
357 NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
359 case Type::DoubleTyID:
360 MCOp = MCOperand::CreateExpr(
361 NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
370 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
371 const TargetRegisterClass *RC = MRI->getRegClass(Reg);
373 DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
374 unsigned RegNum = RegMap[Reg];
376 // Encode the register class in the upper 4 bits
377 // Must be kept in sync with NVPTXInstPrinter::printRegName
379 if (RC == &NVPTX::Int1RegsRegClass) {
381 } else if (RC == &NVPTX::Int16RegsRegClass) {
383 } else if (RC == &NVPTX::Int32RegsRegClass) {
385 } else if (RC == &NVPTX::Int64RegsRegClass) {
387 } else if (RC == &NVPTX::Float32RegsRegClass) {
389 } else if (RC == &NVPTX::Float64RegsRegClass) {
392 report_fatal_error("Bad register class");
395 // Insert the vreg number
396 Ret |= (RegNum & 0x0FFFFFFF);
400 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MachineOperand &MO,
401 const MCSymbol *Symbol) {
403 switch (MO.getTargetFlags()) {
405 Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
410 return MCOperand::CreateExpr(Expr);
413 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
414 const DataLayout *TD = TM.getDataLayout();
415 const TargetLowering *TLI = TM.getTargetLowering();
417 Type *Ty = F->getReturnType();
419 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
421 if (Ty->getTypeID() == Type::VoidTyID)
427 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
429 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
430 size = ITy->getBitWidth();
434 assert(Ty->isFloatingPointTy() && "Floating point type expected here");
435 size = Ty->getPrimitiveSizeInBits();
438 O << ".param .b" << size << " func_retval0";
439 } else if (isa<PointerType>(Ty)) {
440 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
443 if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
444 SmallVector<EVT, 16> vtparts;
445 ComputeValueVTs(*TLI, Ty, vtparts);
446 unsigned totalsz = 0;
447 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
449 EVT elemtype = vtparts[i];
450 if (vtparts[i].isVector()) {
451 elems = vtparts[i].getVectorNumElements();
452 elemtype = vtparts[i].getVectorElementType();
454 for (unsigned j = 0, je = elems; j != je; ++j) {
455 unsigned sz = elemtype.getSizeInBits();
456 if (elemtype.isInteger() && (sz < 8))
461 unsigned retAlignment = 0;
462 if (!llvm::getAlign(*F, 0, retAlignment))
463 retAlignment = TD->getABITypeAlignment(Ty);
464 O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
467 assert(false && "Unknown return type");
470 SmallVector<EVT, 16> vtparts;
471 ComputeValueVTs(*TLI, Ty, vtparts);
473 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
475 EVT elemtype = vtparts[i];
476 if (vtparts[i].isVector()) {
477 elems = vtparts[i].getVectorNumElements();
478 elemtype = vtparts[i].getVectorElementType();
481 for (unsigned j = 0, je = elems; j != je; ++j) {
482 unsigned sz = elemtype.getSizeInBits();
483 if (elemtype.isInteger() && (sz < 32))
485 O << ".reg .b" << sz << " func_retval" << idx;
498 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
500 const Function *F = MF.getFunction();
501 printReturnValStr(F, O);
504 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
505 SmallString<128> Str;
506 raw_svector_ostream O(Str);
508 if (!GlobalsEmitted) {
509 emitGlobals(*MF->getFunction()->getParent());
510 GlobalsEmitted = true;
514 MRI = &MF->getRegInfo();
515 F = MF->getFunction();
516 emitLinkageDirective(F, O);
517 if (llvm::isKernelFunction(*F))
521 printReturnValStr(*MF, O);
526 emitFunctionParamList(*MF, O);
528 if (llvm::isKernelFunction(*F))
529 emitKernelFunctionDirectives(*F, O);
531 OutStreamer.EmitRawText(O.str());
533 prevDebugLoc = DebugLoc();
536 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
538 OutStreamer.EmitRawText(StringRef("{\n"));
539 setAndEmitFunctionVirtualRegisters(*MF);
541 SmallString<128> Str;
542 raw_svector_ostream O(Str);
543 emitDemotedVars(MF->getFunction(), O);
544 OutStreamer.EmitRawText(O.str());
547 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
548 OutStreamer.EmitRawText(StringRef("}\n"));
552 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
553 raw_ostream &O) const {
554 // If the NVVM IR has some of reqntid* specified, then output
555 // the reqntid directive, and set the unspecified ones to 1.
556 // If none of reqntid* is specified, don't output reqntid directive.
557 unsigned reqntidx, reqntidy, reqntidz;
558 bool specified = false;
559 if (llvm::getReqNTIDx(F, reqntidx) == false)
563 if (llvm::getReqNTIDy(F, reqntidy) == false)
567 if (llvm::getReqNTIDz(F, reqntidz) == false)
573 O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
576 // If the NVVM IR has some of maxntid* specified, then output
577 // the maxntid directive, and set the unspecified ones to 1.
578 // If none of maxntid* is specified, don't output maxntid directive.
579 unsigned maxntidx, maxntidy, maxntidz;
581 if (llvm::getMaxNTIDx(F, maxntidx) == false)
585 if (llvm::getMaxNTIDy(F, maxntidy) == false)
589 if (llvm::getMaxNTIDz(F, maxntidz) == false)
595 O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
599 if (llvm::getMinCTASm(F, mincta))
600 O << ".minnctapersm " << mincta << "\n";
603 void NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
605 const TargetRegisterClass *RC = MRI->getRegClass(vr);
607 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
608 unsigned mapped_vr = regmap[vr];
611 O << getNVPTXRegClassStr(RC) << mapped_vr;
614 report_fatal_error("Bad register!");
617 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
619 getVirtualRegisterName(vr, isVec, O);
622 void NVPTXAsmPrinter::printVecModifiedImmediate(
623 const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
624 static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
625 int Imm = (int) MO.getImm();
626 if (0 == strcmp(Modifier, "vecelem"))
627 O << "_" << vecelem[Imm];
628 else if (0 == strcmp(Modifier, "vecv4comm1")) {
629 if ((Imm < 0) || (Imm > 3))
631 } else if (0 == strcmp(Modifier, "vecv4comm2")) {
632 if ((Imm < 4) || (Imm > 7))
634 } else if (0 == strcmp(Modifier, "vecv4pos")) {
637 O << "_" << vecelem[Imm % 4];
638 } else if (0 == strcmp(Modifier, "vecv2comm1")) {
639 if ((Imm < 0) || (Imm > 1))
641 } else if (0 == strcmp(Modifier, "vecv2comm2")) {
642 if ((Imm < 2) || (Imm > 3))
644 } else if (0 == strcmp(Modifier, "vecv2pos")) {
647 O << "_" << vecelem[Imm % 2];
649 llvm_unreachable("Unknown Modifier on immediate operand");
654 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
656 emitLinkageDirective(F, O);
657 if (llvm::isKernelFunction(*F))
661 printReturnValStr(F, O);
662 O << *Mang->getSymbol(F) << "\n";
663 emitFunctionParamList(F, O);
667 static bool usedInGlobalVarDef(const Constant *C) {
671 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
672 if (GV->getName().str() == "llvm.used")
677 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
679 const Constant *C = dyn_cast<Constant>(*ui);
680 if (usedInGlobalVarDef(C))
686 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
687 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
688 if (othergv->getName().str() == "llvm.used")
692 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
693 if (instr->getParent() && instr->getParent()->getParent()) {
694 const Function *curFunc = instr->getParent()->getParent();
695 if (oneFunc && (curFunc != oneFunc))
703 if (const MDNode *md = dyn_cast<MDNode>(U))
704 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
705 (md->getName().str() == "llvm.dbg.sp")))
708 for (User::const_use_iterator ui = U->use_begin(), ue = U->use_end();
710 if (usedInOneFunc(*ui, oneFunc) == false)
716 /* Find out if a global variable can be demoted to local scope.
717 * Currently, this is valid for CUDA shared variables, which have local
718 * scope and global lifetime. So the conditions to check are :
719 * 1. Is the global variable in shared address space?
720 * 2. Does it have internal linkage?
721 * 3. Is the global variable referenced only in one function?
723 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
724 if (gv->hasInternalLinkage() == false)
726 const PointerType *Pty = gv->getType();
727 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
730 const Function *oneFunc = 0;
732 bool flag = usedInOneFunc(gv, oneFunc);
741 static bool useFuncSeen(const Constant *C,
742 llvm::DenseMap<const Function *, bool> &seenMap) {
743 for (Value::const_use_iterator ui = C->use_begin(), ue = C->use_end();
745 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
746 if (useFuncSeen(cu, seenMap))
748 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
749 const BasicBlock *bb = I->getParent();
752 const Function *caller = bb->getParent();
755 if (seenMap.find(caller) != seenMap.end())
762 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
763 llvm::DenseMap<const Function *, bool> seenMap;
764 for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
765 const Function *F = FI;
767 if (F->isDeclaration()) {
770 if (F->getIntrinsicID())
772 emitDeclaration(F, O);
775 for (Value::const_use_iterator iter = F->use_begin(),
776 iterEnd = F->use_end();
777 iter != iterEnd; ++iter) {
778 if (const Constant *C = dyn_cast<Constant>(*iter)) {
779 if (usedInGlobalVarDef(C)) {
780 // The use is in the initialization of a global variable
781 // that is a function pointer, so print a declaration
782 // for the original function
783 emitDeclaration(F, O);
786 // Emit a declaration of this function if the function that
787 // uses this constant expr has already been seen.
788 if (useFuncSeen(C, seenMap)) {
789 emitDeclaration(F, O);
794 if (!isa<Instruction>(*iter))
796 const Instruction *instr = cast<Instruction>(*iter);
797 const BasicBlock *bb = instr->getParent();
800 const Function *caller = bb->getParent();
804 // If a caller has already been seen, then the caller is
805 // appearing in the module before the callee. so print out
806 // a declaration for the callee.
807 if (seenMap.find(caller) != seenMap.end()) {
808 emitDeclaration(F, O);
816 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
817 DebugInfoFinder DbgFinder;
818 DbgFinder.processModule(M);
821 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
822 E = DbgFinder.compile_unit_end();
824 DICompileUnit DIUnit(*I);
825 StringRef Filename(DIUnit.getFilename());
826 StringRef Dirname(DIUnit.getDirectory());
827 SmallString<128> FullPathName = Dirname;
828 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
829 sys::path::append(FullPathName, Filename);
830 Filename = FullPathName.str();
832 if (filenameMap.find(Filename.str()) != filenameMap.end())
834 filenameMap[Filename.str()] = i;
835 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
839 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
840 E = DbgFinder.subprogram_end();
843 StringRef Filename(SP.getFilename());
844 StringRef Dirname(SP.getDirectory());
845 SmallString<128> FullPathName = Dirname;
846 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
847 sys::path::append(FullPathName, Filename);
848 Filename = FullPathName.str();
850 if (filenameMap.find(Filename.str()) != filenameMap.end())
852 filenameMap[Filename.str()] = i;
857 bool NVPTXAsmPrinter::doInitialization(Module &M) {
859 SmallString<128> Str1;
860 raw_svector_ostream OS1(Str1);
862 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
863 MMI->AnalyzeModule(M);
865 // We need to call the parent's one explicitly.
866 //bool Result = AsmPrinter::doInitialization(M);
868 // Initialize TargetLoweringObjectFile.
869 const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
870 .Initialize(OutContext, TM);
872 Mang = new Mangler(OutContext, &TM);
874 // Emit header before any dwarf directives are emitted below.
876 OutStreamer.EmitRawText(OS1.str());
878 // Already commented out
879 //bool Result = AsmPrinter::doInitialization(M);
881 // Emit module-level inline asm if it exists.
882 if (!M.getModuleInlineAsm().empty()) {
883 OutStreamer.AddComment("Start of file scope inline assembly");
884 OutStreamer.AddBlankLine();
885 OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
886 OutStreamer.AddBlankLine();
887 OutStreamer.AddComment("End of file scope inline assembly");
888 OutStreamer.AddBlankLine();
891 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
892 recordAndEmitFilenames(M);
894 GlobalsEmitted = false;
896 return false; // success
899 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
900 SmallString<128> Str2;
901 raw_svector_ostream OS2(Str2);
903 emitDeclarations(M, OS2);
905 // As ptxas does not support forward references of globals, we need to first
906 // sort the list of module-level globals in def-use order. We visit each
907 // global variable in order, and ensure that we emit it *after* its dependent
908 // globals. We use a little extra memory maintaining both a set and a list to
909 // have fast searches while maintaining a strict ordering.
910 SmallVector<const GlobalVariable *, 8> Globals;
911 DenseSet<const GlobalVariable *> GVVisited;
912 DenseSet<const GlobalVariable *> GVVisiting;
914 // Visit each global variable, in order
915 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
917 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
919 assert(GVVisited.size() == M.getGlobalList().size() &&
920 "Missed a global variable");
921 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
923 // Print out module-level global variables in proper order
924 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
925 printModuleLevelGV(Globals[i], OS2);
929 OutStreamer.EmitRawText(OS2.str());
932 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
934 O << "// Generated by LLVM NVPTX Back-End\n";
938 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
939 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
942 O << nvptxSubtarget.getTargetName();
944 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
945 O << ", texmode_independent";
946 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
947 if (!nvptxSubtarget.hasDouble())
948 O << ", map_f64_to_f32";
951 if (MAI->doesSupportDebugInformation())
956 O << ".address_size ";
957 if (nvptxSubtarget.is64Bit())
966 bool NVPTXAsmPrinter::doFinalization(Module &M) {
968 // If we did not emit any functions, then the global declarations have not
970 if (!GlobalsEmitted) {
972 GlobalsEmitted = true;
975 // XXX Temproarily remove global variables so that doFinalization() will not
976 // emit them again (global variables are emitted at beginning).
978 Module::GlobalListType &global_list = M.getGlobalList();
979 int i, n = global_list.size();
980 GlobalVariable **gv_array = new GlobalVariable *[n];
982 // first, back-up GlobalVariable in gv_array
984 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
988 // second, empty global_list
989 while (!global_list.empty())
990 global_list.remove(global_list.begin());
992 // call doFinalization
993 bool ret = AsmPrinter::doFinalization(M);
995 // now we restore global variables
996 for (i = 0; i < n; i++)
997 global_list.insert(global_list.end(), gv_array[i]);
1002 //bool Result = AsmPrinter::doFinalization(M);
1003 // Instead of calling the parents doFinalization, we may
1004 // clone parents doFinalization and customize here.
1005 // Currently, we if NVISA out the EmitGlobals() in
1006 // parent's doFinalization, which is too intrusive.
1008 // Same for the doInitialization.
1012 // This function emits appropriate linkage directives for
1013 // functions and global variables.
1015 // extern function declaration -> .extern
1016 // extern function definition -> .visible
1017 // external global variable with init -> .visible
1018 // external without init -> .extern
1019 // appending -> not allowed, assert.
1021 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1023 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1024 if (V->hasExternalLinkage()) {
1025 if (isa<GlobalVariable>(V)) {
1026 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1028 if (GVar->hasInitializer())
1033 } else if (V->isDeclaration())
1037 } else if (V->hasAppendingLinkage()) {
1039 msg.append("Error: ");
1040 msg.append("Symbol ");
1042 msg.append(V->getName().str());
1043 msg.append("has unsupported appending linkage type");
1044 llvm_unreachable(msg.c_str());
1049 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1051 bool processDemoted) {
1054 if (GVar->hasSection()) {
1055 if (GVar->getSection() == "llvm.metadata")
1059 const DataLayout *TD = TM.getDataLayout();
1061 // GlobalVariables are always constant pointers themselves.
1062 const PointerType *PTy = GVar->getType();
1063 Type *ETy = PTy->getElementType();
1065 if (GVar->hasExternalLinkage()) {
1066 if (GVar->hasInitializer())
1072 if (llvm::isTexture(*GVar)) {
1073 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1077 if (llvm::isSurface(*GVar)) {
1078 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1082 if (GVar->isDeclaration()) {
1083 // (extern) declarations, no definition or initializer
1084 // Currently the only known declaration is for an automatic __local
1085 // (.shared) promoted to global.
1086 emitPTXGlobalVariable(GVar, O);
1091 if (llvm::isSampler(*GVar)) {
1092 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1094 const Constant *Initializer = NULL;
1095 if (GVar->hasInitializer())
1096 Initializer = GVar->getInitializer();
1097 const ConstantInt *CI = NULL;
1099 CI = dyn_cast<ConstantInt>(Initializer);
1101 unsigned sample = CI->getZExtValue();
1106 addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1108 O << "addr_mode_" << i << " = ";
1114 O << "clamp_to_border";
1117 O << "clamp_to_edge";
1128 O << "filter_mode = ";
1129 switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1137 assert(0 && "Anisotropic filtering is not supported");
1142 if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1143 O << ", force_unnormalized_coords = 1";
1152 if (GVar->hasPrivateLinkage()) {
1154 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1157 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1158 if (!strncmp(GVar->getName().data(), "filename", 8))
1160 if (GVar->use_empty())
1164 const Function *demotedFunc = 0;
1165 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1166 O << "// " << GVar->getName().str() << " has been demoted\n";
1167 if (localDecls.find(demotedFunc) != localDecls.end())
1168 localDecls[demotedFunc].push_back(GVar);
1170 std::vector<const GlobalVariable *> temp;
1171 temp.push_back(GVar);
1172 localDecls[demotedFunc] = temp;
1178 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1179 if (GVar->getAlignment() == 0)
1180 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1182 O << " .align " << GVar->getAlignment();
1184 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1186 // Special case: ABI requires that we use .u8 for predicates
1187 if (ETy->isIntegerTy(1))
1190 O << getPTXFundamentalTypeStr(ETy, false);
1192 O << *Mang->getSymbol(GVar);
1194 // Ptx allows variable initilization only for constant and global state
1196 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1197 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1198 GVar->hasInitializer()) {
1199 const Constant *Initializer = GVar->getInitializer();
1200 if (!Initializer->isNullValue()) {
1202 printScalarConstant(Initializer, O);
1206 unsigned int ElementSize = 0;
1208 // Although PTX has direct support for struct type and array type and
1209 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1210 // targets that support these high level field accesses. Structs, arrays
1211 // and vectors are lowered into arrays of bytes.
1212 switch (ETy->getTypeID()) {
1213 case Type::StructTyID:
1214 case Type::ArrayTyID:
1215 case Type::VectorTyID:
1216 ElementSize = TD->getTypeStoreSize(ETy);
1217 // Ptx allows variable initilization only for constant and
1218 // global state spaces.
1219 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1220 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1221 GVar->hasInitializer()) {
1222 const Constant *Initializer = GVar->getInitializer();
1223 if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1224 AggBuffer aggBuffer(ElementSize, O, *this);
1225 bufferAggregateConstant(Initializer, &aggBuffer);
1226 if (aggBuffer.numSymbols) {
1227 if (nvptxSubtarget.is64Bit()) {
1228 O << " .u64 " << *Mang->getSymbol(GVar) << "[";
1229 O << ElementSize / 8;
1231 O << " .u32 " << *Mang->getSymbol(GVar) << "[";
1232 O << ElementSize / 4;
1236 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1244 O << " .b8 " << *Mang->getSymbol(GVar);
1252 O << " .b8 " << *Mang->getSymbol(GVar);
1261 assert(0 && "type not supported yet");
1268 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1269 if (localDecls.find(f) == localDecls.end())
1272 std::vector<const GlobalVariable *> &gvars = localDecls[f];
1274 for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1275 O << "\t// demoted variable\n\t";
1276 printModuleLevelGV(gvars[i], O, true);
1280 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1281 raw_ostream &O) const {
1282 switch (AddressSpace) {
1283 case llvm::ADDRESS_SPACE_LOCAL:
1286 case llvm::ADDRESS_SPACE_GLOBAL:
1289 case llvm::ADDRESS_SPACE_CONST:
1292 case llvm::ADDRESS_SPACE_SHARED:
1296 report_fatal_error("Bad address space found while emitting PTX");
1302 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1303 switch (Ty->getTypeID()) {
1305 llvm_unreachable("unexpected type");
1307 case Type::IntegerTyID: {
1308 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1311 else if (NumBits <= 64) {
1312 std::string name = "u";
1313 return name + utostr(NumBits);
1315 llvm_unreachable("Integer too large");
1320 case Type::FloatTyID:
1322 case Type::DoubleTyID:
1324 case Type::PointerTyID:
1325 if (nvptxSubtarget.is64Bit())
1335 llvm_unreachable("unexpected type");
1339 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1342 const DataLayout *TD = TM.getDataLayout();
1344 // GlobalVariables are always constant pointers themselves.
1345 const PointerType *PTy = GVar->getType();
1346 Type *ETy = PTy->getElementType();
1349 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1350 if (GVar->getAlignment() == 0)
1351 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1353 O << " .align " << GVar->getAlignment();
1355 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1357 O << getPTXFundamentalTypeStr(ETy);
1359 O << *Mang->getSymbol(GVar);
1363 int64_t ElementSize = 0;
1365 // Although PTX has direct support for struct type and array type and LLVM IR
1366 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1367 // support these high level field accesses. Structs and arrays are lowered
1368 // into arrays of bytes.
1369 switch (ETy->getTypeID()) {
1370 case Type::StructTyID:
1371 case Type::ArrayTyID:
1372 case Type::VectorTyID:
1373 ElementSize = TD->getTypeStoreSize(ETy);
1374 O << " .b8 " << *Mang->getSymbol(GVar) << "[";
1376 O << itostr(ElementSize);
1381 assert(0 && "type not supported yet");
1386 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1387 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1388 return TD->getPrefTypeAlignment(Ty);
1390 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1392 return getOpenCLAlignment(TD, ATy->getElementType());
1394 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1396 Type *ETy = VTy->getElementType();
1397 unsigned int numE = VTy->getNumElements();
1398 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1402 return numE * alignE;
1405 const StructType *STy = dyn_cast<StructType>(Ty);
1407 unsigned int alignStruct = 1;
1408 // Go through each element of the struct and find the
1409 // largest alignment.
1410 for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1411 Type *ETy = STy->getElementType(i);
1412 unsigned int align = getOpenCLAlignment(TD, ETy);
1413 if (align > alignStruct)
1414 alignStruct = align;
1419 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1421 return TD->getPointerPrefAlignment();
1422 return TD->getPrefTypeAlignment(Ty);
1425 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1426 int paramIndex, raw_ostream &O) {
1427 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1428 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1429 O << *Mang->getSymbol(I->getParent()) << "_param_" << paramIndex;
1431 std::string argName = I->getName();
1432 const char *p = argName.c_str();
1443 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1444 Function::const_arg_iterator I, E;
1447 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1448 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1449 O << *CurrentFnSym << "_param_" << paramIndex;
1453 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1454 if (i == paramIndex) {
1455 printParamName(I, paramIndex, O);
1459 llvm_unreachable("paramIndex out of bound");
1462 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1463 const DataLayout *TD = TM.getDataLayout();
1464 const AttributeSet &PAL = F->getAttributes();
1465 const TargetLowering *TLI = TM.getTargetLowering();
1466 Function::const_arg_iterator I, E;
1467 unsigned paramIndex = 0;
1469 bool isKernelFunc = llvm::isKernelFunction(*F);
1470 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1471 MVT thePointerTy = TLI->getPointerTy();
1475 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1476 Type *Ty = I->getType();
1483 // Handle image/sampler parameters
1484 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1485 if (llvm::isImage(*I)) {
1486 std::string sname = I->getName();
1487 if (llvm::isImageWriteOnly(*I))
1488 O << "\t.param .surfref " << *Mang->getSymbol(F) << "_param_"
1490 else // Default image is read_only
1491 O << "\t.param .texref " << *Mang->getSymbol(F) << "_param_"
1493 } else // Should be llvm::isSampler(*I)
1494 O << "\t.param .samplerref " << *Mang->getSymbol(F) << "_param_"
1499 if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1500 if (Ty->isVectorTy()) {
1501 // Just print .param .b8 .align <a> .param[size];
1502 // <a> = PAL.getparamalignment
1503 // size = typeallocsize of element type
1504 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1506 align = TD->getABITypeAlignment(Ty);
1508 unsigned sz = TD->getTypeAllocSize(Ty);
1509 O << "\t.param .align " << align << " .b8 ";
1510 printParamName(I, paramIndex, O);
1511 O << "[" << sz << "]";
1516 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1519 // Special handling for pointer arguments to kernel
1520 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1522 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1523 Type *ETy = PTy->getElementType();
1524 int addrSpace = PTy->getAddressSpace();
1525 switch (addrSpace) {
1529 case llvm::ADDRESS_SPACE_CONST:
1530 O << ".ptr .const ";
1532 case llvm::ADDRESS_SPACE_SHARED:
1533 O << ".ptr .shared ";
1535 case llvm::ADDRESS_SPACE_GLOBAL:
1536 O << ".ptr .global ";
1539 O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1541 printParamName(I, paramIndex, O);
1545 // non-pointer scalar to kernel func
1547 // Special case: predicate operands become .u8 types
1548 if (Ty->isIntegerTy(1))
1551 O << getPTXFundamentalTypeStr(Ty);
1553 printParamName(I, paramIndex, O);
1556 // Non-kernel function, just print .param .b<size> for ABI
1557 // and .reg .b<size> for non ABY
1559 if (isa<IntegerType>(Ty)) {
1560 sz = cast<IntegerType>(Ty)->getBitWidth();
1563 } else if (isa<PointerType>(Ty))
1564 sz = thePointerTy.getSizeInBits();
1566 sz = Ty->getPrimitiveSizeInBits();
1568 O << "\t.param .b" << sz << " ";
1570 O << "\t.reg .b" << sz << " ";
1571 printParamName(I, paramIndex, O);
1575 // param has byVal attribute. So should be a pointer
1576 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1577 assert(PTy && "Param with byval attribute should be a pointer type");
1578 Type *ETy = PTy->getElementType();
1580 if (isABI || isKernelFunc) {
1581 // Just print .param .b8 .align <a> .param[size];
1582 // <a> = PAL.getparamalignment
1583 // size = typeallocsize of element type
1584 unsigned align = PAL.getParamAlignment(paramIndex + 1);
1586 align = TD->getABITypeAlignment(ETy);
1588 unsigned sz = TD->getTypeAllocSize(ETy);
1589 O << "\t.param .align " << align << " .b8 ";
1590 printParamName(I, paramIndex, O);
1591 O << "[" << sz << "]";
1594 // Split the ETy into constituent parts and
1595 // print .param .b<size> <name> for each part.
1596 // Further, if a part is vector, print the above for
1597 // each vector element.
1598 SmallVector<EVT, 16> vtparts;
1599 ComputeValueVTs(*TLI, ETy, vtparts);
1600 for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1602 EVT elemtype = vtparts[i];
1603 if (vtparts[i].isVector()) {
1604 elems = vtparts[i].getVectorNumElements();
1605 elemtype = vtparts[i].getVectorElementType();
1608 for (unsigned j = 0, je = elems; j != je; ++j) {
1609 unsigned sz = elemtype.getSizeInBits();
1610 if (elemtype.isInteger() && (sz < 32))
1612 O << "\t.reg .b" << sz << " ";
1613 printParamName(I, paramIndex, O);
1629 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1631 const Function *F = MF.getFunction();
1632 emitFunctionParamList(F, O);
1635 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1636 const MachineFunction &MF) {
1637 SmallString<128> Str;
1638 raw_svector_ostream O(Str);
1640 // Map the global virtual register number to a register class specific
1641 // virtual register number starting from 1 with that class.
1642 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1643 //unsigned numRegClasses = TRI->getNumRegClasses();
1645 // Emit the Fake Stack Object
1646 const MachineFrameInfo *MFI = MF.getFrameInfo();
1647 int NumBytes = (int) MFI->getStackSize();
1649 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1650 << getFunctionNumber() << "[" << NumBytes << "];\n";
1651 if (nvptxSubtarget.is64Bit()) {
1652 O << "\t.reg .b64 \t%SP;\n";
1653 O << "\t.reg .b64 \t%SPL;\n";
1655 O << "\t.reg .b32 \t%SP;\n";
1656 O << "\t.reg .b32 \t%SPL;\n";
1660 // Go through all virtual registers to establish the mapping between the
1662 // register number and the per class virtual register number.
1663 // We use the per class virtual register number in the ptx output.
1664 unsigned int numVRs = MRI->getNumVirtRegs();
1665 for (unsigned i = 0; i < numVRs; i++) {
1666 unsigned int vr = TRI->index2VirtReg(i);
1667 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1668 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1669 int n = regmap.size();
1670 regmap.insert(std::make_pair(vr, n + 1));
1673 // Emit register declarations
1674 // @TODO: Extract out the real register usage
1675 // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1676 // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1677 // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1678 // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1679 // O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1680 // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1681 // O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1683 // Emit declaration of the virtual registers or 'physical' registers for
1684 // each register class
1685 for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1686 const TargetRegisterClass *RC = TRI->getRegClass(i);
1687 DenseMap<unsigned, unsigned> ®map = VRegMapping[RC];
1688 std::string rcname = getNVPTXRegClassName(RC);
1689 std::string rcStr = getNVPTXRegClassStr(RC);
1690 int n = regmap.size();
1692 // Only declare those registers that may be used.
1694 O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1699 OutStreamer.EmitRawText(O.str());
1702 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1703 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1705 unsigned int numHex;
1708 if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1711 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1712 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1715 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1717 llvm_unreachable("unsupported fp type");
1719 APInt API = APF.bitcastToAPInt();
1720 std::string hexstr(utohexstr(API.getZExtValue()));
1722 if (hexstr.length() < numHex)
1723 O << std::string(numHex - hexstr.length(), '0');
1724 O << utohexstr(API.getZExtValue());
1727 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1728 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1729 O << CI->getValue();
1732 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1733 printFPConstant(CFP, O);
1736 if (isa<ConstantPointerNull>(CPV)) {
1740 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1741 O << *Mang->getSymbol(GVar);
1744 if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1745 const Value *v = Cexpr->stripPointerCasts();
1746 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1747 O << *Mang->getSymbol(GVar);
1750 O << *LowerConstant(CPV, *this);
1754 llvm_unreachable("Not scalar type found in printScalarConstant()");
1757 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1758 AggBuffer *aggBuffer) {
1760 const DataLayout *TD = TM.getDataLayout();
1762 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1763 int s = TD->getTypeAllocSize(CPV->getType());
1766 aggBuffer->addZeros(s);
1771 switch (CPV->getType()->getTypeID()) {
1773 case Type::IntegerTyID: {
1774 const Type *ETy = CPV->getType();
1775 if (ETy == Type::getInt8Ty(CPV->getContext())) {
1777 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1779 aggBuffer->addBytes(ptr, 1, Bytes);
1780 } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1781 short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1782 ptr = (unsigned char *)&int16;
1783 aggBuffer->addBytes(ptr, 2, Bytes);
1784 } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1785 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1786 int int32 = (int)(constInt->getZExtValue());
1787 ptr = (unsigned char *)&int32;
1788 aggBuffer->addBytes(ptr, 4, Bytes);
1790 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1791 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1792 ConstantFoldConstantExpression(Cexpr, TD))) {
1793 int int32 = (int)(constInt->getZExtValue());
1794 ptr = (unsigned char *)&int32;
1795 aggBuffer->addBytes(ptr, 4, Bytes);
1798 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1799 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1800 aggBuffer->addSymbol(v);
1801 aggBuffer->addZeros(4);
1805 llvm_unreachable("unsupported integer const type");
1806 } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1807 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1808 long long int64 = (long long)(constInt->getZExtValue());
1809 ptr = (unsigned char *)&int64;
1810 aggBuffer->addBytes(ptr, 8, Bytes);
1812 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1813 if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1814 ConstantFoldConstantExpression(Cexpr, TD))) {
1815 long long int64 = (long long)(constInt->getZExtValue());
1816 ptr = (unsigned char *)&int64;
1817 aggBuffer->addBytes(ptr, 8, Bytes);
1820 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1821 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1822 aggBuffer->addSymbol(v);
1823 aggBuffer->addZeros(8);
1827 llvm_unreachable("unsupported integer const type");
1829 llvm_unreachable("unsupported integer const type");
1832 case Type::FloatTyID:
1833 case Type::DoubleTyID: {
1834 const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1835 const Type *Ty = CFP->getType();
1836 if (Ty == Type::getFloatTy(CPV->getContext())) {
1837 float float32 = (float) CFP->getValueAPF().convertToFloat();
1838 ptr = (unsigned char *)&float32;
1839 aggBuffer->addBytes(ptr, 4, Bytes);
1840 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1841 double float64 = CFP->getValueAPF().convertToDouble();
1842 ptr = (unsigned char *)&float64;
1843 aggBuffer->addBytes(ptr, 8, Bytes);
1845 llvm_unreachable("unsupported fp const type");
1849 case Type::PointerTyID: {
1850 if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1851 aggBuffer->addSymbol(GVar);
1852 } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1853 const Value *v = Cexpr->stripPointerCasts();
1854 aggBuffer->addSymbol(v);
1856 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1857 aggBuffer->addZeros(s);
1861 case Type::ArrayTyID:
1862 case Type::VectorTyID:
1863 case Type::StructTyID: {
1864 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1865 isa<ConstantStruct>(CPV)) {
1866 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1867 bufferAggregateConstant(CPV, aggBuffer);
1868 if (Bytes > ElementSize)
1869 aggBuffer->addZeros(Bytes - ElementSize);
1870 } else if (isa<ConstantAggregateZero>(CPV))
1871 aggBuffer->addZeros(Bytes);
1873 llvm_unreachable("Unexpected Constant type");
1878 llvm_unreachable("unsupported type");
1882 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1883 AggBuffer *aggBuffer) {
1884 const DataLayout *TD = TM.getDataLayout();
1888 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1889 if (CPV->getNumOperands())
1890 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1891 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1895 if (const ConstantDataSequential *CDS =
1896 dyn_cast<ConstantDataSequential>(CPV)) {
1897 if (CDS->getNumElements())
1898 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1899 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1904 if (isa<ConstantStruct>(CPV)) {
1905 if (CPV->getNumOperands()) {
1906 StructType *ST = cast<StructType>(CPV->getType());
1907 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1909 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1910 TD->getTypeAllocSize(ST) -
1911 TD->getStructLayout(ST)->getElementOffset(i);
1913 Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
1914 TD->getStructLayout(ST)->getElementOffset(i);
1915 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1920 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1923 // buildTypeNameMap - Run through symbol table looking for type names.
1926 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1928 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1930 if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
1931 !PI->second.compare("struct._image2d_t") ||
1932 !PI->second.compare("struct._image3d_t")))
1939 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
1940 switch (MI.getOpcode()) {
1943 case NVPTX::CallArgBeginInst:
1944 case NVPTX::CallArgEndInst0:
1945 case NVPTX::CallArgEndInst1:
1946 case NVPTX::CallArgF32:
1947 case NVPTX::CallArgF64:
1948 case NVPTX::CallArgI16:
1949 case NVPTX::CallArgI32:
1950 case NVPTX::CallArgI32imm:
1951 case NVPTX::CallArgI64:
1952 case NVPTX::CallArgParam:
1953 case NVPTX::CallVoidInst:
1954 case NVPTX::CallVoidInstReg:
1955 case NVPTX::Callseq_End:
1956 case NVPTX::CallVoidInstReg64:
1957 case NVPTX::DeclareParamInst:
1958 case NVPTX::DeclareRetMemInst:
1959 case NVPTX::DeclareRetRegInst:
1960 case NVPTX::DeclareRetScalarInst:
1961 case NVPTX::DeclareScalarParamInst:
1962 case NVPTX::DeclareScalarRegInst:
1963 case NVPTX::StoreParamF32:
1964 case NVPTX::StoreParamF64:
1965 case NVPTX::StoreParamI16:
1966 case NVPTX::StoreParamI32:
1967 case NVPTX::StoreParamI64:
1968 case NVPTX::StoreParamI8:
1969 case NVPTX::StoreRetvalF32:
1970 case NVPTX::StoreRetvalF64:
1971 case NVPTX::StoreRetvalI16:
1972 case NVPTX::StoreRetvalI32:
1973 case NVPTX::StoreRetvalI64:
1974 case NVPTX::StoreRetvalI8:
1975 case NVPTX::LastCallArgF32:
1976 case NVPTX::LastCallArgF64:
1977 case NVPTX::LastCallArgI16:
1978 case NVPTX::LastCallArgI32:
1979 case NVPTX::LastCallArgI32imm:
1980 case NVPTX::LastCallArgI64:
1981 case NVPTX::LastCallArgParam:
1982 case NVPTX::LoadParamMemF32:
1983 case NVPTX::LoadParamMemF64:
1984 case NVPTX::LoadParamMemI16:
1985 case NVPTX::LoadParamMemI32:
1986 case NVPTX::LoadParamMemI64:
1987 case NVPTX::LoadParamMemI8:
1988 case NVPTX::PrototypeInst:
1989 case NVPTX::DBG_VALUE:
1995 // Force static initialization.
1996 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
1997 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
1998 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2001 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2002 std::stringstream temp;
2003 LineReader *reader = this->getReader(filename.str());
2005 temp << filename.str();
2009 temp << reader->readLine(line);
2011 this->OutStreamer.EmitRawText(Twine(temp.str()));
2014 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2015 if (reader == NULL) {
2016 reader = new LineReader(filename);
2019 if (reader->fileName() != filename) {
2021 reader = new LineReader(filename);
2027 std::string LineReader::readLine(unsigned lineNum) {
2028 if (lineNum < theCurLine) {
2030 fstr.seekg(0, std::ios::beg);
2032 while (theCurLine < lineNum) {
2033 fstr.getline(buff, 500);
2039 // Force static initialization.
2040 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2041 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2042 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);