1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
13 //===----------------------------------------------------------------------===//
15 #include "NVPTXAsmPrinter.h"
16 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
18 #include "NVPTXInstrInfo.h"
19 #include "NVPTXNumRegisters.h"
20 #include "NVPTXRegisterInfo.h"
21 #include "NVPTXTargetMachine.h"
22 #include "NVPTXUtilities.h"
23 #include "cl_common_defines.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/CodeGen/Analysis.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/DebugInfo.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Function.h"
34 #include "llvm/GlobalVariable.h"
35 #include "llvm/MC/MCStreamer.h"
36 #include "llvm/MC/MCSymbol.h"
37 #include "llvm/Module.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/Path.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TimeValue.h"
44 #include "llvm/Target/Mangler.h"
45 #include "llvm/Target/TargetLoweringObjectFile.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));
72 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
74 void DiscoverDependentGlobals(Value *V,
75 DenseSet<GlobalVariable*> &Globals) {
76 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
79 if (User *U = dyn_cast<User>(V)) {
80 for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
81 DiscoverDependentGlobals(U->getOperand(i), Globals);
87 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
88 /// instances to be emitted, but only after any dependents have been added
90 void VisitGlobalVariableForEmission(GlobalVariable *GV,
91 SmallVectorImpl<GlobalVariable*> &Order,
92 DenseSet<GlobalVariable*> &Visited,
93 DenseSet<GlobalVariable*> &Visiting) {
94 // Have we already visited this one?
95 if (Visited.count(GV)) return;
97 // Do we have a circular dependency?
98 if (Visiting.count(GV))
99 report_fatal_error("Circular dependency found in global variable set");
101 // Start visiting this global
104 // Make sure we visit all dependents first
105 DenseSet<GlobalVariable*> Others;
106 for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
107 DiscoverDependentGlobals(GV->getOperand(i), Others);
109 for (DenseSet<GlobalVariable*>::iterator I = Others.begin(),
110 E = Others.end(); I != E; ++I)
111 VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
113 // Now we can visit ourself
120 // @TODO: This is a copy from AsmPrinter.cpp. The function is static, so we
121 // cannot just link to the existing version.
122 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
124 using namespace nvptx;
125 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
126 MCContext &Ctx = AP.OutContext;
128 if (CV->isNullValue() || isa<UndefValue>(CV))
129 return MCConstantExpr::Create(0, Ctx);
131 if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
132 return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
134 if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
135 return MCSymbolRefExpr::Create(AP.Mang->getSymbol(GV), Ctx);
137 if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
138 return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
140 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
142 llvm_unreachable("Unknown constant value to lower!");
145 switch (CE->getOpcode()) {
147 // If the code isn't optimized, there may be outstanding folding
148 // opportunities. Attempt to fold the expression using DataLayout as a
149 // last resort before giving up.
151 ConstantFoldConstantExpression(CE, AP.TM.getDataLayout()))
153 return LowerConstant(C, AP);
155 // Otherwise report the problem to the user.
158 raw_string_ostream OS(S);
159 OS << "Unsupported expression in static initializer: ";
160 WriteAsOperand(OS, CE, /*PrintType=*/false,
161 !AP.MF ? 0 : AP.MF->getFunction()->getParent());
162 report_fatal_error(OS.str());
164 case Instruction::GetElementPtr: {
165 const DataLayout &TD = *AP.TM.getDataLayout();
166 // Generate a symbolic expression for the byte address
167 const Constant *PtrVal = CE->getOperand(0);
168 SmallVector<Value*, 8> IdxVec(CE->op_begin()+1, CE->op_end());
169 int64_t Offset = TD.getIndexedOffset(PtrVal->getType(), IdxVec);
171 const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
175 // Truncate/sext the offset to the pointer size.
176 if (TD.getPointerSizeInBits() != 64) {
177 int SExtAmount = 64-TD.getPointerSizeInBits();
178 Offset = (Offset << SExtAmount) >> SExtAmount;
181 return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
185 case Instruction::Trunc:
186 // We emit the value and depend on the assembler to truncate the generated
187 // expression properly. This is important for differences between
188 // blockaddress labels. Since the two labels are in the same function, it
189 // is reasonable to treat their delta as a 32-bit value.
191 case Instruction::BitCast:
192 return LowerConstant(CE->getOperand(0), AP);
194 case Instruction::IntToPtr: {
195 const DataLayout &TD = *AP.TM.getDataLayout();
196 // Handle casts to pointers by changing them into casts to the appropriate
197 // integer type. This promotes constant folding and simplifies this code.
198 Constant *Op = CE->getOperand(0);
199 Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
201 return LowerConstant(Op, AP);
204 case Instruction::PtrToInt: {
205 const DataLayout &TD = *AP.TM.getDataLayout();
206 // Support only foldable casts to/from pointers that can be eliminated by
207 // changing the pointer to the appropriately sized integer type.
208 Constant *Op = CE->getOperand(0);
209 Type *Ty = CE->getType();
211 const MCExpr *OpExpr = LowerConstant(Op, AP);
213 // We can emit the pointer value into this slot if the slot is an
214 // integer slot equal to the size of the pointer.
215 if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
218 // Otherwise the pointer is smaller than the resultant integer, mask off
219 // the high bits so we are sure to get a proper truncation if the input is
221 unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
222 const MCExpr *MaskExpr = MCConstantExpr::Create(~0ULL >> (64-InBits), Ctx);
223 return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
226 // The MC library also has a right-shift operator, but it isn't consistently
227 // signed or unsigned between different targets.
228 case Instruction::Add:
229 case Instruction::Sub:
230 case Instruction::Mul:
231 case Instruction::SDiv:
232 case Instruction::SRem:
233 case Instruction::Shl:
234 case Instruction::And:
235 case Instruction::Or:
236 case Instruction::Xor: {
237 const MCExpr *LHS = LowerConstant(CE->getOperand(0), AP);
238 const MCExpr *RHS = LowerConstant(CE->getOperand(1), AP);
239 switch (CE->getOpcode()) {
240 default: llvm_unreachable("Unknown binary operator constant cast expr");
241 case Instruction::Add: return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
242 case Instruction::Sub: return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
243 case Instruction::Mul: return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
244 case Instruction::SDiv: return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
245 case Instruction::SRem: return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
246 case Instruction::Shl: return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
247 case Instruction::And: return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
248 case Instruction::Or: return MCBinaryExpr::CreateOr (LHS, RHS, Ctx);
249 case Instruction::Xor: return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
256 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI)
258 if (!EmitLineNumbers)
263 DebugLoc curLoc = MI.getDebugLoc();
265 if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
268 if (prevDebugLoc == curLoc)
271 prevDebugLoc = curLoc;
273 if (curLoc.isUnknown())
277 const MachineFunction *MF = MI.getParent()->getParent();
278 //const TargetMachine &TM = MF->getTarget();
280 const LLVMContext &ctx = MF->getFunction()->getContext();
281 DIScope Scope(curLoc.getScope(ctx));
286 StringRef fileName(Scope.getFilename());
287 StringRef dirName(Scope.getDirectory());
288 SmallString<128> FullPathName = dirName;
289 if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
290 sys::path::append(FullPathName, fileName);
291 fileName = FullPathName.str();
294 if (filenameMap.find(fileName.str()) == filenameMap.end())
298 // Emit the line from the source file.
299 if (llvm::InterleaveSrcInPtx)
300 this->emitSrcInText(fileName.str(), curLoc.getLine());
302 std::stringstream temp;
303 temp << "\t.loc " << filenameMap[fileName.str()]
304 << " " << curLoc.getLine() << " " << curLoc.getCol();
305 OutStreamer.EmitRawText(Twine(temp.str().c_str()));
308 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
309 SmallString<128> Str;
310 raw_svector_ostream OS(Str);
311 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
312 emitLineNumberAsDotLoc(*MI);
313 printInstruction(MI, OS);
314 OutStreamer.EmitRawText(OS.str());
317 void NVPTXAsmPrinter::printReturnValStr(const Function *F,
320 const DataLayout *TD = TM.getDataLayout();
321 const TargetLowering *TLI = TM.getTargetLowering();
323 Type *Ty = F->getReturnType();
325 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
327 if (Ty->getTypeID() == Type::VoidTyID)
333 if (Ty->isPrimitiveType() || Ty->isIntegerTy()) {
335 if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
336 size = ITy->getBitWidth();
337 if (size < 32) size = 32;
339 assert(Ty->isFloatingPointTy() &&
340 "Floating point type expected here");
341 size = Ty->getPrimitiveSizeInBits();
344 O << ".param .b" << size << " func_retval0";
346 else if (isa<PointerType>(Ty)) {
347 O << ".param .b" << TLI->getPointerTy().getSizeInBits()
350 if ((Ty->getTypeID() == Type::StructTyID) ||
351 isa<VectorType>(Ty)) {
352 SmallVector<EVT, 16> vtparts;
353 ComputeValueVTs(*TLI, Ty, vtparts);
354 unsigned totalsz = 0;
355 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
357 EVT elemtype = vtparts[i];
358 if (vtparts[i].isVector()) {
359 elems = vtparts[i].getVectorNumElements();
360 elemtype = vtparts[i].getVectorElementType();
362 for (unsigned j=0, je=elems; j!=je; ++j) {
363 unsigned sz = elemtype.getSizeInBits();
364 if (elemtype.isInteger() && (sz < 8)) sz = 8;
368 unsigned retAlignment = 0;
369 if (!llvm::getAlign(*F, 0, retAlignment))
370 retAlignment = TD->getABITypeAlignment(Ty);
371 O << ".param .align "
373 << " .b8 func_retval0["
377 "Unknown return type");
380 SmallVector<EVT, 16> vtparts;
381 ComputeValueVTs(*TLI, Ty, vtparts);
383 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
385 EVT elemtype = vtparts[i];
386 if (vtparts[i].isVector()) {
387 elems = vtparts[i].getVectorNumElements();
388 elemtype = vtparts[i].getVectorElementType();
391 for (unsigned j=0, je=elems; j!=je; ++j) {
392 unsigned sz = elemtype.getSizeInBits();
393 if (elemtype.isInteger() && (sz < 32)) sz = 32;
394 O << ".reg .b" << sz << " func_retval" << idx;
395 if (j<je-1) O << ", ";
406 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
408 const Function *F = MF.getFunction();
409 printReturnValStr(F, O);
412 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
413 SmallString<128> Str;
414 raw_svector_ostream O(Str);
417 MRI = &MF->getRegInfo();
418 F = MF->getFunction();
419 emitLinkageDirective(F,O);
420 if (llvm::isKernelFunction(*F))
424 printReturnValStr(*MF, O);
429 emitFunctionParamList(*MF, O);
431 if (llvm::isKernelFunction(*F))
432 emitKernelFunctionDirectives(*F, O);
434 OutStreamer.EmitRawText(O.str());
436 prevDebugLoc = DebugLoc();
439 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
440 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
441 unsigned numRegClasses = TRI.getNumRegClasses();
442 VRidGlobal2LocalMap = new std::map<unsigned, unsigned>[numRegClasses+1];
443 OutStreamer.EmitRawText(StringRef("{\n"));
444 setAndEmitFunctionVirtualRegisters(*MF);
446 SmallString<128> Str;
447 raw_svector_ostream O(Str);
448 emitDemotedVars(MF->getFunction(), O);
449 OutStreamer.EmitRawText(O.str());
452 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
453 OutStreamer.EmitRawText(StringRef("}\n"));
454 delete []VRidGlobal2LocalMap;
459 NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function& F,
460 raw_ostream &O) const {
461 // If the NVVM IR has some of reqntid* specified, then output
462 // the reqntid directive, and set the unspecified ones to 1.
463 // If none of reqntid* is specified, don't output reqntid directive.
464 unsigned reqntidx, reqntidy, reqntidz;
465 bool specified = false;
466 if (llvm::getReqNTIDx(F, reqntidx) == false) reqntidx = 1;
467 else specified = true;
468 if (llvm::getReqNTIDy(F, reqntidy) == false) reqntidy = 1;
469 else specified = true;
470 if (llvm::getReqNTIDz(F, reqntidz) == false) reqntidz = 1;
471 else specified = true;
474 O << ".reqntid " << reqntidx << ", "
475 << reqntidy << ", " << reqntidz << "\n";
477 // If the NVVM IR has some of maxntid* specified, then output
478 // the maxntid directive, and set the unspecified ones to 1.
479 // If none of maxntid* is specified, don't output maxntid directive.
480 unsigned maxntidx, maxntidy, maxntidz;
482 if (llvm::getMaxNTIDx(F, maxntidx) == false) maxntidx = 1;
483 else specified = true;
484 if (llvm::getMaxNTIDy(F, maxntidy) == false) maxntidy = 1;
485 else specified = true;
486 if (llvm::getMaxNTIDz(F, maxntidz) == false) maxntidz = 1;
487 else specified = true;
490 O << ".maxntid " << maxntidx << ", "
491 << maxntidy << ", " << maxntidz << "\n";
494 if (llvm::getMinCTASm(F, mincta))
495 O << ".minnctapersm " << mincta << "\n";
499 NVPTXAsmPrinter::getVirtualRegisterName(unsigned vr, bool isVec,
501 const TargetRegisterClass * RC = MRI->getRegClass(vr);
502 unsigned id = RC->getID();
504 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[id];
505 unsigned mapped_vr = regmap[vr];
508 O << getNVPTXRegClassStr(RC) << mapped_vr;
511 // Vector virtual register
512 if (getNVPTXVectorSize(RC) == 4)
514 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
515 << getNVPTXRegClassStr(RC) << mapped_vr << "_1, "
516 << getNVPTXRegClassStr(RC) << mapped_vr << "_2, "
517 << getNVPTXRegClassStr(RC) << mapped_vr << "_3"
519 else if (getNVPTXVectorSize(RC) == 2)
521 << getNVPTXRegClassStr(RC) << mapped_vr << "_0, "
522 << getNVPTXRegClassStr(RC) << mapped_vr << "_1"
525 llvm_unreachable("Unsupported vector size");
529 NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr, bool isVec,
531 getVirtualRegisterName(vr, isVec, O);
534 void NVPTXAsmPrinter::printVecModifiedImmediate(const MachineOperand &MO,
535 const char *Modifier,
537 static const char vecelem[] = {'0', '1', '2', '3', '0', '1', '2', '3'};
538 int Imm = (int)MO.getImm();
539 if(0 == strcmp(Modifier, "vecelem"))
540 O << "_" << vecelem[Imm];
541 else if(0 == strcmp(Modifier, "vecv4comm1")) {
542 if((Imm < 0) || (Imm > 3))
545 else if(0 == strcmp(Modifier, "vecv4comm2")) {
546 if((Imm < 4) || (Imm > 7))
549 else if(0 == strcmp(Modifier, "vecv4pos")) {
551 O << "_" << vecelem[Imm%4];
553 else if(0 == strcmp(Modifier, "vecv2comm1")) {
554 if((Imm < 0) || (Imm > 1))
557 else if(0 == strcmp(Modifier, "vecv2comm2")) {
558 if((Imm < 2) || (Imm > 3))
561 else if(0 == strcmp(Modifier, "vecv2pos")) {
563 O << "_" << vecelem[Imm%2];
566 llvm_unreachable("Unknown Modifier on immediate operand");
569 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
570 raw_ostream &O, const char *Modifier) {
571 const MachineOperand &MO = MI->getOperand(opNum);
572 switch (MO.getType()) {
573 case MachineOperand::MO_Register:
574 if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
575 if (MO.getReg() == NVPTX::VRDepot)
576 O << DEPOTNAME << getFunctionNumber();
578 O << getRegisterName(MO.getReg());
581 emitVirtualRegister(MO.getReg(), false, O);
583 if (strcmp(Modifier, "vecfull") == 0)
584 emitVirtualRegister(MO.getReg(), true, O);
587 "Don't know how to handle the modifier on virtual register.");
592 case MachineOperand::MO_Immediate:
595 else if (strstr(Modifier, "vec") == Modifier)
596 printVecModifiedImmediate(MO, Modifier, O);
598 llvm_unreachable("Don't know how to handle modifier on immediate operand");
601 case MachineOperand::MO_FPImmediate:
602 printFPConstant(MO.getFPImm(), O);
605 case MachineOperand::MO_GlobalAddress:
606 O << *Mang->getSymbol(MO.getGlobal());
609 case MachineOperand::MO_ExternalSymbol: {
610 const char * symbname = MO.getSymbolName();
611 if (strstr(symbname, ".PARAM") == symbname) {
613 sscanf(symbname+6, "%u[];", &index);
614 printParamName(index, O);
616 else if (strstr(symbname, ".HLPPARAM") == symbname) {
618 sscanf(symbname+9, "%u[];", &index);
619 O << *CurrentFnSym << "_param_" << index << "_offset";
626 case MachineOperand::MO_MachineBasicBlock:
627 O << *MO.getMBB()->getSymbol();
631 llvm_unreachable("Operand type not supported.");
635 void NVPTXAsmPrinter::
636 printImplicitDef(const MachineInstr *MI, raw_ostream &O) const {
638 O << "\t// Implicit def :";
639 //printOperand(MI, 0);
644 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
645 raw_ostream &O, const char *Modifier) {
646 printOperand(MI, opNum, O);
648 if (Modifier && !strcmp(Modifier, "add")) {
650 printOperand(MI, opNum+1, O);
652 if (MI->getOperand(opNum+1).isImm() &&
653 MI->getOperand(opNum+1).getImm() == 0)
654 return; // don't print ',0' or '+0'
656 printOperand(MI, opNum+1, O);
660 void NVPTXAsmPrinter::printLdStCode(const MachineInstr *MI, int opNum,
661 raw_ostream &O, const char *Modifier)
664 const MachineOperand &MO = MI->getOperand(opNum);
665 int Imm = (int)MO.getImm();
666 if (!strcmp(Modifier, "volatile")) {
669 } else if (!strcmp(Modifier, "addsp")) {
671 case NVPTX::PTXLdStInstCode::GLOBAL: O << ".global"; break;
672 case NVPTX::PTXLdStInstCode::SHARED: O << ".shared"; break;
673 case NVPTX::PTXLdStInstCode::LOCAL: O << ".local"; break;
674 case NVPTX::PTXLdStInstCode::PARAM: O << ".param"; break;
675 case NVPTX::PTXLdStInstCode::CONSTANT: O << ".const"; break;
676 case NVPTX::PTXLdStInstCode::GENERIC:
677 if (!nvptxSubtarget.hasGenericLdSt())
681 llvm_unreachable("Wrong Address Space");
684 else if (!strcmp(Modifier, "sign")) {
685 if (Imm==NVPTX::PTXLdStInstCode::Signed)
687 else if (Imm==NVPTX::PTXLdStInstCode::Unsigned)
692 else if (!strcmp(Modifier, "vec")) {
693 if (Imm==NVPTX::PTXLdStInstCode::V2)
695 else if (Imm==NVPTX::PTXLdStInstCode::V4)
699 llvm_unreachable("Unknown Modifier");
702 llvm_unreachable("Empty Modifier");
705 void NVPTXAsmPrinter::emitDeclaration (const Function *F, raw_ostream &O) {
707 emitLinkageDirective(F,O);
708 if (llvm::isKernelFunction(*F))
712 printReturnValStr(F, O);
713 O << *CurrentFnSym << "\n";
714 emitFunctionParamList(F, O);
718 static bool usedInGlobalVarDef(const Constant *C)
723 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
724 if (GV->getName().str() == "llvm.used")
729 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
731 const Constant *C = dyn_cast<Constant>(*ui);
732 if (usedInGlobalVarDef(C))
738 static bool usedInOneFunc(const User *U, Function const *&oneFunc)
740 if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
741 if (othergv->getName().str() == "llvm.used")
745 if (const Instruction *instr = dyn_cast<Instruction>(U)) {
746 if (instr->getParent() && instr->getParent()->getParent()) {
747 const Function *curFunc = instr->getParent()->getParent();
748 if (oneFunc && (curFunc != oneFunc))
757 if (const MDNode *md = dyn_cast<MDNode>(U))
758 if (md->hasName() && ((md->getName().str() == "llvm.dbg.gv") ||
759 (md->getName().str() == "llvm.dbg.sp")))
763 for (User::const_use_iterator ui=U->use_begin(), ue=U->use_end();
765 if (usedInOneFunc(*ui, oneFunc) == false)
771 /* Find out if a global variable can be demoted to local scope.
772 * Currently, this is valid for CUDA shared variables, which have local
773 * scope and global lifetime. So the conditions to check are :
774 * 1. Is the global variable in shared address space?
775 * 2. Does it have internal linkage?
776 * 3. Is the global variable referenced only in one function?
778 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
779 if (gv->hasInternalLinkage() == false)
781 const PointerType *Pty = gv->getType();
782 if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
785 const Function *oneFunc = 0;
787 bool flag = usedInOneFunc(gv, oneFunc);
796 static bool useFuncSeen(const Constant *C,
797 llvm::DenseMap<const Function *, bool> &seenMap) {
798 for (Value::const_use_iterator ui=C->use_begin(), ue=C->use_end();
800 if (const Constant *cu = dyn_cast<Constant>(*ui)) {
801 if (useFuncSeen(cu, seenMap))
803 } else if (const Instruction *I = dyn_cast<Instruction>(*ui)) {
804 const BasicBlock *bb = I->getParent();
806 const Function *caller = bb->getParent();
807 if (!caller) continue;
808 if (seenMap.find(caller) != seenMap.end())
815 void NVPTXAsmPrinter::emitDeclarations (Module &M, raw_ostream &O) {
816 llvm::DenseMap<const Function *, bool> seenMap;
817 for (Module::const_iterator FI=M.begin(), FE=M.end();
819 const Function *F = FI;
821 if (F->isDeclaration()) {
824 if (F->getIntrinsicID())
826 CurrentFnSym = Mang->getSymbol(F);
827 emitDeclaration(F, O);
830 for (Value::const_use_iterator iter=F->use_begin(),
831 iterEnd=F->use_end(); iter!=iterEnd; ++iter) {
832 if (const Constant *C = dyn_cast<Constant>(*iter)) {
833 if (usedInGlobalVarDef(C)) {
834 // The use is in the initialization of a global variable
835 // that is a function pointer, so print a declaration
836 // for the original function
837 CurrentFnSym = Mang->getSymbol(F);
838 emitDeclaration(F, O);
841 // Emit a declaration of this function if the function that
842 // uses this constant expr has already been seen.
843 if (useFuncSeen(C, seenMap)) {
844 CurrentFnSym = Mang->getSymbol(F);
845 emitDeclaration(F, O);
850 if (!isa<Instruction>(*iter)) continue;
851 const Instruction *instr = cast<Instruction>(*iter);
852 const BasicBlock *bb = instr->getParent();
854 const Function *caller = bb->getParent();
855 if (!caller) continue;
857 // If a caller has already been seen, then the caller is
858 // appearing in the module before the callee. so print out
859 // a declaration for the callee.
860 if (seenMap.find(caller) != seenMap.end()) {
861 CurrentFnSym = Mang->getSymbol(F);
862 emitDeclaration(F, O);
870 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
871 DebugInfoFinder DbgFinder;
872 DbgFinder.processModule(M);
875 for (DebugInfoFinder::iterator I = DbgFinder.compile_unit_begin(),
876 E = DbgFinder.compile_unit_end(); I != E; ++I) {
877 DICompileUnit DIUnit(*I);
878 StringRef Filename(DIUnit.getFilename());
879 StringRef Dirname(DIUnit.getDirectory());
880 SmallString<128> FullPathName = Dirname;
881 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
882 sys::path::append(FullPathName, Filename);
883 Filename = FullPathName.str();
885 if (filenameMap.find(Filename.str()) != filenameMap.end())
887 filenameMap[Filename.str()] = i;
888 OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
892 for (DebugInfoFinder::iterator I = DbgFinder.subprogram_begin(),
893 E = DbgFinder.subprogram_end(); I != E; ++I) {
895 StringRef Filename(SP.getFilename());
896 StringRef Dirname(SP.getDirectory());
897 SmallString<128> FullPathName = Dirname;
898 if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
899 sys::path::append(FullPathName, Filename);
900 Filename = FullPathName.str();
902 if (filenameMap.find(Filename.str()) != filenameMap.end())
904 filenameMap[Filename.str()] = i;
909 bool NVPTXAsmPrinter::doInitialization (Module &M) {
911 SmallString<128> Str1;
912 raw_svector_ostream OS1(Str1);
914 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
915 MMI->AnalyzeModule(M);
917 // We need to call the parent's one explicitly.
918 //bool Result = AsmPrinter::doInitialization(M);
920 // Initialize TargetLoweringObjectFile.
921 const_cast<TargetLoweringObjectFile&>(getObjFileLowering())
922 .Initialize(OutContext, TM);
924 Mang = new Mangler(OutContext, *TM.getDataLayout());
926 // Emit header before any dwarf directives are emitted below.
928 OutStreamer.EmitRawText(OS1.str());
931 // Already commented out
932 //bool Result = AsmPrinter::doInitialization(M);
935 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
936 recordAndEmitFilenames(M);
938 SmallString<128> Str2;
939 raw_svector_ostream OS2(Str2);
941 emitDeclarations(M, OS2);
943 // As ptxas does not support forward references of globals, we need to first
944 // sort the list of module-level globals in def-use order. We visit each
945 // global variable in order, and ensure that we emit it *after* its dependent
946 // globals. We use a little extra memory maintaining both a set and a list to
947 // have fast searches while maintaining a strict ordering.
948 SmallVector<GlobalVariable*,8> Globals;
949 DenseSet<GlobalVariable*> GVVisited;
950 DenseSet<GlobalVariable*> GVVisiting;
952 // Visit each global variable, in order
953 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
955 VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
957 assert(GVVisited.size() == M.getGlobalList().size() &&
958 "Missed a global variable");
959 assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
961 // Print out module-level global variables in proper order
962 for (unsigned i = 0, e = Globals.size(); i != e; ++i)
963 printModuleLevelGV(Globals[i], OS2);
967 OutStreamer.EmitRawText(OS2.str());
968 return false; // success
971 void NVPTXAsmPrinter::emitHeader (Module &M, raw_ostream &O) {
973 O << "// Generated by LLVM NVPTX Back-End\n";
977 unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
978 O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
981 O << nvptxSubtarget.getTargetName();
983 if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
984 O << ", texmode_independent";
985 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
986 if (!nvptxSubtarget.hasDouble())
987 O << ", map_f64_to_f32";
990 if (MAI->doesSupportDebugInformation())
995 O << ".address_size ";
996 if (nvptxSubtarget.is64Bit())
1005 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1006 // XXX Temproarily remove global variables so that doFinalization() will not
1007 // emit them again (global variables are emitted at beginning).
1009 Module::GlobalListType &global_list = M.getGlobalList();
1010 int i, n = global_list.size();
1011 GlobalVariable **gv_array = new GlobalVariable* [n];
1013 // first, back-up GlobalVariable in gv_array
1015 for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1017 gv_array[i++] = &*I;
1019 // second, empty global_list
1020 while (!global_list.empty())
1021 global_list.remove(global_list.begin());
1023 // call doFinalization
1024 bool ret = AsmPrinter::doFinalization(M);
1026 // now we restore global variables
1027 for (i = 0; i < n; i ++)
1028 global_list.insert(global_list.end(), gv_array[i]);
1034 //bool Result = AsmPrinter::doFinalization(M);
1035 // Instead of calling the parents doFinalization, we may
1036 // clone parents doFinalization and customize here.
1037 // Currently, we if NVISA out the EmitGlobals() in
1038 // parent's doFinalization, which is too intrusive.
1040 // Same for the doInitialization.
1044 // This function emits appropriate linkage directives for
1045 // functions and global variables.
1047 // extern function declaration -> .extern
1048 // extern function definition -> .visible
1049 // external global variable with init -> .visible
1050 // external without init -> .extern
1051 // appending -> not allowed, assert.
1053 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue* V, raw_ostream &O)
1055 if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1056 if (V->hasExternalLinkage()) {
1057 if (isa<GlobalVariable>(V)) {
1058 const GlobalVariable *GVar = cast<GlobalVariable>(V);
1060 if (GVar->hasInitializer())
1065 } else if (V->isDeclaration())
1069 } else if (V->hasAppendingLinkage()) {
1071 msg.append("Error: ");
1072 msg.append("Symbol ");
1074 msg.append(V->getName().str());
1075 msg.append("has unsupported appending linkage type");
1076 llvm_unreachable(msg.c_str());
1082 void NVPTXAsmPrinter::printModuleLevelGV(GlobalVariable* GVar, raw_ostream &O,
1083 bool processDemoted) {
1086 if (GVar->hasSection()) {
1087 if (GVar->getSection() == "llvm.metadata")
1091 const DataLayout *TD = TM.getDataLayout();
1093 // GlobalVariables are always constant pointers themselves.
1094 const PointerType *PTy = GVar->getType();
1095 Type *ETy = PTy->getElementType();
1097 if (GVar->hasExternalLinkage()) {
1098 if (GVar->hasInitializer())
1104 if (llvm::isTexture(*GVar)) {
1105 O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1109 if (llvm::isSurface(*GVar)) {
1110 O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1114 if (GVar->isDeclaration()) {
1115 // (extern) declarations, no definition or initializer
1116 // Currently the only known declaration is for an automatic __local
1117 // (.shared) promoted to global.
1118 emitPTXGlobalVariable(GVar, O);
1123 if (llvm::isSampler(*GVar)) {
1124 O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1126 Constant *Initializer = NULL;
1127 if (GVar->hasInitializer())
1128 Initializer = GVar->getInitializer();
1129 ConstantInt *CI = NULL;
1131 CI = dyn_cast<ConstantInt>(Initializer);
1133 unsigned sample=CI->getZExtValue();
1137 for (int i =0, addr=((sample & __CLK_ADDRESS_MASK ) >>
1138 __CLK_ADDRESS_BASE) ; i < 3 ; i++) {
1139 O << "addr_mode_" << i << " = ";
1141 case 0: O << "wrap"; break;
1142 case 1: O << "clamp_to_border"; break;
1143 case 2: O << "clamp_to_edge"; break;
1144 case 3: O << "wrap"; break;
1145 case 4: O << "mirror"; break;
1149 O << "filter_mode = ";
1150 switch (( sample & __CLK_FILTER_MASK ) >> __CLK_FILTER_BASE ) {
1151 case 0: O << "nearest"; break;
1152 case 1: O << "linear"; break;
1153 case 2: assert ( 0 && "Anisotropic filtering is not supported");
1154 default: O << "nearest"; break;
1156 if (!(( sample &__CLK_NORMALIZED_MASK ) >> __CLK_NORMALIZED_BASE)) {
1157 O << ", force_unnormalized_coords = 1";
1166 if (GVar->hasPrivateLinkage()) {
1168 if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1171 // FIXME - need better way (e.g. Metadata) to avoid generating this global
1172 if (!strncmp(GVar->getName().data(), "filename", 8))
1174 if (GVar->use_empty())
1178 const Function *demotedFunc = 0;
1179 if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1180 O << "// " << GVar->getName().str() << " has been demoted\n";
1181 if (localDecls.find(demotedFunc) != localDecls.end())
1182 localDecls[demotedFunc].push_back(GVar);
1184 std::vector<GlobalVariable *> temp;
1185 temp.push_back(GVar);
1186 localDecls[demotedFunc] = temp;
1192 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1193 if (GVar->getAlignment() == 0)
1194 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1196 O << " .align " << GVar->getAlignment();
1199 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1201 O << getPTXFundamentalTypeStr(ETy, false);
1203 O << *Mang->getSymbol(GVar);
1205 // Ptx allows variable initilization only for constant and global state
1207 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1208 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1209 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1210 && GVar->hasInitializer()) {
1211 Constant *Initializer = GVar->getInitializer();
1212 if (!Initializer->isNullValue()) {
1214 printScalarConstant(Initializer, O);
1218 unsigned int ElementSize =0;
1220 // Although PTX has direct support for struct type and array type and
1221 // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1222 // targets that support these high level field accesses. Structs, arrays
1223 // and vectors are lowered into arrays of bytes.
1224 switch (ETy->getTypeID()) {
1225 case Type::StructTyID:
1226 case Type::ArrayTyID:
1227 case Type::VectorTyID:
1228 ElementSize = TD->getTypeStoreSize(ETy);
1229 // Ptx allows variable initilization only for constant and
1230 // global state spaces.
1231 if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1232 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST_NOT_GEN) ||
1233 (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST))
1234 && GVar->hasInitializer()) {
1235 Constant *Initializer = GVar->getInitializer();
1236 if (!isa<UndefValue>(Initializer) &&
1237 !Initializer->isNullValue()) {
1238 AggBuffer aggBuffer(ElementSize, O, *this);
1239 bufferAggregateConstant(Initializer, &aggBuffer);
1240 if (aggBuffer.numSymbols) {
1241 if (nvptxSubtarget.is64Bit()) {
1242 O << " .u64 " << *Mang->getSymbol(GVar) <<"[" ;
1246 O << " .u32 " << *Mang->getSymbol(GVar) <<"[" ;
1252 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1261 O << " .b8 " << *Mang->getSymbol(GVar) ;
1270 O << " .b8 " << *Mang->getSymbol(GVar);
1279 assert( 0 && "type not supported yet");
1286 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1287 if (localDecls.find(f) == localDecls.end())
1290 std::vector<GlobalVariable *> &gvars = localDecls[f];
1292 for (unsigned i=0, e=gvars.size(); i!=e; ++i) {
1293 O << "\t// demoted variable\n\t";
1294 printModuleLevelGV(gvars[i], O, true);
1298 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1299 raw_ostream &O) const {
1300 switch (AddressSpace) {
1301 case llvm::ADDRESS_SPACE_LOCAL:
1304 case llvm::ADDRESS_SPACE_GLOBAL:
1307 case llvm::ADDRESS_SPACE_CONST:
1308 // This logic should be consistent with that in
1309 // getCodeAddrSpace() (NVPTXISelDATToDAT.cpp)
1310 if (nvptxSubtarget.hasGenericLdSt())
1315 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1318 case llvm::ADDRESS_SPACE_SHARED:
1322 llvm_unreachable("unexpected address space");
1326 std::string NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty,
1327 bool useB4PTR) const {
1328 switch (Ty->getTypeID()) {
1330 llvm_unreachable("unexpected type");
1332 case Type::IntegerTyID: {
1333 unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1336 else if (NumBits <= 64) {
1337 std::string name = "u";
1338 return name + utostr(NumBits);
1340 llvm_unreachable("Integer too large");
1345 case Type::FloatTyID:
1347 case Type::DoubleTyID:
1349 case Type::PointerTyID:
1350 if (nvptxSubtarget.is64Bit())
1351 if (useB4PTR) return "b64";
1354 if (useB4PTR) return "b32";
1357 llvm_unreachable("unexpected type");
1361 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable* GVar,
1364 const DataLayout *TD = TM.getDataLayout();
1366 // GlobalVariables are always constant pointers themselves.
1367 const PointerType *PTy = GVar->getType();
1368 Type *ETy = PTy->getElementType();
1371 emitPTXAddressSpace(PTy->getAddressSpace(), O);
1372 if (GVar->getAlignment() == 0)
1373 O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1375 O << " .align " << GVar->getAlignment();
1377 if (ETy->isPrimitiveType() || ETy->isIntegerTy() || isa<PointerType>(ETy)) {
1379 O << getPTXFundamentalTypeStr(ETy);
1381 O << *Mang->getSymbol(GVar);
1385 int64_t ElementSize =0;
1387 // Although PTX has direct support for struct type and array type and LLVM IR
1388 // is very similar to PTX, the LLVM CodeGen does not support for targets that
1389 // support these high level field accesses. Structs and arrays are lowered
1390 // into arrays of bytes.
1391 switch (ETy->getTypeID()) {
1392 case Type::StructTyID:
1393 case Type::ArrayTyID:
1394 case Type::VectorTyID:
1395 ElementSize = TD->getTypeStoreSize(ETy);
1396 O << " .b8 " << *Mang->getSymbol(GVar) <<"[" ;
1398 O << itostr(ElementSize) ;
1403 assert( 0 && "type not supported yet");
1410 getOpenCLAlignment(const DataLayout *TD,
1412 if (Ty->isPrimitiveType() || Ty->isIntegerTy() || isa<PointerType>(Ty))
1413 return TD->getPrefTypeAlignment(Ty);
1415 const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1417 return getOpenCLAlignment(TD, ATy->getElementType());
1419 const VectorType *VTy = dyn_cast<VectorType>(Ty);
1421 Type *ETy = VTy->getElementType();
1422 unsigned int numE = VTy->getNumElements();
1423 unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1430 const StructType *STy = dyn_cast<StructType>(Ty);
1432 unsigned int alignStruct = 1;
1433 // Go through each element of the struct and find the
1434 // largest alignment.
1435 for (unsigned i=0, e=STy->getNumElements(); i != e; i++) {
1436 Type *ETy = STy->getElementType(i);
1437 unsigned int align = getOpenCLAlignment(TD, ETy);
1438 if (align > alignStruct)
1439 alignStruct = align;
1444 const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1446 return TD->getPointerPrefAlignment();
1447 return TD->getPrefTypeAlignment(Ty);
1450 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1451 int paramIndex, raw_ostream &O) {
1452 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1453 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1454 O << *CurrentFnSym << "_param_" << paramIndex;
1456 std::string argName = I->getName();
1457 const char *p = argName.c_str();
1468 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1469 Function::const_arg_iterator I, E;
1472 if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1473 (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1474 O << *CurrentFnSym << "_param_" << paramIndex;
1478 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1479 if (i==paramIndex) {
1480 printParamName(I, paramIndex, O);
1484 llvm_unreachable("paramIndex out of bound");
1487 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F,
1489 const DataLayout *TD = TM.getDataLayout();
1490 const AttributeSet &PAL = F->getAttributes();
1491 const TargetLowering *TLI = TM.getTargetLowering();
1492 Function::const_arg_iterator I, E;
1493 unsigned paramIndex = 0;
1495 bool isKernelFunc = llvm::isKernelFunction(*F);
1496 bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1497 MVT thePointerTy = TLI->getPointerTy();
1501 for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1502 const Type *Ty = I->getType();
1509 // Handle image/sampler parameters
1510 if (llvm::isSampler(*I) || llvm::isImage(*I)) {
1511 if (llvm::isImage(*I)) {
1512 std::string sname = I->getName();
1513 if (llvm::isImageWriteOnly(*I))
1514 O << "\t.param .surfref " << *CurrentFnSym << "_param_" << paramIndex;
1515 else // Default image is read_only
1516 O << "\t.param .texref " << *CurrentFnSym << "_param_" << paramIndex;
1518 else // Should be llvm::isSampler(*I)
1519 O << "\t.param .samplerref " << *CurrentFnSym << "_param_"
1524 if (PAL.getParamAttributes(paramIndex+1).
1525 hasAttribute(Attribute::ByVal) == false) {
1527 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1530 // Special handling for pointer arguments to kernel
1531 O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1533 if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1534 Type *ETy = PTy->getElementType();
1535 int addrSpace = PTy->getAddressSpace();
1540 case llvm::ADDRESS_SPACE_CONST_NOT_GEN:
1541 O << ".ptr .const ";
1543 case llvm::ADDRESS_SPACE_SHARED:
1544 O << ".ptr .shared ";
1546 case llvm::ADDRESS_SPACE_GLOBAL:
1547 case llvm::ADDRESS_SPACE_CONST:
1548 O << ".ptr .global ";
1551 O << ".align " << (int)getOpenCLAlignment(TD, ETy) << " ";
1553 printParamName(I, paramIndex, O);
1557 // non-pointer scalar to kernel func
1559 << getPTXFundamentalTypeStr(Ty) << " ";
1560 printParamName(I, paramIndex, O);
1563 // Non-kernel function, just print .param .b<size> for ABI
1564 // and .reg .b<size> for non ABY
1566 if (isa<IntegerType>(Ty)) {
1567 sz = cast<IntegerType>(Ty)->getBitWidth();
1568 if (sz < 32) sz = 32;
1570 else if (isa<PointerType>(Ty))
1571 sz = thePointerTy.getSizeInBits();
1573 sz = Ty->getPrimitiveSizeInBits();
1575 O << "\t.param .b" << sz << " ";
1577 O << "\t.reg .b" << sz << " ";
1578 printParamName(I, paramIndex, O);
1582 // param has byVal attribute. So should be a pointer
1583 const PointerType *PTy = dyn_cast<PointerType>(Ty);
1585 "Param with byval attribute should be a pointer type");
1586 Type *ETy = PTy->getElementType();
1588 if (isABI || isKernelFunc) {
1589 // Just print .param .b8 .align <a> .param[size];
1590 // <a> = PAL.getparamalignment
1591 // size = typeallocsize of element type
1592 unsigned align = PAL.getParamAlignment(paramIndex+1);
1594 align = TD->getABITypeAlignment(ETy);
1596 unsigned sz = TD->getTypeAllocSize(ETy);
1597 O << "\t.param .align " << align
1599 printParamName(I, paramIndex, O);
1600 O << "[" << sz << "]";
1603 // Split the ETy into constituent parts and
1604 // print .param .b<size> <name> for each part.
1605 // Further, if a part is vector, print the above for
1606 // each vector element.
1607 SmallVector<EVT, 16> vtparts;
1608 ComputeValueVTs(*TLI, ETy, vtparts);
1609 for (unsigned i=0,e=vtparts.size(); i!=e; ++i) {
1611 EVT elemtype = vtparts[i];
1612 if (vtparts[i].isVector()) {
1613 elems = vtparts[i].getVectorNumElements();
1614 elemtype = vtparts[i].getVectorElementType();
1617 for (unsigned j=0,je=elems; j!=je; ++j) {
1618 unsigned sz = elemtype.getSizeInBits();
1619 if (elemtype.isInteger() && (sz < 32)) sz = 32;
1620 O << "\t.reg .b" << sz << " ";
1621 printParamName(I, paramIndex, O);
1622 if (j<je-1) O << ",\n";
1636 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1638 const Function *F = MF.getFunction();
1639 emitFunctionParamList(F, O);
1643 void NVPTXAsmPrinter::
1644 setAndEmitFunctionVirtualRegisters(const MachineFunction &MF) {
1645 SmallString<128> Str;
1646 raw_svector_ostream O(Str);
1648 // Map the global virtual register number to a register class specific
1649 // virtual register number starting from 1 with that class.
1650 const TargetRegisterInfo *TRI = MF.getTarget().getRegisterInfo();
1651 //unsigned numRegClasses = TRI->getNumRegClasses();
1653 // Emit the Fake Stack Object
1654 const MachineFrameInfo *MFI = MF.getFrameInfo();
1655 int NumBytes = (int) MFI->getStackSize();
1657 O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t"
1659 << getFunctionNumber() << "[" << NumBytes << "];\n";
1660 if (nvptxSubtarget.is64Bit()) {
1661 O << "\t.reg .b64 \t%SP;\n";
1662 O << "\t.reg .b64 \t%SPL;\n";
1665 O << "\t.reg .b32 \t%SP;\n";
1666 O << "\t.reg .b32 \t%SPL;\n";
1670 // Go through all virtual registers to establish the mapping between the
1672 // register number and the per class virtual register number.
1673 // We use the per class virtual register number in the ptx output.
1674 unsigned int numVRs = MRI->getNumVirtRegs();
1675 for (unsigned i=0; i< numVRs; i++) {
1676 unsigned int vr = TRI->index2VirtReg(i);
1677 const TargetRegisterClass *RC = MRI->getRegClass(vr);
1678 std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[RC->getID()];
1679 int n = regmap.size();
1680 regmap.insert(std::make_pair(vr, n+1));
1683 // Emit register declarations
1684 // @TODO: Extract out the real register usage
1685 O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1686 O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1687 O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1688 O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1689 O << "\t.reg .s64 %rl<" << NVPTXNumRegisters << ">;\n";
1690 O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1691 O << "\t.reg .f64 %fl<" << NVPTXNumRegisters << ">;\n";
1693 // Emit declaration of the virtual registers or 'physical' registers for
1694 // each register class
1695 //for (unsigned i=0; i< numRegClasses; i++) {
1696 // std::map<unsigned, unsigned> ®map = VRidGlobal2LocalMap[i];
1697 // const TargetRegisterClass *RC = TRI->getRegClass(i);
1698 // std::string rcname = getNVPTXRegClassName(RC);
1699 // std::string rcStr = getNVPTXRegClassStr(RC);
1700 // //int n = regmap.size();
1701 // if (!isNVPTXVectorRegClass(RC)) {
1702 // O << "\t.reg " << rcname << " \t" << rcStr << "<"
1703 // << NVPTXNumRegisters << ">;\n";
1706 // Only declare those registers that may be used. And do not emit vector
1708 // they are all elementized to scalar registers.
1709 //if (n && !isNVPTXVectorRegClass(RC)) {
1710 // if (RegAllocNilUsed) {
1711 // O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1715 // O << "\t.reg " << rcname << " \t" << StrToUpper(rcStr)
1716 // << "<" << 32 << ">;\n";
1721 OutStreamer.EmitRawText(O.str());
1725 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1726 APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1728 unsigned int numHex;
1731 if (Fp->getType()->getTypeID()==Type::FloatTyID) {
1734 APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
1736 } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1739 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven,
1742 llvm_unreachable("unsupported fp type");
1744 APInt API = APF.bitcastToAPInt();
1745 std::string hexstr(utohexstr(API.getZExtValue()));
1747 if (hexstr.length() < numHex)
1748 O << std::string(numHex - hexstr.length(), '0');
1749 O << utohexstr(API.getZExtValue());
1752 void NVPTXAsmPrinter::printScalarConstant(Constant *CPV, raw_ostream &O) {
1753 if (ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1754 O << CI->getValue();
1757 if (ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1758 printFPConstant(CFP, O);
1761 if (isa<ConstantPointerNull>(CPV)) {
1765 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1766 O << *Mang->getSymbol(GVar);
1769 if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1770 Value *v = Cexpr->stripPointerCasts();
1771 if (GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1772 O << *Mang->getSymbol(GVar);
1775 O << *LowerConstant(CPV, *this);
1779 llvm_unreachable("Not scalar type found in printScalarConstant()");
1783 void NVPTXAsmPrinter::bufferLEByte(Constant *CPV, int Bytes,
1784 AggBuffer *aggBuffer) {
1786 const DataLayout *TD = TM.getDataLayout();
1788 if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1789 int s = TD->getTypeAllocSize(CPV->getType());
1792 aggBuffer->addZeros(s);
1797 switch (CPV->getType()->getTypeID()) {
1799 case Type::IntegerTyID: {
1800 const Type *ETy = CPV->getType();
1801 if ( ETy == Type::getInt8Ty(CPV->getContext()) ){
1803 (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1805 aggBuffer->addBytes(ptr, 1, Bytes);
1806 } else if ( ETy == Type::getInt16Ty(CPV->getContext()) ) {
1808 (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1809 ptr = (unsigned char*)&int16;
1810 aggBuffer->addBytes(ptr, 2, Bytes);
1811 } else if ( ETy == Type::getInt32Ty(CPV->getContext()) ) {
1812 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1813 int int32 =(int)(constInt->getZExtValue());
1814 ptr = (unsigned char*)&int32;
1815 aggBuffer->addBytes(ptr, 4, Bytes);
1817 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1818 if (ConstantInt *constInt =
1819 dyn_cast<ConstantInt>(ConstantFoldConstantExpression(
1821 int int32 =(int)(constInt->getZExtValue());
1822 ptr = (unsigned char*)&int32;
1823 aggBuffer->addBytes(ptr, 4, Bytes);
1826 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1827 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1828 aggBuffer->addSymbol(v);
1829 aggBuffer->addZeros(4);
1833 llvm_unreachable("unsupported integer const type");
1834 } else if (ETy == Type::getInt64Ty(CPV->getContext()) ) {
1835 if (ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1836 long long int64 =(long long)(constInt->getZExtValue());
1837 ptr = (unsigned char*)&int64;
1838 aggBuffer->addBytes(ptr, 8, Bytes);
1840 } else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1841 if (ConstantInt *constInt = dyn_cast<ConstantInt>(
1842 ConstantFoldConstantExpression(Cexpr, TD))) {
1843 long long int64 =(long long)(constInt->getZExtValue());
1844 ptr = (unsigned char*)&int64;
1845 aggBuffer->addBytes(ptr, 8, Bytes);
1848 if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1849 Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1850 aggBuffer->addSymbol(v);
1851 aggBuffer->addZeros(8);
1855 llvm_unreachable("unsupported integer const type");
1857 llvm_unreachable("unsupported integer const type");
1860 case Type::FloatTyID:
1861 case Type::DoubleTyID: {
1862 ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1863 const Type* Ty = CFP->getType();
1864 if (Ty == Type::getFloatTy(CPV->getContext())) {
1865 float float32 = (float)CFP->getValueAPF().convertToFloat();
1866 ptr = (unsigned char*)&float32;
1867 aggBuffer->addBytes(ptr, 4, Bytes);
1868 } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1869 double float64 = CFP->getValueAPF().convertToDouble();
1870 ptr = (unsigned char*)&float64;
1871 aggBuffer->addBytes(ptr, 8, Bytes);
1874 llvm_unreachable("unsupported fp const type");
1878 case Type::PointerTyID: {
1879 if (GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1880 aggBuffer->addSymbol(GVar);
1882 else if (ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1883 Value *v = Cexpr->stripPointerCasts();
1884 aggBuffer->addSymbol(v);
1886 unsigned int s = TD->getTypeAllocSize(CPV->getType());
1887 aggBuffer->addZeros(s);
1891 case Type::ArrayTyID:
1892 case Type::VectorTyID:
1893 case Type::StructTyID: {
1894 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
1895 isa<ConstantStruct>(CPV)) {
1896 int ElementSize = TD->getTypeAllocSize(CPV->getType());
1897 bufferAggregateConstant(CPV, aggBuffer);
1898 if ( Bytes > ElementSize )
1899 aggBuffer->addZeros(Bytes-ElementSize);
1901 else if (isa<ConstantAggregateZero>(CPV))
1902 aggBuffer->addZeros(Bytes);
1904 llvm_unreachable("Unexpected Constant type");
1909 llvm_unreachable("unsupported type");
1913 void NVPTXAsmPrinter::bufferAggregateConstant(Constant *CPV,
1914 AggBuffer *aggBuffer) {
1915 const DataLayout *TD = TM.getDataLayout();
1919 if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1920 if (CPV->getNumOperands())
1921 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1922 bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1926 if (const ConstantDataSequential *CDS =
1927 dyn_cast<ConstantDataSequential>(CPV)) {
1928 if (CDS->getNumElements())
1929 for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1930 bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1936 if (isa<ConstantStruct>(CPV)) {
1937 if (CPV->getNumOperands()) {
1938 StructType *ST = cast<StructType>(CPV->getType());
1939 for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1941 Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
1942 TD->getTypeAllocSize(ST)
1943 - TD->getStructLayout(ST)->getElementOffset(i);
1945 Bytes = TD->getStructLayout(ST)->getElementOffset(i+1) -
1946 TD->getStructLayout(ST)->getElementOffset(i);
1947 bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes,
1953 llvm_unreachable("unsupported constant type in printAggregateConstant()");
1956 // buildTypeNameMap - Run through symbol table looking for type names.
1960 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
1962 std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
1964 if (PI != TypeNameMap.end() &&
1965 (!PI->second.compare("struct._image1d_t") ||
1966 !PI->second.compare("struct._image2d_t") ||
1967 !PI->second.compare("struct._image3d_t")))
1973 /// PrintAsmOperand - Print out an operand for an inline asm expression.
1975 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1976 unsigned AsmVariant,
1977 const char *ExtraCode,
1979 if (ExtraCode && ExtraCode[0]) {
1980 if (ExtraCode[1] != 0) return true; // Unknown modifier.
1982 switch (ExtraCode[0]) {
1984 // See if this is a generic print operand
1985 return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
1991 printOperand(MI, OpNo, O);
1996 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
1998 unsigned AsmVariant,
1999 const char *ExtraCode,
2001 if (ExtraCode && ExtraCode[0])
2002 return true; // Unknown modifier
2005 printMemOperand(MI, OpNo, O);
2011 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI)
2013 switch(MI.getOpcode()) {
2016 case NVPTX::CallArgBeginInst: case NVPTX::CallArgEndInst0:
2017 case NVPTX::CallArgEndInst1: case NVPTX::CallArgF32:
2018 case NVPTX::CallArgF64: case NVPTX::CallArgI16:
2019 case NVPTX::CallArgI32: case NVPTX::CallArgI32imm:
2020 case NVPTX::CallArgI64: case NVPTX::CallArgI8:
2021 case NVPTX::CallArgParam: case NVPTX::CallVoidInst:
2022 case NVPTX::CallVoidInstReg: case NVPTX::Callseq_End:
2023 case NVPTX::CallVoidInstReg64:
2024 case NVPTX::DeclareParamInst: case NVPTX::DeclareRetMemInst:
2025 case NVPTX::DeclareRetRegInst: case NVPTX::DeclareRetScalarInst:
2026 case NVPTX::DeclareScalarParamInst: case NVPTX::DeclareScalarRegInst:
2027 case NVPTX::StoreParamF32: case NVPTX::StoreParamF64:
2028 case NVPTX::StoreParamI16: case NVPTX::StoreParamI32:
2029 case NVPTX::StoreParamI64: case NVPTX::StoreParamI8:
2030 case NVPTX::StoreParamS32I8: case NVPTX::StoreParamU32I8:
2031 case NVPTX::StoreParamS32I16: case NVPTX::StoreParamU32I16:
2032 case NVPTX::StoreParamScalar2F32: case NVPTX::StoreParamScalar2F64:
2033 case NVPTX::StoreParamScalar2I16: case NVPTX::StoreParamScalar2I32:
2034 case NVPTX::StoreParamScalar2I64: case NVPTX::StoreParamScalar2I8:
2035 case NVPTX::StoreParamScalar4F32: case NVPTX::StoreParamScalar4I16:
2036 case NVPTX::StoreParamScalar4I32: case NVPTX::StoreParamScalar4I8:
2037 case NVPTX::StoreParamV2F32: case NVPTX::StoreParamV2F64:
2038 case NVPTX::StoreParamV2I16: case NVPTX::StoreParamV2I32:
2039 case NVPTX::StoreParamV2I64: case NVPTX::StoreParamV2I8:
2040 case NVPTX::StoreParamV4F32: case NVPTX::StoreParamV4I16:
2041 case NVPTX::StoreParamV4I32: case NVPTX::StoreParamV4I8:
2042 case NVPTX::StoreRetvalF32: case NVPTX::StoreRetvalF64:
2043 case NVPTX::StoreRetvalI16: case NVPTX::StoreRetvalI32:
2044 case NVPTX::StoreRetvalI64: case NVPTX::StoreRetvalI8:
2045 case NVPTX::StoreRetvalScalar2F32: case NVPTX::StoreRetvalScalar2F64:
2046 case NVPTX::StoreRetvalScalar2I16: case NVPTX::StoreRetvalScalar2I32:
2047 case NVPTX::StoreRetvalScalar2I64: case NVPTX::StoreRetvalScalar2I8:
2048 case NVPTX::StoreRetvalScalar4F32: case NVPTX::StoreRetvalScalar4I16:
2049 case NVPTX::StoreRetvalScalar4I32: case NVPTX::StoreRetvalScalar4I8:
2050 case NVPTX::StoreRetvalV2F32: case NVPTX::StoreRetvalV2F64:
2051 case NVPTX::StoreRetvalV2I16: case NVPTX::StoreRetvalV2I32:
2052 case NVPTX::StoreRetvalV2I64: case NVPTX::StoreRetvalV2I8:
2053 case NVPTX::StoreRetvalV4F32: case NVPTX::StoreRetvalV4I16:
2054 case NVPTX::StoreRetvalV4I32: case NVPTX::StoreRetvalV4I8:
2055 case NVPTX::LastCallArgF32: case NVPTX::LastCallArgF64:
2056 case NVPTX::LastCallArgI16: case NVPTX::LastCallArgI32:
2057 case NVPTX::LastCallArgI32imm: case NVPTX::LastCallArgI64:
2058 case NVPTX::LastCallArgI8: case NVPTX::LastCallArgParam:
2059 case NVPTX::LoadParamMemF32: case NVPTX::LoadParamMemF64:
2060 case NVPTX::LoadParamMemI16: case NVPTX::LoadParamMemI32:
2061 case NVPTX::LoadParamMemI64: case NVPTX::LoadParamMemI8:
2062 case NVPTX::LoadParamRegF32: case NVPTX::LoadParamRegF64:
2063 case NVPTX::LoadParamRegI16: case NVPTX::LoadParamRegI32:
2064 case NVPTX::LoadParamRegI64: case NVPTX::LoadParamRegI8:
2065 case NVPTX::LoadParamScalar2F32: case NVPTX::LoadParamScalar2F64:
2066 case NVPTX::LoadParamScalar2I16: case NVPTX::LoadParamScalar2I32:
2067 case NVPTX::LoadParamScalar2I64: case NVPTX::LoadParamScalar2I8:
2068 case NVPTX::LoadParamScalar4F32: case NVPTX::LoadParamScalar4I16:
2069 case NVPTX::LoadParamScalar4I32: case NVPTX::LoadParamScalar4I8:
2070 case NVPTX::LoadParamV2F32: case NVPTX::LoadParamV2F64:
2071 case NVPTX::LoadParamV2I16: case NVPTX::LoadParamV2I32:
2072 case NVPTX::LoadParamV2I64: case NVPTX::LoadParamV2I8:
2073 case NVPTX::LoadParamV4F32: case NVPTX::LoadParamV4I16:
2074 case NVPTX::LoadParamV4I32: case NVPTX::LoadParamV4I8:
2075 case NVPTX::PrototypeInst: case NVPTX::DBG_VALUE:
2081 // Force static initialization.
2082 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2083 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2084 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2088 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2089 std::stringstream temp;
2090 LineReader * reader = this->getReader(filename.str());
2092 temp << filename.str();
2096 temp << reader->readLine(line);
2098 this->OutStreamer.EmitRawText(Twine(temp.str()));
2102 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2103 if (reader == NULL) {
2104 reader = new LineReader(filename);
2107 if (reader->fileName() != filename) {
2109 reader = new LineReader(filename);
2117 LineReader::readLine(unsigned lineNum) {
2118 if (lineNum < theCurLine) {
2120 fstr.seekg(0,std::ios::beg);
2122 while (theCurLine < lineNum) {
2123 fstr.getline(buff,500);
2129 // Force static initialization.
2130 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2131 RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2132 RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);