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