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