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