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::printVecModifiedImmediate(
603  const MachineOperand &MO, const char *Modifier, raw_ostream &O) {
604  static const char vecelem[] = { '0', '1', '2', '3', '0', '1', '2', '3' };
605  int Imm = (int) MO.getImm();
606  if (0 == strcmp(Modifier, "vecelem"))
607  O << "_" << vecelem[Imm];
608  else if (0 == strcmp(Modifier, "vecv4comm1")) {
609  if ((Imm < 0) || (Imm > 3))
610  O << "//";
611  } else if (0 == strcmp(Modifier, "vecv4comm2")) {
612  if ((Imm < 4) || (Imm > 7))
613  O << "//";
614  } else if (0 == strcmp(Modifier, "vecv4pos")) {
615  if (Imm < 0)
616  Imm = 0;
617  O << "_" << vecelem[Imm % 4];
618  } else if (0 == strcmp(Modifier, "vecv2comm1")) {
619  if ((Imm < 0) || (Imm > 1))
620  O << "//";
621  } else if (0 == strcmp(Modifier, "vecv2comm2")) {
622  if ((Imm < 2) || (Imm > 3))
623  O << "//";
624  } else if (0 == strcmp(Modifier, "vecv2pos")) {
625  if (Imm < 0)
626  Imm = 0;
627  O << "_" << vecelem[Imm % 2];
628  } else
629  llvm_unreachable("Unknown Modifier on immediate operand");
630 }
631 
632 void NVPTXAsmPrinter::emitDeclaration(const Function *F, raw_ostream &O) {
633  emitLinkageDirective(F, O);
634  if (isKernelFunction(*F))
635  O << ".entry ";
636  else
637  O << ".func ";
638  printReturnValStr(F, O);
639  getSymbol(F)->print(O, MAI);
640  O << "\n";
641  emitFunctionParamList(F, O);
642  O << ";\n";
643 }
644 
645 static bool usedInGlobalVarDef(const Constant *C) {
646  if (!C)
647  return false;
648 
649  if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
650  return GV->getName() != "llvm.used";
651  }
652 
653  for (const User *U : C->users())
654  if (const Constant *C = dyn_cast<Constant>(U))
655  if (usedInGlobalVarDef(C))
656  return true;
657 
658  return false;
659 }
660 
661 static bool usedInOneFunc(const User *U, Function const *&oneFunc) {
662  if (const GlobalVariable *othergv = dyn_cast<GlobalVariable>(U)) {
663  if (othergv->getName() == "llvm.used")
664  return true;
665  }
666 
667  if (const Instruction *instr = dyn_cast<Instruction>(U)) {
668  if (instr->getParent() && instr->getParent()->getParent()) {
669  const Function *curFunc = instr->getParent()->getParent();
670  if (oneFunc && (curFunc != oneFunc))
671  return false;
672  oneFunc = curFunc;
673  return true;
674  } else
675  return false;
676  }
677 
678  for (const User *UU : U->users())
679  if (!usedInOneFunc(UU, oneFunc))
680  return false;
681 
682  return true;
683 }
684 
685 /* Find out if a global variable can be demoted to local scope.
686  * Currently, this is valid for CUDA shared variables, which have local
687  * scope and global lifetime. So the conditions to check are :
688  * 1. Is the global variable in shared address space?
689  * 2. Does it have internal linkage?
690  * 3. Is the global variable referenced only in one function?
691  */
692 static bool canDemoteGlobalVar(const GlobalVariable *gv, Function const *&f) {
693  if (!gv->hasInternalLinkage())
694  return false;
695  PointerType *Pty = gv->getType();
697  return false;
698 
699  const Function *oneFunc = nullptr;
700 
701  bool flag = usedInOneFunc(gv, oneFunc);
702  if (!flag)
703  return false;
704  if (!oneFunc)
705  return false;
706  f = oneFunc;
707  return true;
708 }
709 
710 static bool useFuncSeen(const Constant *C,
712  for (const User *U : C->users()) {
713  if (const Constant *cu = dyn_cast<Constant>(U)) {
714  if (useFuncSeen(cu, seenMap))
715  return true;
716  } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
717  const BasicBlock *bb = I->getParent();
718  if (!bb)
719  continue;
720  const Function *caller = bb->getParent();
721  if (!caller)
722  continue;
723  if (seenMap.find(caller) != seenMap.end())
724  return true;
725  }
726  }
727  return false;
728 }
729 
730 void NVPTXAsmPrinter::emitDeclarations(const Module &M, raw_ostream &O) {
732  for (Module::const_iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
733  const Function *F = &*FI;
734 
735  if (F->getAttributes().hasFnAttribute("nvptx-libcall-callee")) {
736  emitDeclaration(F, O);
737  continue;
738  }
739 
740  if (F->isDeclaration()) {
741  if (F->use_empty())
742  continue;
743  if (F->getIntrinsicID())
744  continue;
745  emitDeclaration(F, O);
746  continue;
747  }
748  for (const User *U : F->users()) {
749  if (const Constant *C = dyn_cast<Constant>(U)) {
750  if (usedInGlobalVarDef(C)) {
751  // The use is in the initialization of a global variable
752  // that is a function pointer, so print a declaration
753  // for the original function
754  emitDeclaration(F, O);
755  break;
756  }
757  // Emit a declaration of this function if the function that
758  // uses this constant expr has already been seen.
759  if (useFuncSeen(C, seenMap)) {
760  emitDeclaration(F, O);
761  break;
762  }
763  }
764 
765  if (!isa<Instruction>(U))
766  continue;
767  const Instruction *instr = cast<Instruction>(U);
768  const BasicBlock *bb = instr->getParent();
769  if (!bb)
770  continue;
771  const Function *caller = bb->getParent();
772  if (!caller)
773  continue;
774 
775  // If a caller has already been seen, then the caller is
776  // appearing in the module before the callee. so print out
777  // a declaration for the callee.
778  if (seenMap.find(caller) != seenMap.end()) {
779  emitDeclaration(F, O);
780  break;
781  }
782  }
783  seenMap[F] = true;
784  }
785 }
786 
788  if (!GV) return true;
789  const ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
790  if (!InitList) return true; // Not an array; we don't know how to parse.
791  return InitList->getNumOperands() == 0;
792 }
793 
795  // Construct a default subtarget off of the TargetMachine defaults. The
796  // rest of NVPTX isn't friendly to change subtargets per function and
797  // so the default TargetMachine will have all of the options.
798  const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
799  const auto* STI = static_cast<const NVPTXSubtarget*>(NTM.getSubtargetImpl());
800 
801  if (M.alias_size()) {
802  report_fatal_error("Module has aliases, which NVPTX does not support.");
803  return true; // error
804  }
805  if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_ctors"))) {
807  "Module has a nontrivial global ctor, which NVPTX does not support.");
808  return true; // error
809  }
810  if (!isEmptyXXStructor(M.getNamedGlobal("llvm.global_dtors"))) {
812  "Module has a nontrivial global dtor, which NVPTX does not support.");
813  return true; // error
814  }
815 
816  SmallString<128> Str1;
817  raw_svector_ostream OS1(Str1);
818 
819  // We need to call the parent's one explicitly.
820  bool Result = AsmPrinter::doInitialization(M);
821 
822  // Emit header before any dwarf directives are emitted below.
823  emitHeader(M, OS1, *STI);
824  OutStreamer->EmitRawText(OS1.str());
825 
826  // Emit module-level inline asm if it exists.
827  if (!M.getModuleInlineAsm().empty()) {
828  OutStreamer->AddComment("Start of file scope inline assembly");
829  OutStreamer->AddBlankLine();
830  OutStreamer->EmitRawText(StringRef(M.getModuleInlineAsm()));
831  OutStreamer->AddBlankLine();
832  OutStreamer->AddComment("End of file scope inline assembly");
833  OutStreamer->AddBlankLine();
834  }
835 
836  GlobalsEmitted = false;
837 
838  return Result;
839 }
840 
841 void NVPTXAsmPrinter::emitGlobals(const Module &M) {
842  SmallString<128> Str2;
843  raw_svector_ostream OS2(Str2);
844 
845  emitDeclarations(M, OS2);
846 
847  // As ptxas does not support forward references of globals, we need to first
848  // sort the list of module-level globals in def-use order. We visit each
849  // global variable in order, and ensure that we emit it *after* its dependent
850  // globals. We use a little extra memory maintaining both a set and a list to
851  // have fast searches while maintaining a strict ordering.
855 
856  // Visit each global variable, in order
857  for (const GlobalVariable &I : M.globals())
858  VisitGlobalVariableForEmission(&I, Globals, GVVisited, GVVisiting);
859 
860  assert(GVVisited.size() == M.getGlobalList().size() &&
861  "Missed a global variable");
862  assert(GVVisiting.size() == 0 && "Did not fully process a global variable");
863 
864  // Print out module-level global variables in proper order
865  for (unsigned i = 0, e = Globals.size(); i != e; ++i)
866  printModuleLevelGV(Globals[i], OS2);
867 
868  OS2 << '\n';
869 
870  OutStreamer->EmitRawText(OS2.str());
871 }
872 
873 void NVPTXAsmPrinter::emitHeader(Module &M, raw_ostream &O,
874  const NVPTXSubtarget &STI) {
875  O << "//\n";
876  O << "// Generated by LLVM NVPTX Back-End\n";
877  O << "//\n";
878  O << "\n";
879 
880  unsigned PTXVersion = STI.getPTXVersion();
881  O << ".version " << (PTXVersion / 10) << "." << (PTXVersion % 10) << "\n";
882 
883  O << ".target ";
884  O << STI.getTargetName();
885 
886  const NVPTXTargetMachine &NTM = static_cast<const NVPTXTargetMachine &>(TM);
887  if (NTM.getDrvInterface() == NVPTX::NVCL)
888  O << ", texmode_independent";
889 
890  bool HasFullDebugInfo = false;
891  for (DICompileUnit *CU : M.debug_compile_units()) {
892  switch(CU->getEmissionKind()) {
895  break;
898  HasFullDebugInfo = true;
899  break;
900  }
901  if (HasFullDebugInfo)
902  break;
903  }
904  if (MMI && MMI->hasDebugInfo() && HasFullDebugInfo)
905  O << ", debug";
906 
907  O << "\n";
908 
909  O << ".address_size ";
910  if (NTM.is64Bit())
911  O << "64";
912  else
913  O << "32";
914  O << "\n";
915 
916  O << "\n";
917 }
918 
920  bool HasDebugInfo = MMI && MMI->hasDebugInfo();
921 
922  // If we did not emit any functions, then the global declarations have not
923  // yet been emitted.
924  if (!GlobalsEmitted) {
925  emitGlobals(M);
926  GlobalsEmitted = true;
927  }
928 
929  // XXX Temproarily remove global variables so that doFinalization() will not
930  // emit them again (global variables are emitted at beginning).
931 
932  Module::GlobalListType &global_list = M.getGlobalList();
933  int i, n = global_list.size();
934  GlobalVariable **gv_array = new GlobalVariable *[n];
935 
936  // first, back-up GlobalVariable in gv_array
937  i = 0;
938  for (Module::global_iterator I = global_list.begin(), E = global_list.end();
939  I != E; ++I)
940  gv_array[i++] = &*I;
941 
942  // second, empty global_list
943  while (!global_list.empty())
944  global_list.remove(global_list.begin());
945 
946  // call doFinalization
947  bool ret = AsmPrinter::doFinalization(M);
948 
949  // now we restore global variables
950  for (i = 0; i < n; i++)
951  global_list.insert(global_list.end(), gv_array[i]);
952 
954 
955  delete[] gv_array;
956  // Close the last emitted section
957  if (HasDebugInfo)
958  static_cast<NVPTXTargetStreamer *>(OutStreamer->getTargetStreamer())
959  ->closeLastSection();
960 
961  // Output last DWARF .file directives, if any.
962  static_cast<NVPTXTargetStreamer *>(OutStreamer->getTargetStreamer())
963  ->outputDwarfFileDirectives();
964 
965  return ret;
966 
967  //bool Result = AsmPrinter::doFinalization(M);
968  // Instead of calling the parents doFinalization, we may
969  // clone parents doFinalization and customize here.
970  // Currently, we if NVISA out the EmitGlobals() in
971  // parent's doFinalization, which is too intrusive.
972  //
973  // Same for the doInitialization.
974  //return Result;
975 }
976 
977 // This function emits appropriate linkage directives for
978 // functions and global variables.
979 //
980 // extern function declaration -> .extern
981 // extern function definition -> .visible
982 // external global variable with init -> .visible
983 // external without init -> .extern
984 // appending -> not allowed, assert.
985 // for any linkage other than
986 // internal, private, linker_private,
987 // linker_private_weak, linker_private_weak_def_auto,
988 // we emit -> .weak.
989 
990 void NVPTXAsmPrinter::emitLinkageDirective(const GlobalValue *V,
991  raw_ostream &O) {
992  if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() == NVPTX::CUDA) {
993  if (V->hasExternalLinkage()) {
994  if (isa<GlobalVariable>(V)) {
995  const GlobalVariable *GVar = cast<GlobalVariable>(V);
996  if (GVar) {
997  if (GVar->hasInitializer())
998  O << ".visible ";
999  else
1000  O << ".extern ";
1001  }
1002  } else if (V->isDeclaration())
1003  O << ".extern ";
1004  else
1005  O << ".visible ";
1006  } else if (V->hasAppendingLinkage()) {
1007  std::string msg;
1008  msg.append("Error: ");
1009  msg.append("Symbol ");
1010  if (V->hasName())
1011  msg.append(V->getName());
1012  msg.append("has unsupported appending linkage type");
1013  llvm_unreachable(msg.c_str());
1014  } else if (!V->hasInternalLinkage() &&
1015  !V->hasPrivateLinkage()) {
1016  O << ".weak ";
1017  }
1018  }
1019 }
1020 
1021 void NVPTXAsmPrinter::printModuleLevelGV(const GlobalVariable *GVar,
1022  raw_ostream &O,
1023  bool processDemoted) {
1024  // Skip meta data
1025  if (GVar->hasSection()) {
1026  if (GVar->getSection() == "llvm.metadata")
1027  return;
1028  }
1029 
1030  // Skip LLVM intrinsic global variables
1031  if (GVar->getName().startswith("llvm.") ||
1032  GVar->getName().startswith("nvvm."))
1033  return;
1034 
1035  const DataLayout &DL = getDataLayout();
1036 
1037  // GlobalVariables are always constant pointers themselves.
1038  PointerType *PTy = GVar->getType();
1039  Type *ETy = GVar->getValueType();
1040 
1041  if (GVar->hasExternalLinkage()) {
1042  if (GVar->hasInitializer())
1043  O << ".visible ";
1044  else
1045  O << ".extern ";
1046  } else if (GVar->hasLinkOnceLinkage() || GVar->hasWeakLinkage() ||
1048  GVar->hasCommonLinkage()) {
1049  O << ".weak ";
1050  }
1051 
1052  if (isTexture(*GVar)) {
1053  O << ".global .texref " << getTextureName(*GVar) << ";\n";
1054  return;
1055  }
1056 
1057  if (isSurface(*GVar)) {
1058  O << ".global .surfref " << getSurfaceName(*GVar) << ";\n";
1059  return;
1060  }
1061 
1062  if (GVar->isDeclaration()) {
1063  // (extern) declarations, no definition or initializer
1064  // Currently the only known declaration is for an automatic __local
1065  // (.shared) promoted to global.
1066  emitPTXGlobalVariable(GVar, O);
1067  O << ";\n";
1068  return;
1069  }
1070 
1071  if (isSampler(*GVar)) {
1072  O << ".global .samplerref " << getSamplerName(*GVar);
1073 
1074  const Constant *Initializer = nullptr;
1075  if (GVar->hasInitializer())
1076  Initializer = GVar->getInitializer();
1077  const ConstantInt *CI = nullptr;
1078  if (Initializer)
1079  CI = dyn_cast<ConstantInt>(Initializer);
1080  if (CI) {
1081  unsigned sample = CI->getZExtValue();
1082 
1083  O << " = { ";
1084 
1085  for (int i = 0,
1086  addr = ((sample & __CLK_ADDRESS_MASK) >> __CLK_ADDRESS_BASE);
1087  i < 3; i++) {
1088  O << "addr_mode_" << i << " = ";
1089  switch (addr) {
1090  case 0:
1091  O << "wrap";
1092  break;
1093  case 1:
1094  O << "clamp_to_border";
1095  break;
1096  case 2:
1097  O << "clamp_to_edge";
1098  break;
1099  case 3:
1100  O << "wrap";
1101  break;
1102  case 4:
1103  O << "mirror";
1104  break;
1105  }
1106  O << ", ";
1107  }
1108  O << "filter_mode = ";
1109  switch ((sample & __CLK_FILTER_MASK) >> __CLK_FILTER_BASE) {
1110  case 0:
1111  O << "nearest";
1112  break;
1113  case 1:
1114  O << "linear";
1115  break;
1116  case 2:
1117  llvm_unreachable("Anisotropic filtering is not supported");
1118  default:
1119  O << "nearest";
1120  break;
1121  }
1122  if (!((sample & __CLK_NORMALIZED_MASK) >> __CLK_NORMALIZED_BASE)) {
1123  O << ", force_unnormalized_coords = 1";
1124  }
1125  O << " }";
1126  }
1127 
1128  O << ";\n";
1129  return;
1130  }
1131 
1132  if (GVar->hasPrivateLinkage()) {
1133  if (strncmp(GVar->getName().data(), "unrollpragma", 12) == 0)
1134  return;
1135 
1136  // FIXME - need better way (e.g. Metadata) to avoid generating this global
1137  if (strncmp(GVar->getName().data(), "filename", 8) == 0)
1138  return;
1139  if (GVar->use_empty())
1140  return;
1141  }
1142 
1143  const Function *demotedFunc = nullptr;
1144  if (!processDemoted && canDemoteGlobalVar(GVar, demotedFunc)) {
1145  O << "// " << GVar->getName() << " has been demoted\n";
1146  if (localDecls.find(demotedFunc) != localDecls.end())
1147  localDecls[demotedFunc].push_back(GVar);
1148  else {
1149  std::vector<const GlobalVariable *> temp;
1150  temp.push_back(GVar);
1151  localDecls[demotedFunc] = temp;
1152  }
1153  return;
1154  }
1155 
1156  O << ".";
1157  emitPTXAddressSpace(PTy->getAddressSpace(), O);
1158 
1159  if (isManaged(*GVar)) {
1160  O << " .attribute(.managed)";
1161  }
1162 
1163  if (GVar->getAlignment() == 0)
1164  O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1165  else
1166  O << " .align " << GVar->getAlignment();
1167 
1168  if (ETy->isFloatingPointTy() || ETy->isPointerTy() ||
1169  (ETy->isIntegerTy() && ETy->getScalarSizeInBits() <= 64)) {
1170  O << " .";
1171  // Special case: ABI requires that we use .u8 for predicates
1172  if (ETy->isIntegerTy(1))
1173  O << "u8";
1174  else
1175  O << getPTXFundamentalTypeStr(ETy, false);
1176  O << " ";
1177  getSymbol(GVar)->print(O, MAI);
1178 
1179  // Ptx allows variable initilization only for constant and global state
1180  // spaces.
1181  if (GVar->hasInitializer()) {
1182  if ((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1183  (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) {
1184  const Constant *Initializer = GVar->getInitializer();
1185  // 'undef' is treated as there is no value specified.
1186  if (!Initializer->isNullValue() && !isa<UndefValue>(Initializer)) {
1187  O << " = ";
1188  printScalarConstant(Initializer, O);
1189  }
1190  } else {
1191  // The frontend adds zero-initializer to device and constant variables
1192  // that don't have an initial value, and UndefValue to shared
1193  // variables, so skip warning for this case.
1194  if (!GVar->getInitializer()->isNullValue() &&
1195  !isa<UndefValue>(GVar->getInitializer())) {
1196  report_fatal_error("initial value of '" + GVar->getName() +
1197  "' is not allowed in addrspace(" +
1198  Twine(PTy->getAddressSpace()) + ")");
1199  }
1200  }
1201  }
1202  } else {
1203  unsigned int ElementSize = 0;
1204 
1205  // Although PTX has direct support for struct type and array type and
1206  // LLVM IR is very similar to PTX, the LLVM CodeGen does not support for
1207  // targets that support these high level field accesses. Structs, arrays
1208  // and vectors are lowered into arrays of bytes.
1209  switch (ETy->getTypeID()) {
1210  case Type::IntegerTyID: // Integers larger than 64 bits
1211  case Type::StructTyID:
1212  case Type::ArrayTyID:
1213  case Type::VectorTyID:
1214  ElementSize = DL.getTypeStoreSize(ETy);
1215  // Ptx allows variable initilization only for constant and
1216  // global state spaces.
1217  if (((PTy->getAddressSpace() == ADDRESS_SPACE_GLOBAL) ||
1218  (PTy->getAddressSpace() == ADDRESS_SPACE_CONST)) &&
1219  GVar->hasInitializer()) {
1220  const Constant *Initializer = GVar->getInitializer();
1221  if (!isa<UndefValue>(Initializer) && !Initializer->isNullValue()) {
1222  AggBuffer aggBuffer(ElementSize, O, *this);
1223  bufferAggregateConstant(Initializer, &aggBuffer);
1224  if (aggBuffer.numSymbols) {
1225  if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit()) {
1226  O << " .u64 ";
1227  getSymbol(GVar)->print(O, MAI);
1228  O << "[";
1229  O << ElementSize / 8;
1230  } else {
1231  O << " .u32 ";
1232  getSymbol(GVar)->print(O, MAI);
1233  O << "[";
1234  O << ElementSize / 4;
1235  }
1236  O << "]";
1237  } else {
1238  O << " .b8 ";
1239  getSymbol(GVar)->print(O, MAI);
1240  O << "[";
1241  O << ElementSize;
1242  O << "]";
1243  }
1244  O << " = {";
1245  aggBuffer.print();
1246  O << "}";
1247  } else {
1248  O << " .b8 ";
1249  getSymbol(GVar)->print(O, MAI);
1250  if (ElementSize) {
1251  O << "[";
1252  O << ElementSize;
1253  O << "]";
1254  }
1255  }
1256  } else {
1257  O << " .b8 ";
1258  getSymbol(GVar)->print(O, MAI);
1259  if (ElementSize) {
1260  O << "[";
1261  O << ElementSize;
1262  O << "]";
1263  }
1264  }
1265  break;
1266  default:
1267  llvm_unreachable("type not supported yet");
1268  }
1269  }
1270  O << ";\n";
1271 }
1272 
1273 void NVPTXAsmPrinter::emitDemotedVars(const Function *f, raw_ostream &O) {
1274  if (localDecls.find(f) == localDecls.end())
1275  return;
1276 
1277  std::vector<const GlobalVariable *> &gvars = localDecls[f];
1278 
1279  for (unsigned i = 0, e = gvars.size(); i != e; ++i) {
1280  O << "\t// demoted variable\n\t";
1281  printModuleLevelGV(gvars[i], O, true);
1282  }
1283 }
1284 
1285 void NVPTXAsmPrinter::emitPTXAddressSpace(unsigned int AddressSpace,
1286  raw_ostream &O) const {
1287  switch (AddressSpace) {
1288  case ADDRESS_SPACE_LOCAL:
1289  O << "local";
1290  break;
1291  case ADDRESS_SPACE_GLOBAL:
1292  O << "global";
1293  break;
1294  case ADDRESS_SPACE_CONST:
1295  O << "const";
1296  break;
1297  case ADDRESS_SPACE_SHARED:
1298  O << "shared";
1299  break;
1300  default:
1301  report_fatal_error("Bad address space found while emitting PTX: " +
1303  break;
1304  }
1305 }
1306 
1307 std::string
1308 NVPTXAsmPrinter::getPTXFundamentalTypeStr(Type *Ty, bool useB4PTR) const {
1309  switch (Ty->getTypeID()) {
1310  default:
1311  llvm_unreachable("unexpected type");
1312  break;
1313  case Type::IntegerTyID: {
1314  unsigned NumBits = cast<IntegerType>(Ty)->getBitWidth();
1315  if (NumBits == 1)
1316  return "pred";
1317  else if (NumBits <= 64) {
1318  std::string name = "u";
1319  return name + utostr(NumBits);
1320  } else {
1321  llvm_unreachable("Integer too large");
1322  break;
1323  }
1324  break;
1325  }
1326  case Type::HalfTyID:
1327  // fp16 is stored as .b16 for compatibility with pre-sm_53 PTX assembly.
1328  return "b16";
1329  case Type::FloatTyID:
1330  return "f32";
1331  case Type::DoubleTyID:
1332  return "f64";
1333  case Type::PointerTyID:
1334  if (static_cast<const NVPTXTargetMachine &>(TM).is64Bit())
1335  if (useB4PTR)
1336  return "b64";
1337  else
1338  return "u64";
1339  else if (useB4PTR)
1340  return "b32";
1341  else
1342  return "u32";
1343  }
1344  llvm_unreachable("unexpected type");
1345  return nullptr;
1346 }
1347 
1348 void NVPTXAsmPrinter::emitPTXGlobalVariable(const GlobalVariable *GVar,
1349  raw_ostream &O) {
1350  const DataLayout &DL = getDataLayout();
1351 
1352  // GlobalVariables are always constant pointers themselves.
1353  Type *ETy = GVar->getValueType();
1354 
1355  O << ".";
1356  emitPTXAddressSpace(GVar->getType()->getAddressSpace(), O);
1357  if (GVar->getAlignment() == 0)
1358  O << " .align " << (int)DL.getPrefTypeAlignment(ETy);
1359  else
1360  O << " .align " << GVar->getAlignment();
1361 
1362  // Special case for i128
1363  if (ETy->isIntegerTy(128)) {
1364  O << " .b8 ";
1365  getSymbol(GVar)->print(O, MAI);
1366  O << "[16]";
1367  return;
1368  }
1369 
1370  if (ETy->isFloatingPointTy() || ETy->isIntOrPtrTy()) {
1371  O << " .";
1372  O << getPTXFundamentalTypeStr(ETy);
1373  O << " ";
1374  getSymbol(GVar)->print(O, MAI);
1375  return;
1376  }
1377 
1378  int64_t ElementSize = 0;
1379 
1380  // Although PTX has direct support for struct type and array type and LLVM IR
1381  // is very similar to PTX, the LLVM CodeGen does not support for targets that
1382  // support these high level field accesses. Structs and arrays are lowered
1383  // into arrays of bytes.
1384  switch (ETy->getTypeID()) {
1385  case Type::StructTyID:
1386  case Type::ArrayTyID:
1387  case Type::VectorTyID:
1388  ElementSize = DL.getTypeStoreSize(ETy);
1389  O << " .b8 ";
1390  getSymbol(GVar)->print(O, MAI);
1391  O << "[";
1392  if (ElementSize) {
1393  O << ElementSize;
1394  }
1395  O << "]";
1396  break;
1397  default:
1398  llvm_unreachable("type not supported yet");
1399  }
1400 }
1401 
1402 static unsigned int getOpenCLAlignment(const DataLayout &DL, Type *Ty) {
1403  if (Ty->isSingleValueType())
1404  return DL.getPrefTypeAlignment(Ty);
1405 
1406  auto *ATy = dyn_cast<ArrayType>(Ty);
1407  if (ATy)
1408  return getOpenCLAlignment(DL, ATy->getElementType());
1409 
1410  auto *STy = dyn_cast<StructType>(Ty);
1411  if (STy) {
1412  unsigned int alignStruct = 1;
1413  // Go through each element of the struct and find the
1414  // largest alignment.
1415  for (unsigned i = 0, e = STy->getNumElements(); i != e; i++) {
1416  Type *ETy = STy->getElementType(i);
1417  unsigned int align = getOpenCLAlignment(DL, ETy);
1418  if (align > alignStruct)
1419  alignStruct = align;
1420  }
1421  return alignStruct;
1422  }
1423 
1424  auto *FTy = dyn_cast<FunctionType>(Ty);
1425  if (FTy)
1426  return DL.getPointerPrefAlignment();
1427  return DL.getPrefTypeAlignment(Ty);
1428 }
1429 
1430 void NVPTXAsmPrinter::printParamName(Function::const_arg_iterator I,
1431  int paramIndex, raw_ostream &O) {
1432  getSymbol(I->getParent())->print(O, MAI);
1433  O << "_param_" << paramIndex;
1434 }
1435 
1436 void NVPTXAsmPrinter::emitFunctionParamList(const Function *F, raw_ostream &O) {
1437  const DataLayout &DL = getDataLayout();
1438  const AttributeList &PAL = F->getAttributes();
1439  const NVPTXSubtarget &STI = TM.getSubtarget<NVPTXSubtarget>(*F);
1440  const TargetLowering *TLI = STI.getTargetLowering();
1442  unsigned paramIndex = 0;
1443  bool first = true;
1444  bool isKernelFunc = isKernelFunction(*F);
1445  bool isABI = (STI.getSmVersion() >= 20);
1446  bool hasImageHandles = STI.hasImageHandles();
1447  MVT thePointerTy = TLI->getPointerTy(DL);
1448 
1449  if (F->arg_empty()) {
1450  O << "()\n";
1451  return;
1452  }
1453 
1454  O << "(\n";
1455 
1456  for (I = F->arg_begin(), E = F->arg_end(); I != E; ++I, paramIndex++) {
1457  Type *Ty = I->getType();
1458 
1459  if (!first)
1460  O << ",\n";
1461 
1462  first = false;
1463 
1464  // Handle image/sampler parameters
1465  if (isKernelFunction(*F)) {
1466  if (isSampler(*I) || isImage(*I)) {
1467  if (isImage(*I)) {
1468  std::string sname = I->getName();
1469  if (isImageWriteOnly(*I) || isImageReadWrite(*I)) {
1470  if (hasImageHandles)
1471  O << "\t.param .u64 .ptr .surfref ";
1472  else
1473  O << "\t.param .surfref ";
1474  CurrentFnSym->print(O, MAI);
1475  O << "_param_" << paramIndex;
1476  }
1477  else { // Default image is read_only
1478  if (hasImageHandles)
1479  O << "\t.param .u64 .ptr .texref ";
1480  else
1481  O << "\t.param .texref ";
1482  CurrentFnSym->print(O, MAI);
1483  O << "_param_" << paramIndex;
1484  }
1485  } else {
1486  if (hasImageHandles)
1487  O << "\t.param .u64 .ptr .samplerref ";
1488  else
1489  O << "\t.param .samplerref ";
1490  CurrentFnSym->print(O, MAI);
1491  O << "_param_" << paramIndex;
1492  }
1493  continue;
1494  }
1495  }
1496 
1497  if (!PAL.hasParamAttribute(paramIndex, Attribute::ByVal)) {
1498  if (Ty->isAggregateType() || Ty->isVectorTy() || Ty->isIntegerTy(128)) {
1499  // Just print .param .align <a> .b8 .param[size];
1500  // <a> = PAL.getparamalignment
1501  // size = typeallocsize of element type
1502  unsigned align = PAL.getParamAlignment(paramIndex);
1503  if (align == 0)
1504  align = DL.getABITypeAlignment(Ty);
1505 
1506  unsigned sz = DL.getTypeAllocSize(Ty);
1507  O << "\t.param .align " << align << " .b8 ";
1508  printParamName(I, paramIndex, O);
1509  O << "[" << sz << "]";
1510 
1511  continue;
1512  }
1513  // Just a scalar
1514  auto *PTy = dyn_cast<PointerType>(Ty);
1515  if (isKernelFunc) {
1516  if (PTy) {
1517  // Special handling for pointer arguments to kernel
1518  O << "\t.param .u" << thePointerTy.getSizeInBits() << " ";
1519 
1520  if (static_cast<NVPTXTargetMachine &>(TM).getDrvInterface() !=
1521  NVPTX::CUDA) {
1522  Type *ETy = PTy->getElementType();
1523  int addrSpace = PTy->getAddressSpace();
1524  switch (addrSpace) {
1525  default:
1526  O << ".ptr ";
1527  break;
1528  case ADDRESS_SPACE_CONST:
1529  O << ".ptr .const ";
1530  break;
1531  case ADDRESS_SPACE_SHARED:
1532  O << ".ptr .shared ";
1533  break;
1534  case ADDRESS_SPACE_GLOBAL:
1535  O << ".ptr .global ";
1536  break;
1537  }
1538  O << ".align " << (int)getOpenCLAlignment(DL, ETy) << " ";
1539  }
1540  printParamName(I, paramIndex, O);
1541  continue;
1542  }
1543 
1544  // non-pointer scalar to kernel func
1545  O << "\t.param .";
1546  // Special case: predicate operands become .u8 types
1547  if (Ty->isIntegerTy(1))
1548  O << "u8";
1549  else
1550  O << getPTXFundamentalTypeStr(Ty);
1551  O << " ";
1552  printParamName(I, paramIndex, O);
1553  continue;
1554  }
1555  // Non-kernel function, just print .param .b<size> for ABI
1556  // and .reg .b<size> for non-ABI
1557  unsigned sz = 0;
1558  if (isa<IntegerType>(Ty)) {
1559  sz = cast<IntegerType>(Ty)->getBitWidth();
1560  if (sz < 32)
1561  sz = 32;
1562  } else if (isa<PointerType>(Ty))
1563  sz = thePointerTy.getSizeInBits();
1564  else if (Ty->isHalfTy())
1565  // PTX ABI requires all scalar parameters to be at least 32
1566  // bits in size. fp16 normally uses .b16 as its storage type
1567  // in PTX, so its size must be adjusted here, too.
1568  sz = 32;
1569  else
1570  sz = Ty->getPrimitiveSizeInBits();
1571  if (isABI)
1572  O << "\t.param .b" << sz << " ";
1573  else
1574  O << "\t.reg .b" << sz << " ";
1575  printParamName(I, paramIndex, O);
1576  continue;
1577  }
1578 
1579  // param has byVal attribute. So should be a pointer
1580  auto *PTy = dyn_cast<PointerType>(Ty);
1581  assert(PTy && "Param with byval attribute should be a pointer type");
1582  Type *ETy = PTy->getElementType();
1583 
1584  if (isABI || isKernelFunc) {
1585  // Just print .param .align <a> .b8 .param[size];
1586  // <a> = PAL.getparamalignment
1587  // size = typeallocsize of element type
1588  unsigned align = PAL.getParamAlignment(paramIndex);
1589  if (align == 0)
1590  align = DL.getABITypeAlignment(ETy);
1591  // Work around a bug in ptxas. When PTX code takes address of
1592  // byval parameter with alignment < 4, ptxas generates code to
1593  // spill argument into memory. Alas on sm_50+ ptxas generates
1594  // SASS code that fails with misaligned access. To work around
1595  // the problem, make sure that we align byval parameters by at
1596  // least 4. Matching change must be made in LowerCall() where we
1597  // prepare parameters for the call.
1598  //
1599  // TODO: this will need to be undone when we get to support multi-TU
1600  // device-side compilation as it breaks ABI compatibility with nvcc.
1601  // Hopefully ptxas bug is fixed by then.
1602  if (!isKernelFunc && align < 4)
1603  align = 4;
1604  unsigned sz = DL.getTypeAllocSize(ETy);
1605  O << "\t.param .align " << align << " .b8 ";
1606  printParamName(I, paramIndex, O);
1607  O << "[" << sz << "]";
1608  continue;
1609  } else {
1610  // Split the ETy into constituent parts and
1611  // print .param .b<size> <name> for each part.
1612  // Further, if a part is vector, print the above for
1613  // each vector element.
1614  SmallVector<EVT, 16> vtparts;
1615  ComputeValueVTs(*TLI, DL, ETy, vtparts);
1616  for (unsigned i = 0, e = vtparts.size(); i != e; ++i) {
1617  unsigned elems = 1;
1618  EVT elemtype = vtparts[i];
1619  if (vtparts[i].isVector()) {
1620  elems = vtparts[i].getVectorNumElements();
1621  elemtype = vtparts[i].getVectorElementType();
1622  }
1623 
1624  for (unsigned j = 0, je = elems; j != je; ++j) {
1625  unsigned sz = elemtype.getSizeInBits();
1626  if (elemtype.isInteger() && (sz < 32))
1627  sz = 32;
1628  O << "\t.reg .b" << sz << " ";
1629  printParamName(I, paramIndex, O);
1630  if (j < je - 1)
1631  O << ",\n";
1632  ++paramIndex;
1633  }
1634  if (i < e - 1)
1635  O << ",\n";
1636  }
1637  --paramIndex;
1638  continue;
1639  }
1640  }
1641 
1642  O << "\n)\n";
1643 }
1644 
1645 void NVPTXAsmPrinter::emitFunctionParamList(const MachineFunction &MF,
1646  raw_ostream &O) {
1647  const Function &F = MF.getFunction();
1648  emitFunctionParamList(&F, O);
1649 }
1650 
1651 void NVPTXAsmPrinter::setAndEmitFunctionVirtualRegisters(
1652  const MachineFunction &MF) {
1653  SmallString<128> Str;
1654  raw_svector_ostream O(Str);
1655 
1656  // Map the global virtual register number to a register class specific
1657  // virtual register number starting from 1 with that class.
1659  //unsigned numRegClasses = TRI->getNumRegClasses();
1660 
1661  // Emit the Fake Stack Object
1662  const MachineFrameInfo &MFI = MF.getFrameInfo();
1663  int NumBytes = (int) MFI.getStackSize();
1664  if (NumBytes) {
1665  O << "\t.local .align " << MFI.getMaxAlignment() << " .b8 \t" << DEPOTNAME
1666  << getFunctionNumber() << "[" << NumBytes << "];\n";
1667  if (static_cast<const NVPTXTargetMachine &>(MF.getTarget()).is64Bit()) {
1668  O << "\t.reg .b64 \t%SP;\n";
1669  O << "\t.reg .b64 \t%SPL;\n";
1670  } else {
1671  O << "\t.reg .b32 \t%SP;\n";
1672  O << "\t.reg .b32 \t%SPL;\n";
1673  }
1674  }
1675 
1676  // Go through all virtual registers to establish the mapping between the
1677  // global virtual
1678  // register number and the per class virtual register number.
1679  // We use the per class virtual register number in the ptx output.
1680  unsigned int numVRs = MRI->getNumVirtRegs();
1681  for (unsigned i = 0; i < numVRs; i++) {
1682  unsigned int vr = TRI->index2VirtReg(i);
1683  const TargetRegisterClass *RC = MRI->getRegClass(vr);
1684  DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1685  int n = regmap.size();
1686  regmap.insert(std::make_pair(vr, n + 1));
1687  }
1688 
1689  // Emit register declarations
1690  // @TODO: Extract out the real register usage
1691  // O << "\t.reg .pred %p<" << NVPTXNumRegisters << ">;\n";
1692  // O << "\t.reg .s16 %rc<" << NVPTXNumRegisters << ">;\n";
1693  // O << "\t.reg .s16 %rs<" << NVPTXNumRegisters << ">;\n";
1694  // O << "\t.reg .s32 %r<" << NVPTXNumRegisters << ">;\n";
1695  // O << "\t.reg .s64 %rd<" << NVPTXNumRegisters << ">;\n";
1696  // O << "\t.reg .f32 %f<" << NVPTXNumRegisters << ">;\n";
1697  // O << "\t.reg .f64 %fd<" << NVPTXNumRegisters << ">;\n";
1698 
1699  // Emit declaration of the virtual registers or 'physical' registers for
1700  // each register class
1701  for (unsigned i=0; i< TRI->getNumRegClasses(); i++) {
1702  const TargetRegisterClass *RC = TRI->getRegClass(i);
1703  DenseMap<unsigned, unsigned> &regmap = VRegMapping[RC];
1704  std::string rcname = getNVPTXRegClassName(RC);
1705  std::string rcStr = getNVPTXRegClassStr(RC);
1706  int n = regmap.size();
1707 
1708  // Only declare those registers that may be used.
1709  if (n) {
1710  O << "\t.reg " << rcname << " \t" << rcStr << "<" << (n+1)
1711  << ">;\n";
1712  }
1713  }
1714 
1715  OutStreamer->EmitRawText(O.str());
1716 }
1717 
1718 void NVPTXAsmPrinter::printFPConstant(const ConstantFP *Fp, raw_ostream &O) {
1719  APFloat APF = APFloat(Fp->getValueAPF()); // make a copy
1720  bool ignored;
1721  unsigned int numHex;
1722  const char *lead;
1723 
1724  if (Fp->getType()->getTypeID() == Type::FloatTyID) {
1725  numHex = 8;
1726  lead = "0f";
1728  } else if (Fp->getType()->getTypeID() == Type::DoubleTyID) {
1729  numHex = 16;
1730  lead = "0d";
1732  } else
1733  llvm_unreachable("unsupported fp type");
1734 
1735  APInt API = APF.bitcastToAPInt();
1736  O << lead << format_hex_no_prefix(API.getZExtValue(), numHex, /*Upper=*/true);
1737 }
1738 
1739 void NVPTXAsmPrinter::printScalarConstant(const Constant *CPV, raw_ostream &O) {
1740  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1741  O << CI->getValue();
1742  return;
1743  }
1744  if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV)) {
1745  printFPConstant(CFP, O);
1746  return;
1747  }
1748  if (isa<ConstantPointerNull>(CPV)) {
1749  O << "0";
1750  return;
1751  }
1752  if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1753  bool IsNonGenericPointer = false;
1754  if (GVar->getType()->getAddressSpace() != 0) {
1755  IsNonGenericPointer = true;
1756  }
1757  if (EmitGeneric && !isa<Function>(CPV) && !IsNonGenericPointer) {
1758  O << "generic(";
1759  getSymbol(GVar)->print(O, MAI);
1760  O << ")";
1761  } else {
1762  getSymbol(GVar)->print(O, MAI);
1763  }
1764  return;
1765  }
1766  if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1767  const Value *v = Cexpr->stripPointerCasts();
1768  PointerType *PTy = dyn_cast<PointerType>(Cexpr->getType());
1769  bool IsNonGenericPointer = false;
1770  if (PTy && PTy->getAddressSpace() != 0) {
1771  IsNonGenericPointer = true;
1772  }
1773  if (const GlobalValue *GVar = dyn_cast<GlobalValue>(v)) {
1774  if (EmitGeneric && !isa<Function>(v) && !IsNonGenericPointer) {
1775  O << "generic(";
1776  getSymbol(GVar)->print(O, MAI);
1777  O << ")";
1778  } else {
1779  getSymbol(GVar)->print(O, MAI);
1780  }
1781  return;
1782  } else {
1783  lowerConstant(CPV)->print(O, MAI);
1784  return;
1785  }
1786  }
1787  llvm_unreachable("Not scalar type found in printScalarConstant()");
1788 }
1789 
1790 // These utility functions assure we get the right sequence of bytes for a given
1791 // type even for big-endian machines
1792 template <typename T> static void ConvertIntToBytes(unsigned char *p, T val) {
1793  int64_t vp = (int64_t)val;
1794  for (unsigned i = 0; i < sizeof(T); ++i) {
1795  p[i] = (unsigned char)vp;
1796  vp >>= 8;
1797  }
1798 }
1799 static void ConvertFloatToBytes(unsigned char *p, float val) {
1800  int32_t *vp = (int32_t *)&val;
1801  for (unsigned i = 0; i < sizeof(int32_t); ++i) {
1802  p[i] = (unsigned char)*vp;
1803  *vp >>= 8;
1804  }
1805 }
1806 static void ConvertDoubleToBytes(unsigned char *p, double val) {
1807  int64_t *vp = (int64_t *)&val;
1808  for (unsigned i = 0; i < sizeof(int64_t); ++i) {
1809  p[i] = (unsigned char)*vp;
1810  *vp >>= 8;
1811  }
1812 }
1813 
1814 void NVPTXAsmPrinter::bufferLEByte(const Constant *CPV, int Bytes,
1815  AggBuffer *aggBuffer) {
1816  const DataLayout &DL = getDataLayout();
1817 
1818  if (isa<UndefValue>(CPV) || CPV->isNullValue()) {
1819  int s = DL.getTypeAllocSize(CPV->getType());
1820  if (s < Bytes)
1821  s = Bytes;
1822  aggBuffer->addZeros(s);
1823  return;
1824  }
1825 
1826  unsigned char ptr[8];
1827  switch (CPV->getType()->getTypeID()) {
1828 
1829  case Type::IntegerTyID: {
1830  Type *ETy = CPV->getType();
1831  if (ETy == Type::getInt8Ty(CPV->getContext())) {
1832  unsigned char c = (unsigned char)cast<ConstantInt>(CPV)->getZExtValue();
1833  ConvertIntToBytes<>(ptr, c);
1834  aggBuffer->addBytes(ptr, 1, Bytes);
1835  } else if (ETy == Type::getInt16Ty(CPV->getContext())) {
1836  short int16 = (short)cast<ConstantInt>(CPV)->getZExtValue();
1837  ConvertIntToBytes<>(ptr, int16);
1838  aggBuffer->addBytes(ptr, 2, Bytes);
1839  } else if (ETy == Type::getInt32Ty(CPV->getContext())) {
1840  if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1841  int int32 = (int)(constInt->getZExtValue());
1842  ConvertIntToBytes<>(ptr, int32);
1843  aggBuffer->addBytes(ptr, 4, Bytes);
1844  break;
1845  } else if (const auto *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1846  if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1847  ConstantFoldConstant(Cexpr, DL))) {
1848  int int32 = (int)(constInt->getZExtValue());
1849  ConvertIntToBytes<>(ptr, int32);
1850  aggBuffer->addBytes(ptr, 4, Bytes);
1851  break;
1852  }
1853  if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1854  Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1855  aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1856  aggBuffer->addZeros(4);
1857  break;
1858  }
1859  }
1860  llvm_unreachable("unsupported integer const type");
1861  } else if (ETy == Type::getInt64Ty(CPV->getContext())) {
1862  if (const ConstantInt *constInt = dyn_cast<ConstantInt>(CPV)) {
1863  long long int64 = (long long)(constInt->getZExtValue());
1864  ConvertIntToBytes<>(ptr, int64);
1865  aggBuffer->addBytes(ptr, 8, Bytes);
1866  break;
1867  } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1868  if (const auto *constInt = dyn_cast_or_null<ConstantInt>(
1869  ConstantFoldConstant(Cexpr, DL))) {
1870  long long int64 = (long long)(constInt->getZExtValue());
1871  ConvertIntToBytes<>(ptr, int64);
1872  aggBuffer->addBytes(ptr, 8, Bytes);
1873  break;
1874  }
1875  if (Cexpr->getOpcode() == Instruction::PtrToInt) {
1876  Value *v = Cexpr->getOperand(0)->stripPointerCasts();
1877  aggBuffer->addSymbol(v, Cexpr->getOperand(0));
1878  aggBuffer->addZeros(8);
1879  break;
1880  }
1881  }
1882  llvm_unreachable("unsupported integer const type");
1883  } else
1884  llvm_unreachable("unsupported integer const type");
1885  break;
1886  }
1887  case Type::HalfTyID:
1888  case Type::FloatTyID:
1889  case Type::DoubleTyID: {
1890  const ConstantFP *CFP = dyn_cast<ConstantFP>(CPV);
1891  Type *Ty = CFP->getType();
1892  if (Ty == Type::getHalfTy(CPV->getContext())) {
1893  APInt API = CFP->getValueAPF().bitcastToAPInt();
1894  uint16_t float16 = API.getLoBits(16).getZExtValue();
1895  ConvertIntToBytes<>(ptr, float16);
1896  aggBuffer->addBytes(ptr, 2, Bytes);
1897  } else if (Ty == Type::getFloatTy(CPV->getContext())) {
1898  float float32 = (float) CFP->getValueAPF().convertToFloat();
1899  ConvertFloatToBytes(ptr, float32);
1900  aggBuffer->addBytes(ptr, 4, Bytes);
1901  } else if (Ty == Type::getDoubleTy(CPV->getContext())) {
1902  double float64 = CFP->getValueAPF().convertToDouble();
1903  ConvertDoubleToBytes(ptr, float64);
1904  aggBuffer->addBytes(ptr, 8, Bytes);
1905  } else {
1906  llvm_unreachable("unsupported fp const type");
1907  }
1908  break;
1909  }
1910  case Type::PointerTyID: {
1911  if (const GlobalValue *GVar = dyn_cast<GlobalValue>(CPV)) {
1912  aggBuffer->addSymbol(GVar, GVar);
1913  } else if (const ConstantExpr *Cexpr = dyn_cast<ConstantExpr>(CPV)) {
1914  const Value *v = Cexpr->stripPointerCasts();
1915  aggBuffer->addSymbol(v, Cexpr);
1916  }
1917  unsigned int s = DL.getTypeAllocSize(CPV->getType());
1918  aggBuffer->addZeros(s);
1919  break;
1920  }
1921 
1922  case Type::ArrayTyID:
1923  case Type::VectorTyID:
1924  case Type::StructTyID: {
1925  if (isa<ConstantAggregate>(CPV) || isa<ConstantDataSequential>(CPV)) {
1926  int ElementSize = DL.getTypeAllocSize(CPV->getType());
1927  bufferAggregateConstant(CPV, aggBuffer);
1928  if (Bytes > ElementSize)
1929  aggBuffer->addZeros(Bytes - ElementSize);
1930  } else if (isa<ConstantAggregateZero>(CPV))
1931  aggBuffer->addZeros(Bytes);
1932  else
1933  llvm_unreachable("Unexpected Constant type");
1934  break;
1935  }
1936 
1937  default:
1938  llvm_unreachable("unsupported type");
1939  }
1940 }
1941 
1942 void NVPTXAsmPrinter::bufferAggregateConstant(const Constant *CPV,
1943  AggBuffer *aggBuffer) {
1944  const DataLayout &DL = getDataLayout();
1945  int Bytes;
1946 
1947  // Integers of arbitrary width
1948  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CPV)) {
1949  APInt Val = CI->getValue();
1950  for (unsigned I = 0, E = DL.getTypeAllocSize(CPV->getType()); I < E; ++I) {
1951  uint8_t Byte = Val.getLoBits(8).getZExtValue();
1952  aggBuffer->addBytes(&Byte, 1, 1);
1953  Val.lshrInPlace(8);
1954  }
1955  return;
1956  }
1957 
1958  // Old constants
1959  if (isa<ConstantArray>(CPV) || isa<ConstantVector>(CPV)) {
1960  if (CPV->getNumOperands())
1961  for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i)
1962  bufferLEByte(cast<Constant>(CPV->getOperand(i)), 0, aggBuffer);
1963  return;
1964  }
1965 
1966  if (const ConstantDataSequential *CDS =
1967  dyn_cast<ConstantDataSequential>(CPV)) {
1968  if (CDS->getNumElements())
1969  for (unsigned i = 0; i < CDS->getNumElements(); ++i)
1970  bufferLEByte(cast<Constant>(CDS->getElementAsConstant(i)), 0,
1971  aggBuffer);
1972  return;
1973  }
1974 
1975  if (isa<ConstantStruct>(CPV)) {
1976  if (CPV->getNumOperands()) {
1977  StructType *ST = cast<StructType>(CPV->getType());
1978  for (unsigned i = 0, e = CPV->getNumOperands(); i != e; ++i) {
1979  if (i == (e - 1))
1980  Bytes = DL.getStructLayout(ST)->getElementOffset(0) +
1981  DL.getTypeAllocSize(ST) -
1982  DL.getStructLayout(ST)->getElementOffset(i);
1983  else
1984  Bytes = DL.getStructLayout(ST)->getElementOffset(i + 1) -
1985  DL.getStructLayout(ST)->getElementOffset(i);
1986  bufferLEByte(cast<Constant>(CPV->getOperand(i)), Bytes, aggBuffer);
1987  }
1988  }
1989  return;
1990  }
1991  llvm_unreachable("unsupported constant type in printAggregateConstant()");
1992 }
1993 
1994 /// lowerConstantForGV - Return an MCExpr for the given Constant. This is mostly
1995 /// a copy from AsmPrinter::lowerConstant, except customized to only handle
1996 /// expressions that are representable in PTX and create
1997 /// NVPTXGenericMCSymbolRefExpr nodes for addrspacecast instructions.
1998 const MCExpr *
1999 NVPTXAsmPrinter::lowerConstantForGV(const Constant *CV, bool ProcessingGeneric) {
2000  MCContext &Ctx = OutContext;
2001 
2002  if (CV->isNullValue() || isa<UndefValue>(CV))
2003  return MCConstantExpr::create(0, Ctx);
2004 
2005  if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV))
2006  return MCConstantExpr::create(CI->getZExtValue(), Ctx);
2007 
2008  if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
2009  const MCSymbolRefExpr *Expr =
2011  if (ProcessingGeneric) {
2012  return NVPTXGenericMCSymbolRefExpr::create(Expr, Ctx);
2013  } else {
2014  return Expr;
2015  }
2016  }
2017 
2018  const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
2019  if (!CE) {
2020  llvm_unreachable("Unknown constant value to lower!");
2021  }
2022 
2023  switch (CE->getOpcode()) {
2024  default:
2025  // If the code isn't optimized, there may be outstanding folding
2026  // opportunities. Attempt to fold the expression using DataLayout as a
2027  // last resort before giving up.
2029  if (C && C != CE)
2030  return lowerConstantForGV(C, ProcessingGeneric);
2031 
2032  // Otherwise report the problem to the user.
2033  {
2034  std::string S;
2035  raw_string_ostream OS(S);
2036  OS << "Unsupported expression in static initializer: ";
2037  CE->printAsOperand(OS, /*PrintType=*/false,
2038  !MF ? nullptr : MF->getFunction().getParent());
2039  report_fatal_error(OS.str());
2040  }
2041 
2042  case Instruction::AddrSpaceCast: {
2043  // Strip the addrspacecast and pass along the operand
2044  PointerType *DstTy = cast<PointerType>(CE->getType());
2045  if (DstTy->getAddressSpace() == 0) {
2046  return lowerConstantForGV(cast<const Constant>(CE->getOperand(0)), true);
2047  }
2048  std::string S;
2049  raw_string_ostream OS(S);
2050  OS << "Unsupported expression in static initializer: ";
2051  CE->printAsOperand(OS, /*PrintType=*/ false,
2052  !MF ? nullptr : MF->getFunction().getParent());
2053  report_fatal_error(OS.str());
2054  }
2055 
2056  case Instruction::GetElementPtr: {
2057  const DataLayout &DL = getDataLayout();
2058 
2059  // Generate a symbolic expression for the byte address
2060  APInt OffsetAI(DL.getPointerTypeSizeInBits(CE->getType()), 0);
2061  cast<GEPOperator>(CE)->accumulateConstantOffset(DL, OffsetAI);
2062 
2063  const MCExpr *Base = lowerConstantForGV(CE->getOperand(0),
2064  ProcessingGeneric);
2065  if (!OffsetAI)
2066  return Base;
2067 
2068  int64_t Offset = OffsetAI.getSExtValue();
2069  return MCBinaryExpr::createAdd(Base, MCConstantExpr::create(Offset, Ctx),
2070  Ctx);
2071  }
2072 
2073  case Instruction::Trunc:
2074  // We emit the value and depend on the assembler to truncate the generated
2075  // expression properly. This is important for differences between
2076  // blockaddress labels. Since the two labels are in the same function, it
2077  // is reasonable to treat their delta as a 32-bit value.
2079  case Instruction::BitCast:
2080  return lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2081 
2082  case Instruction::IntToPtr: {
2083  const DataLayout &DL = getDataLayout();
2084 
2085  // Handle casts to pointers by changing them into casts to the appropriate
2086  // integer type. This promotes constant folding and simplifies this code.
2087  Constant *Op = CE->getOperand(0);
2089  false/*ZExt*/);
2090  return lowerConstantForGV(Op, ProcessingGeneric);
2091  }
2092 
2093  case Instruction::PtrToInt: {
2094  const DataLayout &DL = getDataLayout();
2095 
2096  // Support only foldable casts to/from pointers that can be eliminated by
2097  // changing the pointer to the appropriately sized integer type.
2098  Constant *Op = CE->getOperand(0);
2099  Type *Ty = CE->getType();
2100 
2101  const MCExpr *OpExpr = lowerConstantForGV(Op, ProcessingGeneric);
2102 
2103  // We can emit the pointer value into this slot if the slot is an
2104  // integer slot equal to the size of the pointer.
2105  if (DL.getTypeAllocSize(Ty) == DL.getTypeAllocSize(Op->getType()))
2106  return OpExpr;
2107 
2108  // Otherwise the pointer is smaller than the resultant integer, mask off
2109  // the high bits so we are sure to get a proper truncation if the input is
2110  // a constant expr.
2111  unsigned InBits = DL.getTypeAllocSizeInBits(Op->getType());
2112  const MCExpr *MaskExpr = MCConstantExpr::create(~0ULL >> (64-InBits), Ctx);
2113  return MCBinaryExpr::createAnd(OpExpr, MaskExpr, Ctx);
2114  }
2115 
2116  // The MC library also has a right-shift operator, but it isn't consistently
2117  // signed or unsigned between different targets.
2118  case Instruction::Add: {
2119  const MCExpr *LHS = lowerConstantForGV(CE->getOperand(0), ProcessingGeneric);
2120  const MCExpr *RHS = lowerConstantForGV(CE->getOperand(1), ProcessingGeneric);
2121  switch (CE->getOpcode()) {
2122  default: llvm_unreachable("Unknown binary operator constant cast expr");
2123  case Instruction::Add: return MCBinaryExpr::createAdd(LHS, RHS, Ctx);
2124  }
2125  }
2126  }
2127 }
2128 
2129 // Copy of MCExpr::print customized for NVPTX
2130 void NVPTXAsmPrinter::printMCExpr(const MCExpr &Expr, raw_ostream &OS) {
2131  switch (Expr.getKind()) {
2132  case MCExpr::Target:
2133  return cast<MCTargetExpr>(&Expr)->printImpl(OS, MAI);
2134  case MCExpr::Constant:
2135  OS << cast<MCConstantExpr>(Expr).getValue();
2136  return;
2137 
2138  case MCExpr::SymbolRef: {
2139  const MCSymbolRefExpr &SRE = cast<MCSymbolRefExpr>(Expr);
2140  const MCSymbol &Sym = SRE.getSymbol();
2141  Sym.print(OS, MAI);
2142  return;
2143  }
2144 
2145  case MCExpr::Unary: {
2146  const MCUnaryExpr &UE = cast<MCUnaryExpr>(Expr);
2147  switch (UE.getOpcode()) {
2148  case MCUnaryExpr::LNot: OS << '!'; break;
2149  case MCUnaryExpr::Minus: OS << '-'; break;
2150  case MCUnaryExpr::Not: OS << '~'; break;
2151  case MCUnaryExpr::Plus: OS << '+'; break;
2152  }
2153  printMCExpr(*UE.getSubExpr(), OS);
2154  return;
2155  }
2156 
2157  case MCExpr::Binary: {
2158  const MCBinaryExpr &BE = cast<MCBinaryExpr>(Expr);
2159 
2160  // Only print parens around the LHS if it is non-trivial.
2161  if (isa<MCConstantExpr>(BE.getLHS()) || isa<MCSymbolRefExpr>(BE.getLHS()) ||
2162  isa<NVPTXGenericMCSymbolRefExpr>(BE.getLHS())) {
2163  printMCExpr(*BE.getLHS(), OS);
2164  } else {
2165  OS << '(';
2166  printMCExpr(*BE.getLHS(), OS);
2167  OS<< ')';
2168  }
2169 
2170  switch (BE.getOpcode()) {
2171  case MCBinaryExpr::Add:
2172  // Print "X-42" instead of "X+-42".
2173  if (const MCConstantExpr *RHSC = dyn_cast<MCConstantExpr>(BE.getRHS())) {
2174  if (RHSC->getValue() < 0) {
2175  OS << RHSC->getValue();
2176  return;
2177  }
2178  }
2179 
2180  OS << '+';
2181  break;
2182  default: llvm_unreachable("Unhandled binary operator");
2183  }
2184 
2185  // Only print parens around the LHS if it is non-trivial.
2186  if (isa<MCConstantExpr>(BE.getRHS()) || isa<MCSymbolRefExpr>(BE.getRHS())) {
2187  printMCExpr(*BE.getRHS(), OS);
2188  } else {
2189  OS << '(';
2190  printMCExpr(*BE.getRHS(), OS);
2191  OS << ')';
2192  }
2193  return;
2194  }
2195  }
2196 
2197  llvm_unreachable("Invalid expression kind!");
2198 }
2199 
2200 /// PrintAsmOperand - Print out an operand for an inline asm expression.
2201 ///
2202 bool NVPTXAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
2203  unsigned AsmVariant,
2204  const char *ExtraCode, raw_ostream &O) {
2205  if (ExtraCode && ExtraCode[0]) {
2206  if (ExtraCode[1] != 0)
2207  return true; // Unknown modifier.
2208 
2209  switch (ExtraCode[0]) {
2210  default:
2211  // See if this is a generic print operand
2212  return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
2213  case 'r':
2214  break;
2215  }
2216  }
2217 
2218  printOperand(MI, OpNo, O);
2219 
2220  return false;
2221 }
2222 
2223 bool NVPTXAsmPrinter::PrintAsmMemoryOperand(
2224  const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant,
2225  const char *ExtraCode, raw_ostream &O) {
2226  if (ExtraCode && ExtraCode[0])
2227  return true; // Unknown modifier
2228 
2229  O << '[';
2230  printMemOperand(MI, OpNo, O);
2231  O << ']';
2232 
2233  return false;
2234 }
2235 
2236 void NVPTXAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
2237  raw_ostream &O, const char *Modifier) {
2238  const MachineOperand &MO = MI->getOperand(opNum);
2239  switch (MO.getType()) {
2242  if (MO.getReg() == NVPTX::VRDepot)
2243  O << DEPOTNAME << getFunctionNumber();
2244  else
2246  } else {
2247  emitVirtualRegister(MO.getReg(), O);
2248  }
2249  return;
2250 
2252  if (!Modifier)
2253  O << MO.getImm();
2254  else if (strstr(Modifier, "vec") == Modifier)
2255  printVecModifiedImmediate(MO, Modifier, O);
2256  else
2258  "Don't know how to handle modifier on immediate operand");
2259  return;
2260 
2262  printFPConstant(MO.getFPImm(), O);
2263  break;
2264 
2266  getSymbol(MO.getGlobal())->print(O, MAI);
2267  break;
2268 
2270  MO.getMBB()->getSymbol()->print(O, MAI);
2271  return;
2272 
2273  default:
2274  llvm_unreachable("Operand type not supported.");
2275  }
2276 }
2277 
2278 void NVPTXAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
2279  raw_ostream &O, const char *Modifier) {
2280  printOperand(MI, opNum, O);
2281 
2282  if (Modifier && strcmp(Modifier, "add") == 0) {
2283  O << ", ";
2284  printOperand(MI, opNum + 1, O);
2285  } else {
2286  if (MI->getOperand(opNum + 1).isImm() &&
2287  MI->getOperand(opNum + 1).getImm() == 0)
2288  return; // don't print ',0' or '+0'
2289  O << "+";
2290  printOperand(MI, opNum + 1, O);
2291  }
2292 }
2293 
2294 // Force static initialization.
2298 }
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:364
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:322
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:64
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:619
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:587
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:403
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:404
const MCExpr * getLHS() const
Get the left-hand side expression of the binary operator.
Definition: MCExpr.h:563
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
Unary plus.
Definition: MCExpr.h:365
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:465
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:523
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:1612
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:645
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:4443
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:566
#define T
Unary assembler expressions.
Definition: MCExpr.h:359
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:460
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:749
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
virtual bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, unsigned AsmVariant, const char *ExtraCode, raw_ostream &OS)
Print the specified operand of MI, an INLINEASM instruction, using the specified assembler variant...
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:263
size_t alias_size() const
Definition: Module.h:623
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:739
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:362
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:416
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:4269
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:202
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:430
const MCSymbol & getSymbol() const
Definition: MCExpr.h:335
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:839
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:729
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:225
bool doInitialization(Module &M) override
Set up the AsmPrinter when we are working on a new module.
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:895
uint64_t getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:438
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:229
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:248
iterator insert(iterator where, pointer New)
Definition: ilist.h:226
iterator end()
Definition: Module.h:599
const Function * getParent() const
Definition: Argument.h:41
std::string getNVPTXRegClassStr(TargetRegisterClass const *RC)
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:553
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:122
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:780
iterator begin()
Definition: Module.h:597
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:123
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:322
Type * getValueType() const
Definition: GlobalValue.h:275
Unary minus.
Definition: MCExpr.h:363
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:247
Opcode getOpcode() const
Get the kind of this binary expression.
Definition: MCExpr.h:560
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:406
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:421
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:448
const DataLayout & getDataLayout() const
Return information about data layout.
Definition: AsmPrinter.cpp:210
static void ConvertDoubleToBytes(unsigned char *p, double val)
iterator_range< global_iterator > globals()
Definition: Module.h:586
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