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 //===----------------------------------------------------------------------===//
16 #include "NVPTXInstrInfo.h"
17 #include "NVPTXTargetMachine.h"
18 #include "NVPTXRegisterInfo.h"
19 #include "NVPTXAsmPrinter.h"
20 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
21 #include "NVPTXNumRegisters.h"
22 #include "../lib/CodeGen/AsmPrinter/DwarfDebug.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/GlobalVariable.h"
25 #include "llvm/Function.h"
26 #include "llvm/Module.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Target/Mangler.h"
34 #include "llvm/Target/TargetLoweringObjectFile.h"
35 #include "llvm/Support/TargetRegistry.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FormattedStream.h"
38 #include "llvm/DerivedTypes.h"
39 #include "NVPTXUtilities.h"
40 #include "llvm/Support/TimeValue.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Analysis/DebugInfo.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Support/Path.h"
46 #include "llvm/Assembly/Writer.h"
47 #include "cl_common_defines.h"
53 #include "NVPTXGenAsmWriter.inc"
55 bool RegAllocNilUsed = true;
57 #define DEPOTNAME "__local_depot"
60 EmitLineNumbers("nvptx-emit-line-numbers",
61 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
65 bool InterleaveSrcInPtx = false;
68 static cl::opt<bool, true>InterleaveSrc("nvptx-emit-src",
70 cl::desc("NVPTX Specific: Emit source line in ptx file"),
71 cl::location(llvm::InterleaveSrcInPtx));
76 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
77 // cannot just link to the existing version.
78 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
80 using namespace nvptx;
81 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
82 MCContext &Ctx = AP.OutContext;
84 if (CV->isNullValue() || isa<UndefValue>(CV))
85 return MCConstantExpr::Create(0, Ctx);
87 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
88 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
90 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
91 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
93 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
94 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
96 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
98 llvm_unreachable("Unknown constant value to lower!");
101 switch (CE->getOpcode()) {
103 // If the code isn't optimized, there may be outstanding folding
104 // opportunities. Attempt to fold the expression using TargetData as a
105 // last resort before giving up.
107 ConstantFoldConstantExpression(CE, AP.TM.getTargetData()))
109 return LowerConstant(C, AP);
111 // Otherwise report the problem to the user.
114 raw_string_ostream OS(S);
115 OS << "Unsupported expression in static initializer: ";
116 WriteAsOperand(OS, CE, /*PrintType=*/false,
117 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
118 report_fatal_error(OS.str());
120 case Instruction::GetElementPtr: {
121 const TargetData &TD = *AP.TM.getTargetData();
122 // Generate a symbolic expression for the byte address
123 const Constant *PtrVal = CE->getOperand(0);
124 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
125 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
127 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
131 // Truncate/sext the offset to the pointer size.
132 if (TD.getPointerSizeInBits() != 64) {
133 int SExtAmount = 64-TD.getPointerSizeInBits();
134 Offset = (Offset << SExtAmount) >> SExtAmount;
137 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
141 case Instruction::Trunc:
142 // We emit the value and depend on the assembler to truncate the generated
143 // expression properly. This is important for differences between
144 // blockaddress labels. Since the two labels are in the same function, it
145 // is reasonable to treat their delta as a 32-bit value.
147 case Instruction::BitCast:
148 return LowerConstant(CE->getOperand(0), AP);
150 case Instruction::IntToPtr: {
151 const TargetData &TD = *AP.TM.getTargetData();
152 // Handle casts to pointers by changing them into casts to the appropriate
153 // integer type. This promotes constant folding and simplifies this code.
154 Constant *Op = CE->getOperand(0);
155 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
157 return LowerConstant(Op, AP);
160 case Instruction::PtrToInt: {
161 const TargetData &TD = *AP.TM.getTargetData();
162 // Support only foldable casts to/from pointers that can be eliminated by
163 // changing the pointer to the appropriately sized integer type.
164 Constant *Op = CE->getOperand(0);
165 Type *Ty = CE->getType();
167 const MCExpr *OpExpr = LowerConstant(Op, AP);
169 // We can emit the pointer value into this slot if the slot is an
170 // integer slot equal to the size of the pointer.
171 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
174 // Otherwise the pointer is smaller than the resultant integer, mask off
175 // the high bits so we are sure to get a proper truncation if the input is
177 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
178 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
179 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
182 // The MC library also has a right-shift operator, but it isn't consistently
183 // signed or unsigned between different targets.
184 case Instruction::Add:
185 case Instruction::Sub:
186 case Instruction::Mul:
187 case Instruction::SDiv:
188 case Instruction::SRem:
189 case Instruction::Shl:
190 case Instruction::And:
191 case Instruction::Or:
192 case Instruction::Xor: {
193 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
194 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
195 switch (CE->getOpcode()) {
196 default: llvm_unreachable("Unknown binary operator constant cast expr");
197 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
198 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
199 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
200 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
201 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
202 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
203 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
204 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
205 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
212 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI)
214 if (!EmitLineNumbers)
219 DebugLoc curLoc = MI.getDebugLoc();
221 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
224 if (prevDebugLoc == curLoc)
227 prevDebugLoc = curLoc;
229 if (curLoc.isUnknown())
233 const MachineFunction *MF = MI.getParent()->getParent();
234 //const TargetMachine &TM = MF->getTarget();
236 const LLVMContext &ctx = MF->getFunction()->getContext();
237 DIScope Scope(curLoc.getScope(ctx));
242 StringRef fileName(Scope.getFilename());
243 StringRef dirName(Scope.getDirectory());
244 SmallString<128> FullPathName = dirName;
245 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
246 sys::path::append(FullPathName, fileName);
247 fileName = FullPathName.str();
250 if (filenameMap.find(fileName.str()) == filenameMap.end())
254 // Emit the line from the source file.
255 if (llvm::InterleaveSrcInPtx)
256 this->emitSrcInText(fileName.str(), curLoc.getLine());
258 std::stringstream temp;
259 temp << "\t.loc " << filenameMap[fileName.str()]
260 << " " << curLoc.getLine() << " " << curLoc.getCol();
261 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
264 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
265 SmallString<128> Str;
266 raw_svector_ostream OS(Str);
267 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
268 emitLineNumberAsDotLoc(*MI);
269 printInstruction(MI, OS);
270 OutStreamer.EmitRawText(OS.str());
273 void NVPTXAsmPrinter::printReturnValStr(const Function *F,
276 const TargetData *TD = TM.getTargetData();
277 const TargetLowering *TLI = TM.getTargetLowering();
279 Type *Ty = F->getReturnType();
281 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
283 if (Ty->getTypeID() == Type::VoidTyID)
289 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
291 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
292 size = ITy->getBitWidth();
293 if (size < 32) size = 32;
295 assert(Ty->isFloatingPointTy() &&
296 "Floating point type expected here");
297 size = Ty->getPrimitiveSizeInBits();
300 O << ".param .b" << size << " func_retval0";
302 else if (isa<PointerType>(Ty)) {
303 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
306 if ((Ty->getTypeID() == Type::StructTyID) ||
307 isa<VectorType>(Ty)) {
308 SmallVector<EVT, 16> vtparts;
309 ComputeValueVTs(*TLI, Ty, vtparts);
310 unsigned totalsz = 0;
311 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
313 EVT elemtype = vtparts[i];
314 if (vtparts[i].isVector()) {
315 elems = vtparts[i].getVectorNumElements();
316 elemtype = vtparts[i].getVectorElementType();
318 for (unsigned j=0, je=elems; j!=je; ++j) {
319 unsigned sz = elemtype.getSizeInBits();
320 if (elemtype.isInteger() && (sz < 8)) sz = 8;
324 unsigned retAlignment = 0;
325 if (!llvm::getAlign(*F, 0, retAlignment))
326 retAlignment = TD->getABITypeAlignment(Ty);
327 O << ".param .align "
329 << " .b8 func_retval0["
333 "Unknown return type");
336 SmallVector<EVT, 16> vtparts;
337 ComputeValueVTs(*TLI, Ty, vtparts);
339 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
341 EVT elemtype = vtparts[i];
342 if (vtparts[i].isVector()) {
343 elems = vtparts[i].getVectorNumElements();
344 elemtype = vtparts[i].getVectorElementType();
347 for (unsigned j=0, je=elems; j!=je; ++j) {
348 unsigned sz = elemtype.getSizeInBits();
349 if (elemtype.isInteger() && (sz < 32)) sz = 32;
350 O << ".reg .b" << sz << " func_retval" << idx;
351 if (j<je-1) O << ", ";
362 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
364 const Function *F = MF.getFunction();
365 printReturnValStr(F, O);
368 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
369 SmallString<128> Str;
370 raw_svector_ostream O(Str);
373 MRI = &MF->getRegInfo();
374 F = MF->getFunction();
375 emitLinkageDirective(F,O);
376 if (llvm::isKernelFunction(*F))
380 printReturnValStr(*MF, O);
385 emitFunctionParamList(*MF, O);
387 if (llvm::isKernelFunction(*F))
388 emitKernelFunctionDirectives(*F, O);
390 OutStreamer.EmitRawText(O.str());
392 prevDebugLoc = DebugLoc();
395 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
396 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
397 unsigned numRegClasses = TRI.getNumRegClasses();
398 VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses+1];
399 OutStreamer.EmitRawText(StringRef("{\n"));
400 setAndEmitFunctionVirtualRegisters(*MF);
402 SmallString<128> Str;
403 raw_svector_ostream O(Str);
404 emitDemotedVars(MF->getFunction(), O);
405 OutStreamer.EmitRawText(O.str());
408 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
409 OutStreamer.EmitRawText(StringRef("}\n"));
410 delete []VRidGlobal2LocalMap;
415 NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function& F,
416 raw_ostream &O) const {
417 // If the NVVM IR has some of reqntid* specified, then output
418 // the reqntid directive, and set the unspecified ones to 1.
419 // If none of reqntid* is specified, don't output reqntid directive.
420 unsigned reqntidx, reqntidy, reqntidz;
421 bool specified = false;
422 if (llvm::getReqNTIDx(F, reqntidx) == false) reqntidx = 1;
423 else specified = true;
424 if (llvm::getReqNTIDy(F, reqntidy) == false) reqntidy = 1;
425 else specified = true;
426 if (llvm::getReqNTIDz(F, reqntidz) == false) reqntidz = 1;
427 else specified = true;
430 O << ".reqntid " << reqntidx << ", "
431 << reqntidy << ", " << reqntidz << "\n";
433 // If the NVVM IR has some of maxntid* specified, then output
434 // the maxntid directive, and set the unspecified ones to 1.
435 // If none of maxntid* is specified, don't output maxntid directive.
436 unsigned maxntidx, maxntidy, maxntidz;
438 if (llvm::getMaxNTIDx(F, maxntidx) == false) maxntidx = 1;
439 else specified = true;
440 if (llvm::getMaxNTIDy(F, maxntidy) == false) maxntidy = 1;
441 else specified = true;
442 if (llvm::getMaxNTIDz(F, maxntidz) == false) maxntidz = 1;
443 else specified = true;
446 O << ".maxntid " << maxntidx << ", "
447 << maxntidy << ", " << maxntidz << "\n";
450 if (llvm::getMinCTASm(F, mincta))
451 O << ".minnctapersm " << mincta << "\n";
455 NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
457 const TargetRegisterClass * RC = MRI->getRegClass(vr);
458 unsigned id = RC->getID();
460 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[id];
461 unsigned mapped_vr = regmap[vr];
464 O << getNVPTXRegClassStr(RC) << mapped_vr;
467 // Vector virtual register
468 if (getNVPTXVectorSize(RC) == 4)
470 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
471 << getNVPTXRegClassStr(RC) << mapped_vr << "_1, "
472 << getNVPTXRegClassStr(RC) << mapped_vr << "_2, "
473 << getNVPTXRegClassStr(RC) << mapped_vr << "_3"
475 else if (getNVPTXVectorSize(RC) == 2)
477 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
478 << getNVPTXRegClassStr(RC) << mapped_vr << "_1"
481 llvm_unreachable("Unsupported vector size");
485 NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
487 getVirtualRegisterName(vr, isVec, O);
490 void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
491 const char *Modifier,
493 static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
494 int Imm = (int)MO.getImm();
495 if(0 == strcmp(Modifier, "vecelem"))
496 O << "_" << vecelem[Imm];
497 else if(0 == strcmp(Modifier, "vecv4comm1")) {
498 if((Imm < 0) || (Imm > 3))
501 else if(0 == strcmp(Modifier, "vecv4comm2")) {
502 if((Imm < 4) || (Imm > 7))
505 else if(0 == strcmp(Modifier, "vecv4pos")) {
507 O << "_" << vecelem[Imm%4];
509 else if(0 == strcmp(Modifier, "vecv2comm1")) {
510 if((Imm < 0) || (Imm > 1))
513 else if(0 == strcmp(Modifier, "vecv2comm2")) {
514 if((Imm < 2) || (Imm > 3))
517 else if(0 == strcmp(Modifier, "vecv2pos")) {
519 O << "_" << vecelem[Imm%2];
522 llvm_unreachable("Unknown Modifier on immediate operand");
525 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
526 raw_ostream &O, const char *Modifier) {
527 const MachineOperand &MO = MI->getOperand(opNum);
528 switch (MO.getType()) {
529 case MachineOperand::MO_Register:
530 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
531 if (MO.getReg() == NVPTX::VRDepot)
532 O << DEPOTNAME << getFunctionNumber();
534 O << getRegisterName(MO.getReg());
537 emitVirtualRegister(MO.getReg(), false, O);
539 if (strcmp(Modifier, "vecfull") == 0)
540 emitVirtualRegister(MO.getReg(), true, O);
543 "Don't know how to handle the modifier on virtual register.");
548 case MachineOperand::MO_Immediate:
551 else if (strstr(Modifier, "vec") == Modifier)
552 printVecModifiedImmediate(MO, Modifier, O);
554 llvm_unreachable("Don't know how to handle modifier on immediate operand");
557 case MachineOperand::MO_FPImmediate:
558 printFPConstant(MO.getFPImm(), O);
561 case MachineOperand::MO_GlobalAddress:
562 O << *Mang->getSymbol(MO.getGlobal());
565 case MachineOperand::MO_ExternalSymbol: {
566 const char * symbname = MO.getSymbolName();
567 if (strstr(symbname, ".PARAM") == symbname) {
569 sscanf(symbname+6, "%u[];", &index);
570 printParamName(index, O);
572 else if (strstr(symbname, ".HLPPARAM") == symbname) {
574 sscanf(symbname+9, "%u[];", &index);
575 O << *CurrentFnSym << "_param_" << index << "_offset";
582 case MachineOperand::MO_MachineBasicBlock:
583 O << *MO.getMBB()->getSymbol();
587 llvm_unreachable("Operand type not supported.");
591 void NVPTXAsmPrinter::
592 printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
594 O << "\t// Implicit def :";
595 //printOperand(MI, 0);
600 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
601 raw_ostream &O, const char *Modifier) {
602 printOperand(MI, opNum, O);
604 if (Modifier && !strcmp(Modifier, "add")) {
606 printOperand(MI, opNum+1, O);
608 if (MI->getOperand(opNum+1).isImm() &&
609 MI->getOperand(opNum+1).getImm() == 0)
610 return; // don't print ',0' or '+0'
612 printOperand(MI, opNum+1, O);
616 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
617 raw_ostream &O, const char *Modifier)
620 const MachineOperand &MO = MI->getOperand(opNum);
621 int Imm = (int)MO.getImm();
622 if (!strcmp(Modifier, "volatile")) {
625 } else if (!strcmp(Modifier, "addsp")) {
627 case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
628 case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
629 case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
630 case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
631 case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
632 case NVPTX::PTXLdStInstCode::GENERIC:
633 if (!nvptxSubtarget.hasGenericLdSt())
637 assert("wrong value");
640 else if (!strcmp(Modifier, "sign")) {
641 if (Imm==NVPTX::PTXLdStInstCode::Signed)
643 else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
648 else if (!strcmp(Modifier, "vec")) {
649 if (Imm==NVPTX::PTXLdStInstCode::V2)
651 else if (Imm==NVPTX::PTXLdStInstCode::V4)
655 assert("unknown modifier");
658 assert("unknown modifier");
661 void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
663 emitLinkageDirective(F,O);
664 if (llvm::isKernelFunction(*F))
668 printReturnValStr(F, O);
669 O << *CurrentFnSym << "\n";
670 emitFunctionParamList(F, O);
674 static bool usedInGlobalVarDef(const Constant *C)
679 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
680 if (GV->getName().str() == "llvm.used")
685 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
687 const Constant *C = dyn_cast<Constant>(*ui);
688 if (usedInGlobalVarDef(C))
694 static bool usedInOneFunc(const User *U, Function const *&oneFunc)
696 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
697 if (othergv->getName().str() == "llvm.used")
701 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
702 if (instr->getParent() && instr->getParent()->getParent()) {
703 const Function *curFunc = instr->getParent()->getParent();
704 if (oneFunc && (curFunc != oneFunc))
713 if (const MDNode *md = dyn_cast<MDNode>(U))
714 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
715 (md->getName().str() == "llvm.dbg.sp")))
719 for (User::const_use_iterator ui=U->use_begin(), ue=U->use_end();
721 if (usedInOneFunc(*ui, oneFunc) == false)
727 /* Find out if a global variable can be demoted to local scope.
728 * Currently, this is valid for CUDA shared variables, which have local
729 * scope and global lifetime. So the conditions to check are :
730 * 1. Is the global variable in shared address space?
731 * 2. Does it have internal linkage?
732 * 3. Is the global variable referenced only in one function?
734 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
735 if (gv->hasInternalLinkage() == false)
737 const PointerType *Pty = gv->getType();
738 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
741 const Function *oneFunc = 0;
743 bool flag = usedInOneFunc(gv, oneFunc);
752 static bool useFuncSeen(const Constant *C,
753 llvm::DenseMap<const Function *, bool> &seenMap) {
754 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
756 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
757 if (useFuncSeen(cu, seenMap))
759 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
760 const BasicBlock *bb = I->getParent();
762 const Function *caller = bb->getParent();
763 if (!caller) continue;
764 if (seenMap.find(caller) != seenMap.end())
771 void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
772 llvm::DenseMap<const Function *, bool> seenMap;
773 for (Module::const_iterator FI=M.begin(), FE=M.end();
775 const Function *F = FI;
777 if (F->isDeclaration()) {
780 if (F->getIntrinsicID())
782 CurrentFnSym = Mang->getSymbol(F);
783 emitDeclaration(F, O);
786 for (Value::const_use_iterator iter=F->use_begin(),
787 iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
788 if (const Constant *C = dyn_cast<Constant>(*iter)) {
789 if (usedInGlobalVarDef(C)) {
790 // The use is in the initialization of a global variable
791 // that is a function pointer, so print a declaration
792 // for the original function
793 CurrentFnSym = Mang->getSymbol(F);
794 emitDeclaration(F, O);
797 // Emit a declaration of this function if the function that
798 // uses this constant expr has already been seen.
799 if (useFuncSeen(C, seenMap)) {
800 CurrentFnSym = Mang->getSymbol(F);
801 emitDeclaration(F, O);
806 if (!isa<Instruction>(*iter)) continue;
807 const Instruction *instr = cast<Instruction>(*iter);
808 const BasicBlock *bb = instr->getParent();
810 const Function *caller = bb->getParent();
811 if (!caller) continue;
813 // If a caller has already been seen, then the caller is
814 // appearing in the module before the callee. so print out
815 // a declaration for the callee.
816 if (seenMap.find(caller) != seenMap.end()) {
817 CurrentFnSym = Mang->getSymbol(F);
818 emitDeclaration(F, O);
826 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
827 DebugInfoFinder DbgFinder;
828 DbgFinder.processModule(M);
831 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
832 E = DbgFinder.compile_unit_end(); I != E; ++I) {
833 DICompileUnit DIUnit(*I);
834 StringRef Filename(DIUnit.getFilename());
835 StringRef Dirname(DIUnit.getDirectory());
836 SmallString<128> FullPathName = Dirname;
837 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
838 sys::path::append(FullPathName, Filename);
839 Filename = FullPathName.str();
841 if (filenameMap.find(Filename.str()) != filenameMap.end())
843 filenameMap[Filename.str()] = i;
844 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
848 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
849 E = DbgFinder.subprogram_end(); I != E; ++I) {
851 StringRef Filename(SP.getFilename());
852 StringRef Dirname(SP.getDirectory());
853 SmallString<128> FullPathName = Dirname;
854 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
855 sys::path::append(FullPathName, Filename);
856 Filename = FullPathName.str();
858 if (filenameMap.find(Filename.str()) != filenameMap.end())
860 filenameMap[Filename.str()] = i;
865 bool NVPTXAsmPrinter::doInitialization (Module &M) {
867 SmallString<128> Str1;
868 raw_svector_ostream OS1(Str1);
870 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
871 MMI->AnalyzeModule(M);
873 // We need to call the parent's one explicitly.
874 //bool Result = AsmPrinter::doInitialization(M);
876 // Initialize TargetLoweringObjectFile.
877 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
878 .Initialize(OutContext, TM);
880 Mang = new Mangler(OutContext, *TM.getTargetData());
882 // Emit header before any dwarf directives are emitted below.
884 OutStreamer.EmitRawText(OS1.str());
887 // Already commented out
888 //bool Result = AsmPrinter::doInitialization(M);
891 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
892 recordAndEmitFilenames(M);
894 SmallString<128> Str2;
895 raw_svector_ostream OS2(Str2);
897 emitDeclarations(M, OS2);
899 // Print out module-level global variables here.
900 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
902 printModuleLevelGV(I, OS2);
906 OutStreamer.EmitRawText(OS2.str());
907 return false; // success
910 void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
912 O << "// Generated by LLVM NVPTX Back-End\n";
916 O << ".version 3.0\n";
919 O << nvptxSubtarget.getTargetName();
921 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
922 O << ", texmode_independent";
923 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
924 if (!nvptxSubtarget.hasDouble())
925 O << ", map_f64_to_f32";
928 if (MAI->doesSupportDebugInformation())
933 O << ".address_size ";
934 if (nvptxSubtarget.is64Bit())
943 bool NVPTXAsmPrinter::doFinalization(Module &M) {
944 // XXX Temproarily remove global variables so that doFinalization() will not
945 // emit them again (global variables are emitted at beginning).
947 Module::GlobalListType &global_list = M.getGlobalList();
948 int i, n = global_list.size();
949 GlobalVariable **gv_array = new GlobalVariable* [n];
951 // first, back-up GlobalVariable in gv_array
953 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
957 // second, empty global_list
958 while (!global_list.empty())
959 global_list.remove(global_list.begin());
961 // call doFinalization
962 bool ret = AsmPrinter::doFinalization(M);
964 // now we restore global variables
965 for (i = 0; i < n; i ++)
966 global_list.insert(global_list.end(), gv_array[i]);
972 //bool Result = AsmPrinter::doFinalization(M);
973 // Instead of calling the parents doFinalization, we may
974 // clone parents doFinalization and customize here.
975 // Currently, we if NVISA out the EmitGlobals() in
976 // parent's doFinalization, which is too intrusive.
978 // Same for the doInitialization.
982 // This function emits appropriate linkage directives for
983 // functions and global variables.
985 // extern function declaration -> .extern
986 // extern function definition -> .visible
987 // external global variable with init -> .visible
988 // external without init -> .extern
989 // appending -> not allowed, assert.
991 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
993 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
994 if (V->hasExternalLinkage()) {
995 if (isa<GlobalVariable>(V)) {
996 const GlobalVariable *GVar = cast<GlobalVariable>(V);
998 if (GVar->hasInitializer())
1003 } else if (V->isDeclaration())
1007 } else if (V->hasAppendingLinkage()) {
1009 msg.append("Error: ");
1010 msg.append("Symbol ");
1012 msg.append(V->getName().str());
1013 msg.append("has unsupported appending linkage type");
1014 llvm_unreachable(msg.c_str());
1020 void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1021 bool processDemoted) {
1024 if (GVar->hasSection()) {
1025 if (GVar->getSection() == "llvm.metadata")
1029 const TargetData *TD = TM.getTargetData();
1031 // GlobalVariables are always constant pointers themselves.
1032 const PointerType *PTy = GVar->getType();
1033 Type *ETy = PTy->getElementType();
1035 if (GVar->hasExternalLinkage()) {
1036 if (GVar->hasInitializer())
1042 if (llvm::isTexture(*GVar)) {
1043 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1047 if (llvm::isSurface(*GVar)) {
1048 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1052 if (GVar->isDeclaration()) {
1053 // (extern) declarations, no definition or initializer
1054 // Currently the only known declaration is for an automatic __local
1055 // (.shared) promoted to global.
1056 emitPTXGlobalVariable(GVar, O);
1061 if (llvm::isSampler(*GVar)) {
1062 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1064 Constant *Initializer = NULL;
1065 if (GVar->hasInitializer())
1066 Initializer = GVar->getInitializer();
1067 ConstantInt *CI = NULL;
1069 CI = dyn_cast<ConstantInt>(Initializer);
1071 unsigned sample=CI->getZExtValue();
1075 for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1076 __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1077 O << "addr_mode_" << i << " = ";
1079 case 0: O << "wrap"; break;
1080 case 1: O << "clamp_to_border"; break;
1081 case 2: O << "clamp_to_edge"; break;
1082 case 3: O << "wrap"; break;
1083 case 4: O << "mirror"; break;
1087 O << "filter_mode = ";
1088 switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1089 case 0: O << "nearest"; break;
1090 case 1: O << "linear"; break;
1091 case 2: assert ( 0 && "Anisotropic filtering is not supported");
1092 default: O << "nearest"; break;
1094 if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1095 O << ", force_unnormalized_coords = 1";
1104 if (GVar->hasPrivateLinkage()) {
1106 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1109 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1110 if (!strncmp(GVar->getName().data(), "filename", 8))
1112 if (GVar->use_empty())
1116 const Function *demotedFunc = 0;
1117 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1118 O << "// " << GVar->getName().str() << " has been demoted\n";
1119 if (localDecls.find(demotedFunc) != localDecls.end())
1120 localDecls[demotedFunc].push_back(GVar);
1122 std::vector<GlobalVariable *> temp;
1123 temp.push_back(GVar);
1124 localDecls[demotedFunc] = temp;
1130 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1131 if (GVar->getAlignment() == 0)
1132 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1134 O << " .align " << GVar->getAlignment();
1137 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1139 O << getPTXFundamentalTypeStr(ETy, false);
1141 O << *Mang->getSymbol(GVar);
1143 // Ptx allows variable initilization only for constant and global state
1145 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1146 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1147 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1148 && GVar->hasInitializer()) {
1149 Constant *Initializer = GVar->getInitializer();
1150 if (!Initializer->isNullValue()) {
1152 printScalarConstant(Initializer, O);
1156 unsigned int ElementSize =0;
1158 // Although PTX has direct support for struct type and array type and
1159 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1160 // targets that support these high level field accesses. Structs, arrays
1161 // and vectors are lowered into arrays of bytes.
1162 switch (ETy->getTypeID()) {
1163 case Type::StructTyID:
1164 case Type::ArrayTyID:
1165 case Type::VectorTyID:
1166 ElementSize = TD->getTypeStoreSize(ETy);
1167 // Ptx allows variable initilization only for constant and
1168 // global state spaces.
1169 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1170 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1171 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1172 && GVar->hasInitializer()) {
1173 Constant *Initializer = GVar->getInitializer();
1174 if (!isa<UndefValue>(Initializer) &&
1175 !Initializer->isNullValue()) {
1176 AggBuffer aggBuffer(ElementSize, O, *this);
1177 bufferAggregateConstant(Initializer, &aggBuffer);
1178 if (aggBuffer.numSymbols) {
1179 if (nvptxSubtarget.is64Bit()) {
1180 O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1184 O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1190 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1199 O << " .b8 " << *Mang->getSymbol(GVar) ;
1208 O << " .b8 " << *Mang->getSymbol(GVar);
1217 assert( 0 && "type not supported yet");
1224 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1225 if (localDecls.find(f) == localDecls.end())
1228 std::vector<GlobalVariable *> &gvars = localDecls[f];
1230 for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1231 O << "\t// demoted variable\n\t";
1232 printModuleLevelGV(gvars[i], O, true);
1236 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1237 raw_ostream &O) const {
1238 switch (AddressSpace) {
1239 case llvm::ADDRESS_SPACE_LOCAL:
1242 case llvm::ADDRESS_SPACE_GLOBAL:
1245 case llvm::ADDRESS_SPACE_CONST:
1246 // This logic should be consistent with that in
1247 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1248 if (nvptxSubtarget.hasGenericLdSt())
1253 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1256 case llvm::ADDRESS_SPACE_SHARED:
1260 llvm_unreachable("unexpected address space");
1264 std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1265 bool useB4PTR) const {
1266 switch (Ty->getTypeID()) {
1268 llvm_unreachable("unexpected type");
1270 case Type::IntegerTyID: {
1271 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1274 else if (NumBits <= 64) {
1275 std::string name = "u";
1276 return name + utostr(NumBits);
1278 llvm_unreachable("Integer too large");
1283 case Type::FloatTyID:
1285 case Type::DoubleTyID:
1287 case Type::PointerTyID:
1288 if (nvptxSubtarget.is64Bit())
1289 if (useB4PTR) return "b64";
1292 if (useB4PTR) return "b32";
1295 llvm_unreachable("unexpected type");
1299 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1302 const TargetData *TD = TM.getTargetData();
1304 // GlobalVariables are always constant pointers themselves.
1305 const PointerType *PTy = GVar->getType();
1306 Type *ETy = PTy->getElementType();
1309 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1310 if (GVar->getAlignment() == 0)
1311 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1313 O << " .align " << GVar->getAlignment();
1315 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1317 O << getPTXFundamentalTypeStr(ETy);
1319 O << *Mang->getSymbol(GVar);
1323 int64_t ElementSize =0;
1325 // Although PTX has direct support for struct type and array type and LLVM IR
1326 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1327 // support these high level field accesses. Structs and arrays are lowered
1328 // into arrays of bytes.
1329 switch (ETy->getTypeID()) {
1330 case Type::StructTyID:
1331 case Type::ArrayTyID:
1332 case Type::VectorTyID:
1333 ElementSize = TD->getTypeStoreSize(ETy);
1334 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1336 O << itostr(ElementSize) ;
1341 assert( 0 && "type not supported yet");
1348 getOpenCLAlignment(const TargetData *TD,
1350 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1351 return TD->getPrefTypeAlignment(Ty);
1353 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1355 return getOpenCLAlignment(TD, ATy->getElementType());
1357 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1359 Type *ETy = VTy->getElementType();
1360 unsigned int numE = VTy->getNumElements();
1361 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1368 const StructType *STy = dyn_cast<StructType>(Ty);
1370 unsigned int alignStruct = 1;
1371 // Go through each element of the struct and find the
1372 // largest alignment.
1373 for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1374 Type *ETy = STy->getElementType(i);
1375 unsigned int align = getOpenCLAlignment(TD, ETy);
1376 if (align > alignStruct)
1377 alignStruct = align;
1382 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1384 return TD->getPointerPrefAlignment();
1385 return TD->getPrefTypeAlignment(Ty);
1388 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1389 int paramIndex, raw_ostream &O) {
1390 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1391 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1392 O << *CurrentFnSym << "_param_" << paramIndex;
1394 std::string argName = I->getName();
1395 const char *p = argName.c_str();
1406 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1407 Function::const_arg_iterator I, E;
1410 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1411 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1412 O << *CurrentFnSym << "_param_" << paramIndex;
1416 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1417 if (i==paramIndex) {
1418 printParamName(I, paramIndex, O);
1422 llvm_unreachable("paramIndex out of bound");
1425 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1427 const TargetData *TD = TM.getTargetData();
1428 const AttrListPtr &PAL = F->getAttributes();
1429 const TargetLowering *TLI = TM.getTargetLowering();
1430 Function::const_arg_iterator I, E;
1431 unsigned paramIndex = 0;
1433 bool isKernelFunc = llvm::isKernelFunction(*F);
1434 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1435 MVT thePointerTy = TLI->getPointerTy();
1439 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1440 const Type *Ty = I->getType();
1447 // Handle image/sampler parameters
1448 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1449 if (llvm::isImage(*I)) {
1450 std::string sname = I->getName();
1451 if (llvm::isImageWriteOnly(*I))
1452 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1453 else // Default image is read_only
1454 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1456 else // Should be llvm::isSampler(*I)
1457 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1462 if (PAL.paramHasAttr(paramIndex+1, Attribute::ByVal) == false) {
1464 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1467 // Special handling for pointer arguments to kernel
1468 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1470 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1471 Type *ETy = PTy->getElementType();
1472 int addrSpace = PTy->getAddressSpace();
1477 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1478 O << ".ptr .const ";
1480 case llvm::ADDRESS_SPACE_SHARED:
1481 O << ".ptr .shared ";
1483 case llvm::ADDRESS_SPACE_GLOBAL:
1484 case llvm::ADDRESS_SPACE_CONST:
1485 O << ".ptr .global ";
1488 O << ".align " << (int)getOpenCLAlignment(TD, ETy) << " ";
1490 printParamName(I, paramIndex, O);
1494 // non-pointer scalar to kernel func
1496 << getPTXFundamentalTypeStr(Ty) << " ";
1497 printParamName(I, paramIndex, O);
1500 // Non-kernel function, just print .param .b<size> for ABI
1501 // and .reg .b<size> for non ABY
1503 if (isa<IntegerType>(Ty)) {
1504 sz = cast<IntegerType>(Ty)->getBitWidth();
1505 if (sz < 32) sz = 32;
1507 else if (isa<PointerType>(Ty))
1508 sz = thePointerTy.getSizeInBits();
1510 sz = Ty->getPrimitiveSizeInBits();
1512 O << "\t.param .b" << sz << " ";
1514 O << "\t.reg .b" << sz << " ";
1515 printParamName(I, paramIndex, O);
1519 // param has byVal attribute. So should be a pointer
1520 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1522 "Param with byval attribute should be a pointer type");
1523 Type *ETy = PTy->getElementType();
1525 if (isABI || isKernelFunc) {
1526 // Just print .param .b8 .align <a> .param[size];
1527 // <a> = PAL.getparamalignment
1528 // size = typeallocsize of element type
1529 unsigned align = PAL.getParamAlignment(paramIndex+1);
1530 unsigned sz = TD->getTypeAllocSize(ETy);
1531 O << "\t.param .align " << align
1533 printParamName(I, paramIndex, O);
1534 O << "[" << sz << "]";
1537 // Split the ETy into constituent parts and
1538 // print .param .b<size> <name> for each part.
1539 // Further, if a part is vector, print the above for
1540 // each vector element.
1541 SmallVector<EVT, 16> vtparts;
1542 ComputeValueVTs(*TLI, ETy, vtparts);
1543 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
1545 EVT elemtype = vtparts[i];
1546 if (vtparts[i].isVector()) {
1547 elems = vtparts[i].getVectorNumElements();
1548 elemtype = vtparts[i].getVectorElementType();
1551 for (unsigned j=0,je=elems; j!=je; ++j) {
1552 unsigned sz = elemtype.getSizeInBits();
1553 if (elemtype.isInteger() && (sz < 32)) sz = 32;
1554 O << "\t.reg .b" << sz << " ";
1555 printParamName(I, paramIndex, O);
1556 if (j<je-1) O << ",\n";
1570 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1572 const Function *F = MF.getFunction();
1573 emitFunctionParamList(F, O);
1577 void NVPTXAsmPrinter::
1578 setAndEmitFunctionVirtualRegisters(const MachineFunction &MF) {
1579 SmallString<128> Str;
1580 raw_svector_ostream O(Str);
1582 // Map the global virtual register number to a register class specific
1583 // virtual register number starting from 1 with that class.
1584 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1585 //unsigned numRegClasses = TRI->getNumRegClasses();
1587 // Emit the Fake Stack Object
1588 const MachineFrameInfo *MFI = MF.getFrameInfo();
1589 int NumBytes = (int) MFI->getStackSize();
1591 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t"
1593 << getFunctionNumber() << "[" << NumBytes << "];\n";
1594 if (nvptxSubtarget.is64Bit()) {
1595 O << "\t.reg .b64 \t%SP;\n";
1596 O << "\t.reg .b64 \t%SPL;\n";
1599 O << "\t.reg .b32 \t%SP;\n";
1600 O << "\t.reg .b32 \t%SPL;\n";
1604 // Go through all virtual registers to establish the mapping between the
1606 // register number and the per class virtual register number.
1607 // We use the per class virtual register number in the ptx output.
1608 unsigned int numVRs = MRI->getNumVirtRegs();
1609 for (unsigned i=0; i< numVRs; i++) {
1610 unsigned int vr = TRI->index2VirtReg(i);
1611 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1612 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[RC->getID()];
1613 int n = regmap.size();
1614 regmap.insert(std::make_pair(vr, n+1));
1617 // Emit register declarations
1618 // @TODO: Extract out the real register usage
1619 O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1620 O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1621 O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1622 O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1623 O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1624 O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1625 O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1627 // Emit declaration of the virtual registers or 'physical' registers for
1628 // each register class
1629 //for (unsigned i=0; i< numRegClasses; i++) {
1630 // std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[i];
1631 // const TargetRegisterClass *RC = TRI->getRegClass(i);
1632 // std::string rcname = getNVPTXRegClassName(RC);
1633 // std::string rcStr = getNVPTXRegClassStr(RC);
1634 // //int n = regmap.size();
1635 // if (!isNVPTXVectorRegClass(RC)) {
1636 // O << "\t.reg " << rcname << " \t" << rcStr << "<"
1637 // << NVPTXNumRegisters << ">;\n";
1640 // Only declare those registers that may be used. And do not emit vector
1642 // they are all elementized to scalar registers.
1643 //if (n && !isNVPTXVectorRegClass(RC)) {
1644 // if (RegAllocNilUsed) {
1645 // O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1649 // O << "\t.reg " << rcname << " \t" << StrToUpper(rcStr)
1650 // << "<" << 32 << ">;\n";
1655 OutStreamer.EmitRawText(O.str());
1659 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1660 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1662 unsigned int numHex;
1665 if (Fp->getType()->getTypeID()==Type::FloatTyID) {
1668 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1670 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1673 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1676 llvm_unreachable("unsupported fp type");
1678 APInt API = APF.bitcastToAPInt();
1679 std::string hexstr(utohexstr(API.getZExtValue()));
1681 if (hexstr.length() < numHex)
1682 O << std::string(numHex - hexstr.length(), '0');
1683 O << utohexstr(API.getZExtValue());
1686 void NVPTXAsmPrinter::printScalarConstant(Constant *CPV, raw_ostream &O) {
1687 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1688 O << CI->getValue();
1691 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1692 printFPConstant(CFP, O);
1695 if (isa<ConstantPointerNull>(CPV)) {
1699 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1700 O << *Mang->getSymbol(GVar);
1703 if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1704 Value *v = Cexpr->stripPointerCasts();
1705 if (GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1706 O << *Mang->getSymbol(GVar);
1709 O << *LowerConstant(CPV, *this);
1713 llvm_unreachable("Not scalar type found in printScalarConstant()");
1717 void NVPTXAsmPrinter::bufferLEByte(Constant *CPV, int Bytes,
1718 AggBuffer *aggBuffer) {
1720 const TargetData *TD = TM.getTargetData();
1722 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1723 int s = TD->getTypeAllocSize(CPV->getType());
1726 aggBuffer->addZeros(s);
1731 switch (CPV->getType()->getTypeID()) {
1733 case Type::IntegerTyID: {
1734 const Type *ETy = CPV->getType();
1735 if ( ETy == Type::getInt8Ty(CPV->getContext()) ){
1737 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1739 aggBuffer->addBytes(ptr, 1, Bytes);
1740 } else if ( ETy == Type::getInt16Ty(CPV->getContext()) ) {
1742 (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1743 ptr = (unsigned char*)&int16;
1744 aggBuffer->addBytes(ptr, 2, Bytes);
1745 } else if ( ETy == Type::getInt32Ty(CPV->getContext()) ) {
1746 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1747 int int32 =(int)(constInt->getZExtValue());
1748 ptr = (unsigned char*)&int32;
1749 aggBuffer->addBytes(ptr, 4, Bytes);
1751 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1752 if (ConstantInt *constInt =
1753 dyn_cast<ConstantInt>(ConstantFoldConstantExpression(
1755 int int32 =(int)(constInt->getZExtValue());
1756 ptr = (unsigned char*)&int32;
1757 aggBuffer->addBytes(ptr, 4, Bytes);
1760 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1761 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1762 aggBuffer->addSymbol(v);
1763 aggBuffer->addZeros(4);
1767 llvm_unreachable("unsupported integer const type");
1768 } else if (ETy == Type::getInt64Ty(CPV->getContext()) ) {
1769 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1770 long long int64 =(long long)(constInt->getZExtValue());
1771 ptr = (unsigned char*)&int64;
1772 aggBuffer->addBytes(ptr, 8, Bytes);
1774 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1775 if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1776 ConstantFoldConstantExpression(Cexpr, TD))) {
1777 long long int64 =(long long)(constInt->getZExtValue());
1778 ptr = (unsigned char*)&int64;
1779 aggBuffer->addBytes(ptr, 8, Bytes);
1782 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1783 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1784 aggBuffer->addSymbol(v);
1785 aggBuffer->addZeros(8);
1789 llvm_unreachable("unsupported integer const type");
1791 llvm_unreachable("unsupported integer const type");
1794 case Type::FloatTyID:
1795 case Type::DoubleTyID: {
1796 ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1797 const Type* Ty = CFP->getType();
1798 if (Ty == Type::getFloatTy(CPV->getContext())) {
1799 float float32 = (float)CFP->getValueAPF().convertToFloat();
1800 ptr = (unsigned char*)&float32;
1801 aggBuffer->addBytes(ptr, 4, Bytes);
1802 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1803 double float64 = CFP->getValueAPF().convertToDouble();
1804 ptr = (unsigned char*)&float64;
1805 aggBuffer->addBytes(ptr, 8, Bytes);
1808 llvm_unreachable("unsupported fp const type");
1812 case Type::PointerTyID: {
1813 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1814 aggBuffer->addSymbol(GVar);
1816 else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1817 Value *v = Cexpr->stripPointerCasts();
1818 aggBuffer->addSymbol(v);
1820 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1821 aggBuffer->addZeros(s);
1825 case Type::ArrayTyID:
1826 case Type::VectorTyID:
1827 case Type::StructTyID: {
1828 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1829 isa<ConstantStruct>(CPV)) {
1830 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1831 bufferAggregateConstant(CPV, aggBuffer);
1832 if ( Bytes > ElementSize )
1833 aggBuffer->addZeros(Bytes-ElementSize);
1835 else if (isa<ConstantAggregateZero>(CPV))
1836 aggBuffer->addZeros(Bytes);
1838 llvm_unreachable("Unexpected Constant type");
1843 llvm_unreachable("unsupported type");
1847 void NVPTXAsmPrinter::bufferAggregateConstant(Constant *CPV,
1848 AggBuffer *aggBuffer) {
1849 const TargetData *TD = TM.getTargetData();
1853 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1854 if (CPV->getNumOperands())
1855 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1856 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1860 if (const ConstantDataSequential *CDS =
1861 dyn_cast<ConstantDataSequential>(CPV)) {
1862 if (CDS->getNumElements())
1863 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1864 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1870 if (isa<ConstantStruct>(CPV)) {
1871 if (CPV->getNumOperands()) {
1872 StructType *ST = cast<StructType>(CPV->getType());
1873 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1875 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1876 TD->getTypeAllocSize(ST)
1877 - TD->getStructLayout(ST)->getElementOffset(i);
1879 Bytes = TD->getStructLayout(ST)->getElementOffset(i+1) -
1880 TD->getStructLayout(ST)->getElementOffset(i);
1881 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes,
1887 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1890 // buildTypeNameMap - Run through symbol table looking for type names.
1894 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1896 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1898 if (PI != TypeNameMap.end() &&
1899 (!PI->second.compare("struct._image1d_t") ||
1900 !PI->second.compare("struct._image2d_t") ||
1901 !PI->second.compare("struct._image3d_t")))
1907 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1909 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1910 unsigned AsmVariant,
1911 const char *ExtraCode,
1913 if (ExtraCode && ExtraCode[0]) {
1914 if (ExtraCode[1] != 0) return true; // Unknown modifier.
1916 switch (ExtraCode[0]) {
1917 default: return true; // Unknown modifier.
1923 printOperand(MI, OpNo, O);
1928 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1930 unsigned AsmVariant,
1931 const char *ExtraCode,
1933 if (ExtraCode && ExtraCode[0])
1934 return true; // Unknown modifier
1937 printMemOperand(MI, OpNo, O);
1943 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI)
1945 switch(MI.getOpcode()) {
1948 case NVPTX::CallArgBeginInst: case NVPTX::CallArgEndInst0:
1949 case NVPTX::CallArgEndInst1: case NVPTX::CallArgF32:
1950 case NVPTX::CallArgF64: case NVPTX::CallArgI16:
1951 case NVPTX::CallArgI32: case NVPTX::CallArgI32imm:
1952 case NVPTX::CallArgI64: case NVPTX::CallArgI8:
1953 case NVPTX::CallArgParam: case NVPTX::CallVoidInst:
1954 case NVPTX::CallVoidInstReg: case NVPTX::Callseq_End:
1955 case NVPTX::CallVoidInstReg64:
1956 case NVPTX::DeclareParamInst: case NVPTX::DeclareRetMemInst:
1957 case NVPTX::DeclareRetRegInst: case NVPTX::DeclareRetScalarInst:
1958 case NVPTX::DeclareScalarParamInst: case NVPTX::DeclareScalarRegInst:
1959 case NVPTX::StoreParamF32: case NVPTX::StoreParamF64:
1960 case NVPTX::StoreParamI16: case NVPTX::StoreParamI32:
1961 case NVPTX::StoreParamI64: case NVPTX::StoreParamI8:
1962 case NVPTX::StoreParamS32I8: case NVPTX::StoreParamU32I8:
1963 case NVPTX::StoreParamS32I16: case NVPTX::StoreParamU32I16:
1964 case NVPTX::StoreParamScalar2F32: case NVPTX::StoreParamScalar2F64:
1965 case NVPTX::StoreParamScalar2I16: case NVPTX::StoreParamScalar2I32:
1966 case NVPTX::StoreParamScalar2I64: case NVPTX::StoreParamScalar2I8:
1967 case NVPTX::StoreParamScalar4F32: case NVPTX::StoreParamScalar4I16:
1968 case NVPTX::StoreParamScalar4I32: case NVPTX::StoreParamScalar4I8:
1969 case NVPTX::StoreParamV2F32: case NVPTX::StoreParamV2F64:
1970 case NVPTX::StoreParamV2I16: case NVPTX::StoreParamV2I32:
1971 case NVPTX::StoreParamV2I64: case NVPTX::StoreParamV2I8:
1972 case NVPTX::StoreParamV4F32: case NVPTX::StoreParamV4I16:
1973 case NVPTX::StoreParamV4I32: case NVPTX::StoreParamV4I8:
1974 case NVPTX::StoreRetvalF32: case NVPTX::StoreRetvalF64:
1975 case NVPTX::StoreRetvalI16: case NVPTX::StoreRetvalI32:
1976 case NVPTX::StoreRetvalI64: case NVPTX::StoreRetvalI8:
1977 case NVPTX::StoreRetvalScalar2F32: case NVPTX::StoreRetvalScalar2F64:
1978 case NVPTX::StoreRetvalScalar2I16: case NVPTX::StoreRetvalScalar2I32:
1979 case NVPTX::StoreRetvalScalar2I64: case NVPTX::StoreRetvalScalar2I8:
1980 case NVPTX::StoreRetvalScalar4F32: case NVPTX::StoreRetvalScalar4I16:
1981 case NVPTX::StoreRetvalScalar4I32: case NVPTX::StoreRetvalScalar4I8:
1982 case NVPTX::StoreRetvalV2F32: case NVPTX::StoreRetvalV2F64:
1983 case NVPTX::StoreRetvalV2I16: case NVPTX::StoreRetvalV2I32:
1984 case NVPTX::StoreRetvalV2I64: case NVPTX::StoreRetvalV2I8:
1985 case NVPTX::StoreRetvalV4F32: case NVPTX::StoreRetvalV4I16:
1986 case NVPTX::StoreRetvalV4I32: case NVPTX::StoreRetvalV4I8:
1987 case NVPTX::LastCallArgF32: case NVPTX::LastCallArgF64:
1988 case NVPTX::LastCallArgI16: case NVPTX::LastCallArgI32:
1989 case NVPTX::LastCallArgI32imm: case NVPTX::LastCallArgI64:
1990 case NVPTX::LastCallArgI8: case NVPTX::LastCallArgParam:
1991 case NVPTX::LoadParamMemF32: case NVPTX::LoadParamMemF64:
1992 case NVPTX::LoadParamMemI16: case NVPTX::LoadParamMemI32:
1993 case NVPTX::LoadParamMemI64: case NVPTX::LoadParamMemI8:
1994 case NVPTX::LoadParamRegF32: case NVPTX::LoadParamRegF64:
1995 case NVPTX::LoadParamRegI16: case NVPTX::LoadParamRegI32:
1996 case NVPTX::LoadParamRegI64: case NVPTX::LoadParamRegI8:
1997 case NVPTX::LoadParamScalar2F32: case NVPTX::LoadParamScalar2F64:
1998 case NVPTX::LoadParamScalar2I16: case NVPTX::LoadParamScalar2I32:
1999 case NVPTX::LoadParamScalar2I64: case NVPTX::LoadParamScalar2I8:
2000 case NVPTX::LoadParamScalar4F32: case NVPTX::LoadParamScalar4I16:
2001 case NVPTX::LoadParamScalar4I32: case NVPTX::LoadParamScalar4I8:
2002 case NVPTX::LoadParamV2F32: case NVPTX::LoadParamV2F64:
2003 case NVPTX::LoadParamV2I16: case NVPTX::LoadParamV2I32:
2004 case NVPTX::LoadParamV2I64: case NVPTX::LoadParamV2I8:
2005 case NVPTX::LoadParamV4F32: case NVPTX::LoadParamV4I16:
2006 case NVPTX::LoadParamV4I32: case NVPTX::LoadParamV4I8:
2007 case NVPTX::PrototypeInst: case NVPTX::DBG_VALUE:
2013 // Force static initialization.
2014 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2015 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2016 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2020 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2021 std::stringstream temp;
2022 LineReader * reader = this->getReader(filename.str());
2024 temp << filename.str();
2028 temp << reader->readLine(line);
2030 this->OutStreamer.EmitRawText(Twine(temp.str()));
2034 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2035 if (reader == NULL) {
2036 reader = new LineReader(filename);
2039 if (reader->fileName() != filename) {
2041 reader = new LineReader(filename);
2049 LineReader::readLine(unsigned lineNum) {
2050 if (lineNum < theCurLine) {
2052 fstr.seekg(0,std::ios::beg);
2054 while (theCurLine < lineNum) {
2055 fstr.getline(buff,500);
2061 // Force static initialization.
2062 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2063 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2064 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);