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