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"
17 #include "NVPTXInstrInfo.h"
18 #include "NVPTXTargetMachine.h"
19 #include "NVPTXRegisterInfo.h"
20 #include "NVPTXUtilities.h"
21 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
22 #include "NVPTXNumRegisters.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/DebugInfo.h"
25 #include "llvm/Function.h"
26 #include "llvm/GlobalVariable.h"
27 #include "llvm/Module.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/MachineFrameInfo.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Target/Mangler.h"
35 #include "llvm/Target/TargetLoweringObjectFile.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/DerivedTypes.h"
40 #include "llvm/Support/TimeValue.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Assembly/Writer.h"
45 #include "cl_common_defines.h"
50 #include "NVPTXGenAsmWriter.inc"
52 bool RegAllocNilUsed = true;
54 #define DEPOTNAME "__local_depot"
57 EmitLineNumbers("nvptx-emit-line-numbers",
58 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
62 bool InterleaveSrcInPtx = false;
65 static cl::opt<bool, true>InterleaveSrc("nvptx-emit-src",
67 cl::desc("NVPTX Specific: Emit source line in ptx file"),
68 cl::location(llvm::InterleaveSrcInPtx));
73 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
74 // cannot just link to the existing version.
75 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
77 using namespace nvptx;
78 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
79 MCContext &Ctx = AP.OutContext;
81 if (CV->isNullValue() || isa<UndefValue>(CV))
82 return MCConstantExpr::Create(0, Ctx);
84 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
85 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
87 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
88 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
90 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
91 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
93 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
95 llvm_unreachable("Unknown constant value to lower!");
98 switch (CE->getOpcode()) {
100 // If the code isn't optimized, there may be outstanding folding
101 // opportunities. Attempt to fold the expression using DataLayout as a
102 // last resort before giving up.
104 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
106 return LowerConstant(C, AP);
108 // Otherwise report the problem to the user.
111 raw_string_ostream OS(S);
112 OS << "Unsupported expression in static initializer: ";
113 WriteAsOperand(OS, CE, /*PrintType=*/false,
114 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
115 report_fatal_error(OS.str());
117 case Instruction::GetElementPtr: {
118 const DataLayout &TD = *AP.TM.getDataLayout();
119 // Generate a symbolic expression for the byte address
120 const Constant *PtrVal = CE->getOperand(0);
121 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
122 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
124 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
128 // Truncate/sext the offset to the pointer size.
129 unsigned AS = PtrVal->getType()->isPointerTy() ?
130 cast<PointerType>(PtrVal->getType())->getAddressSpace() : 0;
131 if (TD.getPointerSizeInBits(AS) != 64) {
132 int SExtAmount = 64-TD.getPointerSizeInBits(AS);
133 Offset = (Offset << SExtAmount) >> SExtAmount;
136 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
140 case Instruction::Trunc:
141 // We emit the value and depend on the assembler to truncate the generated
142 // expression properly. This is important for differences between
143 // blockaddress labels. Since the two labels are in the same function, it
144 // is reasonable to treat their delta as a 32-bit value.
146 case Instruction::BitCast:
147 return LowerConstant(CE->getOperand(0), AP);
149 case Instruction::IntToPtr: {
150 const DataLayout &TD = *AP.TM.getDataLayout();
151 // Handle casts to pointers by changing them into casts to the appropriate
152 // integer type. This promotes constant folding and simplifies this code.
153 Constant *Op = CE->getOperand(0);
154 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
156 return LowerConstant(Op, AP);
159 case Instruction::PtrToInt: {
160 const DataLayout &TD = *AP.TM.getDataLayout();
161 // Support only foldable casts to/from pointers that can be eliminated by
162 // changing the pointer to the appropriately sized integer type.
163 Constant *Op = CE->getOperand(0);
164 Type *Ty = CE->getType();
166 const MCExpr *OpExpr = LowerConstant(Op, AP);
168 // We can emit the pointer value into this slot if the slot is an
169 // integer slot equal to the size of the pointer.
170 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
173 // Otherwise the pointer is smaller than the resultant integer, mask off
174 // the high bits so we are sure to get a proper truncation if the input is
176 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
177 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
178 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
181 // The MC library also has a right-shift operator, but it isn't consistently
182 // signed or unsigned between different targets.
183 case Instruction::Add:
184 case Instruction::Sub:
185 case Instruction::Mul:
186 case Instruction::SDiv:
187 case Instruction::SRem:
188 case Instruction::Shl:
189 case Instruction::And:
190 case Instruction::Or:
191 case Instruction::Xor: {
192 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
193 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
194 switch (CE->getOpcode()) {
195 default: llvm_unreachable("Unknown binary operator constant cast expr");
196 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
197 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
198 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
199 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
200 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
201 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
202 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
203 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
204 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
211 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI)
213 if (!EmitLineNumbers)
218 DebugLoc curLoc = MI.getDebugLoc();
220 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
223 if (prevDebugLoc == curLoc)
226 prevDebugLoc = curLoc;
228 if (curLoc.isUnknown())
232 const MachineFunction *MF = MI.getParent()->getParent();
233 //const TargetMachine &TM = MF->getTarget();
235 const LLVMContext &ctx = MF->getFunction()->getContext();
236 DIScope Scope(curLoc.getScope(ctx));
241 StringRef fileName(Scope.getFilename());
242 StringRef dirName(Scope.getDirectory());
243 SmallString<128> FullPathName = dirName;
244 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
245 sys::path::append(FullPathName, fileName);
246 fileName = FullPathName.str();
249 if (filenameMap.find(fileName.str()) == filenameMap.end())
253 // Emit the line from the source file.
254 if (llvm::InterleaveSrcInPtx)
255 this->emitSrcInText(fileName.str(), curLoc.getLine());
257 std::stringstream temp;
258 temp << "\t.loc " << filenameMap[fileName.str()]
259 << " " << curLoc.getLine() << " " << curLoc.getCol();
260 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
263 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
264 SmallString<128> Str;
265 raw_svector_ostream OS(Str);
266 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
267 emitLineNumberAsDotLoc(*MI);
268 printInstruction(MI, OS);
269 OutStreamer.EmitRawText(OS.str());
272 void NVPTXAsmPrinter::printReturnValStr(const Function *F,
275 const DataLayout *TD = TM.getDataLayout();
276 const TargetLowering *TLI = TM.getTargetLowering();
278 Type *Ty = F->getReturnType();
280 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
282 if (Ty->getTypeID() == Type::VoidTyID)
288 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
290 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
291 size = ITy->getBitWidth();
292 if (size < 32) size = 32;
294 assert(Ty->isFloatingPointTy() &&
295 "Floating point type expected here");
296 size = Ty->getPrimitiveSizeInBits();
299 O << ".param .b" << size << " func_retval0";
301 else if (isa<PointerType>(Ty)) {
302 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
305 if ((Ty->getTypeID() == Type::StructTyID) ||
306 isa<VectorType>(Ty)) {
307 SmallVector<EVT, 16> vtparts;
308 ComputeValueVTs(*TLI, Ty, vtparts);
309 unsigned totalsz = 0;
310 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
312 EVT elemtype = vtparts[i];
313 if (vtparts[i].isVector()) {
314 elems = vtparts[i].getVectorNumElements();
315 elemtype = vtparts[i].getVectorElementType();
317 for (unsigned j=0, je=elems; j!=je; ++j) {
318 unsigned sz = elemtype.getSizeInBits();
319 if (elemtype.isInteger() && (sz < 8)) sz = 8;
323 unsigned retAlignment = 0;
324 if (!llvm::getAlign(*F, 0, retAlignment))
325 retAlignment = TD->getABITypeAlignment(Ty);
326 O << ".param .align "
328 << " .b8 func_retval0["
332 "Unknown return type");
335 SmallVector<EVT, 16> vtparts;
336 ComputeValueVTs(*TLI, Ty, vtparts);
338 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
340 EVT elemtype = vtparts[i];
341 if (vtparts[i].isVector()) {
342 elems = vtparts[i].getVectorNumElements();
343 elemtype = vtparts[i].getVectorElementType();
346 for (unsigned j=0, je=elems; j!=je; ++j) {
347 unsigned sz = elemtype.getSizeInBits();
348 if (elemtype.isInteger() && (sz < 32)) sz = 32;
349 O << ".reg .b" << sz << " func_retval" << idx;
350 if (j<je-1) O << ", ";
361 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
363 const Function *F = MF.getFunction();
364 printReturnValStr(F, O);
367 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
368 SmallString<128> Str;
369 raw_svector_ostream O(Str);
372 MRI = &MF->getRegInfo();
373 F = MF->getFunction();
374 emitLinkageDirective(F,O);
375 if (llvm::isKernelFunction(*F))
379 printReturnValStr(*MF, O);
384 emitFunctionParamList(*MF, O);
386 if (llvm::isKernelFunction(*F))
387 emitKernelFunctionDirectives(*F, O);
389 OutStreamer.EmitRawText(O.str());
391 prevDebugLoc = DebugLoc();
394 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
395 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
396 unsigned numRegClasses = TRI.getNumRegClasses();
397 VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses+1];
398 OutStreamer.EmitRawText(StringRef("{\n"));
399 setAndEmitFunctionVirtualRegisters(*MF);
401 SmallString<128> Str;
402 raw_svector_ostream O(Str);
403 emitDemotedVars(MF->getFunction(), O);
404 OutStreamer.EmitRawText(O.str());
407 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
408 OutStreamer.EmitRawText(StringRef("}\n"));
409 delete []VRidGlobal2LocalMap;
414 NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function& F,
415 raw_ostream &O) const {
416 // If the NVVM IR has some of reqntid* specified, then output
417 // the reqntid directive, and set the unspecified ones to 1.
418 // If none of reqntid* is specified, don't output reqntid directive.
419 unsigned reqntidx, reqntidy, reqntidz;
420 bool specified = false;
421 if (llvm::getReqNTIDx(F, reqntidx) == false) reqntidx = 1;
422 else specified = true;
423 if (llvm::getReqNTIDy(F, reqntidy) == false) reqntidy = 1;
424 else specified = true;
425 if (llvm::getReqNTIDz(F, reqntidz) == false) reqntidz = 1;
426 else specified = true;
429 O << ".reqntid " << reqntidx << ", "
430 << reqntidy << ", " << reqntidz << "\n";
432 // If the NVVM IR has some of maxntid* specified, then output
433 // the maxntid directive, and set the unspecified ones to 1.
434 // If none of maxntid* is specified, don't output maxntid directive.
435 unsigned maxntidx, maxntidy, maxntidz;
437 if (llvm::getMaxNTIDx(F, maxntidx) == false) maxntidx = 1;
438 else specified = true;
439 if (llvm::getMaxNTIDy(F, maxntidy) == false) maxntidy = 1;
440 else specified = true;
441 if (llvm::getMaxNTIDz(F, maxntidz) == false) maxntidz = 1;
442 else specified = true;
445 O << ".maxntid " << maxntidx << ", "
446 << maxntidy << ", " << maxntidz << "\n";
449 if (llvm::getMinCTASm(F, mincta))
450 O << ".minnctapersm " << mincta << "\n";
454 NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
456 const TargetRegisterClass * RC = MRI->getRegClass(vr);
457 unsigned id = RC->getID();
459 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[id];
460 unsigned mapped_vr = regmap[vr];
463 O << getNVPTXRegClassStr(RC) << mapped_vr;
466 // Vector virtual register
467 if (getNVPTXVectorSize(RC) == 4)
469 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
470 << getNVPTXRegClassStr(RC) << mapped_vr << "_1, "
471 << getNVPTXRegClassStr(RC) << mapped_vr << "_2, "
472 << getNVPTXRegClassStr(RC) << mapped_vr << "_3"
474 else if (getNVPTXVectorSize(RC) == 2)
476 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
477 << getNVPTXRegClassStr(RC) << mapped_vr << "_1"
480 llvm_unreachable("Unsupported vector size");
484 NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
486 getVirtualRegisterName(vr, isVec, O);
489 void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
490 const char *Modifier,
492 static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
493 int Imm = (int)MO.getImm();
494 if(0 == strcmp(Modifier, "vecelem"))
495 O << "_" << vecelem[Imm];
496 else if(0 == strcmp(Modifier, "vecv4comm1")) {
497 if((Imm < 0) || (Imm > 3))
500 else if(0 == strcmp(Modifier, "vecv4comm2")) {
501 if((Imm < 4) || (Imm > 7))
504 else if(0 == strcmp(Modifier, "vecv4pos")) {
506 O << "_" << vecelem[Imm%4];
508 else if(0 == strcmp(Modifier, "vecv2comm1")) {
509 if((Imm < 0) || (Imm > 1))
512 else if(0 == strcmp(Modifier, "vecv2comm2")) {
513 if((Imm < 2) || (Imm > 3))
516 else if(0 == strcmp(Modifier, "vecv2pos")) {
518 O << "_" << vecelem[Imm%2];
521 llvm_unreachable("Unknown Modifier on immediate operand");
524 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
525 raw_ostream &O, const char *Modifier) {
526 const MachineOperand &MO = MI->getOperand(opNum);
527 switch (MO.getType()) {
528 case MachineOperand::MO_Register:
529 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
530 if (MO.getReg() == NVPTX::VRDepot)
531 O << DEPOTNAME << getFunctionNumber();
533 O << getRegisterName(MO.getReg());
536 emitVirtualRegister(MO.getReg(), false, O);
538 if (strcmp(Modifier, "vecfull") == 0)
539 emitVirtualRegister(MO.getReg(), true, O);
542 "Don't know how to handle the modifier on virtual register.");
547 case MachineOperand::MO_Immediate:
550 else if (strstr(Modifier, "vec") == Modifier)
551 printVecModifiedImmediate(MO, Modifier, O);
553 llvm_unreachable("Don't know how to handle modifier on immediate operand");
556 case MachineOperand::MO_FPImmediate:
557 printFPConstant(MO.getFPImm(), O);
560 case MachineOperand::MO_GlobalAddress:
561 O << *Mang->getSymbol(MO.getGlobal());
564 case MachineOperand::MO_ExternalSymbol: {
565 const char * symbname = MO.getSymbolName();
566 if (strstr(symbname, ".PARAM") == symbname) {
568 sscanf(symbname+6, "%u[];", &index);
569 printParamName(index, O);
571 else if (strstr(symbname, ".HLPPARAM") == symbname) {
573 sscanf(symbname+9, "%u[];", &index);
574 O << *CurrentFnSym << "_param_" << index << "_offset";
581 case MachineOperand::MO_MachineBasicBlock:
582 O << *MO.getMBB()->getSymbol();
586 llvm_unreachable("Operand type not supported.");
590 void NVPTXAsmPrinter::
591 printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
593 O << "\t// Implicit def :";
594 //printOperand(MI, 0);
599 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
600 raw_ostream &O, const char *Modifier) {
601 printOperand(MI, opNum, O);
603 if (Modifier && !strcmp(Modifier, "add")) {
605 printOperand(MI, opNum+1, O);
607 if (MI->getOperand(opNum+1).isImm() &&
608 MI->getOperand(opNum+1).getImm() == 0)
609 return; // don't print ',0' or '+0'
611 printOperand(MI, opNum+1, O);
615 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
616 raw_ostream &O, const char *Modifier)
619 const MachineOperand &MO = MI->getOperand(opNum);
620 int Imm = (int)MO.getImm();
621 if (!strcmp(Modifier, "volatile")) {
624 } else if (!strcmp(Modifier, "addsp")) {
626 case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
627 case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
628 case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
629 case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
630 case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
631 case NVPTX::PTXLdStInstCode::GENERIC:
632 if (!nvptxSubtarget.hasGenericLdSt())
636 assert("wrong value");
639 else if (!strcmp(Modifier, "sign")) {
640 if (Imm==NVPTX::PTXLdStInstCode::Signed)
642 else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
647 else if (!strcmp(Modifier, "vec")) {
648 if (Imm==NVPTX::PTXLdStInstCode::V2)
650 else if (Imm==NVPTX::PTXLdStInstCode::V4)
654 assert("unknown modifier");
657 assert("unknown modifier");
660 void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
662 emitLinkageDirective(F,O);
663 if (llvm::isKernelFunction(*F))
667 printReturnValStr(F, O);
668 O << *CurrentFnSym << "\n";
669 emitFunctionParamList(F, O);
673 static bool usedInGlobalVarDef(const Constant *C)
678 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
679 if (GV->getName().str() == "llvm.used")
684 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
686 const Constant *C = dyn_cast<Constant>(*ui);
687 if (usedInGlobalVarDef(C))
693 static bool usedInOneFunc(const User *U, Function const *&oneFunc)
695 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
696 if (othergv->getName().str() == "llvm.used")
700 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
701 if (instr->getParent() && instr->getParent()->getParent()) {
702 const Function *curFunc = instr->getParent()->getParent();
703 if (oneFunc && (curFunc != oneFunc))
712 if (const MDNode *md = dyn_cast<MDNode>(U))
713 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
714 (md->getName().str() == "llvm.dbg.sp")))
718 for (User::const_use_iterator ui=U->use_begin(), ue=U->use_end();
720 if (usedInOneFunc(*ui, oneFunc) == false)
726 /* Find out if a global variable can be demoted to local scope.
727 * Currently, this is valid for CUDA shared variables, which have local
728 * scope and global lifetime. So the conditions to check are :
729 * 1. Is the global variable in shared address space?
730 * 2. Does it have internal linkage?
731 * 3. Is the global variable referenced only in one function?
733 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
734 if (gv->hasInternalLinkage() == false)
736 const PointerType *Pty = gv->getType();
737 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
740 const Function *oneFunc = 0;
742 bool flag = usedInOneFunc(gv, oneFunc);
751 static bool useFuncSeen(const Constant *C,
752 llvm::DenseMap<const Function *, bool> &seenMap) {
753 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
755 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
756 if (useFuncSeen(cu, seenMap))
758 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
759 const BasicBlock *bb = I->getParent();
761 const Function *caller = bb->getParent();
762 if (!caller) continue;
763 if (seenMap.find(caller) != seenMap.end())
770 void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
771 llvm::DenseMap<const Function *, bool> seenMap;
772 for (Module::const_iterator FI=M.begin(), FE=M.end();
774 const Function *F = FI;
776 if (F->isDeclaration()) {
779 if (F->getIntrinsicID())
781 CurrentFnSym = Mang->getSymbol(F);
782 emitDeclaration(F, O);
785 for (Value::const_use_iterator iter=F->use_begin(),
786 iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
787 if (const Constant *C = dyn_cast<Constant>(*iter)) {
788 if (usedInGlobalVarDef(C)) {
789 // The use is in the initialization of a global variable
790 // that is a function pointer, so print a declaration
791 // for the original function
792 CurrentFnSym = Mang->getSymbol(F);
793 emitDeclaration(F, O);
796 // Emit a declaration of this function if the function that
797 // uses this constant expr has already been seen.
798 if (useFuncSeen(C, seenMap)) {
799 CurrentFnSym = Mang->getSymbol(F);
800 emitDeclaration(F, O);
805 if (!isa<Instruction>(*iter)) continue;
806 const Instruction *instr = cast<Instruction>(*iter);
807 const BasicBlock *bb = instr->getParent();
809 const Function *caller = bb->getParent();
810 if (!caller) continue;
812 // If a caller has already been seen, then the caller is
813 // appearing in the module before the callee. so print out
814 // a declaration for the callee.
815 if (seenMap.find(caller) != seenMap.end()) {
816 CurrentFnSym = Mang->getSymbol(F);
817 emitDeclaration(F, O);
825 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
826 DebugInfoFinder DbgFinder;
827 DbgFinder.processModule(M);
830 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
831 E = DbgFinder.compile_unit_end(); I != E; ++I) {
832 DICompileUnit DIUnit(*I);
833 StringRef Filename(DIUnit.getFilename());
834 StringRef Dirname(DIUnit.getDirectory());
835 SmallString<128> FullPathName = Dirname;
836 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
837 sys::path::append(FullPathName, Filename);
838 Filename = FullPathName.str();
840 if (filenameMap.find(Filename.str()) != filenameMap.end())
842 filenameMap[Filename.str()] = i;
843 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
847 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
848 E = DbgFinder.subprogram_end(); I != E; ++I) {
850 StringRef Filename(SP.getFilename());
851 StringRef Dirname(SP.getDirectory());
852 SmallString<128> FullPathName = Dirname;
853 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
854 sys::path::append(FullPathName, Filename);
855 Filename = FullPathName.str();
857 if (filenameMap.find(Filename.str()) != filenameMap.end())
859 filenameMap[Filename.str()] = i;
864 bool NVPTXAsmPrinter::doInitialization (Module &M) {
866 SmallString<128> Str1;
867 raw_svector_ostream OS1(Str1);
869 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
870 MMI->AnalyzeModule(M);
872 // We need to call the parent's one explicitly.
873 //bool Result = AsmPrinter::doInitialization(M);
875 // Initialize TargetLoweringObjectFile.
876 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
877 .Initialize(OutContext, TM);
879 Mang = new Mangler(OutContext, *TM.getDataLayout());
881 // Emit header before any dwarf directives are emitted below.
883 OutStreamer.EmitRawText(OS1.str());
886 // Already commented out
887 //bool Result = AsmPrinter::doInitialization(M);
890 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
891 recordAndEmitFilenames(M);
893 SmallString<128> Str2;
894 raw_svector_ostream OS2(Str2);
896 emitDeclarations(M, OS2);
898 // Print out module-level global variables here.
899 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
901 printModuleLevelGV(I, OS2);
905 OutStreamer.EmitRawText(OS2.str());
906 return false; // success
909 void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
911 O << "// Generated by LLVM NVPTX Back-End\n";
915 O << ".version 3.0\n";
918 O << nvptxSubtarget.getTargetName();
920 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
921 O << ", texmode_independent";
922 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
923 if (!nvptxSubtarget.hasDouble())
924 O << ", map_f64_to_f32";
927 if (MAI->doesSupportDebugInformation())
932 O << ".address_size ";
933 if (nvptxSubtarget.is64Bit())
942 bool NVPTXAsmPrinter::doFinalization(Module &M) {
943 // XXX Temproarily remove global variables so that doFinalization() will not
944 // emit them again (global variables are emitted at beginning).
946 Module::GlobalListType &global_list = M.getGlobalList();
947 int i, n = global_list.size();
948 GlobalVariable **gv_array = new GlobalVariable* [n];
950 // first, back-up GlobalVariable in gv_array
952 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
956 // second, empty global_list
957 while (!global_list.empty())
958 global_list.remove(global_list.begin());
960 // call doFinalization
961 bool ret = AsmPrinter::doFinalization(M);
963 // now we restore global variables
964 for (i = 0; i < n; i ++)
965 global_list.insert(global_list.end(), gv_array[i]);
971 //bool Result = AsmPrinter::doFinalization(M);
972 // Instead of calling the parents doFinalization, we may
973 // clone parents doFinalization and customize here.
974 // Currently, we if NVISA out the EmitGlobals() in
975 // parent's doFinalization, which is too intrusive.
977 // Same for the doInitialization.
981 // This function emits appropriate linkage directives for
982 // functions and global variables.
984 // extern function declaration -> .extern
985 // extern function definition -> .visible
986 // external global variable with init -> .visible
987 // external without init -> .extern
988 // appending -> not allowed, assert.
990 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
992 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
993 if (V->hasExternalLinkage()) {
994 if (isa<GlobalVariable>(V)) {
995 const GlobalVariable *GVar = cast<GlobalVariable>(V);
997 if (GVar->hasInitializer())
1002 } else if (V->isDeclaration())
1006 } else if (V->hasAppendingLinkage()) {
1008 msg.append("Error: ");
1009 msg.append("Symbol ");
1011 msg.append(V->getName().str());
1012 msg.append("has unsupported appending linkage type");
1013 llvm_unreachable(msg.c_str());
1019 void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1020 bool processDemoted) {
1023 if (GVar->hasSection()) {
1024 if (GVar->getSection() == "llvm.metadata")
1028 const DataLayout *TD = TM.getDataLayout();
1030 // GlobalVariables are always constant pointers themselves.
1031 const PointerType *PTy = GVar->getType();
1032 Type *ETy = PTy->getElementType();
1034 if (GVar->hasExternalLinkage()) {
1035 if (GVar->hasInitializer())
1041 if (llvm::isTexture(*GVar)) {
1042 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1046 if (llvm::isSurface(*GVar)) {
1047 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1051 if (GVar->isDeclaration()) {
1052 // (extern) declarations, no definition or initializer
1053 // Currently the only known declaration is for an automatic __local
1054 // (.shared) promoted to global.
1055 emitPTXGlobalVariable(GVar, O);
1060 if (llvm::isSampler(*GVar)) {
1061 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1063 Constant *Initializer = NULL;
1064 if (GVar->hasInitializer())
1065 Initializer = GVar->getInitializer();
1066 ConstantInt *CI = NULL;
1068 CI = dyn_cast<ConstantInt>(Initializer);
1070 unsigned sample=CI->getZExtValue();
1074 for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1075 __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1076 O << "addr_mode_" << i << " = ";
1078 case 0: O << "wrap"; break;
1079 case 1: O << "clamp_to_border"; break;
1080 case 2: O << "clamp_to_edge"; break;
1081 case 3: O << "wrap"; break;
1082 case 4: O << "mirror"; break;
1086 O << "filter_mode = ";
1087 switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1088 case 0: O << "nearest"; break;
1089 case 1: O << "linear"; break;
1090 case 2: assert ( 0 && "Anisotropic filtering is not supported");
1091 default: O << "nearest"; break;
1093 if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1094 O << ", force_unnormalized_coords = 1";
1103 if (GVar->hasPrivateLinkage()) {
1105 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1108 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1109 if (!strncmp(GVar->getName().data(), "filename", 8))
1111 if (GVar->use_empty())
1115 const Function *demotedFunc = 0;
1116 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1117 O << "// " << GVar->getName().str() << " has been demoted\n";
1118 if (localDecls.find(demotedFunc) != localDecls.end())
1119 localDecls[demotedFunc].push_back(GVar);
1121 std::vector<GlobalVariable *> temp;
1122 temp.push_back(GVar);
1123 localDecls[demotedFunc] = temp;
1129 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1130 if (GVar->getAlignment() == 0)
1131 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1133 O << " .align " << GVar->getAlignment();
1136 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1138 O << getPTXFundamentalTypeStr(ETy, false);
1140 O << *Mang->getSymbol(GVar);
1142 // Ptx allows variable initilization only for constant and global state
1144 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1145 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1146 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1147 && GVar->hasInitializer()) {
1148 Constant *Initializer = GVar->getInitializer();
1149 if (!Initializer->isNullValue()) {
1151 printScalarConstant(Initializer, O);
1155 unsigned int ElementSize =0;
1157 // Although PTX has direct support for struct type and array type and
1158 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1159 // targets that support these high level field accesses. Structs, arrays
1160 // and vectors are lowered into arrays of bytes.
1161 switch (ETy->getTypeID()) {
1162 case Type::StructTyID:
1163 case Type::ArrayTyID:
1164 case Type::VectorTyID:
1165 ElementSize = TD->getTypeStoreSize(ETy);
1166 // Ptx allows variable initilization only for constant and
1167 // global state spaces.
1168 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1169 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1170 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1171 && GVar->hasInitializer()) {
1172 Constant *Initializer = GVar->getInitializer();
1173 if (!isa<UndefValue>(Initializer) &&
1174 !Initializer->isNullValue()) {
1175 AggBuffer aggBuffer(ElementSize, O, *this);
1176 bufferAggregateConstant(Initializer, &aggBuffer);
1177 if (aggBuffer.numSymbols) {
1178 if (nvptxSubtarget.is64Bit()) {
1179 O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1183 O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1189 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1198 O << " .b8 " << *Mang->getSymbol(GVar) ;
1207 O << " .b8 " << *Mang->getSymbol(GVar);
1216 assert( 0 && "type not supported yet");
1223 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1224 if (localDecls.find(f) == localDecls.end())
1227 std::vector<GlobalVariable *> &gvars = localDecls[f];
1229 for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1230 O << "\t// demoted variable\n\t";
1231 printModuleLevelGV(gvars[i], O, true);
1235 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1236 raw_ostream &O) const {
1237 switch (AddressSpace) {
1238 case llvm::ADDRESS_SPACE_LOCAL:
1241 case llvm::ADDRESS_SPACE_GLOBAL:
1244 case llvm::ADDRESS_SPACE_CONST:
1245 // This logic should be consistent with that in
1246 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1247 if (nvptxSubtarget.hasGenericLdSt())
1252 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1255 case llvm::ADDRESS_SPACE_SHARED:
1259 llvm_unreachable("unexpected address space");
1263 std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1264 bool useB4PTR) const {
1265 switch (Ty->getTypeID()) {
1267 llvm_unreachable("unexpected type");
1269 case Type::IntegerTyID: {
1270 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1273 else if (NumBits <= 64) {
1274 std::string name = "u";
1275 return name + utostr(NumBits);
1277 llvm_unreachable("Integer too large");
1282 case Type::FloatTyID:
1284 case Type::DoubleTyID:
1286 case Type::PointerTyID:
1287 if (nvptxSubtarget.is64Bit())
1288 if (useB4PTR) return "b64";
1291 if (useB4PTR) return "b32";
1294 llvm_unreachable("unexpected type");
1298 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1301 const DataLayout *TD = TM.getDataLayout();
1303 // GlobalVariables are always constant pointers themselves.
1304 const PointerType *PTy = GVar->getType();
1305 Type *ETy = PTy->getElementType();
1308 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1309 if (GVar->getAlignment() == 0)
1310 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1312 O << " .align " << GVar->getAlignment();
1314 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1316 O << getPTXFundamentalTypeStr(ETy);
1318 O << *Mang->getSymbol(GVar);
1322 int64_t ElementSize =0;
1324 // Although PTX has direct support for struct type and array type and LLVM IR
1325 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1326 // support these high level field accesses. Structs and arrays are lowered
1327 // into arrays of bytes.
1328 switch (ETy->getTypeID()) {
1329 case Type::StructTyID:
1330 case Type::ArrayTyID:
1331 case Type::VectorTyID:
1332 ElementSize = TD->getTypeStoreSize(ETy);
1333 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1335 O << itostr(ElementSize) ;
1340 assert( 0 && "type not supported yet");
1347 getOpenCLAlignment(const DataLayout *TD,
1349 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1350 return TD->getPrefTypeAlignment(Ty);
1352 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1354 return getOpenCLAlignment(TD, ATy->getElementType());
1356 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1358 Type *ETy = VTy->getElementType();
1359 unsigned int numE = VTy->getNumElements();
1360 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1367 const StructType *STy = dyn_cast<StructType>(Ty);
1369 unsigned int alignStruct = 1;
1370 // Go through each element of the struct and find the
1371 // largest alignment.
1372 for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1373 Type *ETy = STy->getElementType(i);
1374 unsigned int align = getOpenCLAlignment(TD, ETy);
1375 if (align > alignStruct)
1376 alignStruct = align;
1381 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1383 return TD->getPointerPrefAlignment(0);
1384 return TD->getPrefTypeAlignment(Ty);
1387 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1388 int paramIndex, raw_ostream &O) {
1389 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1390 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1391 O << *CurrentFnSym << "_param_" << paramIndex;
1393 std::string argName = I->getName();
1394 const char *p = argName.c_str();
1405 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1406 Function::const_arg_iterator I, E;
1409 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1410 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1411 O << *CurrentFnSym << "_param_" << paramIndex;
1415 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1416 if (i==paramIndex) {
1417 printParamName(I, paramIndex, O);
1421 llvm_unreachable("paramIndex out of bound");
1424 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1426 const DataLayout *TD = TM.getDataLayout();
1427 const AttrListPtr &PAL = F->getAttributes();
1428 const TargetLowering *TLI = TM.getTargetLowering();
1429 Function::const_arg_iterator I, E;
1430 unsigned paramIndex = 0;
1432 bool isKernelFunc = llvm::isKernelFunction(*F);
1433 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1434 MVT thePointerTy = TLI->getPointerTy();
1438 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1439 const Type *Ty = I->getType();
1446 // Handle image/sampler parameters
1447 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1448 if (llvm::isImage(*I)) {
1449 std::string sname = I->getName();
1450 if (llvm::isImageWriteOnly(*I))
1451 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1452 else // Default image is read_only
1453 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1455 else // Should be llvm::isSampler(*I)
1456 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1461 if (PAL.getParamAttributes(paramIndex+1).
1462 hasAttribute(Attributes::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 DataLayout *TD = TM.getDataLayout();
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 DataLayout *TD = TM.getDataLayout();
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]) {
1918 // See if this is a generic print operand
1919 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
1925 printOperand(MI, OpNo, O);
1930 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1932 unsigned AsmVariant,
1933 const char *ExtraCode,
1935 if (ExtraCode && ExtraCode[0])
1936 return true; // Unknown modifier
1939 printMemOperand(MI, OpNo, O);
1945 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI)
1947 switch(MI.getOpcode()) {
1950 case NVPTX::CallArgBeginInst: case NVPTX::CallArgEndInst0:
1951 case NVPTX::CallArgEndInst1: case NVPTX::CallArgF32:
1952 case NVPTX::CallArgF64: case NVPTX::CallArgI16:
1953 case NVPTX::CallArgI32: case NVPTX::CallArgI32imm:
1954 case NVPTX::CallArgI64: case NVPTX::CallArgI8:
1955 case NVPTX::CallArgParam: case NVPTX::CallVoidInst:
1956 case NVPTX::CallVoidInstReg: case NVPTX::Callseq_End:
1957 case NVPTX::CallVoidInstReg64:
1958 case NVPTX::DeclareParamInst: case NVPTX::DeclareRetMemInst:
1959 case NVPTX::DeclareRetRegInst: case NVPTX::DeclareRetScalarInst:
1960 case NVPTX::DeclareScalarParamInst: case NVPTX::DeclareScalarRegInst:
1961 case NVPTX::StoreParamF32: case NVPTX::StoreParamF64:
1962 case NVPTX::StoreParamI16: case NVPTX::StoreParamI32:
1963 case NVPTX::StoreParamI64: case NVPTX::StoreParamI8:
1964 case NVPTX::StoreParamS32I8: case NVPTX::StoreParamU32I8:
1965 case NVPTX::StoreParamS32I16: case NVPTX::StoreParamU32I16:
1966 case NVPTX::StoreParamScalar2F32: case NVPTX::StoreParamScalar2F64:
1967 case NVPTX::StoreParamScalar2I16: case NVPTX::StoreParamScalar2I32:
1968 case NVPTX::StoreParamScalar2I64: case NVPTX::StoreParamScalar2I8:
1969 case NVPTX::StoreParamScalar4F32: case NVPTX::StoreParamScalar4I16:
1970 case NVPTX::StoreParamScalar4I32: case NVPTX::StoreParamScalar4I8:
1971 case NVPTX::StoreParamV2F32: case NVPTX::StoreParamV2F64:
1972 case NVPTX::StoreParamV2I16: case NVPTX::StoreParamV2I32:
1973 case NVPTX::StoreParamV2I64: case NVPTX::StoreParamV2I8:
1974 case NVPTX::StoreParamV4F32: case NVPTX::StoreParamV4I16:
1975 case NVPTX::StoreParamV4I32: case NVPTX::StoreParamV4I8:
1976 case NVPTX::StoreRetvalF32: case NVPTX::StoreRetvalF64:
1977 case NVPTX::StoreRetvalI16: case NVPTX::StoreRetvalI32:
1978 case NVPTX::StoreRetvalI64: case NVPTX::StoreRetvalI8:
1979 case NVPTX::StoreRetvalScalar2F32: case NVPTX::StoreRetvalScalar2F64:
1980 case NVPTX::StoreRetvalScalar2I16: case NVPTX::StoreRetvalScalar2I32:
1981 case NVPTX::StoreRetvalScalar2I64: case NVPTX::StoreRetvalScalar2I8:
1982 case NVPTX::StoreRetvalScalar4F32: case NVPTX::StoreRetvalScalar4I16:
1983 case NVPTX::StoreRetvalScalar4I32: case NVPTX::StoreRetvalScalar4I8:
1984 case NVPTX::StoreRetvalV2F32: case NVPTX::StoreRetvalV2F64:
1985 case NVPTX::StoreRetvalV2I16: case NVPTX::StoreRetvalV2I32:
1986 case NVPTX::StoreRetvalV2I64: case NVPTX::StoreRetvalV2I8:
1987 case NVPTX::StoreRetvalV4F32: case NVPTX::StoreRetvalV4I16:
1988 case NVPTX::StoreRetvalV4I32: case NVPTX::StoreRetvalV4I8:
1989 case NVPTX::LastCallArgF32: case NVPTX::LastCallArgF64:
1990 case NVPTX::LastCallArgI16: case NVPTX::LastCallArgI32:
1991 case NVPTX::LastCallArgI32imm: case NVPTX::LastCallArgI64:
1992 case NVPTX::LastCallArgI8: case NVPTX::LastCallArgParam:
1993 case NVPTX::LoadParamMemF32: case NVPTX::LoadParamMemF64:
1994 case NVPTX::LoadParamMemI16: case NVPTX::LoadParamMemI32:
1995 case NVPTX::LoadParamMemI64: case NVPTX::LoadParamMemI8:
1996 case NVPTX::LoadParamRegF32: case NVPTX::LoadParamRegF64:
1997 case NVPTX::LoadParamRegI16: case NVPTX::LoadParamRegI32:
1998 case NVPTX::LoadParamRegI64: case NVPTX::LoadParamRegI8:
1999 case NVPTX::LoadParamScalar2F32: case NVPTX::LoadParamScalar2F64:
2000 case NVPTX::LoadParamScalar2I16: case NVPTX::LoadParamScalar2I32:
2001 case NVPTX::LoadParamScalar2I64: case NVPTX::LoadParamScalar2I8:
2002 case NVPTX::LoadParamScalar4F32: case NVPTX::LoadParamScalar4I16:
2003 case NVPTX::LoadParamScalar4I32: case NVPTX::LoadParamScalar4I8:
2004 case NVPTX::LoadParamV2F32: case NVPTX::LoadParamV2F64:
2005 case NVPTX::LoadParamV2I16: case NVPTX::LoadParamV2I32:
2006 case NVPTX::LoadParamV2I64: case NVPTX::LoadParamV2I8:
2007 case NVPTX::LoadParamV4F32: case NVPTX::LoadParamV4I16:
2008 case NVPTX::LoadParamV4I32: case NVPTX::LoadParamV4I8:
2009 case NVPTX::PrototypeInst: case NVPTX::DBG_VALUE:
2015 // Force static initialization.
2016 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2017 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2018 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2022 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2023 std::stringstream temp;
2024 LineReader * reader = this->getReader(filename.str());
2026 temp << filename.str();
2030 temp << reader->readLine(line);
2032 this->OutStreamer.EmitRawText(Twine(temp.str()));
2036 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2037 if (reader == NULL) {
2038 reader = new LineReader(filename);
2041 if (reader->fileName() != filename) {
2043 reader = new LineReader(filename);
2051 LineReader::readLine(unsigned lineNum) {
2052 if (lineNum < theCurLine) {
2054 fstr.seekg(0,std::ios::beg);
2056 while (theCurLine < lineNum) {
2057 fstr.getline(buff,500);
2063 // Force static initialization.
2064 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2065 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2066 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);