1 //===-- NVPTXAssignValidGlobalNames.cpp - Assign valid names to globals ---===//
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
7 //===----------------------------------------------------------------------===//
9 // Clean up the names of global variables in the module to not contain symbols
10 // that are invalid in PTX.
12 // Currently NVPTX, like other backends, relies on generic symbol name
13 // sanitizing done by MC. However, the ptxas assembler is more stringent and
14 // disallows some additional characters in symbol names. This pass makes sure
15 // such names do not reach MC at all.
17 //===----------------------------------------------------------------------===//
20 #include "llvm/IR/Function.h"
21 #include "llvm/IR/GlobalVariable.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/Support/raw_ostream.h"
30 /// NVPTXAssignValidGlobalNames
31 class NVPTXAssignValidGlobalNames
: public ModulePass
{
34 NVPTXAssignValidGlobalNames() : ModulePass(ID
) {}
36 bool runOnModule(Module
&M
) override
;
38 /// Clean up the name to remove symbols invalid in PTX.
39 std::string
cleanUpName(StringRef Name
);
43 char NVPTXAssignValidGlobalNames::ID
= 0;
46 void initializeNVPTXAssignValidGlobalNamesPass(PassRegistry
&);
49 INITIALIZE_PASS(NVPTXAssignValidGlobalNames
, "nvptx-assign-valid-global-names",
50 "Assign valid PTX names to globals", false, false)
52 bool NVPTXAssignValidGlobalNames::runOnModule(Module
&M
) {
53 for (GlobalVariable
&GV
: M
.globals()) {
54 // We are only allowed to rename local symbols.
55 if (GV
.hasLocalLinkage()) {
56 // setName doesn't do extra work if the name does not change.
57 // Note: this does not create collisions - if setName is asked to set the
58 // name to something that already exists, it adds a proper postfix to
60 GV
.setName(cleanUpName(GV
.getName()));
64 // Do the same for local functions.
65 for (Function
&F
: M
.functions())
66 if (F
.hasLocalLinkage())
67 F
.setName(cleanUpName(F
.getName()));
72 std::string
NVPTXAssignValidGlobalNames::cleanUpName(StringRef Name
) {
73 std::string ValidName
;
74 raw_string_ostream
ValidNameStream(ValidName
);
75 for (unsigned I
= 0, E
= Name
.size(); I
!= E
; ++I
) {
77 if (C
== '.' || C
== '@') {
78 ValidNameStream
<< "_$_";
84 return ValidNameStream
.str();
87 ModulePass
*llvm::createNVPTXAssignValidGlobalNamesPass() {
88 return new NVPTXAssignValidGlobalNames();