NVPTX: Delete dead code
[oota-llvm.git] / lib / Target / NVPTX / NVPTXAsmPrinter.cpp
1 //===-- NVPTXAsmPrinter.cpp - NVPTX LLVM assembly writer ------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a printer that converts from our internal representation
11 // of machine-dependent LLVM code to NVPTX assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "NVPTXAsmPrinter.h"
16 #include "InstPrinter/NVPTXInstPrinter.h"
17 #include "MCTargetDesc/NVPTXMCAsmInfo.h"
18 #include "NVPTX.h"
19 #include "NVPTXInstrInfo.h"
20 #include "NVPTXMachineFunctionInfo.h"
21 #include "NVPTXMCExpr.h"
22 #include "NVPTXRegisterInfo.h"
23 #include "NVPTXTargetMachine.h"
24 #include "NVPTXUtilities.h"
25 #include "cl_common_defines.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/CodeGen/Analysis.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/IR/DebugInfo.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/Function.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Operator.h"
39 #include "llvm/MC/MCStreamer.h"
40 #include "llvm/MC/MCSymbol.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/FormattedStream.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Support/TimeValue.h"
47 #include "llvm/Target/TargetLoweringObjectFile.h"
48 #include <sstream>
49 using namespace llvm;
50
51 #define DEPOTNAME "__local_depot"
52
53 static cl::opt<bool>
54 EmitLineNumbers("nvptx-emit-line-numbers", cl::Hidden,
55                 cl::desc("NVPTX Specific: Emit Line numbers even without -G"),
56                 cl::init(true));
57
58 static cl::opt<bool>
59 InterleaveSrc("nvptx-emit-src", cl::ZeroOrMore, cl::Hidden,
60               cl::desc("NVPTX Specific: Emit source line in ptx file"),
61               cl::init(false));
62
63 namespace {
64 /// DiscoverDependentGlobals - Return a set of GlobalVariables on which \p V
65 /// depends.
66 void DiscoverDependentGlobals(const Value *V,
67                               DenseSet<const GlobalVariable *> &Globals) {
68   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
69     Globals.insert(GV);
70   else {
71     if (const User *U = dyn_cast<User>(V)) {
72       for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i) {
73         DiscoverDependentGlobals(U->getOperand(i), Globals);
74       }
75     }
76   }
77 }
78
79 /// VisitGlobalVariableForEmission - Add \p GV to the list of GlobalVariable
80 /// instances to be emitted, but only after any dependents have been added
81 /// first.
82 void VisitGlobalVariableForEmission(
83     const GlobalVariable *GV, SmallVectorImpl<const GlobalVariable *> &Order,
84     DenseSet<const GlobalVariable *> &Visited,
85     DenseSet<const GlobalVariable *> &Visiting) {
86   // Have we already visited this one?
87   if (Visited.count(GV))
88     return;
89
90   // Do we have a circular dependency?
91   if (!Visiting.insert(GV).second)
92     report_fatal_error("Circular dependency found in global variable set");
93
94   // Make sure we visit all dependents first
95   DenseSet<const GlobalVariable *> Others;
96   for (unsigned i = 0, e = GV->getNumOperands(); i != e; ++i)
97     DiscoverDependentGlobals(GV->getOperand(i), Others);
98
99   for (DenseSet<const GlobalVariable *>::iterator I = Others.begin(),
100                                                   E = Others.end();
101        I != E; ++I)
102     VisitGlobalVariableForEmission(*I, Order, Visited, Visiting);
103
104   // Now we can visit ourself
105   Order.push_back(GV);
106   Visited.insert(GV);
107   Visiting.erase(GV);
108 }
109 }
110
111 // @TODO: This is a copy from AsmPrinter.cpp.  The function is static, so we
112 // cannot just link to the existing version.
113 /// LowerConstant - Lower the specified LLVM Constant to an MCExpr.
114 ///
115 using namespace nvptx;
116 const MCExpr *nvptx::LowerConstant(const Constant *CV, AsmPrinter &AP) {
117   MCContext &Ctx = AP.OutContext;
118
119   if (CV->isNullValue() || isa<UndefValue>(CV))
120     return MCConstantExpr::Create(0, Ctx);
121
122   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
123     return MCConstantExpr::Create(CI->getZExtValue(), Ctx);
124
125   if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV))
126     return MCSymbolRefExpr::Create(AP.getSymbol(GV), Ctx);
127
128   if (const BlockAddress *BA = dyn_cast<BlockAddress>(CV))
129     return MCSymbolRefExpr::Create(AP.GetBlockAddressSymbol(BA), Ctx);
130
131   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
132   if (!CE)
133     llvm_unreachable("Unknown constant value to lower!");
134
135   switch (CE->getOpcode()) {
136   default:
137     // If the code isn't optimized, there may be outstanding folding
138     // opportunities. Attempt to fold the expression using DataLayout as a
139     // last resort before giving up.
140     if (Constant *C = ConstantFoldConstantExpression(
141             CE, AP.TM.getSubtargetImpl()->getDataLayout()))
142       if (C != CE)
143         return LowerConstant(C, AP);
144
145     // Otherwise report the problem to the user.
146     {
147       std::string S;
148       raw_string_ostream OS(S);
149       OS << "Unsupported expression in static initializer: ";
150       CE->printAsOperand(OS, /*PrintType=*/ false,
151                          !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
152       report_fatal_error(OS.str());
153     }
154   case Instruction::AddrSpaceCast: {
155     // Strip any addrspace(1)->addrspace(0) addrspace casts. These will be
156     // handled by the generic() logic in the MCExpr printer
157     PointerType *DstTy            = cast<PointerType>(CE->getType());
158     PointerType *SrcTy            = cast<PointerType>(CE->getOperand(0)->getType());
159     if (SrcTy->getAddressSpace() == 1 && DstTy->getAddressSpace() == 0) {
160       return LowerConstant(cast<const Constant>(CE->getOperand(0)), AP);
161     }
162     std::string S;
163     raw_string_ostream OS(S);
164     OS << "Unsupported expression in static initializer: ";
165     CE->printAsOperand(OS, /*PrintType=*/ false,
166                        !AP.MF ? nullptr : AP.MF->getFunction()->getParent());
167     report_fatal_error(OS.str());
168   }
169   case Instruction::GetElementPtr: {
170     const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
171     // Generate a symbolic expression for the byte address
172     APInt OffsetAI(TD.getPointerSizeInBits(), 0);
173     cast<GEPOperator>(CE)->accumulateConstantOffset(TD, OffsetAI);
174
175     const MCExpr *Base = LowerConstant(CE->getOperand(0), AP);
176     if (!OffsetAI)
177       return Base;
178
179     int64_t Offset = OffsetAI.getSExtValue();
180     return MCBinaryExpr::CreateAdd(Base, MCConstantExpr::Create(Offset, Ctx),
181                                    Ctx);
182   }
183
184   case Instruction::Trunc:
185     // We emit the value and depend on the assembler to truncate the generated
186     // expression properly.  This is important for differences between
187     // blockaddress labels.  Since the two labels are in the same function, it
188     // is reasonable to treat their delta as a 32-bit value.
189   // FALL THROUGH.
190   case Instruction::BitCast:
191     return LowerConstant(CE->getOperand(0), AP);
192
193   case Instruction::IntToPtr: {
194     const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
195     // Handle casts to pointers by changing them into casts to the appropriate
196     // integer type.  This promotes constant folding and simplifies this code.
197     Constant *Op = CE->getOperand(0);
198     Op = ConstantExpr::getIntegerCast(Op, TD.getIntPtrType(CV->getContext()),
199                                       false /*ZExt*/);
200     return LowerConstant(Op, AP);
201   }
202
203   case Instruction::PtrToInt: {
204     const DataLayout &TD = *AP.TM.getSubtargetImpl()->getDataLayout();
205     // Support only foldable casts to/from pointers that can be eliminated by
206     // changing the pointer to the appropriately sized integer type.
207     Constant *Op = CE->getOperand(0);
208     Type *Ty = CE->getType();
209
210     const MCExpr *OpExpr = LowerConstant(Op, AP);
211
212     // We can emit the pointer value into this slot if the slot is an
213     // integer slot equal to the size of the pointer.
214     if (TD.getTypeAllocSize(Ty) == TD.getTypeAllocSize(Op->getType()))
215       return OpExpr;
216
217     // Otherwise the pointer is smaller than the resultant integer, mask off
218     // the high bits so we are sure to get a proper truncation if the input is
219     // a constant expr.
220     unsigned InBits = TD.getTypeAllocSizeInBits(Op->getType());
221     const MCExpr *MaskExpr =
222         MCConstantExpr::Create(~0ULL >> (64 - InBits), Ctx);
223     return MCBinaryExpr::CreateAnd(OpExpr, MaskExpr, Ctx);
224   }
225
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:
241       llvm_unreachable("Unknown binary operator constant cast expr");
242     case Instruction::Add:
243       return MCBinaryExpr::CreateAdd(LHS, RHS, Ctx);
244     case Instruction::Sub:
245       return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
246     case Instruction::Mul:
247       return MCBinaryExpr::CreateMul(LHS, RHS, Ctx);
248     case Instruction::SDiv:
249       return MCBinaryExpr::CreateDiv(LHS, RHS, Ctx);
250     case Instruction::SRem:
251       return MCBinaryExpr::CreateMod(LHS, RHS, Ctx);
252     case Instruction::Shl:
253       return MCBinaryExpr::CreateShl(LHS, RHS, Ctx);
254     case Instruction::And:
255       return MCBinaryExpr::CreateAnd(LHS, RHS, Ctx);
256     case Instruction::Or:
257       return MCBinaryExpr::CreateOr(LHS, RHS, Ctx);
258     case Instruction::Xor:
259       return MCBinaryExpr::CreateXor(LHS, RHS, Ctx);
260     }
261   }
262   }
263 }
264
265 void NVPTXAsmPrinter::emitLineNumberAsDotLoc(const MachineInstr &MI) {
266   if (!EmitLineNumbers)
267     return;
268   if (ignoreLoc(MI))
269     return;
270
271   DebugLoc curLoc = MI.getDebugLoc();
272
273   if (prevDebugLoc.isUnknown() && curLoc.isUnknown())
274     return;
275
276   if (prevDebugLoc == curLoc)
277     return;
278
279   prevDebugLoc = curLoc;
280
281   if (curLoc.isUnknown())
282     return;
283
284   const MachineFunction *MF = MI.getParent()->getParent();
285   //const TargetMachine &TM = MF->getTarget();
286
287   const LLVMContext &ctx = MF->getFunction()->getContext();
288   DIScope Scope(curLoc.getScope(ctx));
289
290   assert((!Scope || Scope.isScope()) &&
291     "Scope of a DebugLoc should be null or a DIScope.");
292   if (!Scope)
293      return;
294
295   StringRef fileName(Scope.getFilename());
296   StringRef dirName(Scope.getDirectory());
297   SmallString<128> FullPathName = dirName;
298   if (!dirName.empty() && !sys::path::is_absolute(fileName)) {
299     sys::path::append(FullPathName, fileName);
300     fileName = FullPathName.str();
301   }
302
303   if (filenameMap.find(fileName.str()) == filenameMap.end())
304     return;
305
306   // Emit the line from the source file.
307   if (InterleaveSrc)
308     this->emitSrcInText(fileName.str(), curLoc.getLine());
309
310   std::stringstream temp;
311   temp << "\t.loc " << filenameMap[fileName.str()] << " " << curLoc.getLine()
312        << " " << curLoc.getCol();
313   OutStreamer.EmitRawText(Twine(temp.str().c_str()));
314 }
315
316 void NVPTXAsmPrinter::EmitInstruction(const MachineInstr *MI) {
317   SmallString<128> Str;
318   raw_svector_ostream OS(Str);
319   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
320     emitLineNumberAsDotLoc(*MI);
321
322   MCInst Inst;
323   lowerToMCInst(MI, Inst);
324   EmitToStreamer(OutStreamer, Inst);
325 }
326
327 // Handle symbol backtracking for targets that do not support image handles
328 bool NVPTXAsmPrinter::lowerImageHandleOperand(const MachineInstr *MI,
329                                            unsigned OpNo, MCOperand &MCOp) {
330   const MachineOperand &MO = MI->getOperand(OpNo);
331   const MCInstrDesc &MCID = MI->getDesc();
332
333   if (MCID.TSFlags & NVPTXII::IsTexFlag) {
334     // This is a texture fetch, so operand 4 is a texref and operand 5 is
335     // a samplerref
336     if (OpNo == 4 && MO.isImm()) {
337       lowerImageHandleSymbol(MO.getImm(), MCOp);
338       return true;
339     }
340     if (OpNo == 5 && MO.isImm() && !(MCID.TSFlags & NVPTXII::IsTexModeUnifiedFlag)) {
341       lowerImageHandleSymbol(MO.getImm(), MCOp);
342       return true;
343     }
344
345     return false;
346   } else if (MCID.TSFlags & NVPTXII::IsSuldMask) {
347     unsigned VecSize =
348       1 << (((MCID.TSFlags & NVPTXII::IsSuldMask) >> NVPTXII::IsSuldShift) - 1);
349
350     // For a surface load of vector size N, the Nth operand will be the surfref
351     if (OpNo == VecSize && MO.isImm()) {
352       lowerImageHandleSymbol(MO.getImm(), MCOp);
353       return true;
354     }
355
356     return false;
357   } else if (MCID.TSFlags & NVPTXII::IsSustFlag) {
358     // This is a surface store, so operand 0 is a surfref
359     if (OpNo == 0 && MO.isImm()) {
360       lowerImageHandleSymbol(MO.getImm(), MCOp);
361       return true;
362     }
363
364     return false;
365   } else if (MCID.TSFlags & NVPTXII::IsSurfTexQueryFlag) {
366     // This is a query, so operand 1 is a surfref/texref
367     if (OpNo == 1 && MO.isImm()) {
368       lowerImageHandleSymbol(MO.getImm(), MCOp);
369       return true;
370     }
371
372     return false;
373   }
374
375   return false;
376 }
377
378 void NVPTXAsmPrinter::lowerImageHandleSymbol(unsigned Index, MCOperand &MCOp) {
379   // Ewwww
380   TargetMachine &TM = const_cast<TargetMachine&>(MF->getTarget());
381   NVPTXTargetMachine &nvTM = static_cast<NVPTXTargetMachine&>(TM);
382   const NVPTXMachineFunctionInfo *MFI = MF->getInfo<NVPTXMachineFunctionInfo>();
383   const char *Sym = MFI->getImageHandleSymbol(Index);
384   std::string *SymNamePtr =
385     nvTM.getManagedStrPool()->getManagedString(Sym);
386   MCOp = GetSymbolRef(OutContext.GetOrCreateSymbol(
387     StringRef(SymNamePtr->c_str())));
388 }
389
390 void NVPTXAsmPrinter::lowerToMCInst(const MachineInstr *MI, MCInst &OutMI) {
391   OutMI.setOpcode(MI->getOpcode());
392   const NVPTXSubtarget &ST = TM.getSubtarget<NVPTXSubtarget>();
393
394   // Special: Do not mangle symbol operand of CALL_PROTOTYPE
395   if (MI->getOpcode() == NVPTX::CALL_PROTOTYPE) {
396     const MachineOperand &MO = MI->getOperand(0);
397     OutMI.addOperand(GetSymbolRef(
398       OutContext.GetOrCreateSymbol(Twine(MO.getSymbolName()))));
399     return;
400   }
401
402   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
403     const MachineOperand &MO = MI->getOperand(i);
404
405     MCOperand MCOp;
406     if (!ST.hasImageHandles()) {
407       if (lowerImageHandleOperand(MI, i, MCOp)) {
408         OutMI.addOperand(MCOp);
409         continue;
410       }
411     }
412
413     if (lowerOperand(MO, MCOp))
414       OutMI.addOperand(MCOp);
415   }
416 }
417
418 bool NVPTXAsmPrinter::lowerOperand(const MachineOperand &MO,
419                                    MCOperand &MCOp) {
420   switch (MO.getType()) {
421   default: llvm_unreachable("unknown operand type");
422   case MachineOperand::MO_Register:
423     MCOp = MCOperand::CreateReg(encodeVirtualRegister(MO.getReg()));
424     break;
425   case MachineOperand::MO_Immediate:
426     MCOp = MCOperand::CreateImm(MO.getImm());
427     break;
428   case MachineOperand::MO_MachineBasicBlock:
429     MCOp = MCOperand::CreateExpr(MCSymbolRefExpr::Create(
430         MO.getMBB()->getSymbol(), OutContext));
431     break;
432   case MachineOperand::MO_ExternalSymbol:
433     MCOp = GetSymbolRef(GetExternalSymbolSymbol(MO.getSymbolName()));
434     break;
435   case MachineOperand::MO_GlobalAddress:
436     MCOp = GetSymbolRef(getSymbol(MO.getGlobal()));
437     break;
438   case MachineOperand::MO_FPImmediate: {
439     const ConstantFP *Cnt = MO.getFPImm();
440     APFloat Val = Cnt->getValueAPF();
441
442     switch (Cnt->getType()->getTypeID()) {
443     default: report_fatal_error("Unsupported FP type"); break;
444     case Type::FloatTyID:
445       MCOp = MCOperand::CreateExpr(
446         NVPTXFloatMCExpr::CreateConstantFPSingle(Val, OutContext));
447       break;
448     case Type::DoubleTyID:
449       MCOp = MCOperand::CreateExpr(
450         NVPTXFloatMCExpr::CreateConstantFPDouble(Val, OutContext));
451       break;
452     }
453     break;
454   }
455   }
456   return true;
457 }
458
459 unsigned NVPTXAsmPrinter::encodeVirtualRegister(unsigned Reg) {
460   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
461     const TargetRegisterClass *RC = MRI->getRegClass(Reg);
462
463     DenseMap<unsigned, unsigned> &RegMap = VRegMapping[RC];
464     unsigned RegNum = RegMap[Reg];
465
466     // Encode the register class in the upper 4 bits
467     // Must be kept in sync with NVPTXInstPrinter::printRegName
468     unsigned Ret = 0;
469     if (RC == &NVPTX::Int1RegsRegClass) {
470       Ret = (1 << 28);
471     } else if (RC == &NVPTX::Int16RegsRegClass) {
472       Ret = (2 << 28);
473     } else if (RC == &NVPTX::Int32RegsRegClass) {
474       Ret = (3 << 28);
475     } else if (RC == &NVPTX::Int64RegsRegClass) {
476       Ret = (4 << 28);
477     } else if (RC == &NVPTX::Float32RegsRegClass) {
478       Ret = (5 << 28);
479     } else if (RC == &NVPTX::Float64RegsRegClass) {
480       Ret = (6 << 28);
481     } else {
482       report_fatal_error("Bad register class");
483     }
484
485     // Insert the vreg number
486     Ret |= (RegNum & 0x0FFFFFFF);
487     return Ret;
488   } else {
489     // Some special-use registers are actually physical registers.
490     // Encode this as the register class ID of 0 and the real register ID.
491     return Reg & 0x0FFFFFFF;
492   }
493 }
494
495 MCOperand NVPTXAsmPrinter::GetSymbolRef(const MCSymbol *Symbol) {
496   const MCExpr *Expr;
497   Expr = MCSymbolRefExpr::Create(Symbol, MCSymbolRefExpr::VK_None,
498                                  OutContext);
499   return MCOperand::CreateExpr(Expr);
500 }
501
502 void NVPTXAsmPrinter::printReturnValStr(const Function *F, raw_ostream &O) {
503   const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
504   const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
505
506   Type *Ty = F->getReturnType();
507
508   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
509
510   if (Ty->getTypeID() == Type::VoidTyID)
511     return;
512
513   O << " (";
514
515   if (isABI) {
516     if (Ty->isFloatingPointTy() || Ty->isIntegerTy()) {
517       unsigned size = 0;
518       if (const IntegerType *ITy = dyn_cast<IntegerType>(Ty)) {
519         size = ITy->getBitWidth();
520         if (size < 32)
521           size = 32;
522       } else {
523         assert(Ty->isFloatingPointTy() && "Floating point type expected here");
524         size = Ty->getPrimitiveSizeInBits();
525       }
526
527       O << ".param .b" << size << " func_retval0";
528     } else if (isa<PointerType>(Ty)) {
529       O << ".param .b" << TLI->getPointerTy().getSizeInBits()
530         << " func_retval0";
531     } else {
532       if ((Ty->getTypeID() == Type::StructTyID) || isa<VectorType>(Ty)) {
533         unsigned totalsz = TD->getTypeAllocSize(Ty);
534         unsigned retAlignment = 0;
535         if (!llvm::getAlign(*F, 0, retAlignment))
536           retAlignment = TD->getABITypeAlignment(Ty);
537         O << ".param .align " << retAlignment << " .b8 func_retval0[" << totalsz
538           << "]";
539       } else
540         assert(false && "Unknown return type");
541     }
542   } else {
543     SmallVector<EVT, 16> vtparts;
544     ComputeValueVTs(*TLI, Ty, vtparts);
545     unsigned idx = 0;
546     for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
547       unsigned elems = 1;
548       EVT elemtype = vtparts[i];
549       if (vtparts[i].isVector()) {
550         elems = vtparts[i].getVectorNumElements();
551         elemtype = vtparts[i].getVectorElementType();
552       }
553
554       for (unsigned j = 0, je = elems; j != je; ++j) {
555         unsigned sz = elemtype.getSizeInBits();
556         if (elemtype.isInteger() && (sz < 32))
557           sz = 32;
558         O << ".reg .b" << sz << " func_retval" << idx;
559         if (j < je - 1)
560           O << ", ";
561         ++idx;
562       }
563       if (i < e - 1)
564         O << ", ";
565     }
566   }
567   O << ") ";
568   return;
569 }
570
571 void NVPTXAsmPrinter::printReturnValStr(const MachineFunction &MF,
572                                         raw_ostream &O) {
573   const Function *F = MF.getFunction();
574   printReturnValStr(F, O);
575 }
576
577 void NVPTXAsmPrinter::EmitFunctionEntryLabel() {
578   SmallString<128> Str;
579   raw_svector_ostream O(Str);
580
581   if (!GlobalsEmitted) {
582     emitGlobals(*MF->getFunction()->getParent());
583     GlobalsEmitted = true;
584   }
585   
586   // Set up
587   MRI = &MF->getRegInfo();
588   F = MF->getFunction();
589   emitLinkageDirective(F, O);
590   if (llvm::isKernelFunction(*F))
591     O << ".entry ";
592   else {
593     O << ".func ";
594     printReturnValStr(*MF, O);
595   }
596
597   O << *CurrentFnSym;
598
599   emitFunctionParamList(*MF, O);
600
601   if (llvm::isKernelFunction(*F))
602     emitKernelFunctionDirectives(*F, O);
603
604   OutStreamer.EmitRawText(O.str());
605
606   prevDebugLoc = DebugLoc();
607 }
608
609 void NVPTXAsmPrinter::EmitFunctionBodyStart() {
610   VRegMapping.clear();
611   OutStreamer.EmitRawText(StringRef("{\n"));
612   setAndEmitFunctionVirtualRegisters(*MF);
613
614   SmallString<128> Str;
615   raw_svector_ostream O(Str);
616   emitDemotedVars(MF->getFunction(), O);
617   OutStreamer.EmitRawText(O.str());
618 }
619
620 void NVPTXAsmPrinter::EmitFunctionBodyEnd() {
621   OutStreamer.EmitRawText(StringRef("}\n"));
622   VRegMapping.clear();
623 }
624
625 void NVPTXAsmPrinter::emitImplicitDef(const MachineInstr *MI) const {
626   unsigned RegNo = MI->getOperand(0).getReg();
627   const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
628   if (TRI->isVirtualRegister(RegNo)) {
629     OutStreamer.AddComment(Twine("implicit-def: ") +
630                            getVirtualRegisterName(RegNo));
631   } else {
632     OutStreamer.AddComment(
633         Twine("implicit-def: ") +
634         TM.getSubtargetImpl()->getRegisterInfo()->getName(RegNo));
635   }
636   OutStreamer.AddBlankLine();
637 }
638
639 void NVPTXAsmPrinter::emitKernelFunctionDirectives(const Function &F,
640                                                    raw_ostream &O) const {
641   // If the NVVM IR has some of reqntid* specified, then output
642   // the reqntid directive, and set the unspecified ones to 1.
643   // If none of reqntid* is specified, don't output reqntid directive.
644   unsigned reqntidx, reqntidy, reqntidz;
645   bool specified = false;
646   if (llvm::getReqNTIDx(F, reqntidx) == false)
647     reqntidx = 1;
648   else
649     specified = true;
650   if (llvm::getReqNTIDy(F, reqntidy) == false)
651     reqntidy = 1;
652   else
653     specified = true;
654   if (llvm::getReqNTIDz(F, reqntidz) == false)
655     reqntidz = 1;
656   else
657     specified = true;
658
659   if (specified)
660     O << ".reqntid " << reqntidx << ", " << reqntidy << ", " << reqntidz
661       << "\n";
662
663   // If the NVVM IR has some of maxntid* specified, then output
664   // the maxntid directive, and set the unspecified ones to 1.
665   // If none of maxntid* is specified, don't output maxntid directive.
666   unsigned maxntidx, maxntidy, maxntidz;
667   specified = false;
668   if (llvm::getMaxNTIDx(F, maxntidx) == false)
669     maxntidx = 1;
670   else
671     specified = true;
672   if (llvm::getMaxNTIDy(F, maxntidy) == false)
673     maxntidy = 1;
674   else
675     specified = true;
676   if (llvm::getMaxNTIDz(F, maxntidz) == false)
677     maxntidz = 1;
678   else
679     specified = true;
680
681   if (specified)
682     O << ".maxntid " << maxntidx << ", " << maxntidy << ", " << maxntidz
683       << "\n";
684
685   unsigned mincta;
686   if (llvm::getMinCTASm(F, mincta))
687     O << ".minnctapersm " << mincta << "\n";
688 }
689
690 std::string
691 NVPTXAsmPrinter::getVirtualRegisterName(unsigned Reg) const {
692   const TargetRegisterClass *RC = MRI->getRegClass(Reg);
693
694   std::string Name;
695   raw_string_ostream NameStr(Name);
696
697   VRegRCMap::const_iterator I = VRegMapping.find(RC);
698   assert(I != VRegMapping.end() && "Bad register class");
699   const DenseMap<unsigned, unsigned> &RegMap = I->second;
700
701   VRegMap::const_iterator VI = RegMap.find(Reg);
702   assert(VI != RegMap.end() && "Bad virtual register");
703   unsigned MappedVR = VI->second;
704
705   NameStr << getNVPTXRegClassStr(RC) << MappedVR;
706
707   NameStr.flush();
708   return Name;
709 }
710
711 void NVPTXAsmPrinter::emitVirtualRegister(unsigned int vr,
712                                           raw_ostream &O) {
713   O << getVirtualRegisterName(vr);
714 }
715
716 void NVPTXAsmPrinter::printVecModifiedImmediate(
717     const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
718   static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
719   int Imm = (int) MO.getImm();
720   if (0 == strcmp(Modifier, "vecelem"))
721     O << "_" << vecelem[Imm];
722   else if (0 == strcmp(Modifier, "vecv4comm1")) {
723     if ((Imm < 0) || (Imm > 3))
724       O << "//";
725   } else if (0 == strcmp(Modifier, "vecv4comm2")) {
726     if ((Imm < 4) || (Imm > 7))
727       O << "//";
728   } else if (0 == strcmp(Modifier, "vecv4pos")) {
729     if (Imm < 0)
730       Imm = 0;
731     O << "_" << vecelem[Imm % 4];
732   } else if (0 == strcmp(Modifier, "vecv2comm1")) {
733     if ((Imm < 0) || (Imm > 1))
734       O << "//";
735   } else if (0 == strcmp(Modifier, "vecv2comm2")) {
736     if ((Imm < 2) || (Imm > 3))
737       O << "//";
738   } else if (0 == strcmp(Modifier, "vecv2pos")) {
739     if (Imm < 0)
740       Imm = 0;
741     O << "_" << vecelem[Imm % 2];
742   } else
743     llvm_unreachable("Unknown Modifier on immediate operand");
744 }
745
746
747
748 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
749
750   emitLinkageDirective(F, O);
751   if (llvm::isKernelFunction(*F))
752     O << ".entry ";
753   else
754     O << ".func ";
755   printReturnValStr(F, O);
756   O << *getSymbol(F) << "\n";
757   emitFunctionParamList(F, O);
758   O << ";\n";
759 }
760
761 static bool usedInGlobalVarDef(const Constant *C) {
762   if (!C)
763     return false;
764
765   if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
766     if (GV->getName().str() == "llvm.used")
767       return false;
768     return true;
769   }
770
771   for (const User *U : C->users())
772     if (const Constant *C = dyn_cast<Constant>(U))
773       if (usedInGlobalVarDef(C))
774         return true;
775
776   return false;
777 }
778
779 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
780   if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
781     if (othergv->getName().str() == "llvm.used")
782       return true;
783   }
784
785   if (const Instruction *instr = dyn_cast<Instruction>(U)) {
786     if (instr->getParent() && instr->getParent()->getParent()) {
787       const Function *curFunc = instr->getParent()->getParent();
788       if (oneFunc && (curFunc != oneFunc))
789         return false;
790       oneFunc = curFunc;
791       return true;
792     } else
793       return false;
794   }
795
796   for (const User *UU : U->users())
797     if (usedInOneFunc(UU, oneFunc) == false)
798       return false;
799
800   return true;
801 }
802
803 /* Find out if a global variable can be demoted to local scope.
804  * Currently, this is valid for CUDA shared variables, which have local
805  * scope and global lifetime. So the conditions to check are :
806  * 1. Is the global variable in shared address space?
807  * 2. Does it have internal linkage?
808  * 3. Is the global variable referenced only in one function?
809  */
810 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
811   if (gv->hasInternalLinkage() == false)
812     return false;
813   const PointerType *Pty = gv->getType();
814   if (Pty->getAddressSpace() != llvm::ADDRESS_SPACE_SHARED)
815     return false;
816
817   const Function *oneFunc = nullptr;
818
819   bool flag = usedInOneFunc(gv, oneFunc);
820   if (flag == false)
821     return false;
822   if (!oneFunc)
823     return false;
824   f = oneFunc;
825   return true;
826 }
827
828 static bool useFuncSeen(const Constant *C,
829                         llvm::DenseMap<const Function *, bool> &seenMap) {
830   for (const User *U : C->users()) {
831     if (const Constant *cu = dyn_cast<Constant>(U)) {
832       if (useFuncSeen(cu, seenMap))
833         return true;
834     } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
835       const BasicBlock *bb = I->getParent();
836       if (!bb)
837         continue;
838       const Function *caller = bb->getParent();
839       if (!caller)
840         continue;
841       if (seenMap.find(caller) != seenMap.end())
842         return true;
843     }
844   }
845   return false;
846 }
847
848 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
849   llvm::DenseMap<const Function *, bool> seenMap;
850   for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
851     const Function *F = FI;
852
853     if (F->isDeclaration()) {
854       if (F->use_empty())
855         continue;
856       if (F->getIntrinsicID())
857         continue;
858       emitDeclaration(F, O);
859       continue;
860     }
861     for (const User *U : F->users()) {
862       if (const Constant *C = dyn_cast<Constant>(U)) {
863         if (usedInGlobalVarDef(C)) {
864           // The use is in the initialization of a global variable
865           // that is a function pointer, so print a declaration
866           // for the original function
867           emitDeclaration(F, O);
868           break;
869         }
870         // Emit a declaration of this function if the function that
871         // uses this constant expr has already been seen.
872         if (useFuncSeen(C, seenMap)) {
873           emitDeclaration(F, O);
874           break;
875         }
876       }
877
878       if (!isa<Instruction>(U))
879         continue;
880       const Instruction *instr = cast<Instruction>(U);
881       const BasicBlock *bb = instr->getParent();
882       if (!bb)
883         continue;
884       const Function *caller = bb->getParent();
885       if (!caller)
886         continue;
887
888       // If a caller has already been seen, then the caller is
889       // appearing in the module before the callee. so print out
890       // a declaration for the callee.
891       if (seenMap.find(caller) != seenMap.end()) {
892         emitDeclaration(F, O);
893         break;
894       }
895     }
896     seenMap[F] = true;
897   }
898 }
899
900 void NVPTXAsmPrinter::recordAndEmitFilenames(Module &M) {
901   DebugInfoFinder DbgFinder;
902   DbgFinder.processModule(M);
903
904   unsigned i = 1;
905   for (DICompileUnit DIUnit : DbgFinder.compile_units()) {
906     StringRef Filename(DIUnit.getFilename());
907     StringRef Dirname(DIUnit.getDirectory());
908     SmallString<128> FullPathName = Dirname;
909     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
910       sys::path::append(FullPathName, Filename);
911       Filename = FullPathName.str();
912     }
913     if (filenameMap.find(Filename.str()) != filenameMap.end())
914       continue;
915     filenameMap[Filename.str()] = i;
916     OutStreamer.EmitDwarfFileDirective(i, "", Filename.str());
917     ++i;
918   }
919
920   for (DISubprogram SP : DbgFinder.subprograms()) {
921     StringRef Filename(SP.getFilename());
922     StringRef Dirname(SP.getDirectory());
923     SmallString<128> FullPathName = Dirname;
924     if (!Dirname.empty() && !sys::path::is_absolute(Filename)) {
925       sys::path::append(FullPathName, Filename);
926       Filename = FullPathName.str();
927     }
928     if (filenameMap.find(Filename.str()) != filenameMap.end())
929       continue;
930     filenameMap[Filename.str()] = i;
931     ++i;
932   }
933 }
934
935 bool NVPTXAsmPrinter::doInitialization(Module &M) {
936
937   SmallString<128> Str1;
938   raw_svector_ostream OS1(Str1);
939
940   MMI = getAnalysisIfAvailable<MachineModuleInfo>();
941   MMI->AnalyzeModule(M);
942
943   // We need to call the parent's one explicitly.
944   //bool Result = AsmPrinter::doInitialization(M);
945
946   // Initialize TargetLoweringObjectFile.
947   const_cast<TargetLoweringObjectFile &>(getObjFileLowering())
948       .Initialize(OutContext, TM);
949
950   Mang = new Mangler(TM.getSubtargetImpl()->getDataLayout());
951
952   // Emit header before any dwarf directives are emitted below.
953   emitHeader(M, OS1);
954   OutStreamer.EmitRawText(OS1.str());
955
956   // Already commented out
957   //bool Result = AsmPrinter::doInitialization(M);
958
959   // Emit module-level inline asm if it exists.
960   if (!M.getModuleInlineAsm().empty()) {
961     OutStreamer.AddComment("Start of file scope inline assembly");
962     OutStreamer.AddBlankLine();
963     OutStreamer.EmitRawText(StringRef(M.getModuleInlineAsm()));
964     OutStreamer.AddBlankLine();
965     OutStreamer.AddComment("End of file scope inline assembly");
966     OutStreamer.AddBlankLine();
967   }
968
969   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)
970     recordAndEmitFilenames(M);
971
972   GlobalsEmitted = false;
973     
974   return false; // success
975 }
976
977 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
978   SmallString<128> Str2;
979   raw_svector_ostream OS2(Str2);
980
981   emitDeclarations(M, OS2);
982
983   // As ptxas does not support forward references of globals, we need to first
984   // sort the list of module-level globals in def-use order. We visit each
985   // global variable in order, and ensure that we emit it *after* its dependent
986   // globals. We use a little extra memory maintaining both a set and a list to
987   // have fast searches while maintaining a strict ordering.
988   SmallVector<const GlobalVariable *, 8> Globals;
989   DenseSet<const GlobalVariable *> GVVisited;
990   DenseSet<const GlobalVariable *> GVVisiting;
991
992   // Visit each global variable, in order
993   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
994        I != E; ++I)
995     VisitGlobalVariableForEmission(I, Globals, GVVisited, GVVisiting);
996
997   assert(GVVisited.size() == M.getGlobalList().size() &&
998          "Missed a global variable");
999   assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
1000
1001   // Print out module-level global variables in proper order
1002   for (unsigned i = 0, e = Globals.size(); i != e; ++i)
1003     printModuleLevelGV(Globals[i], OS2);
1004
1005   OS2 << '\n';
1006
1007   OutStreamer.EmitRawText(OS2.str());
1008 }
1009
1010 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O) {
1011   O << "//\n";
1012   O << "// Generated by LLVM NVPTX Back-End\n";
1013   O << "//\n";
1014   O << "\n";
1015
1016   unsigned PTXVersion = nvptxSubtarget.getPTXVersion();
1017   O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
1018
1019   O << ".target ";
1020   O << nvptxSubtarget.getTargetName();
1021
1022   if (nvptxSubtarget.getDrvInterface() == NVPTX::NVCL)
1023     O << ", texmode_independent";
1024   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1025     if (!nvptxSubtarget.hasDouble())
1026       O << ", map_f64_to_f32";
1027   }
1028
1029   if (MAI->doesSupportDebugInformation())
1030     O << ", debug";
1031
1032   O << "\n";
1033
1034   O << ".address_size ";
1035   if (nvptxSubtarget.is64Bit())
1036     O << "64";
1037   else
1038     O << "32";
1039   O << "\n";
1040
1041   O << "\n";
1042 }
1043
1044 bool NVPTXAsmPrinter::doFinalization(Module &M) {
1045
1046   // If we did not emit any functions, then the global declarations have not
1047   // yet been emitted.
1048   if (!GlobalsEmitted) {
1049     emitGlobals(M);
1050     GlobalsEmitted = true;
1051   }
1052
1053   // XXX Temproarily remove global variables so that doFinalization() will not
1054   // emit them again (global variables are emitted at beginning).
1055
1056   Module::GlobalListType &global_list = M.getGlobalList();
1057   int i, n = global_list.size();
1058   GlobalVariable **gv_array = new GlobalVariable *[n];
1059
1060   // first, back-up GlobalVariable in gv_array
1061   i = 0;
1062   for (Module::global_iterator I = global_list.begin(), E = global_list.end();
1063        I != E; ++I)
1064     gv_array[i++] = &*I;
1065
1066   // second, empty global_list
1067   while (!global_list.empty())
1068     global_list.remove(global_list.begin());
1069
1070   // call doFinalization
1071   bool ret = AsmPrinter::doFinalization(M);
1072
1073   // now we restore global variables
1074   for (i = 0; i < n; i++)
1075     global_list.insert(global_list.end(), gv_array[i]);
1076
1077   clearAnnotationCache(&M);
1078
1079   delete[] gv_array;
1080   return ret;
1081
1082   //bool Result = AsmPrinter::doFinalization(M);
1083   // Instead of calling the parents doFinalization, we may
1084   // clone parents doFinalization and customize here.
1085   // Currently, we if NVISA out the EmitGlobals() in
1086   // parent's doFinalization, which is too intrusive.
1087   //
1088   // Same for the doInitialization.
1089   //return Result;
1090 }
1091
1092 // This function emits appropriate linkage directives for
1093 // functions and global variables.
1094 //
1095 // extern function declaration            -> .extern
1096 // extern function definition             -> .visible
1097 // external global variable with init     -> .visible
1098 // external without init                  -> .extern
1099 // appending                              -> not allowed, assert.
1100 // for any linkage other than
1101 // internal, private, linker_private,
1102 // linker_private_weak, linker_private_weak_def_auto,
1103 // we emit                                -> .weak.
1104
1105 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
1106                                            raw_ostream &O) {
1107   if (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA) {
1108     if (V->hasExternalLinkage()) {
1109       if (isa<GlobalVariable>(V)) {
1110         const GlobalVariable *GVar = cast<GlobalVariable>(V);
1111         if (GVar) {
1112           if (GVar->hasInitializer())
1113             O << ".visible ";
1114           else
1115             O << ".extern ";
1116         }
1117       } else if (V->isDeclaration())
1118         O << ".extern ";
1119       else
1120         O << ".visible ";
1121     } else if (V->hasAppendingLinkage()) {
1122       std::string msg;
1123       msg.append("Error: ");
1124       msg.append("Symbol ");
1125       if (V->hasName())
1126         msg.append(V->getName().str());
1127       msg.append("has unsupported appending linkage type");
1128       llvm_unreachable(msg.c_str());
1129     } else if (!V->hasInternalLinkage() &&
1130                !V->hasPrivateLinkage()) {
1131       O << ".weak ";
1132     }
1133   }
1134 }
1135
1136 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1137                                          raw_ostream &O,
1138                                          bool processDemoted) {
1139
1140   // Skip meta data
1141   if (GVar->hasSection()) {
1142     if (GVar->getSection() == StringRef("llvm.metadata"))
1143       return;
1144   }
1145
1146   // Skip LLVM intrinsic global variables
1147   if (GVar->getName().startswith("llvm.") ||
1148       GVar->getName().startswith("nvvm."))
1149     return;
1150
1151   const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1152
1153   // GlobalVariables are always constant pointers themselves.
1154   const PointerType *PTy = GVar->getType();
1155   Type *ETy = PTy->getElementType();
1156
1157   if (GVar->hasExternalLinkage()) {
1158     if (GVar->hasInitializer())
1159       O << ".visible ";
1160     else
1161       O << ".extern ";
1162   } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1163              GVar->hasAvailableExternallyLinkage() ||
1164              GVar->hasCommonLinkage()) {
1165     O << ".weak ";
1166   }
1167
1168   if (llvm::isTexture(*GVar)) {
1169     O << ".global .texref " << llvm::getTextureName(*GVar) << ";\n";
1170     return;
1171   }
1172
1173   if (llvm::isSurface(*GVar)) {
1174     O << ".global .surfref " << llvm::getSurfaceName(*GVar) << ";\n";
1175     return;
1176   }
1177
1178   if (GVar->isDeclaration()) {
1179     // (extern) declarations, no definition or initializer
1180     // Currently the only known declaration is for an automatic __local
1181     // (.shared) promoted to global.
1182     emitPTXGlobalVariable(GVar, O);
1183     O << ";\n";
1184     return;
1185   }
1186
1187   if (llvm::isSampler(*GVar)) {
1188     O << ".global .samplerref " << llvm::getSamplerName(*GVar);
1189
1190     const Constant *Initializer = nullptr;
1191     if (GVar->hasInitializer())
1192       Initializer = GVar->getInitializer();
1193     const ConstantInt *CI = nullptr;
1194     if (Initializer)
1195       CI = dyn_cast<ConstantInt>(Initializer);
1196     if (CI) {
1197       unsigned sample = CI->getZExtValue();
1198
1199       O << " = { ";
1200
1201       for (int i = 0,
1202                addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1203            i < 3; i++) {
1204         O << "addr_mode_" << i << " = ";
1205         switch (addr) {
1206         case 0:
1207           O << "wrap";
1208           break;
1209         case 1:
1210           O << "clamp_to_border";
1211           break;
1212         case 2:
1213           O << "clamp_to_edge";
1214           break;
1215         case 3:
1216           O << "wrap";
1217           break;
1218         case 4:
1219           O << "mirror";
1220           break;
1221         }
1222         O << ", ";
1223       }
1224       O << "filter_mode = ";
1225       switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1226       case 0:
1227         O << "nearest";
1228         break;
1229       case 1:
1230         O << "linear";
1231         break;
1232       case 2:
1233         llvm_unreachable("Anisotropic filtering is not supported");
1234       default:
1235         O << "nearest";
1236         break;
1237       }
1238       if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1239         O << ", force_unnormalized_coords = 1";
1240       }
1241       O << " }";
1242     }
1243
1244     O << ";\n";
1245     return;
1246   }
1247
1248   if (GVar->hasPrivateLinkage()) {
1249
1250     if (!strncmp(GVar->getName().data(), "unrollpragma", 12))
1251       return;
1252
1253     // FIXME - need better way (e.g. Metadata) to avoid generating this global
1254     if (!strncmp(GVar->getName().data(), "filename", 8))
1255       return;
1256     if (GVar->use_empty())
1257       return;
1258   }
1259
1260   const Function *demotedFunc = nullptr;
1261   if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1262     O << "// " << GVar->getName().str() << " has been demoted\n";
1263     if (localDecls.find(demotedFunc) != localDecls.end())
1264       localDecls[demotedFunc].push_back(GVar);
1265     else {
1266       std::vector<const GlobalVariable *> temp;
1267       temp.push_back(GVar);
1268       localDecls[demotedFunc] = temp;
1269     }
1270     return;
1271   }
1272
1273   O << ".";
1274   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1275
1276   if (isManaged(*GVar)) {
1277     O << " .attribute(.managed)";
1278   }
1279
1280   if (GVar->getAlignment() == 0)
1281     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1282   else
1283     O << " .align " << GVar->getAlignment();
1284
1285   if (ETy->isSingleValueType()) {
1286     O << " .";
1287     // Special case: ABI requires that we use .u8 for predicates
1288     if (ETy->isIntegerTy(1))
1289       O << "u8";
1290     else
1291       O << getPTXFundamentalTypeStr(ETy, false);
1292     O << " ";
1293     O << *getSymbol(GVar);
1294
1295     // Ptx allows variable initilization only for constant and global state
1296     // spaces.
1297     if (GVar->hasInitializer()) {
1298       if ((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1299           (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) {
1300         const Constant *Initializer = GVar->getInitializer();
1301         // 'undef' is treated as there is no value spefied.
1302         if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1303           O << " = ";
1304           printScalarConstant(Initializer, O);
1305         }
1306       } else {
1307         // The frontend adds zero-initializer to variables that don't have an
1308         // initial value, so skip warning for this case.
1309         if (!GVar->getInitializer()->isNullValue()) {
1310           std::string warnMsg = "initial value of '" + GVar->getName().str() +
1311               "' is not allowed in addrspace(" +
1312               llvm::utostr_32(PTy->getAddressSpace()) + ")";
1313           report_fatal_error(warnMsg.c_str());
1314         }
1315       }
1316     }
1317   } else {
1318     unsigned int ElementSize = 0;
1319
1320     // Although PTX has direct support for struct type and array type and
1321     // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1322     // targets that support these high level field accesses. Structs, arrays
1323     // and vectors are lowered into arrays of bytes.
1324     switch (ETy->getTypeID()) {
1325     case Type::StructTyID:
1326     case Type::ArrayTyID:
1327     case Type::VectorTyID:
1328       ElementSize = TD->getTypeStoreSize(ETy);
1329       // Ptx allows variable initilization only for constant and
1330       // global state spaces.
1331       if (((PTy->getAddressSpace() == llvm::ADDRESS_SPACE_GLOBAL) ||
1332            (PTy->getAddressSpace() == llvm::ADDRESS_SPACE_CONST)) &&
1333           GVar->hasInitializer()) {
1334         const Constant *Initializer = GVar->getInitializer();
1335         if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1336           AggBuffer aggBuffer(ElementSize, O, *this);
1337           bufferAggregateConstant(Initializer, &aggBuffer);
1338           if (aggBuffer.numSymbols) {
1339             if (nvptxSubtarget.is64Bit()) {
1340               O << " .u64 " << *getSymbol(GVar) << "[";
1341               O << ElementSize / 8;
1342             } else {
1343               O << " .u32 " << *getSymbol(GVar) << "[";
1344               O << ElementSize / 4;
1345             }
1346             O << "]";
1347           } else {
1348             O << " .b8 " << *getSymbol(GVar) << "[";
1349             O << ElementSize;
1350             O << "]";
1351           }
1352           O << " = {";
1353           aggBuffer.print();
1354           O << "}";
1355         } else {
1356           O << " .b8 " << *getSymbol(GVar);
1357           if (ElementSize) {
1358             O << "[";
1359             O << ElementSize;
1360             O << "]";
1361           }
1362         }
1363       } else {
1364         O << " .b8 " << *getSymbol(GVar);
1365         if (ElementSize) {
1366           O << "[";
1367           O << ElementSize;
1368           O << "]";
1369         }
1370       }
1371       break;
1372     default:
1373       llvm_unreachable("type not supported yet");
1374     }
1375
1376   }
1377   O << ";\n";
1378 }
1379
1380 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1381   if (localDecls.find(f) == localDecls.end())
1382     return;
1383
1384   std::vector<const GlobalVariable *> &gvars = localDecls[f];
1385
1386   for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1387     O << "\t// demoted variable\n\t";
1388     printModuleLevelGV(gvars[i], O, true);
1389   }
1390 }
1391
1392 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1393                                           raw_ostream &O) const {
1394   switch (AddressSpace) {
1395   case llvm::ADDRESS_SPACE_LOCAL:
1396     O << "local";
1397     break;
1398   case llvm::ADDRESS_SPACE_GLOBAL:
1399     O << "global";
1400     break;
1401   case llvm::ADDRESS_SPACE_CONST:
1402     O << "const";
1403     break;
1404   case llvm::ADDRESS_SPACE_SHARED:
1405     O << "shared";
1406     break;
1407   default:
1408     report_fatal_error("Bad address space found while emitting PTX");
1409     break;
1410   }
1411 }
1412
1413 std::string
1414 NVPTXAsmPrinter::getPTXFundamentalTypeStr(const Type *Ty, bool useB4PTR) const {
1415   switch (Ty->getTypeID()) {
1416   default:
1417     llvm_unreachable("unexpected type");
1418     break;
1419   case Type::IntegerTyID: {
1420     unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1421     if (NumBits == 1)
1422       return "pred";
1423     else if (NumBits <= 64) {
1424       std::string name = "u";
1425       return name + utostr(NumBits);
1426     } else {
1427       llvm_unreachable("Integer too large");
1428       break;
1429     }
1430     break;
1431   }
1432   case Type::FloatTyID:
1433     return "f32";
1434   case Type::DoubleTyID:
1435     return "f64";
1436   case Type::PointerTyID:
1437     if (nvptxSubtarget.is64Bit())
1438       if (useB4PTR)
1439         return "b64";
1440       else
1441         return "u64";
1442     else if (useB4PTR)
1443       return "b32";
1444     else
1445       return "u32";
1446   }
1447   llvm_unreachable("unexpected type");
1448   return nullptr;
1449 }
1450
1451 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1452                                             raw_ostream &O) {
1453
1454   const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1455
1456   // GlobalVariables are always constant pointers themselves.
1457   const PointerType *PTy = GVar->getType();
1458   Type *ETy = PTy->getElementType();
1459
1460   O << ".";
1461   emitPTXAddressSpace(PTy->getAddressSpace(), O);
1462   if (GVar->getAlignment() == 0)
1463     O << " .align " << (int) TD->getPrefTypeAlignment(ETy);
1464   else
1465     O << " .align " << GVar->getAlignment();
1466
1467   if (ETy->isSingleValueType()) {
1468     O << " .";
1469     O << getPTXFundamentalTypeStr(ETy);
1470     O << " ";
1471     O << *getSymbol(GVar);
1472     return;
1473   }
1474
1475   int64_t ElementSize = 0;
1476
1477   // Although PTX has direct support for struct type and array type and LLVM IR
1478   // is very similar to PTX, the LLVM CodeGen does not support for targets that
1479   // support these high level field accesses. Structs and arrays are lowered
1480   // into arrays of bytes.
1481   switch (ETy->getTypeID()) {
1482   case Type::StructTyID:
1483   case Type::ArrayTyID:
1484   case Type::VectorTyID:
1485     ElementSize = TD->getTypeStoreSize(ETy);
1486     O << " .b8 " << *getSymbol(GVar) << "[";
1487     if (ElementSize) {
1488       O << itostr(ElementSize);
1489     }
1490     O << "]";
1491     break;
1492   default:
1493     llvm_unreachable("type not supported yet");
1494   }
1495   return;
1496 }
1497
1498 static unsigned int getOpenCLAlignment(const DataLayout *TD, Type *Ty) {
1499   if (Ty->isSingleValueType())
1500     return TD->getPrefTypeAlignment(Ty);
1501
1502   const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1503   if (ATy)
1504     return getOpenCLAlignment(TD, ATy->getElementType());
1505
1506   const VectorType *VTy = dyn_cast<VectorType>(Ty);
1507   if (VTy) {
1508     Type *ETy = VTy->getElementType();
1509     unsigned int numE = VTy->getNumElements();
1510     unsigned int alignE = TD->getPrefTypeAlignment(ETy);
1511     if (numE == 3)
1512       return 4 * alignE;
1513     else
1514       return numE * alignE;
1515   }
1516
1517   const StructType *STy = dyn_cast<StructType>(Ty);
1518   if (STy) {
1519     unsigned int alignStruct = 1;
1520     // Go through each element of the struct and find the
1521     // largest alignment.
1522     for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1523       Type *ETy = STy->getElementType(i);
1524       unsigned int align = getOpenCLAlignment(TD, ETy);
1525       if (align > alignStruct)
1526         alignStruct = align;
1527     }
1528     return alignStruct;
1529   }
1530
1531   const FunctionType *FTy = dyn_cast<FunctionType>(Ty);
1532   if (FTy)
1533     return TD->getPointerPrefAlignment();
1534   return TD->getPrefTypeAlignment(Ty);
1535 }
1536
1537 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1538                                      int paramIndex, raw_ostream &O) {
1539   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1540       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA))
1541     O << *getSymbol(I->getParent()) << "_param_" << paramIndex;
1542   else {
1543     std::string argName = I->getName();
1544     const char *p = argName.c_str();
1545     while (*p) {
1546       if (*p == '.')
1547         O << "_";
1548       else
1549         O << *p;
1550       p++;
1551     }
1552   }
1553 }
1554
1555 void NVPTXAsmPrinter::printParamName(int paramIndex, raw_ostream &O) {
1556   Function::const_arg_iterator I, E;
1557   int i = 0;
1558
1559   if ((nvptxSubtarget.getDrvInterface() == NVPTX::NVCL) ||
1560       (nvptxSubtarget.getDrvInterface() == NVPTX::CUDA)) {
1561     O << *CurrentFnSym << "_param_" << paramIndex;
1562     return;
1563   }
1564
1565   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, i++) {
1566     if (i == paramIndex) {
1567       printParamName(I, paramIndex, O);
1568       return;
1569     }
1570   }
1571   llvm_unreachable("paramIndex out of bound");
1572 }
1573
1574 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1575   const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1576   const AttributeSet &PAL = F->getAttributes();
1577   const TargetLowering *TLI = TM.getSubtargetImpl()->getTargetLowering();
1578   Function::const_arg_iterator I, E;
1579   unsigned paramIndex = 0;
1580   bool first = true;
1581   bool isKernelFunc = llvm::isKernelFunction(*F);
1582   bool isABI = (nvptxSubtarget.getSmVersion() >= 20);
1583   MVT thePointerTy = TLI->getPointerTy();
1584
1585   O << "(\n";
1586
1587   for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1588     Type *Ty = I->getType();
1589
1590     if (!first)
1591       O << ",\n";
1592
1593     first = false;
1594
1595     // Handle image/sampler parameters
1596     if (isKernelFunction(*F)) {
1597       if (isSampler(*I) || isImage(*I)) {
1598         if (isImage(*I)) {
1599           std::string sname = I->getName();
1600           if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1601             if (nvptxSubtarget.hasImageHandles())
1602               O << "\t.param .u64 .ptr .surfref ";
1603             else
1604               O << "\t.param .surfref ";
1605             O << *CurrentFnSym << "_param_" << paramIndex;
1606           }
1607           else { // Default image is read_only
1608             if (nvptxSubtarget.hasImageHandles())
1609               O << "\t.param .u64 .ptr .texref ";
1610             else
1611               O << "\t.param .texref ";
1612             O << *CurrentFnSym << "_param_" << paramIndex;
1613           }
1614         } else {
1615           if (nvptxSubtarget.hasImageHandles())
1616             O << "\t.param .u64 .ptr .samplerref ";
1617           else
1618             O << "\t.param .samplerref ";
1619           O << *CurrentFnSym << "_param_" << paramIndex;
1620         }
1621         continue;
1622       }
1623     }
1624
1625     if (PAL.hasAttribute(paramIndex + 1, Attribute::ByVal) == false) {
1626       if (Ty->isAggregateType() || Ty->isVectorTy()) {
1627         // Just print .param .align <a> .b8 .param[size];
1628         // <a> = PAL.getparamalignment
1629         // size = typeallocsize of element type
1630         unsigned align = PAL.getParamAlignment(paramIndex + 1);
1631         if (align == 0)
1632           align = TD->getABITypeAlignment(Ty);
1633
1634         unsigned sz = TD->getTypeAllocSize(Ty);
1635         O << "\t.param .align " << align << " .b8 ";
1636         printParamName(I, paramIndex, O);
1637         O << "[" << sz << "]";
1638
1639         continue;
1640       }
1641       // Just a scalar
1642       const PointerType *PTy = dyn_cast<PointerType>(Ty);
1643       if (isKernelFunc) {
1644         if (PTy) {
1645           // Special handling for pointer arguments to kernel
1646           O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1647
1648           if (nvptxSubtarget.getDrvInterface() != NVPTX::CUDA) {
1649             Type *ETy = PTy->getElementType();
1650             int addrSpace = PTy->getAddressSpace();
1651             switch (addrSpace) {
1652             default:
1653               O << ".ptr ";
1654               break;
1655             case llvm::ADDRESS_SPACE_CONST:
1656               O << ".ptr .const ";
1657               break;
1658             case llvm::ADDRESS_SPACE_SHARED:
1659               O << ".ptr .shared ";
1660               break;
1661             case llvm::ADDRESS_SPACE_GLOBAL:
1662               O << ".ptr .global ";
1663               break;
1664             }
1665             O << ".align " << (int) getOpenCLAlignment(TD, ETy) << " ";
1666           }
1667           printParamName(I, paramIndex, O);
1668           continue;
1669         }
1670
1671         // non-pointer scalar to kernel func
1672         O << "\t.param .";
1673         // Special case: predicate operands become .u8 types
1674         if (Ty->isIntegerTy(1))
1675           O << "u8";
1676         else
1677           O << getPTXFundamentalTypeStr(Ty);
1678         O << " ";
1679         printParamName(I, paramIndex, O);
1680         continue;
1681       }
1682       // Non-kernel function, just print .param .b<size> for ABI
1683       // and .reg .b<size> for non-ABI
1684       unsigned sz = 0;
1685       if (isa<IntegerType>(Ty)) {
1686         sz = cast<IntegerType>(Ty)->getBitWidth();
1687         if (sz < 32)
1688           sz = 32;
1689       } else if (isa<PointerType>(Ty))
1690         sz = thePointerTy.getSizeInBits();
1691       else
1692         sz = Ty->getPrimitiveSizeInBits();
1693       if (isABI)
1694         O << "\t.param .b" << sz << " ";
1695       else
1696         O << "\t.reg .b" << sz << " ";
1697       printParamName(I, paramIndex, O);
1698       continue;
1699     }
1700
1701     // param has byVal attribute. So should be a pointer
1702     const PointerType *PTy = dyn_cast<PointerType>(Ty);
1703     assert(PTy && "Param with byval attribute should be a pointer type");
1704     Type *ETy = PTy->getElementType();
1705
1706     if (isABI || isKernelFunc) {
1707       // Just print .param .align <a> .b8 .param[size];
1708       // <a> = PAL.getparamalignment
1709       // size = typeallocsize of element type
1710       unsigned align = PAL.getParamAlignment(paramIndex + 1);
1711       if (align == 0)
1712         align = TD->getABITypeAlignment(ETy);
1713
1714       unsigned sz = TD->getTypeAllocSize(ETy);
1715       O << "\t.param .align " << align << " .b8 ";
1716       printParamName(I, paramIndex, O);
1717       O << "[" << sz << "]";
1718       continue;
1719     } else {
1720       // Split the ETy into constituent parts and
1721       // print .param .b<size> <name> for each part.
1722       // Further, if a part is vector, print the above for
1723       // each vector element.
1724       SmallVector<EVT, 16> vtparts;
1725       ComputeValueVTs(*TLI, ETy, vtparts);
1726       for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1727         unsigned elems = 1;
1728         EVT elemtype = vtparts[i];
1729         if (vtparts[i].isVector()) {
1730           elems = vtparts[i].getVectorNumElements();
1731           elemtype = vtparts[i].getVectorElementType();
1732         }
1733
1734         for (unsigned j = 0, je = elems; j != je; ++j) {
1735           unsigned sz = elemtype.getSizeInBits();
1736           if (elemtype.isInteger() && (sz < 32))
1737             sz = 32;
1738           O << "\t.reg .b" << sz << " ";
1739           printParamName(I, paramIndex, O);
1740           if (j < je - 1)
1741             O << ",\n";
1742           ++paramIndex;
1743         }
1744         if (i < e - 1)
1745           O << ",\n";
1746       }
1747       --paramIndex;
1748       continue;
1749     }
1750   }
1751
1752   O << "\n)\n";
1753 }
1754
1755 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1756                                             raw_ostream &O) {
1757   const Function *F = MF.getFunction();
1758   emitFunctionParamList(F, O);
1759 }
1760
1761 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1762     const MachineFunction &MF) {
1763   SmallString<128> Str;
1764   raw_svector_ostream O(Str);
1765
1766   // Map the global virtual register number to a register class specific
1767   // virtual register number starting from 1 with that class.
1768   const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
1769   //unsigned numRegClasses = TRI->getNumRegClasses();
1770
1771   // Emit the Fake Stack Object
1772   const MachineFrameInfo *MFI = MF.getFrameInfo();
1773   int NumBytes = (int) MFI->getStackSize();
1774   if (NumBytes) {
1775     O << "\t.local .align " << MFI->getMaxAlignment() << " .b8 \t" << DEPOTNAME
1776       << getFunctionNumber() << "[" << NumBytes << "];\n";
1777     if (nvptxSubtarget.is64Bit()) {
1778       O << "\t.reg .b64 \t%SP;\n";
1779       O << "\t.reg .b64 \t%SPL;\n";
1780     } else {
1781       O << "\t.reg .b32 \t%SP;\n";
1782       O << "\t.reg .b32 \t%SPL;\n";
1783     }
1784   }
1785
1786   // Go through all virtual registers to establish the mapping between the
1787   // global virtual
1788   // register number and the per class virtual register number.
1789   // We use the per class virtual register number in the ptx output.
1790   unsigned int numVRs = MRI->getNumVirtRegs();
1791   for (unsigned i = 0; i < numVRs; i++) {
1792     unsigned int vr = TRI->index2VirtReg(i);
1793     const TargetRegisterClass *RC = MRI->getRegClass(vr);
1794     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1795     int n = regmap.size();
1796     regmap.insert(std::make_pair(vr, n + 1));
1797   }
1798
1799   // Emit register declarations
1800   // @TODO: Extract out the real register usage
1801   // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1802   // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1803   // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1804   // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1805   // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1806   // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1807   // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1808
1809   // Emit declaration of the virtual registers or 'physical' registers for
1810   // each register class
1811   for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1812     const TargetRegisterClass *RC = TRI->getRegClass(i);
1813     DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1814     std::string rcname = getNVPTXRegClassName(RC);
1815     std::string rcStr = getNVPTXRegClassStr(RC);
1816     int n = regmap.size();
1817
1818     // Only declare those registers that may be used.
1819     if (n) {
1820        O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1821          << ">;\n";
1822     }
1823   }
1824
1825   OutStreamer.EmitRawText(O.str());
1826 }
1827
1828 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1829   APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1830   bool ignored;
1831   unsigned int numHex;
1832   const char *lead;
1833
1834   if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1835     numHex = 8;
1836     lead = "0f";
1837     APF.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &ignored);
1838   } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1839     numHex = 16;
1840     lead = "0d";
1841     APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &ignored);
1842   } else
1843     llvm_unreachable("unsupported fp type");
1844
1845   APInt API = APF.bitcastToAPInt();
1846   std::string hexstr(utohexstr(API.getZExtValue()));
1847   O << lead;
1848   if (hexstr.length() < numHex)
1849     O << std::string(numHex - hexstr.length(), '0');
1850   O << utohexstr(API.getZExtValue());
1851 }
1852
1853 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1854   if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1855     O << CI->getValue();
1856     return;
1857   }
1858   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1859     printFPConstant(CFP, O);
1860     return;
1861   }
1862   if (isa<ConstantPointerNull>(CPV)) {
1863     O << "0";
1864     return;
1865   }
1866   if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1867     PointerType *PTy = dyn_cast<PointerType>(GVar->getType());
1868     bool IsNonGenericPointer = false;
1869     if (PTy && PTy->getAddressSpace() != 0) {
1870       IsNonGenericPointer = true;
1871     }
1872     if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1873       O << "generic(";
1874       O << *getSymbol(GVar);
1875       O << ")";
1876     } else {
1877       O << *getSymbol(GVar);
1878     }
1879     return;
1880   }
1881   if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1882     const Value *v = Cexpr->stripPointerCasts();
1883     PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1884     bool IsNonGenericPointer = false;
1885     if (PTy && PTy->getAddressSpace() != 0) {
1886       IsNonGenericPointer = true;
1887     }
1888     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1889       if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1890         O << "generic(";
1891         O << *getSymbol(GVar);
1892         O << ")";
1893       } else {
1894         O << *getSymbol(GVar);
1895       }
1896       return;
1897     } else {
1898       O << *LowerConstant(CPV, *this);
1899       return;
1900     }
1901   }
1902   llvm_unreachable("Not scalar type found in printScalarConstant()");
1903 }
1904
1905 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1906                                    AggBuffer *aggBuffer) {
1907
1908   const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
1909
1910   if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1911     int s = TD->getTypeAllocSize(CPV->getType());
1912     if (s < Bytes)
1913       s = Bytes;
1914     aggBuffer->addZeros(s);
1915     return;
1916   }
1917
1918   unsigned char *ptr;
1919   switch (CPV->getType()->getTypeID()) {
1920
1921   case Type::IntegerTyID: {
1922     const Type *ETy = CPV->getType();
1923     if (ETy == Type::getInt8Ty(CPV->getContext())) {
1924       unsigned char c =
1925           (unsigned char)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1926       ptr = &c;
1927       aggBuffer->addBytes(ptr, 1, Bytes);
1928     } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1929       short int16 = (short)(dyn_cast<ConstantInt>(CPV))->getZExtValue();
1930       ptr = (unsigned char *)&int16;
1931       aggBuffer->addBytes(ptr, 2, Bytes);
1932     } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1933       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1934         int int32 = (int)(constInt->getZExtValue());
1935         ptr = (unsigned char *)&int32;
1936         aggBuffer->addBytes(ptr, 4, Bytes);
1937         break;
1938       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1939         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1940                 ConstantFoldConstantExpression(Cexpr, TD))) {
1941           int int32 = (int)(constInt->getZExtValue());
1942           ptr = (unsigned char *)&int32;
1943           aggBuffer->addBytes(ptr, 4, Bytes);
1944           break;
1945         }
1946         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1947           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1948           aggBuffer->addSymbol(v);
1949           aggBuffer->addZeros(4);
1950           break;
1951         }
1952       }
1953       llvm_unreachable("unsupported integer const type");
1954     } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1955       if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1956         long long int64 = (long long)(constInt->getZExtValue());
1957         ptr = (unsigned char *)&int64;
1958         aggBuffer->addBytes(ptr, 8, Bytes);
1959         break;
1960       } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1961         if (const ConstantInt *constInt = dyn_cast<ConstantInt>(
1962                 ConstantFoldConstantExpression(Cexpr, TD))) {
1963           long long int64 = (long long)(constInt->getZExtValue());
1964           ptr = (unsigned char *)&int64;
1965           aggBuffer->addBytes(ptr, 8, Bytes);
1966           break;
1967         }
1968         if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1969           Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1970           aggBuffer->addSymbol(v);
1971           aggBuffer->addZeros(8);
1972           break;
1973         }
1974       }
1975       llvm_unreachable("unsupported integer const type");
1976     } else
1977       llvm_unreachable("unsupported integer const type");
1978     break;
1979   }
1980   case Type::FloatTyID:
1981   case Type::DoubleTyID: {
1982     const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1983     const Type *Ty = CFP->getType();
1984     if (Ty == Type::getFloatTy(CPV->getContext())) {
1985       float float32 = (float) CFP->getValueAPF().convertToFloat();
1986       ptr = (unsigned char *)&float32;
1987       aggBuffer->addBytes(ptr, 4, Bytes);
1988     } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1989       double float64 = CFP->getValueAPF().convertToDouble();
1990       ptr = (unsigned char *)&float64;
1991       aggBuffer->addBytes(ptr, 8, Bytes);
1992     } else {
1993       llvm_unreachable("unsupported fp const type");
1994     }
1995     break;
1996   }
1997   case Type::PointerTyID: {
1998     if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1999       aggBuffer->addSymbol(GVar);
2000     } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
2001       const Value *v = Cexpr->stripPointerCasts();
2002       aggBuffer->addSymbol(v);
2003     }
2004     unsigned int s = TD->getTypeAllocSize(CPV->getType());
2005     aggBuffer->addZeros(s);
2006     break;
2007   }
2008
2009   case Type::ArrayTyID:
2010   case Type::VectorTyID:
2011   case Type::StructTyID: {
2012     if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV) ||
2013         isa<ConstantStruct>(CPV) || isa<ConstantDataSequential>(CPV)) {
2014       int ElementSize = TD->getTypeAllocSize(CPV->getType());
2015       bufferAggregateConstant(CPV, aggBuffer);
2016       if (Bytes > ElementSize)
2017         aggBuffer->addZeros(Bytes - ElementSize);
2018     } else if (isa<ConstantAggregateZero>(CPV))
2019       aggBuffer->addZeros(Bytes);
2020     else
2021       llvm_unreachable("Unexpected Constant type");
2022     break;
2023   }
2024
2025   default:
2026     llvm_unreachable("unsupported type");
2027   }
2028 }
2029
2030 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
2031                                               AggBuffer *aggBuffer) {
2032   const DataLayout *TD = TM.getSubtargetImpl()->getDataLayout();
2033   int Bytes;
2034
2035   // Old constants
2036   if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
2037     if (CPV->getNumOperands())
2038       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
2039         bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
2040     return;
2041   }
2042
2043   if (const ConstantDataSequential *CDS =
2044           dyn_cast<ConstantDataSequential>(CPV)) {
2045     if (CDS->getNumElements())
2046       for (unsigned i = 0; i < CDS->getNumElements(); ++i)
2047         bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
2048                      aggBuffer);
2049     return;
2050   }
2051
2052   if (isa<ConstantStruct>(CPV)) {
2053     if (CPV->getNumOperands()) {
2054       StructType *ST = cast<StructType>(CPV->getType());
2055       for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
2056         if (i == (e - 1))
2057           Bytes = TD->getStructLayout(ST)->getElementOffset(0) +
2058                   TD->getTypeAllocSize(ST) -
2059                   TD->getStructLayout(ST)->getElementOffset(i);
2060         else
2061           Bytes = TD->getStructLayout(ST)->getElementOffset(i + 1) -
2062                   TD->getStructLayout(ST)->getElementOffset(i);
2063         bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
2064       }
2065     }
2066     return;
2067   }
2068   llvm_unreachable("unsupported constant type in printAggregateConstant()");
2069 }
2070
2071 // buildTypeNameMap - Run through symbol table looking for type names.
2072 //
2073
2074 bool NVPTXAsmPrinter::isImageType(const Type *Ty) {
2075
2076   std::map<const Type *, std::string>::iterator PI = TypeNameMap.find(Ty);
2077
2078   if (PI != TypeNameMap.end() && (!PI->second.compare("struct._image1d_t") ||
2079                                   !PI->second.compare("struct._image2d_t") ||
2080                                   !PI->second.compare("struct._image3d_t")))
2081     return true;
2082
2083   return false;
2084 }
2085
2086
2087 bool NVPTXAsmPrinter::ignoreLoc(const MachineInstr &MI) {
2088   switch (MI.getOpcode()) {
2089   default:
2090     return false;
2091   case NVPTX::CallArgBeginInst:
2092   case NVPTX::CallArgEndInst0:
2093   case NVPTX::CallArgEndInst1:
2094   case NVPTX::CallArgF32:
2095   case NVPTX::CallArgF64:
2096   case NVPTX::CallArgI16:
2097   case NVPTX::CallArgI32:
2098   case NVPTX::CallArgI32imm:
2099   case NVPTX::CallArgI64:
2100   case NVPTX::CallArgParam:
2101   case NVPTX::CallVoidInst:
2102   case NVPTX::CallVoidInstReg:
2103   case NVPTX::Callseq_End:
2104   case NVPTX::CallVoidInstReg64:
2105   case NVPTX::DeclareParamInst:
2106   case NVPTX::DeclareRetMemInst:
2107   case NVPTX::DeclareRetRegInst:
2108   case NVPTX::DeclareRetScalarInst:
2109   case NVPTX::DeclareScalarParamInst:
2110   case NVPTX::DeclareScalarRegInst:
2111   case NVPTX::StoreParamF32:
2112   case NVPTX::StoreParamF64:
2113   case NVPTX::StoreParamI16:
2114   case NVPTX::StoreParamI32:
2115   case NVPTX::StoreParamI64:
2116   case NVPTX::StoreParamI8:
2117   case NVPTX::StoreRetvalF32:
2118   case NVPTX::StoreRetvalF64:
2119   case NVPTX::StoreRetvalI16:
2120   case NVPTX::StoreRetvalI32:
2121   case NVPTX::StoreRetvalI64:
2122   case NVPTX::StoreRetvalI8:
2123   case NVPTX::LastCallArgF32:
2124   case NVPTX::LastCallArgF64:
2125   case NVPTX::LastCallArgI16:
2126   case NVPTX::LastCallArgI32:
2127   case NVPTX::LastCallArgI32imm:
2128   case NVPTX::LastCallArgI64:
2129   case NVPTX::LastCallArgParam:
2130   case NVPTX::LoadParamMemF32:
2131   case NVPTX::LoadParamMemF64:
2132   case NVPTX::LoadParamMemI16:
2133   case NVPTX::LoadParamMemI32:
2134   case NVPTX::LoadParamMemI64:
2135   case NVPTX::LoadParamMemI8:
2136   case NVPTX::PrototypeInst:
2137   case NVPTX::DBG_VALUE:
2138     return true;
2139   }
2140   return false;
2141 }
2142
2143 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2144 ///
2145 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2146                                       unsigned AsmVariant,
2147                                       const char *ExtraCode, raw_ostream &O) {
2148   if (ExtraCode && ExtraCode[0]) {
2149     if (ExtraCode[1] != 0)
2150       return true; // Unknown modifier.
2151
2152     switch (ExtraCode[0]) {
2153     default:
2154       // See if this is a generic print operand
2155       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2156     case 'r':
2157       break;
2158     }
2159   }
2160
2161   printOperand(MI, OpNo, O);
2162
2163   return false;
2164 }
2165
2166 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2167     const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2168     const char *ExtraCode, raw_ostream &O) {
2169   if (ExtraCode && ExtraCode[0])
2170     return true; // Unknown modifier
2171
2172   O << '[';
2173   printMemOperand(MI, OpNo, O);
2174   O << ']';
2175
2176   return false;
2177 }
2178
2179 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2180                                    raw_ostream &O, const char *Modifier) {
2181   const MachineOperand &MO = MI->getOperand(opNum);
2182   switch (MO.getType()) {
2183   case MachineOperand::MO_Register:
2184     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg())) {
2185       if (MO.getReg() == NVPTX::VRDepot)
2186         O << DEPOTNAME << getFunctionNumber();
2187       else
2188         O << NVPTXInstPrinter::getRegisterName(MO.getReg());
2189     } else {
2190       emitVirtualRegister(MO.getReg(), O);
2191     }
2192     return;
2193
2194   case MachineOperand::MO_Immediate:
2195     if (!Modifier)
2196       O << MO.getImm();
2197     else if (strstr(Modifier, "vec") == Modifier)
2198       printVecModifiedImmediate(MO, Modifier, O);
2199     else
2200       llvm_unreachable(
2201           "Don't know how to handle modifier on immediate operand");
2202     return;
2203
2204   case MachineOperand::MO_FPImmediate:
2205     printFPConstant(MO.getFPImm(), O);
2206     break;
2207
2208   case MachineOperand::MO_GlobalAddress:
2209     O << *getSymbol(MO.getGlobal());
2210     break;
2211
2212   case MachineOperand::MO_MachineBasicBlock:
2213     O << *MO.getMBB()->getSymbol();
2214     return;
2215
2216   default:
2217     llvm_unreachable("Operand type not supported.");
2218   }
2219 }
2220
2221 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2222                                       raw_ostream &O, const char *Modifier) {
2223   printOperand(MI, opNum, O);
2224
2225   if (Modifier && !strcmp(Modifier, "add")) {
2226     O << ", ";
2227     printOperand(MI, opNum + 1, O);
2228   } else {
2229     if (MI->getOperand(opNum + 1).isImm() &&
2230         MI->getOperand(opNum + 1).getImm() == 0)
2231       return; // don't print ',0' or '+0'
2232     O << "+";
2233     printOperand(MI, opNum + 1, O);
2234   }
2235 }
2236
2237
2238 // Force static initialization.
2239 extern "C" void LLVMInitializeNVPTXBackendAsmPrinter() {
2240   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2241   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2242 }
2243
2244 void NVPTXAsmPrinter::emitSrcInText(StringRef filename, unsigned line) {
2245   std::stringstream temp;
2246   LineReader *reader = this->getReader(filename.str());
2247   temp << "\n//";
2248   temp << filename.str();
2249   temp << ":";
2250   temp << line;
2251   temp << " ";
2252   temp << reader->readLine(line);
2253   temp << "\n";
2254   this->OutStreamer.EmitRawText(Twine(temp.str()));
2255 }
2256
2257 LineReader *NVPTXAsmPrinter::getReader(std::string filename) {
2258   if (!reader) {
2259     reader = new LineReader(filename);
2260   }
2261
2262   if (reader->fileName() != filename) {
2263     delete reader;
2264     reader = new LineReader(filename);
2265   }
2266
2267   return reader;
2268 }
2269
2270 std::string LineReader::readLine(unsigned lineNum) {
2271   if (lineNum < theCurLine) {
2272     theCurLine = 0;
2273     fstr.seekg(0, std::ios::beg);
2274   }
2275   while (theCurLine < lineNum) {
2276     fstr.getline(buff, 500);
2277     theCurLine++;
2278   }
2279   return buff;
2280 }
2281
2282 // Force static initialization.
2283 extern "C" void LLVMInitializeNVPTXAsmPrinter() {
2284   RegisterAsmPrinter<NVPTXAsmPrinter> X(TheNVPTXTarget32);
2285   RegisterAsmPrinter<NVPTXAsmPrinter> Y(TheNVPTXTarget64);
2286 }