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