[NVPTX] Assign valid global names

PTX requires that identifiers consist only of [a-zA-Z0-9_$]. The
existing pass already ensured this for globals and this patch adds
the cleanup for functions with local linkage.

However, there was a different problem in the case of collisions
of the adjusted name: The ValueSymbolTable then automatically
appended ".N" with increasing Ns to get a unique name while helping
the ABI demangling. Special case this behavior to omit the dots and
append N directly. This will always give us legal names according
to the PTX requirements.

Differential Revision: https://reviews.llvm.org/D40573

llvm-svn: 319657
diff --git a/llvm/lib/IR/ValueSymbolTable.cpp b/llvm/lib/IR/ValueSymbolTable.cpp
index ccdabe0..0da1990 100644
--- a/llvm/lib/IR/ValueSymbolTable.cpp
+++ b/llvm/lib/IR/ValueSymbolTable.cpp
@@ -13,7 +13,9 @@
 
 #include "llvm/IR/ValueSymbolTable.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/ADT/Triple.h"
 #include "llvm/IR/GlobalValue.h"
+#include "llvm/IR/Module.h"
 #include "llvm/IR/Type.h"
 #include "llvm/IR/Value.h"
 #include "llvm/Support/Casting.h"
@@ -45,8 +47,17 @@
     // Trim any suffix off and append the next number.
     UniqueName.resize(BaseSize);
     raw_svector_ostream S(UniqueName);
-    if (isa<GlobalValue>(V))
-      S << ".";
+    if (auto *GV = dyn_cast<GlobalValue>(V)) {
+      // A dot is appended to mark it as clone during ABI demangling so that
+      // for example "_Z1fv" and "_Z1fv.1" both demangle to "f()", the second
+      // one being a clone.
+      // On NVPTX we cannot use a dot because PTX only allows [A-Za-z0-9_$] for
+      // identifiers. This breaks ABI demangling but at least ptxas accepts and
+      // compiles the program.
+      const Module *M = GV->getParent();
+      if (!(M && Triple(M->getTargetTriple()).isNVPTX()))
+        S << ".";
+    }
     S << ++LastUnique;
 
     // Try insert the vmap entry with this suffix.