[clang] [lld] [llvm] Reland #184065 (PR #201849)

Mircea Trofin via cfe-commits cfe-commits at lists.llvm.org
Fri Jun 5 08:00:57 PDT 2026


https://github.com/mtrofin updated https://github.com/llvm/llvm-project/pull/201849

>From ad94f681568e4ff68eac986b5f406bfa391f61f7 Mon Sep 17 00:00:00 2001
From: Mircea Trofin <mtrofin at google.com>
Date: Fri, 5 Jun 2026 07:22:53 -0700
Subject: [PATCH] Reland #184065

---
 clang/lib/CodeGen/CGCUDANV.cpp                |  6 +-
 .../CodeGen/cfi-icall-trap-recover-runtime.c  | 24 +++---
 clang/test/CodeGen/lto-newpm-pipeline.c       |  3 +
 .../cfi-vcall-trap-recover-runtime.cpp        | 12 +--
 .../lto/devirt_vcall_vis_export_dynamic.ll    | 12 +--
 lld/test/ELF/lto/devirt_vcall_vis_public.ll   |  6 +-
 .../ELF/lto/devirt_vcall_vis_shared_def.ll    | 12 +--
 llvm/include/llvm/Analysis/CtxProfAnalysis.h  | 36 ++-------
 llvm/include/llvm/Bitcode/BitcodeReader.h     |  4 +-
 llvm/include/llvm/Bitcode/LLVMBitCodes.h      |  3 +
 llvm/include/llvm/IR/GlobalObject.h           |  2 +-
 llvm/include/llvm/IR/GlobalValue.h            | 47 +++++++++--
 llvm/include/llvm/IR/Module.h                 | 31 +++++++-
 llvm/include/llvm/IR/ModuleSummaryIndex.h     | 14 +++-
 llvm/include/llvm/LTO/LTO.h                   | 20 +++++
 .../llvm/Transforms/Utils/AssignGUID.h        | 49 ++++++++++++
 llvm/lib/Analysis/CtxProfAnalysis.cpp         | 42 +---------
 llvm/lib/AsmParser/LLParser.cpp               |  6 +-
 llvm/lib/Bitcode/Reader/BitcodeAnalyzer.cpp   |  1 +
 llvm/lib/Bitcode/Reader/BitcodeReader.cpp     | 78 +++++++++++++++----
 llvm/lib/Bitcode/Writer/BitcodeWriter.cpp     | 52 ++++++++++++-
 llvm/lib/CodeGen/GlobalMerge.cpp              | 20 +++--
 llvm/lib/IR/Globals.cpp                       | 59 +++++++++++++-
 llvm/lib/LTO/LTO.cpp                          | 75 +++++++++++-------
 llvm/lib/LTO/LTOBackend.cpp                   | 10 ++-
 llvm/lib/Passes/PassBuilder.cpp               |  1 +
 llvm/lib/Passes/PassBuilderPipelines.cpp      | 10 ++-
 llvm/lib/Transforms/IPO/ConstantMerge.cpp     |  8 +-
 llvm/lib/Transforms/IPO/FunctionImport.cpp    | 30 ++++---
 llvm/lib/Transforms/IPO/LowerTypeTests.cpp    | 14 ++--
 .../Transforms/IPO/ThinLTOBitcodeWriter.cpp   |  6 +-
 .../lib/Transforms/IPO/WholeProgramDevirt.cpp |  1 +
 .../Instrumentation/PGOCtxProfFlattening.cpp  |  4 +-
 .../Instrumentation/PGOCtxProfLowering.cpp    |  3 +-
 .../Transforms/Scalar/JumpTableToSwitch.cpp   |  7 +-
 llvm/lib/Transforms/Utils/AssignGUID.cpp      | 41 ++++++++++
 llvm/lib/Transforms/Utils/CMakeLists.txt      |  1 +
 .../Transforms/Utils/CallPromotionUtils.cpp   |  5 +-
 llvm/lib/Transforms/Utils/CloneModule.cpp     |  6 +-
 .../Transforms/Utils/FunctionImportUtils.cpp  |  4 +-
 llvm/lib/Transforms/Utils/InlineFunction.cpp  |  4 +-
 llvm/test/Assembler/index-value-order.ll      |  9 ++-
 llvm/test/Bitcode/thinlto-alias.ll            |  1 +
 ...allgraph-partial-sample-profile-summary.ll |  5 +-
 .../thinlto-function-summary-callgraph-pgo.ll |  1 +
 ...ction-summary-callgraph-profile-summary.ll |  5 +-
 ...ummary-callgraph-sample-profile-summary.ll |  5 +-
 .../thinlto-function-summary-callgraph.ll     |  1 +
 .../thinlto-function-summary-refgraph.ll      |  1 +
 llvm/test/Bitcode/thinlto-function-summary.ll |  1 +
 llvm/test/CodeGen/X86/fat-lto-section.ll      |  2 +-
 .../Resolution/X86/not-prevailing-alias.ll    |  2 +-
 .../X86/not-prevailing-weak-aliasee.ll        |  2 +-
 llvm/test/Linker/funcimport2.ll               |  2 +-
 llvm/test/Other/new-pm-O0-defaults.ll         |  3 +-
 llvm/test/Other/new-pm-defaults.ll            |  3 +-
 .../Other/new-pm-thinlto-prelink-defaults.ll  |  3 +-
 .../new-pm-thinlto-prelink-pgo-defaults.ll    |  3 +-
 ...w-pm-thinlto-prelink-samplepgo-defaults.ll |  1 +
 llvm/test/ThinLTO/AArch64/aarch64_inline.ll   |  2 +-
 .../X86/Inputs/cache-typeid-resolutions1.ll   |  3 +-
 .../X86/Inputs/cache-typeid-resolutions2.ll   |  6 +-
 .../X86/Inputs/cache-typeid-resolutions3.ll   | 12 ++-
 llvm/test/ThinLTO/X86/ctor-dtor-alias.ll      |  4 +-
 llvm/test/ThinLTO/X86/ctor-dtor-alias2.ll     |  4 +-
 llvm/test/ThinLTO/X86/deadstrip.ll            |  8 +-
 .../test/ThinLTO/X86/devirt_function_alias.ll |  6 +-
 .../ThinLTO/X86/devirt_function_alias2.ll     |  6 +-
 .../ThinLTO/X86/devirt_pure_virtual_base.ll   |  6 +-
 .../ThinLTO/X86/devirt_vcall_vis_public.ll    |  6 +-
 llvm/test/ThinLTO/X86/distributed_import.ll   |  4 +-
 .../X86/funcattrs-prop-exported-internal.ll   |  4 +-
 .../ThinLTO/X86/funcattrs-prop-unknown.ll     |  6 +-
 llvm/test/ThinLTO/X86/funcattrs-prop-weak.ll  |  2 +-
 llvm/test/ThinLTO/X86/globals-import.ll       |  4 +-
 .../ThinLTO/X86/hidden-escaped-symbols-alt.ll |  2 +-
 .../ThinLTO/X86/hidden-escaped-symbols.ll     |  2 +-
 llvm/test/ThinLTO/X86/import-ro-constant.ll   |  2 +-
 .../ThinLTO/X86/index-const-prop-alias.ll     |  2 +-
 llvm/test/ThinLTO/X86/index-const-prop.ll     |  6 +-
 .../ThinLTO/X86/linkonce_resolution_comdat.ll | 16 ++--
 llvm/test/ThinLTO/X86/memprof-dups.ll         |  2 +-
 .../X86/memprof_callee_type_mismatch.ll       |  2 +-
 .../ThinLTO/X86/memprof_imported_internal.ll  |  2 +-
 .../ThinLTO/X86/memprof_imported_internal2.ll |  2 +-
 .../X86/prevailing_weak_globals_import.ll     |  2 +-
 llvm/test/ThinLTO/X86/visibility-elf.ll       | 12 +--
 llvm/test/ThinLTO/X86/visibility-macho.ll     |  6 +-
 llvm/test/ThinLTO/X86/weak_resolution.ll      |  4 +-
 llvm/test/ThinLTO/X86/windows-vftable.ll      |  4 +-
 llvm/test/ThinLTO/X86/writeonly.ll            |  4 +-
 .../test/Transforms/AssignGUID/assign_guid.ll | 18 +++++
 .../Transforms/ConstantMerge/merge-dbg.ll     |  1 +
 .../test/Transforms/EmbedBitcode/embed-wpd.ll |  2 +-
 llvm/test/Transforms/EmbedBitcode/embed.ll    | 13 ++--
 .../funcimport-debug-retained-nodes.ll        |  3 +-
 .../Transforms/FunctionImport/funcimport.ll   | 24 +++---
 llvm/test/Transforms/GlobalMerge/guid.ll      | 38 +++++++++
 .../LowerTypeTests/cfi-icall-alias.ll         |  2 +-
 .../Transforms/LowerTypeTests/export-icall.ll | 17 ++--
 .../thinlto_indirect_call_promotion.ll        |  4 +-
 .../speculative-devirt-then-inliner.ll        |  2 +-
 .../test/Transforms/SampleProfile/ctxsplit.ll |  8 +-
 .../split-internal-typeid.ll                  |  2 +-
 .../ThinLTOBitcodeWriter/split-internal1.ll   |  2 +-
 .../ThinLTOBitcodeWriter/split-internal2.ll   |  9 ++-
 .../split-vfunc-internal.ll                   |  2 +-
 .../ThinLTOBitcodeWriter/split-vfunc.ll       | 16 ++--
 .../Transforms/ThinLTOBitcodeWriter/split.ll  |  4 +-
 .../ThinLTOBitcodeWriter/unsplittable.ll      |  2 +-
 .../branch-funnel-profile.ll                  | 44 +++++------
 .../WholeProgramDevirt/export-single-impl.ll  |  4 +-
 .../WholeProgramDevirt/export-vcp.ll          |  6 +-
 .../X86/devirt_vcall_vis_export_dynamic.ll    |  4 +-
 .../tools/gold/X86/devirt_vcall_vis_public.ll |  2 +-
 .../gold/X86/devirt_vcall_vis_shared_def.ll   |  4 +-
 .../tools/gold/X86/thinlto_weak_library.ll    |  2 +-
 .../tools/gold/X86/thinlto_weak_resolution.ll |  4 +-
 .../v1.16/devirt_vcall_vis_export_dynamic.ll  |  2 +-
 llvm/tools/llvm-link/llvm-link.cpp            |  3 +-
 llvm/tools/opt/NewPMDriver.cpp                |  8 ++
 llvm/tools/opt/optdriver.cpp                  |  7 ++
 122 files changed, 831 insertions(+), 400 deletions(-)
 create mode 100644 llvm/include/llvm/Transforms/Utils/AssignGUID.h
 create mode 100644 llvm/lib/Transforms/Utils/AssignGUID.cpp
 create mode 100644 llvm/test/Transforms/AssignGUID/assign_guid.ll
 create mode 100644 llvm/test/Transforms/GlobalMerge/guid.ll

diff --git a/clang/lib/CodeGen/CGCUDANV.cpp b/clang/lib/CodeGen/CGCUDANV.cpp
index 259b6c040706b..383f752a3a417 100644
--- a/clang/lib/CodeGen/CGCUDANV.cpp
+++ b/clang/lib/CodeGen/CGCUDANV.cpp
@@ -25,6 +25,7 @@
 #include "llvm/IR/BasicBlock.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
+#include "llvm/IR/GlobalValue.h"
 #include "llvm/IR/ReplaceConstant.h"
 #include "llvm/Support/Format.h"
 #include "llvm/Support/VirtualFileSystem.h"
@@ -975,7 +976,10 @@ llvm::Function *CGNVCUDARuntime::makeModuleCtorFunction() {
     // Generate a unique module ID.
     SmallString<64> ModuleID;
     llvm::raw_svector_ostream OS(ModuleID);
-    OS << ModuleIDPrefix << llvm::format("%" PRIx64, FatbinWrapper->getGUID());
+    OS << ModuleIDPrefix
+       << llvm::format("%" PRIx64,
+                       llvm::GlobalValue::getGUIDAssumingExternalLinkage(
+                           FatbinWrapper->getName()));
     llvm::Constant *ModuleIDConstant = makeConstantArray(
         std::string(ModuleID), "", ModuleIDSectionName, 32, /*AddNull=*/true);
 
diff --git a/clang/test/CodeGen/cfi-icall-trap-recover-runtime.c b/clang/test/CodeGen/cfi-icall-trap-recover-runtime.c
index 2c44842f9d28e..5717fc66488af 100644
--- a/clang/test/CodeGen/cfi-icall-trap-recover-runtime.c
+++ b/clang/test/CodeGen/cfi-icall-trap-recover-runtime.c
@@ -15,32 +15,32 @@
 
 
 // TRAP-LABEL: define hidden void @f(
-// TRAP-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]] {
+// TRAP-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]]
 // TRAP-NEXT:  [[ENTRY:.*:]]
 // TRAP-NEXT:    ret void
 //
 // ABORT-LABEL: define hidden void @f(
-// ABORT-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]] {
+// ABORT-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]]
 // ABORT-NEXT:  [[ENTRY:.*:]]
 // ABORT-NEXT:    ret void
 //
 // RECOVER-LABEL: define hidden void @f(
-// RECOVER-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]] {
+// RECOVER-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]]
 // RECOVER-NEXT:  [[ENTRY:.*:]]
 // RECOVER-NEXT:    ret void
 //
 // ABORT_MIN-LABEL: define hidden void @f(
-// ABORT_MIN-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]] {
+// ABORT_MIN-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]]
 // ABORT_MIN-NEXT:  [[ENTRY:.*:]]
 // ABORT_MIN-NEXT:    ret void
 //
 // RECOVER_MIN-LABEL: define hidden void @f(
-// RECOVER_MIN-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]] {
+// RECOVER_MIN-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]]
 // RECOVER_MIN-NEXT:  [[ENTRY:.*:]]
 // RECOVER_MIN-NEXT:    ret void
 //
 // PRESERVE_MIN-LABEL: define hidden void @f(
-// PRESERVE_MIN-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]] {
+// PRESERVE_MIN-SAME: ) #[[ATTR0:[0-9]+]] !type [[META6:![0-9]+]] !type [[META7:![0-9]+]]
 // PRESERVE_MIN-NEXT:  [[ENTRY:.*:]]
 // PRESERVE_MIN-NEXT:    ret void
 //
@@ -50,7 +50,7 @@ void f() {
 void xf();
 
 // TRAP-LABEL: define hidden void @g(
-// TRAP-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]] {
+// TRAP-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]]
 // TRAP-NEXT:  [[ENTRY:.*:]]
 // TRAP-NEXT:    [[B_ADDR:%.*]] = alloca i32, align 4
 // TRAP-NEXT:    [[FP:%.*]] = alloca ptr, align 8
@@ -71,7 +71,7 @@ void xf();
 // TRAP-NEXT:    ret void
 //
 // ABORT-LABEL: define hidden void @g(
-// ABORT-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]] {
+// ABORT-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]]
 // ABORT-NEXT:  [[ENTRY:.*:]]
 // ABORT-NEXT:    [[B_ADDR:%.*]] = alloca i32, align 4
 // ABORT-NEXT:    [[FP:%.*]] = alloca ptr, align 8
@@ -93,7 +93,7 @@ void xf();
 // ABORT-NEXT:    ret void
 //
 // RECOVER-LABEL: define hidden void @g(
-// RECOVER-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]] {
+// RECOVER-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]]
 // RECOVER-NEXT:  [[ENTRY:.*:]]
 // RECOVER-NEXT:    [[B_ADDR:%.*]] = alloca i32, align 4
 // RECOVER-NEXT:    [[FP:%.*]] = alloca ptr, align 8
@@ -115,7 +115,7 @@ void xf();
 // RECOVER-NEXT:    ret void
 //
 // ABORT_MIN-LABEL: define hidden void @g(
-// ABORT_MIN-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]] {
+// ABORT_MIN-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]]
 // ABORT_MIN-NEXT:  [[ENTRY:.*:]]
 // ABORT_MIN-NEXT:    [[B_ADDR:%.*]] = alloca i32, align 4
 // ABORT_MIN-NEXT:    [[FP:%.*]] = alloca ptr, align 8
@@ -136,7 +136,7 @@ void xf();
 // ABORT_MIN-NEXT:    ret void
 //
 // RECOVER_MIN-LABEL: define hidden void @g(
-// RECOVER_MIN-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]] {
+// RECOVER_MIN-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]]
 // RECOVER_MIN-NEXT:  [[ENTRY:.*:]]
 // RECOVER_MIN-NEXT:    [[B_ADDR:%.*]] = alloca i32, align 4
 // RECOVER_MIN-NEXT:    [[FP:%.*]] = alloca ptr, align 8
@@ -157,7 +157,7 @@ void xf();
 // RECOVER_MIN-NEXT:    ret void
 //
 // PRESERVE_MIN-LABEL: define hidden void @g(
-// PRESERVE_MIN-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]] {
+// PRESERVE_MIN-SAME: i32 noundef [[B:%.*]]) #[[ATTR0]] !type [[META8:![0-9]+]] !type [[META9:![0-9]+]]
 // PRESERVE_MIN-NEXT:  [[ENTRY:.*:]]
 // PRESERVE_MIN-NEXT:    [[B_ADDR:%.*]] = alloca i32, align 4
 // PRESERVE_MIN-NEXT:    [[FP:%.*]] = alloca ptr, align 8
diff --git a/clang/test/CodeGen/lto-newpm-pipeline.c b/clang/test/CodeGen/lto-newpm-pipeline.c
index ea9784a76f923..c8ee5e949ae87 100644
--- a/clang/test/CodeGen/lto-newpm-pipeline.c
+++ b/clang/test/CodeGen/lto-newpm-pipeline.c
@@ -34,6 +34,7 @@
 // CHECK-FULL-O0-NEXT: Running pass: CoroConditionalWrapper
 // CHECK-FULL-O0-NEXT: Running pass: CanonicalizeAliasesPass
 // CHECK-FULL-O0-NEXT: Running pass: NameAnonGlobalPass
+// CHECK-FULL-O0-NEXT: Running pass: AssignGUIDPass
 // CHECK-FULL-O0-NEXT: Running pass: AnnotationRemarksPass
 // CHECK-FULL-O0-NEXT: Running analysis: TargetLibraryAnalysis
 // CHECK-FULL-O0-NEXT: Running pass: VerifierPass
@@ -48,6 +49,7 @@
 // CHECK-THIN-O0-NEXT: Running pass: CoroConditionalWrapper
 // CHECK-THIN-O0-NEXT: Running pass: CanonicalizeAliasesPass
 // CHECK-THIN-O0-NEXT: Running pass: NameAnonGlobalPass
+// CHECK-THIN-O0-NEXT: Running pass: AssignGUIDPass
 // CHECK-THIN-O0-NEXT: Running pass: AnnotationRemarksPass
 // CHECK-THIN-O0-NEXT: Running analysis: TargetLibraryAnalysis
 // CHECK-THIN-O0-NEXT: Running pass: VerifierPass
@@ -64,6 +66,7 @@
 // CHECK-THIN-OPTIMIZED-NOT: Running pass: LoopVectorizePass
 // CHECK-THIN-OPTIMIZED: Running pass: CanonicalizeAliasesPass
 // CHECK-THIN-OPTIMIZED: Running pass: NameAnonGlobalPass
+// CHECK-THIN-OPTIMIZED: Running pass: AssignGUIDPass
 // CHECK-THIN-OPTIMIZED: Running pass: ThinLTOBitcodeWriterPass
 
 void Foo(void) {}
diff --git a/clang/test/CodeGenCXX/cfi-vcall-trap-recover-runtime.cpp b/clang/test/CodeGenCXX/cfi-vcall-trap-recover-runtime.cpp
index 2451d31e9a489..a1e1563a4f38d 100644
--- a/clang/test/CodeGenCXX/cfi-vcall-trap-recover-runtime.cpp
+++ b/clang/test/CodeGenCXX/cfi-vcall-trap-recover-runtime.cpp
@@ -19,7 +19,7 @@ struct S1 {
 };
 
 // TRAP-LABEL: define hidden void @_Z3s1fP2S1(
-// TRAP-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]] {
+// TRAP-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]]
 // TRAP-NEXT:  [[ENTRY:.*:]]
 // TRAP-NEXT:    [[S1_ADDR:%.*]] = alloca ptr, align 8
 // TRAP-NEXT:    store ptr [[S1]], ptr [[S1_ADDR]], align 8
@@ -37,7 +37,7 @@ struct S1 {
 // TRAP-NEXT:    ret void
 //
 // ABORT-LABEL: define hidden void @_Z3s1fP2S1(
-// ABORT-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]] {
+// ABORT-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]]
 // ABORT-NEXT:  [[ENTRY:.*:]]
 // ABORT-NEXT:    [[S1_ADDR:%.*]] = alloca ptr, align 8
 // ABORT-NEXT:    store ptr [[S1]], ptr [[S1_ADDR]], align 8
@@ -58,7 +58,7 @@ struct S1 {
 // ABORT-NEXT:    ret void
 //
 // RECOVER-LABEL: define hidden void @_Z3s1fP2S1(
-// RECOVER-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]] {
+// RECOVER-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]]
 // RECOVER-NEXT:  [[ENTRY:.*:]]
 // RECOVER-NEXT:    [[S1_ADDR:%.*]] = alloca ptr, align 8
 // RECOVER-NEXT:    store ptr [[S1]], ptr [[S1_ADDR]], align 8
@@ -79,7 +79,7 @@ struct S1 {
 // RECOVER-NEXT:    ret void
 //
 // ABORT_MIN-LABEL: define hidden void @_Z3s1fP2S1(
-// ABORT_MIN-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]] {
+// ABORT_MIN-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]]
 // ABORT_MIN-NEXT:  [[ENTRY:.*:]]
 // ABORT_MIN-NEXT:    [[S1_ADDR:%.*]] = alloca ptr, align 8
 // ABORT_MIN-NEXT:    store ptr [[S1]], ptr [[S1_ADDR]], align 8
@@ -98,7 +98,7 @@ struct S1 {
 // ABORT_MIN-NEXT:    ret void
 //
 // RECOVER_MIN-LABEL: define hidden void @_Z3s1fP2S1(
-// RECOVER_MIN-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]] {
+// RECOVER_MIN-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]]
 // RECOVER_MIN-NEXT:  [[ENTRY:.*:]]
 // RECOVER_MIN-NEXT:    [[S1_ADDR:%.*]] = alloca ptr, align 8
 // RECOVER_MIN-NEXT:    store ptr [[S1]], ptr [[S1_ADDR]], align 8
@@ -117,7 +117,7 @@ struct S1 {
 // RECOVER_MIN-NEXT:    ret void
 //
 // PRESERVE_MIN-LABEL: define hidden void @_Z3s1fP2S1(
-// PRESERVE_MIN-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]] {
+// PRESERVE_MIN-SAME: ptr noundef [[S1:%.*]]) #[[ATTR0:[0-9]+]]
 // PRESERVE_MIN-NEXT:  [[ENTRY:.*:]]
 // PRESERVE_MIN-NEXT:    [[S1_ADDR:%.*]] = alloca ptr, align 8
 // PRESERVE_MIN-NEXT:    store ptr [[S1]], ptr [[S1_ADDR]], align 8
diff --git a/lld/test/ELF/lto/devirt_vcall_vis_export_dynamic.ll b/lld/test/ELF/lto/devirt_vcall_vis_export_dynamic.ll
index bcb92a1beb17b..9b9c7891a6da6 100644
--- a/lld/test/ELF/lto/devirt_vcall_vis_export_dynamic.ll
+++ b/lld/test/ELF/lto/devirt_vcall_vis_export_dynamic.ll
@@ -5,7 +5,7 @@
 
 ;; Index based WPD
 ;; Generate unsplit module with summary for ThinLTO index-based WPD.
-; RUN: opt --thinlto-bc -o %t2.o %s
+; RUN: opt --passes=assign-guid --thinlto-bc -o %t2.o %s
 ; RUN: ld.lld %t2.o -o %t3 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t2.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
@@ -16,13 +16,13 @@
 
 ;; Hybrid WPD
 ;; Generate split module with summary for hybrid Thin/Regular LTO WPD.
-; RUN: opt --thinlto-bc --thinlto-split-lto-unit -o %t.o %s
+; RUN: opt --passes=assign-guid --thinlto-bc --thinlto-split-lto-unit -o %t.o %s
 ; RUN: ld.lld %t.o -o %t3 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t4.o %s
+; RUN: opt --passes=assign-guid -o %t4.o %s
 ; RUN: ld.lld %t4.o -o %t3 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t3.0.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
@@ -107,19 +107,19 @@
 ;; preemption, even without any options.
 
 ;; Index based WPD
-; RUN: opt -relocation-model=pic --thinlto-bc -o %t5.o %s
+; RUN: opt --passes=assign-guid -relocation-model=pic --thinlto-bc -o %t5.o %s
 ; RUN: ld.lld %t5.o -o %t5.so -shared
 ; RUN: ld.lld %t5.o %t5.so -o %t5 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck /dev/null --implicit-check-not single-impl --allow-empty
 
 ;; Hybrid WPD
-; RUN: opt -relocation-model=pic --thinlto-bc --thinlto-split-lto-unit -o %t5.o %s
+; RUN: opt --passes=assign-guid -relocation-model=pic --thinlto-bc --thinlto-split-lto-unit -o %t5.o %s
 ; RUN: ld.lld %t5.o -o %t5.so -shared
 ; RUN: ld.lld %t5.o %t5.so -o %t5 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck /dev/null --implicit-check-not single-impl --allow-empty
 
 ;; Regular LTO WPD
-; RUN: opt -relocation-model=pic -o %t5.o %s
+; RUN: opt --passes=assign-guid -relocation-model=pic -o %t5.o %s
 ; RUN: ld.lld %t5.o -o %t5.so -shared
 ; RUN: ld.lld %t5.o %t5.so -o %t5 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck /dev/null --implicit-check-not single-impl --allow-empty
diff --git a/lld/test/ELF/lto/devirt_vcall_vis_public.ll b/lld/test/ELF/lto/devirt_vcall_vis_public.ll
index a827fea465fd7..0030e5804af81 100644
--- a/lld/test/ELF/lto/devirt_vcall_vis_public.ll
+++ b/lld/test/ELF/lto/devirt_vcall_vis_public.ll
@@ -3,20 +3,20 @@
 
 ;; Index based WPD
 ;; Generate unsplit module with summary for ThinLTO index-based WPD.
-; RUN: opt --thinlto-bc -o %t2.o %s
+; RUN: opt --passes=assign-guid --thinlto-bc -o %t2.o %s
 ; RUN: ld.lld %t2.o -o %t3 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t2.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Hybrid WPD
 ;; Generate split module with summary for hybrid Thin/Regular LTO WPD.
-; RUN: opt --thinlto-bc --thinlto-split-lto-unit -o %t.o %s
+; RUN: opt --passes=assign-guid --thinlto-bc --thinlto-split-lto-unit -o %t.o %s
 ; RUN: ld.lld %t.o -o %t3 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t4.o %s
+; RUN: opt --passes=assign-guid -o %t4.o %s
 ; RUN: ld.lld %t4.o -o %t3 -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t3.0.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
diff --git a/lld/test/ELF/lto/devirt_vcall_vis_shared_def.ll b/lld/test/ELF/lto/devirt_vcall_vis_shared_def.ll
index a61e290bb0eb1..b77dde97a2c05 100644
--- a/lld/test/ELF/lto/devirt_vcall_vis_shared_def.ll
+++ b/lld/test/ELF/lto/devirt_vcall_vis_shared_def.ll
@@ -6,23 +6,23 @@
 
 ;; Index based WPD
 ;; Generate unsplit module with summary for ThinLTO index-based WPD.
-; RUN: opt --thinlto-bc -o %t1a.o %s
-; RUN: opt --thinlto-bc -o %t2a.o %S/Inputs/devirt_vcall_vis_shared_def.ll
+; RUN: opt --passes=assign-guid --thinlto-bc -o %t1a.o %s
+; RUN: opt --passes=assign-guid --thinlto-bc -o %t2a.o %S/Inputs/devirt_vcall_vis_shared_def.ll
 ; RUN: ld.lld %t1a.o %t2a.o -o %t3a -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t1a.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Hybrid WPD
 ;; Generate split module with summary for hybrid Thin/Regular LTO WPD.
-; RUN: opt --thinlto-bc --thinlto-split-lto-unit -o %t1b.o %s
-; RUN: opt --thinlto-bc --thinlto-split-lto-unit -o %t2b.o %S/Inputs/devirt_vcall_vis_shared_def.ll
+; RUN: opt --passes=assign-guid --thinlto-bc --thinlto-split-lto-unit -o %t1b.o %s
+; RUN: opt --passes=assign-guid --thinlto-bc --thinlto-split-lto-unit -o %t2b.o %S/Inputs/devirt_vcall_vis_shared_def.ll
 ; RUN: ld.lld %t1b.o %t2b.o -o %t3b -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t1b.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t1c.o %s
-; RUN: opt -o %t2c.o %S/Inputs/devirt_vcall_vis_shared_def.ll
+; RUN: opt --passes=assign-guid -o %t1c.o %s
+; RUN: opt --passes=assign-guid -o %t2c.o %S/Inputs/devirt_vcall_vis_shared_def.ll
 ; RUN: ld.lld %t1c.o %t2c.o -o %t3c -save-temps --lto-whole-program-visibility \
 ; RUN:   -mllvm -pass-remarks=. 2>&1 | FileCheck %s --check-prefix=REMARK
 ; RUN: llvm-dis %t3c.0.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
diff --git a/llvm/include/llvm/Analysis/CtxProfAnalysis.h b/llvm/include/llvm/Analysis/CtxProfAnalysis.h
index 8260b95026ad2..d2a1c07bd58e4 100644
--- a/llvm/include/llvm/Analysis/CtxProfAnalysis.h
+++ b/llvm/include/llvm/Analysis/CtxProfAnalysis.h
@@ -47,9 +47,6 @@ class PGOContextualProfile {
   // we'll need when we maintain the profiles during IPO transformations.
   std::map<GlobalValue::GUID, FunctionInfo> FuncInfo;
 
-  /// Get the GUID of this Function if it's defined in this module.
-  LLVM_ABI GlobalValue::GUID getDefinedFunctionGUID(const Function &F) const;
-
   // This is meant to be constructed from CtxProfAnalysis, which will also set
   // its state piecemeal.
   PGOContextualProfile() = default;
@@ -68,9 +65,7 @@ class PGOContextualProfile {
 
   LLVM_ABI bool isInSpecializedModule() const;
 
-  bool isFunctionKnown(const Function &F) const {
-    return getDefinedFunctionGUID(F) != 0;
-  }
+  bool isFunctionKnown(const Function &F) const { return !F.isDeclaration(); }
 
   StringRef getFunctionName(GlobalValue::GUID GUID) const {
     auto It = FuncInfo.find(GUID);
@@ -81,22 +76,22 @@ class PGOContextualProfile {
 
   uint32_t getNumCounters(const Function &F) const {
     assert(isFunctionKnown(F));
-    return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCounterIndex;
+    return FuncInfo.find(F.getGUID())->second.NextCounterIndex;
   }
 
   uint32_t getNumCallsites(const Function &F) const {
     assert(isFunctionKnown(F));
-    return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCallsiteIndex;
+    return FuncInfo.find(F.getGUID())->second.NextCallsiteIndex;
   }
 
   uint32_t allocateNextCounterIndex(const Function &F) {
     assert(isFunctionKnown(F));
-    return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCounterIndex++;
+    return FuncInfo.find(F.getGUID())->second.NextCounterIndex++;
   }
 
   uint32_t allocateNextCallsiteIndex(const Function &F) {
     assert(isFunctionKnown(F));
-    return FuncInfo.find(getDefinedFunctionGUID(F))->second.NextCallsiteIndex++;
+    return FuncInfo.find(F.getGUID())->second.NextCallsiteIndex++;
   }
 
   using ConstVisitor = function_ref<void(const PGOCtxProfContext &)>;
@@ -187,26 +182,5 @@ class ProfileAnnotator {
   LLVM_ABI ~ProfileAnnotator();
 };
 
-/// Assign a GUID to functions as metadata. GUID calculation takes linkage into
-/// account, which may change especially through and after thinlto. By
-/// pre-computing and assigning as metadata, this mechanism is resilient to such
-/// changes (as well as name changes e.g. suffix ".llvm." additions).
-
-// FIXME(mtrofin): we can generalize this mechanism to calculate a GUID early in
-// the pass pipeline, associate it with any Global Value, and then use it for
-// PGO and ThinLTO.
-// At that point, this should be moved elsewhere.
-class AssignGUIDPass : public OptionalPassInfoMixin<AssignGUIDPass> {
-public:
-  explicit AssignGUIDPass() = default;
-
-  /// Assign a GUID *if* one is not already assign, as a function metadata named
-  /// `GUIDMetadataName`.
-  LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM);
-  LLVM_ABI static const char *GUIDMetadataName;
-  // This should become GlobalValue::getGUID
-  LLVM_ABI static uint64_t getGUID(const Function &F);
-};
-
 } // namespace llvm
 #endif // LLVM_ANALYSIS_CTXPROFANALYSIS_H
diff --git a/llvm/include/llvm/Bitcode/BitcodeReader.h b/llvm/include/llvm/Bitcode/BitcodeReader.h
index 772ca82019278..b7cab51857f0b 100644
--- a/llvm/include/llvm/Bitcode/BitcodeReader.h
+++ b/llvm/include/llvm/Bitcode/BitcodeReader.h
@@ -17,6 +17,7 @@
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Bitstream/BitCodeEnums.h"
 #include "llvm/IR/GlobalValue.h"
+#include "llvm/IR/ModuleSummaryIndex.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/Endian.h"
 #include "llvm/Support/Error.h"
@@ -165,7 +166,8 @@ struct ParserCallbacks {
     /// into CombinedIndex.
     LLVM_ABI Error
     readSummary(ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
-                std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
+                std::function<bool(StringRef)> IsPrevailing = nullptr,
+                std::function<void(ValueInfo)> OnValueInfo = nullptr);
   };
 
   struct BitcodeFileContents {
diff --git a/llvm/include/llvm/Bitcode/LLVMBitCodes.h b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
index 95787c595dff7..3f9727782b131 100644
--- a/llvm/include/llvm/Bitcode/LLVMBitCodes.h
+++ b/llvm/include/llvm/Bitcode/LLVMBitCodes.h
@@ -120,6 +120,9 @@ enum ModuleCodes {
 
   // IFUNC: [ifunc value type, addrspace, resolver val#, linkage, visibility]
   MODULE_CODE_IFUNC = 18,
+
+  // GUIDLIST: [n x i64]
+  MODULE_CODE_GUIDLIST = 19,
 };
 
 /// PARAMATTR blocks have code for defining a parameter attribute set.
diff --git a/llvm/include/llvm/IR/GlobalObject.h b/llvm/include/llvm/IR/GlobalObject.h
index 1e03e22f0403b..746ccf5ecc994 100644
--- a/llvm/include/llvm/IR/GlobalObject.h
+++ b/llvm/include/llvm/IR/GlobalObject.h
@@ -181,7 +181,7 @@ class GlobalObject : public GlobalValue {
                             SmallVectorImpl<MDNode *> &MDs) const;
   /// @}
 
-  LLVM_ABI bool hasMetadataOtherThanDebugLoc() const;
+  LLVM_ABI bool hasMetadataOtherThanDebugLocAndGuid() const;
 
   /// Copy metadata from Src, adjusting offsets by Offset.
   LLVM_ABI void copyMetadata(const GlobalObject *Src, unsigned Offset);
diff --git a/llvm/include/llvm/IR/GlobalValue.h b/llvm/include/llvm/IR/GlobalValue.h
index 83e695cdd27d9..ef037a25fac2e 100644
--- a/llvm/include/llvm/IR/GlobalValue.h
+++ b/llvm/include/llvm/IR/GlobalValue.h
@@ -589,17 +589,54 @@ class GlobalValue : public Constant {
   /// used as the key for a global lookup (e.g. profile or ThinLTO).
   LLVM_ABI std::string getGlobalIdentifier() const;
 
+  /// Assign a GUID to this value based on its current name and linkage.
+  /// This GUID will remain the same even if those change. This method is
+  /// idempotent -- if a GUID has already been assigned, calling it again
+  /// will do nothing.
+  ///
+  /// This is private (exposed only to \c AssignGUIDPass), as users don't need
+  /// to call it. GUIDs are assigned only by \c AssignGUIDPass. The pass
+  /// pipeline should be set up such that GUIDs are always available when
+  /// needed. If not, the GUID assignment pass should be moved (or run again)
+  /// such that they are.
+  void assignGUID();
+
+  // assignGUID needs to be accessible from AssignGUIDPass, which is called
+  // early in the pipeline to make GUIDs available to later passes. But we'd
+  // rather not expose it publicly, as no-one else should call it.
+  friend class AssignGUIDPass;
+
+  MDNode *getGUIDMetadata() const;
+
 public:
   /// Return a 64-bit global unique ID constructed from the name of a global
   /// symbol. Since this call doesn't supply the linkage or defining filename,
   /// the GUID computation will assume that the global has external linkage.
   LLVM_ABI static GUID getGUIDAssumingExternalLinkage(StringRef GlobalName);
 
-  /// Return a 64-bit global unique ID constructed from global value name
-  /// (i.e. returned by getGlobalIdentifier()).
-  GUID getGUID() const {
-    return getGUIDAssumingExternalLinkage(getGlobalIdentifier());
-  }
+  /// Return a 64-bit global unique ID for this value. It is based on the
+  /// "original" name and linkage of this value (i.e. whenever its GUID was
+  /// assigned). This might not match the current name and linkage.
+  ///
+  /// The \c AssignGUIDPass must be run before this is called, otherwise
+  /// GUIDs won't be available. This pass can be run multiple times as it does
+  /// nothing if GUID metadata is already present.
+  GUID getGUID() const;
+
+  /// Return the GUID for this value if it has been assigned, nullopt
+  /// otherwise. This should only need to be used in some exceptional
+  /// situations. If possible whatever code needs access to a GUID should
+  /// be set up to run after AssignGUIDPass, in which case it will always
+  /// be available.
+  std::optional<GUID> getGUIDIfAssigned() const;
+
+  /// Return the GUID for this value if it has been assigned, otherwise fall
+  /// back to computing it based on its current name and linkage.
+  ///
+  /// This is to be used in situations where we need a GUID but can't guarantee
+  /// that it's been computed. Notably, if we're reading from bitcode files
+  /// that might pre-date the storage of GUIDs in metadata.
+  GUID getGUIDOrFallback() const;
 
   /// @name Materialization
   /// Materialization is used to construct functions only as they're needed.
diff --git a/llvm/include/llvm/IR/Module.h b/llvm/include/llvm/IR/Module.h
index 2032c0ceb2088..1c8c2c2fbd77c 100644
--- a/llvm/include/llvm/IR/Module.h
+++ b/llvm/include/llvm/IR/Module.h
@@ -32,6 +32,7 @@
 #include "llvm/Support/CBindingWrapping.h"
 #include "llvm/Support/CodeGen.h"
 #include "llvm/Support/Compiler.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/TargetParser/Triple.h"
 #include <cstddef>
 #include <cstdint>
@@ -578,10 +579,34 @@ class LLVM_ABI Module {
   // Use global_size() to get the total number of global variables.
   // Use globals() to get the range of all global variables.
 
+  std::optional<GlobalValue::GUID> getGUID(const Value *V) const {
+    const auto It = ValueToGUIDMap.find(V);
+    if (It == ValueToGUIDMap.end())
+      return std::nullopt;
+
+    return It->getSecond();
+  }
+
+  void insertGUID(const Value *V, GlobalValue::GUID GUID) {
+    const auto [It, WasInserted] = ValueToGUIDMap.insert({V, GUID});
+
+    (void)It, (void)WasInserted;
+#ifndef NDEBUG
+    if (!WasInserted) {
+      assert((It->second == GUID) && "insertGUID called with different value");
+    }
+#endif
+  }
+
 private:
-/// @}
-/// @name Direct access to the globals list, functions list, and symbol table
-/// @{
+  /// A mapping directly from Value to GUID. Populated from bitcode
+  /// (MODULE_CODE_GUIDLIST). Necessary for lazy-loading modules, where we
+  /// don't load metadata.
+  DenseMap<const Value *, GlobalValue::GUID> ValueToGUIDMap;
+
+  /// @}
+  /// @name Direct access to the globals list, functions list, and symbol table
+  /// @{
 
   /// Get the Module's list of global variables (constant).
   const GlobalListType   &getGlobalList() const       { return GlobalList; }
diff --git a/llvm/include/llvm/IR/ModuleSummaryIndex.h b/llvm/include/llvm/IR/ModuleSummaryIndex.h
index ae99593d16b6b..c0315c77ceff8 100644
--- a/llvm/include/llvm/IR/ModuleSummaryIndex.h
+++ b/llvm/include/llvm/IR/ModuleSummaryIndex.h
@@ -31,6 +31,7 @@
 #include "llvm/IR/Module.h"
 #include "llvm/Support/Allocator.h"
 #include "llvm/Support/Compiler.h"
+#include "llvm/Support/Debug.h"
 #include "llvm/Support/InterleavedRange.h"
 #include "llvm/Support/ScaledNumber.h"
 #include "llvm/Support/StringSaver.h"
@@ -1762,14 +1763,21 @@ class ModuleSummaryIndex {
     return ValueInfo(HaveGVs, VP);
   }
 
-  /// Return a ValueInfo for \p GV and mark it as belonging to GV.
-  ValueInfo getOrInsertValueInfo(const GlobalValue *GV) {
+  /// Return a ValueInfo for \p GV with GUID \p GUID and mark it as belonging to
+  /// GV.
+  ValueInfo getOrInsertValueInfo(const GlobalValue *GV,
+                                 GlobalValue::GUID GUID) {
     assert(HaveGVs);
-    auto VP = getOrInsertValuePtr(GV->getGUID());
+    auto VP = getOrInsertValuePtr(GUID);
     VP->second.U.GV = GV;
     return ValueInfo(HaveGVs, VP);
   }
 
+  /// Return a ValueInfo for \p GV and mark it as belonging to GV.
+  ValueInfo getOrInsertValueInfo(const GlobalValue *GV) {
+    return getOrInsertValueInfo(GV, GV->getGUID());
+  }
+
   /// Return the GUID for \p OriginalId in the OidGuidMap.
   GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const {
     const auto I = OidGuidMap.find(OriginalID);
diff --git a/llvm/include/llvm/LTO/LTO.h b/llvm/include/llvm/LTO/LTO.h
index bfb5388c8c7cb..9fea1e399ec61 100644
--- a/llvm/include/llvm/LTO/LTO.h
+++ b/llvm/include/llvm/LTO/LTO.h
@@ -521,6 +521,8 @@ class LTO {
   // been added and the client has called run(). During run() we apply
   // internalization decisions either directly to the module (for regular LTO)
   // or to the combined index (for ThinLTO).
+  // FIXME: Make this GlobalResolution a class, it has been becoming more than
+  // just a data bag.
   struct GlobalResolution {
     /// The unmangled name of the global.
     std::string IRName;
@@ -557,6 +559,24 @@ class LTO {
     /// LTO backend.
     unsigned Partition = Unknown;
 
+  private:
+    GlobalValue::GUID GUID = 0;
+
+  public:
+    void setGUID(GlobalValue::GUID G) {
+      assert(G);
+      assert(!GUID || GUID == G);
+      GUID = G;
+    }
+
+    GlobalValue::GUID getGUID() const {
+      return GUID ? GUID
+                  : GlobalValue::getGUIDAssumingExternalLinkage(
+                        GlobalValue::getGlobalIdentifier(
+                            IRName, GlobalValue::LinkageTypes::ExternalLinkage,
+                            ""));
+    }
+
     /// Special partition numbers.
     enum : unsigned {
       /// A partition number has not yet been assigned to this global.
diff --git a/llvm/include/llvm/Transforms/Utils/AssignGUID.h b/llvm/include/llvm/Transforms/Utils/AssignGUID.h
new file mode 100644
index 0000000000000..1b2d718681da8
--- /dev/null
+++ b/llvm/include/llvm/Transforms/Utils/AssignGUID.h
@@ -0,0 +1,49 @@
+//===-- AssignGUID.h - Unique identifier assignment pass --------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provides a pass which assigns a a GUID (globally unique identifier)
+// to every GlobalValue in the module, according to its current name, linkage,
+// and originating file. This way we have a consistent identifier even when
+// these inputs to the GUID change (for instance, after externalising a global
+// in ThinLTO).
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_TRANSFORMS_UTILS_ASSIGNGUID_H
+#define LLVM_TRANSFORMS_UTILS_ASSIGNGUID_H
+
+#include "llvm/IR/GlobalVariable.h"
+#include "llvm/IR/LLVMContext.h"
+#include "llvm/IR/Module.h"
+#include "llvm/IR/PassManager.h"
+#include "llvm/Support/Debug.h"
+
+namespace llvm {
+
+class AssignGUIDPass : public PassInfoMixin<AssignGUIDPass> {
+public:
+  AssignGUIDPass() = default;
+
+  static void runOnModule(Module &M);
+
+  PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM) {
+    AssignGUIDPass::runOnModule(M);
+    return PreservedAnalyses::all();
+  }
+
+  static bool isRequired() { return true; }
+
+  // Let GlobalMerge assign a GUID for merged GVs, instead of needing to
+  // traverse all the module; or instead of making GlobalValue::assignGUID
+  // public.
+  static void assignGUIDForMergedGV(GlobalVariable &GV);
+};
+
+} // end namespace llvm
+
+#endif // LLVM_TRANSFORMS_UTILS_ASSIGNGUID_H
\ No newline at end of file
diff --git a/llvm/lib/Analysis/CtxProfAnalysis.cpp b/llvm/lib/Analysis/CtxProfAnalysis.cpp
index c4abec02e765a..9df6ab048d382 100644
--- a/llvm/lib/Analysis/CtxProfAnalysis.cpp
+++ b/llvm/lib/Analysis/CtxProfAnalysis.cpp
@@ -51,8 +51,6 @@ static cl::opt<bool> ForceIsInSpecializedModule(
     cl::desc("Treat the given module as-if it were containing the "
              "post-thinlink module containing the root"));
 
-const char *AssignGUIDPass::GUIDMetadataName = "guid";
-
 class ProfileAnnotatorImpl final {
   friend class ProfileAnnotator;
   class BBInfo;
@@ -420,33 +418,6 @@ bool ProfileAnnotator::getOutgoingBranchWeights(
   return MaxCount > 0;
 }
 
-PreservedAnalyses AssignGUIDPass::run(Module &M, ModuleAnalysisManager &MAM) {
-  for (auto &F : M.functions()) {
-    if (F.isDeclaration())
-      continue;
-    if (F.getMetadata(GUIDMetadataName))
-      continue;
-    const GlobalValue::GUID GUID = F.getGUID();
-    F.setMetadata(GUIDMetadataName,
-                  MDNode::get(M.getContext(),
-                              {ConstantAsMetadata::get(ConstantInt::get(
-                                  Type::getInt64Ty(M.getContext()), GUID))}));
-  }
-  return PreservedAnalyses::none();
-}
-
-GlobalValue::GUID AssignGUIDPass::getGUID(const Function &F) {
-  if (F.isDeclaration()) {
-    assert(GlobalValue::isExternalLinkage(F.getLinkage()));
-    return F.getGUID();
-  }
-  auto *MD = F.getMetadata(GUIDMetadataName);
-  assert(MD && "guid not found for defined function");
-  return cast<ConstantInt>(cast<ConstantAsMetadata>(MD->getOperand(0))
-                               ->getValue()
-                               ->stripPointerCasts())
-      ->getZExtValue();
-}
 AnalysisKey CtxProfAnalysis::Key;
 
 CtxProfAnalysis::CtxProfAnalysis(std::optional<StringRef> Profile)
@@ -515,7 +486,7 @@ PGOContextualProfile CtxProfAnalysis::run(Module &M,
   for (const auto &F : M) {
     if (F.isDeclaration())
       continue;
-    auto GUID = AssignGUIDPass::getGUID(F);
+    auto GUID = F.getGUID();
     assert(GUID && "guid not found for defined function");
     const auto &Entry = F.begin();
     uint32_t MaxCounters = 0; // we expect at least a counter.
@@ -549,13 +520,6 @@ PGOContextualProfile CtxProfAnalysis::run(Module &M,
   return Result;
 }
 
-GlobalValue::GUID
-PGOContextualProfile::getDefinedFunctionGUID(const Function &F) const {
-  if (auto It = FuncInfo.find(AssignGUIDPass::getGUID(F)); It != FuncInfo.end())
-    return It->first;
-  return 0;
-}
-
 CtxProfAnalysisPrinterPass::CtxProfAnalysisPrinterPass(raw_ostream &OS)
     : OS(OS), Mode(PrintLevel) {}
 
@@ -671,7 +635,7 @@ bool PGOContextualProfile::isInSpecializedModule() const {
 
 void PGOContextualProfile::update(Visitor V, const Function &F) {
   assert(isFunctionKnown(F));
-  GlobalValue::GUID G = getDefinedFunctionGUID(F);
+  GlobalValue::GUID G = F.getGUID();
   for (auto *Node = FuncInfo.find(G)->second.Index.Next; Node;
        Node = Node->Next)
     V(*reinterpret_cast<PGOCtxProfContext *>(Node));
@@ -682,7 +646,7 @@ void PGOContextualProfile::visit(ConstVisitor V, const Function *F) const {
     return preorderVisit<const PGOCtxProfContext::CallTargetMapTy,
                          const PGOCtxProfContext>(Profiles.Contexts, V);
   assert(isFunctionKnown(*F));
-  GlobalValue::GUID G = getDefinedFunctionGUID(*F);
+  GlobalValue::GUID G = F->getGUID();
   for (const auto *Node = FuncInfo.find(G)->second.Index.Next; Node;
        Node = Node->Next)
     V(*reinterpret_cast<const PGOCtxProfContext *>(Node));
diff --git a/llvm/lib/AsmParser/LLParser.cpp b/llvm/lib/AsmParser/LLParser.cpp
index 75e6add0ec76f..6582adee57b8a 100644
--- a/llvm/lib/AsmParser/LLParser.cpp
+++ b/llvm/lib/AsmParser/LLParser.cpp
@@ -9962,7 +9962,11 @@ bool LLParser::addGlobalValueToIndex(
       if (!GV)
         return error(Loc, "Reference to undefined global \"" + Name + "\"");
 
-      VI = Index->getOrInsertValueInfo(GV);
+      // Be a little lenient here, to accomodate older files without GUIDs
+      // already computed and assigned as metadata.
+      GUID = GV->getGUIDOrFallback();
+
+      VI = Index->getOrInsertValueInfo(GV, GUID);
     } else {
       assert(
           (!GlobalValue::isLocalLinkage(Linkage) || !SourceFileName.empty()) &&
diff --git a/llvm/lib/Bitcode/Reader/BitcodeAnalyzer.cpp b/llvm/lib/Bitcode/Reader/BitcodeAnalyzer.cpp
index 911ec7501eb8b..6574ab7a93c58 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeAnalyzer.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeAnalyzer.cpp
@@ -142,6 +142,7 @@ GetCodeName(unsigned CodeID, unsigned BlockID,
       STRINGIFY_CODE(MODULE_CODE, METADATA_VALUES_UNUSED)
       STRINGIFY_CODE(MODULE_CODE, SOURCE_FILENAME)
       STRINGIFY_CODE(MODULE_CODE, HASH)
+      STRINGIFY_CODE(MODULE_CODE, GUIDLIST)
     }
   case bitc::IDENTIFICATION_BLOCK_ID:
     switch (CodeID) {
diff --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index 35c417d8d26c2..ab2a62218cd85 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -697,6 +697,9 @@ class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
 
   std::optional<ValueTypeCallbackTy> ValueTypeCallback;
 
+  /// A list of GUIDs defined by this module. Indexed by ValueID.
+  std::vector<GlobalValue::GUID> GUIDList;
+
 public:
   BitcodeReader(BitstreamCursor Stream, StringRef Strtab,
                 StringRef ProducerIdentification, LLVMContext &Context);
@@ -975,9 +978,12 @@ class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
 
   /// Callback to ask whether a symbol is the prevailing copy when invoked
   /// during combined index building.
-  std::function<bool(GlobalValue::GUID)> IsPrevailing;
+  std::function<bool(StringRef)> IsPrevailing = nullptr;
+
+  /// Callback invoked whenever a new ValueInfo is generated.
+  std::function<void(ValueInfo)> OnValueInfo = nullptr;
 
-  /// Saves the stack ids from the STACK_IDS record to consult when adding stack
+  /// Saves the stack ids from the STACK_IDS record to consult when adding
   /// ids from the lists in the callsite and alloc entries to the index.
   std::vector<uint64_t> StackIds;
 
@@ -990,11 +996,15 @@ class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
   /// list and used to avoid repeated hash lookups.
   std::vector<unsigned> StackIdToIndex;
 
+  /// A list of GUIDs defined by this module. Indexed by ValueID.
+  std::vector<uint64_t> DefinedGUIDs;
+
 public:
   ModuleSummaryIndexBitcodeReader(
       BitstreamCursor Stream, StringRef Strtab, ModuleSummaryIndex &TheIndex,
       StringRef ModulePath,
-      std::function<bool(GlobalValue::GUID)> IsPrevailing = nullptr);
+      std::function<bool(StringRef)> IsPrevailing = nullptr,
+      std::function<void(ValueInfo)> OnValueInfo = nullptr);
 
   Error parseModule();
 
@@ -4038,6 +4048,15 @@ Error BitcodeReader::globalCleanup() {
     TheModule->insertGlobalVariable(Pair.second);
   }
 
+  for (size_t ValueID = 0; ValueID < GUIDList.size(); ValueID++) {
+    const auto GUID = GUIDList[ValueID];
+    if (GUID == 0)
+      continue;
+
+    const auto *Value = ValueList[ValueID];
+    TheModule->insertGUID(Value, GUID);
+  }
+
   // Force deallocation of memory for these vectors to favor the client that
   // want lazy deserialization.
   std::vector<std::pair<GlobalVariable *, unsigned>>().swap(GlobalInits);
@@ -4841,6 +4860,13 @@ Error BitcodeReader::parseModule(uint64_t ResumeBit,
       // historically always the start of the regular bitcode header.
       VSTOffset = Record[0] - 1;
       break;
+    // MODULE_CODE_GUIDLIST: [i64 x N]
+    case bitc::MODULE_CODE_GUIDLIST:
+      assert(Record.size() % 2 == 0);
+      GUIDList.reserve(GUIDList.size() + Record.size() / 2);
+      for (size_t i = 0; i < Record.size(); i += 2)
+        GUIDList.push_back(Record[i] << 32 | Record[i + 1]);
+      break;
     /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
     case bitc::MODULE_CODE_SOURCE_FILENAME:
       SmallString<128> ValueName;
@@ -4851,6 +4877,7 @@ Error BitcodeReader::parseModule(uint64_t ResumeBit,
     }
     Record.clear();
   }
+
   this->ValueTypeCallback = std::nullopt;
   return Error::success();
 }
@@ -7227,9 +7254,11 @@ std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
 
 ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
     BitstreamCursor Cursor, StringRef Strtab, ModuleSummaryIndex &TheIndex,
-    StringRef ModulePath, std::function<bool(GlobalValue::GUID)> IsPrevailing)
+    StringRef ModulePath, std::function<bool(StringRef)> IsPrevailing,
+    std::function<void(ValueInfo)> OnValueInfo)
     : BitcodeReaderBase(std::move(Cursor), Strtab), TheIndex(TheIndex),
-      ModulePath(ModulePath), IsPrevailing(IsPrevailing) {}
+      ModulePath(ModulePath), IsPrevailing(IsPrevailing),
+      OnValueInfo(OnValueInfo) {}
 
 void ModuleSummaryIndexBitcodeReader::addThisModule() {
   TheIndex.addModule(ModulePath);
@@ -7257,9 +7286,15 @@ ModuleSummaryIndexBitcodeReader::getValueInfoFromValueId(unsigned ValueId) {
 void ModuleSummaryIndexBitcodeReader::setValueGUID(
     uint64_t ValueID, StringRef ValueName, GlobalValue::LinkageTypes Linkage,
     StringRef SourceFileName) {
-  std::string GlobalId =
-      GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
-  auto ValueGUID = GlobalValue::getGUIDAssumingExternalLinkage(GlobalId);
+  GlobalValue::GUID ValueGUID = 0;
+  if (ValueID < DefinedGUIDs.size())
+    ValueGUID = DefinedGUIDs[ValueID];
+  if (ValueGUID == 0)
+    // DefinedGUIDs is a sparse array and can contain zero entries, so this
+    // can't just be an `else`.
+    ValueGUID = GlobalValue::getGUIDAssumingExternalLinkage(
+        GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName));
+
   auto OriginalNameID = ValueGUID;
   if (GlobalValue::isLocalLinkage(Linkage))
     OriginalNameID = GlobalValue::getGUIDAssumingExternalLinkage(ValueName);
@@ -7270,10 +7305,11 @@ void ModuleSummaryIndexBitcodeReader::setValueGUID(
   // UseStrtab is false for legacy summary formats and value names are
   // created on stack. In that case we save the name in a string saver in
   // the index so that the value name can be recorded.
-  ValueIdToValueInfoMap[ValueID] = std::make_pair(
-      TheIndex.getOrInsertValueInfo(
-          ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName)),
-      OriginalNameID);
+  auto VI = TheIndex.getOrInsertValueInfo(
+      ValueGUID, UseStrtab ? ValueName : TheIndex.saveString(ValueName));
+  ValueIdToValueInfoMap[ValueID] = std::make_pair(VI, OriginalNameID);
+  if (OnValueInfo)
+    OnValueInfo(VI);
 }
 
 // Specialized value symbol table parser used when reading module index
@@ -7482,6 +7518,13 @@ Error ModuleSummaryIndexBitcodeReader::parseModule() {
           // was historically always the start of the regular bitcode header.
           VSTOffset = Record[0] - 1;
           break;
+        // MODULE_CODE_GUIDLIST: [i64 x N]
+        case bitc::MODULE_CODE_GUIDLIST:
+          assert(Record.size() % 2 == 0);
+          DefinedGUIDs.reserve(DefinedGUIDs.size() + Record.size() / 2);
+          for (size_t i = 0; i < Record.size(); i += 2)
+            DefinedGUIDs.push_back(Record[i] << 32 | Record[i + 1]);
+          break;
         // v1 GLOBALVAR: [pointer type, isconst,     initid,       linkage, ...]
         // v1 FUNCTION:  [type,         callingconv, isproto,      linkage, ...]
         // v1 ALIAS:     [alias type,   addrspace,   aliasee val#, linkage, ...]
@@ -7878,7 +7921,7 @@ Error ModuleSummaryIndexBitcodeReader::parseEntireSummary(unsigned ID) {
       // and kept).
       auto LT = (GlobalValue::LinkageTypes)Flags.Linkage;
       bool IsPrevailingSym = !IsPrevailing || GlobalValue::isLocalLinkage(LT) ||
-                             IsPrevailing(VI.getGUID());
+                             IsPrevailing(VI.name());
 
       // If this is not the prevailing copy, and the records are in the "old"
       // order (preceding), clear them now. They should already be empty in
@@ -8718,15 +8761,16 @@ BitcodeModule::getLazyModule(LLVMContext &Context, bool ShouldLazyLoadMetadata,
 // We don't use ModuleIdentifier here because the client may need to control the
 // module path used in the combined summary (e.g. when reading summaries for
 // regular LTO modules).
-Error BitcodeModule::readSummary(
-    ModuleSummaryIndex &CombinedIndex, StringRef ModulePath,
-    std::function<bool(GlobalValue::GUID)> IsPrevailing) {
+Error BitcodeModule::readSummary(ModuleSummaryIndex &CombinedIndex,
+                                 StringRef ModulePath,
+                                 std::function<bool(StringRef)> IsPrevailing,
+                                 std::function<void(ValueInfo)> OnValueInfo) {
   BitstreamCursor Stream(Buffer);
   if (Error JumpFailed = Stream.JumpToBit(ModuleBit))
     return JumpFailed;
 
   ModuleSummaryIndexBitcodeReader R(std::move(Stream), Strtab, CombinedIndex,
-                                    ModulePath, IsPrevailing);
+                                    ModulePath, IsPrevailing, OnValueInfo);
   return R.parseModule();
 }
 
diff --git a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
index f4857461ca58e..15906a2e3cef6 100644
--- a/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
+++ b/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp
@@ -254,6 +254,7 @@ class ModuleBitcodeWriterBase : public BitcodeWriterBase {
 
 protected:
   void writePerModuleGlobalValueSummary();
+  void writeGUIDList();
 
 private:
   void writePerModuleFunctionSummaryRecord(
@@ -1647,6 +1648,8 @@ void ModuleBitcodeWriter::writeModuleInfo() {
     Vals.clear();
   }
 
+  writeGUIDList();
+
   // Emit the global variable information.
   for (const GlobalVariable &GV : M.globals()) {
     unsigned AbbrevToUse = 0;
@@ -4681,7 +4684,11 @@ void ModuleBitcodeWriterBase::writePerModuleFunctionSummaryRecord(
 void ModuleBitcodeWriterBase::writeModuleLevelReferences(
     const GlobalVariable &V, SmallVector<uint64_t, 64> &NameVals,
     unsigned FSModRefsAbbrev, unsigned FSModVTableRefsAbbrev) {
-  auto VI = Index->getValueInfo(V.getGUID());
+  // Be a little lenient here, to accomodate older files without GUIDs
+  // already computed and assigned as metadata.
+  GlobalValue::GUID GUID = V.getGUIDOrFallback();
+
+  auto VI = Index->getValueInfo(GUID);
   if (!VI || VI.getSummaryList().empty()) {
     // Only declarations should not have a summary (a declaration might however
     // have a summary if the def was in module level asm).
@@ -4894,7 +4901,11 @@ void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
     if (!F.hasName())
       report_fatal_error("Unexpected anonymous function when writing summary");
 
-    ValueInfo VI = Index->getValueInfo(F.getGUID());
+    // Be a little lenient here, to accomodate older files without GUIDs
+    // already computed and assigned as metadata.
+    GlobalValue::GUID GUID = F.getGUIDOrFallback();
+
+    ValueInfo VI = Index->getValueInfo(GUID);
     if (!VI || VI.getSummaryList().empty()) {
       // Only declarations should not have a summary (a declaration might
       // however have a summary if the def was in module level asm).
@@ -4926,7 +4937,9 @@ void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
     if (!F.hasName())
       report_fatal_error("Unexpected anonymous function when writing summary");
 
-    ValueInfo VI = Index->getValueInfo(F.getGUID());
+    GlobalValue::GUID GUID = F.getGUIDOrFallback();
+
+    ValueInfo VI = Index->getValueInfo(GUID);
     if (!VI || VI.getSummaryList().empty()) {
       // Only declarations should not have a summary (a declaration might
       // however have a summary if the def was in module level asm).
@@ -4978,6 +4991,37 @@ void ModuleBitcodeWriterBase::writePerModuleGlobalValueSummary() {
   Stream.ExitBlock();
 }
 
+void ModuleBitcodeWriterBase::writeGUIDList() {
+  const ValueEnumerator::ValueList &Vals = VE.getValues();
+  const size_t Max = Vals.size();
+
+  std::vector<GlobalValue::GUID> GUIDs(Max, 0);
+  for (const GlobalValue &GV : M.global_values()) {
+    auto MaybeGUID = GV.getGUIDIfAssigned();
+    if (!MaybeGUID)
+      continue;
+    auto GUID = *MaybeGUID;
+
+    const auto ValueID = VE.getValueID(&GV);
+    GUIDs[ValueID] = GUID;
+  }
+
+  auto Abbv = std::make_shared<BitCodeAbbrev>();
+  Abbv->Add(BitCodeAbbrevOp(bitc::MODULE_CODE_GUIDLIST));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
+  Abbv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
+  unsigned GUIDListAbbrev = Stream.EmitAbbrev(std::move(Abbv));
+
+  SmallVector<uint32_t> RecordVals;
+  RecordVals.reserve(Max * 2);
+  for (auto GUID : GUIDs) {
+    RecordVals.push_back(static_cast<uint32_t>(GUID >> 32));
+    RecordVals.push_back(static_cast<uint32_t>(GUID));
+  }
+
+  Stream.EmitRecord(bitc::MODULE_CODE_GUIDLIST, RecordVals, GUIDListAbbrev);
+}
+
 /// Emit the combined summary section into the combined index file.
 void IndexBitcodeWriter::writeCombinedGlobalValueSummary() {
   Stream.EnterSubblock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID, 4);
@@ -5772,6 +5816,8 @@ void ThinLinkBitcodeWriter::writeSimplifiedModuleInfo() {
     Vals.clear();
   }
 
+  writeGUIDList();
+
   // Emit the global variable information.
   for (const GlobalVariable &GV : M.globals()) {
     // GLOBALVAR: [strtab offset, strtab size, 0, 0, 0, linkage]
diff --git a/llvm/lib/CodeGen/GlobalMerge.cpp b/llvm/lib/CodeGen/GlobalMerge.cpp
index d52706b5f9bef..98e62605a9643 100644
--- a/llvm/lib/CodeGen/GlobalMerge.cpp
+++ b/llvm/lib/CodeGen/GlobalMerge.cpp
@@ -80,6 +80,7 @@
 #include "llvm/IR/GlobalVariable.h"
 #include "llvm/IR/Instruction.h"
 #include "llvm/IR/IntrinsicInst.h"
+#include "llvm/IR/LLVMContext.h"
 #include "llvm/IR/Module.h"
 #include "llvm/IR/Type.h"
 #include "llvm/IR/Use.h"
@@ -94,6 +95,7 @@
 #include "llvm/Target/TargetLoweringObjectFile.h"
 #include "llvm/Target/TargetMachine.h"
 #include "llvm/TargetParser/Triple.h"
+#include "llvm/Transforms/Utils/AssignGUID.h"
 #include <algorithm>
 #include <cassert>
 #include <cstddef>
@@ -605,6 +607,7 @@ bool GlobalMergeImpl::doMerge(const SmallVectorImpl<GlobalVariable *> &Globals,
 
       NumMerged++;
     }
+    AssignGUIDPass::assignGUIDForMergedGV(*MergedGV);
     Changed = true;
     i = j;
   }
@@ -726,14 +729,15 @@ bool GlobalMergeImpl::run(Module &M) {
     if (GV.isTagged())
       continue;
 
-    // Don't merge globals with metadata other than !dbg, as this is essentially
-    // equivalent to adding metadata to an existing global, which is not
-    // necessarily a correct transformation depending on the specific metadata's
-    // semantics. We will later use copyMetadata() to copy metadata from
-    // component globals to the combined global, which only knows how to do this
-    // correctly for !dbg (and !type, but by this point LowerTypeTests will have
-    // already run).
-    if (GV.hasMetadataOtherThanDebugLoc())
+    // Don't merge globals with metadata other than !dbg or !guid, as this is
+    // essentially equivalent to adding metadata to an existing global, which is
+    // not necessarily a correct transformation depending on the specific
+    // metadata's semantics. We will later use copyMetadata() to copy metadata
+    // from component globals to the combined global, which only knows how to do
+    // this correctly for !dbg (and !type, but by this point LowerTypeTests will
+    // have already run).
+    // Note that a new !guid will be created as part of doMerge
+    if (GV.hasMetadataOtherThanDebugLocAndGuid())
       continue;
 
     Type *Ty = GV.getValueType();
diff --git a/llvm/lib/IR/Globals.cpp b/llvm/lib/IR/Globals.cpp
index 805595a80a054..2ee580d5ec754 100644
--- a/llvm/lib/IR/Globals.cpp
+++ b/llvm/lib/IR/Globals.cpp
@@ -81,6 +81,61 @@ GlobalValue::getGUIDAssumingExternalLinkage(StringRef GlobalIdentifier) {
   return MD5Hash(GlobalIdentifier);
 }
 
+void GlobalValue::assignGUID() {
+  if (getGUIDMetadata() != nullptr)
+    return;
+
+  const GUID G =
+      GlobalValue::getGUIDAssumingExternalLinkage(getGlobalIdentifier());
+  setMetadata(
+      LLVMContext::MD_unique_id,
+      MDNode::get(getContext(), {ConstantAsMetadata::get(ConstantInt::get(
+                                    Type::getInt64Ty(getContext()), G))}));
+}
+
+GlobalValue::GUID GlobalValue::getGUID() const {
+  auto MaybeGUID = getGUIDIfAssigned();
+  assert(MaybeGUID.has_value() &&
+         "GUID was not assigned before calling GetGUID()");
+  return *MaybeGUID;
+}
+
+GlobalValue::GUID GlobalValue::getGUIDOrFallback() const {
+  if (auto MaybeGUID = getGUIDIfAssigned(); MaybeGUID)
+    return *MaybeGUID;
+  return getGUIDAssumingExternalLinkage(getGlobalIdentifier());
+}
+
+std::optional<GlobalValue::GUID> GlobalValue::getGUIDIfAssigned() const {
+  // First check the metadata.
+  auto *MD = getGUIDMetadata();
+  if (MD != nullptr)
+    return cast<ConstantInt>(cast<ConstantAsMetadata>(MD->getOperand(0))
+                                 ->getValue()
+                                 ->stripPointerCasts())
+        ->getZExtValue();
+
+  // Handle a few special cases where we just want to compute it based on the
+  // current properties.
+  // TODO: Maybe we should use a more robust check for intrinsics than just
+  // matching on the name?
+  if (isDeclaration() || isa<GlobalAlias>(this) ||
+      getName().starts_with("llvm.")) {
+    return GlobalValue::getGUIDAssumingExternalLinkage(getGlobalIdentifier());
+  }
+
+  // Otherwise we try to look it up in the module, for cases where we've read
+  // the GUID table but not the metadata. This happens when lazy-loading a
+  // module.
+  return getParent()->getGUID(this);
+}
+
+MDNode *GlobalValue::getGUIDMetadata() const {
+  if (auto *GO = dyn_cast<GlobalObject>(this))
+    return GO->getMetadata(LLVMContext::MD_unique_id);
+  return nullptr;
+}
+
 void GlobalValue::removeFromParent() {
   switch (getValueID()) {
 #define HANDLE_GLOBAL_VALUE(NAME)                                              \
@@ -397,11 +452,11 @@ bool GlobalObject::canIncreaseAlignment() const {
   return true;
 }
 
-bool GlobalObject::hasMetadataOtherThanDebugLoc() const {
+bool GlobalObject::hasMetadataOtherThanDebugLocAndGuid() const {
   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
   getAllMetadata(MDs);
   for (const auto &V : MDs)
-    if (V.first != LLVMContext::MD_dbg)
+    if (V.first != LLVMContext::MD_dbg && V.first != LLVMContext::MD_unique_id)
       return true;
   return false;
 }
diff --git a/llvm/lib/LTO/LTO.cpp b/llvm/lib/LTO/LTO.cpp
index 6a754f95092bb..3838d5443d577 100644
--- a/llvm/lib/LTO/LTO.cpp
+++ b/llvm/lib/LTO/LTO.cpp
@@ -27,6 +27,7 @@
 #include "llvm/Config/llvm-config.h"
 #include "llvm/IR/AutoUpgrade.h"
 #include "llvm/IR/DiagnosticPrinter.h"
+#include "llvm/IR/GlobalValue.h"
 #include "llvm/IR/Intrinsics.h"
 #include "llvm/IR/LLVMRemarkStreamer.h"
 #include "llvm/IR/LegacyPassManager.h"
@@ -758,6 +759,7 @@ void LTO::addModuleToGlobalRes(ArrayRef<InputFile::Symbol> Syms,
     // FIXME: instead of this check, it would be desirable to compute GUIDs
     // based on mangled name, but this requires an access to the Target Triple
     // and would be relatively invasive on the codebase.
+    // FIXME: use the GUID member of GlobalRes.
     if (GlobalRes.IRName != Sym.getIRName()) {
       GlobalRes.Partition = GlobalResolution::External;
       GlobalRes.VisibleOutsideSummary = true;
@@ -1136,17 +1138,20 @@ Error LTO::linkRegularLTO(RegularLTOState::AddedModule Mod,
   llvm::TimeTraceScope timeScope("LTO link regular LTO");
   std::vector<GlobalValue *> Keep;
   for (GlobalValue *GV : Mod.Keep) {
-    if (LivenessFromIndex && !ThinLTO.CombinedIndex.isGUIDLive(GV->getGUID())) {
-      if (Function *F = dyn_cast<Function>(GV)) {
-        if (DiagnosticOutputFile) {
-          if (Error Err = F->materialize())
-            return Err;
-          auto R = OptimizationRemark(DEBUG_TYPE, "deadfunction", F);
-          R << ore::NV("Function", F) << " not added to the combined module ";
-          emitRemark(R);
+    if (LivenessFromIndex) {
+      const auto GUID = GV->getGUIDOrFallback();
+      if (!ThinLTO.CombinedIndex.isGUIDLive(GUID)) {
+        if (Function *F = dyn_cast<Function>(GV)) {
+          if (DiagnosticOutputFile) {
+            if (Error Err = F->materialize())
+              return Err;
+            auto R = OptimizationRemark(DEBUG_TYPE, "deadfunction", F);
+            R << ore::NV("Function", F) << " not added to the combined module ";
+            emitRemark(R);
+          }
         }
+        continue;
       }
-      continue;
     }
 
     if (!GV->hasAvailableExternallyLinkage()) {
@@ -1175,21 +1180,28 @@ LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
   llvm::TimeTraceScope timeScope("LTO add thin LTO");
   const auto BMID = BM.getModuleIdentifier();
   ArrayRef<SymbolResolution> ResTmp = Res;
+  DenseSet<StringRef> Prevailing;
   for (const InputFile::Symbol &Sym : Syms) {
     assert(!ResTmp.empty());
     const SymbolResolution &R = ResTmp.consume_front();
-
-    if (!Sym.getIRName().empty() && R.Prevailing) {
-      auto GUID = GlobalValue::getGUIDAssumingExternalLinkage(
-          GlobalValue::getGlobalIdentifier(Sym.getIRName(),
-                                           GlobalValue::ExternalLinkage, ""));
-      ThinLTO.setPrevailingModuleForGUID(GUID, BMID);
-    }
+    if (!Sym.getIRName().empty() && R.Prevailing)
+      Prevailing.insert(Sym.getIRName());
   }
 
+  // Track the GUIDs stored in the bitcode GUID table.
+  StringMap<GlobalValue::GUID> IRSpecifiedGUIDs;
   if (Error Err = BM.readSummary(
-          ThinLTO.CombinedIndex, BMID, [&](GlobalValue::GUID GUID) {
-            return ThinLTO.isPrevailingModuleForGUID(GUID, BMID);
+          ThinLTO.CombinedIndex, BMID,
+          [&](StringRef Name) { return (Prevailing.count(Name) > 0); },
+          [&](ValueInfo VI) {
+            auto IT = IRSpecifiedGUIDs.insert({VI.name(), VI.getGUID()});
+            (void)IT;
+            assert(IT.second);
+            if (auto GRIt = GlobalResolutions->find(VI.name());
+                GRIt != GlobalResolutions->end() &&
+                Prevailing.count(VI.name())) {
+              GRIt->second.setGUID(VI.getGUID());
+            }
           }))
     return Err;
   LLVM_DEBUG(dbgs() << "Module " << BMID << "\n");
@@ -1197,28 +1209,33 @@ LTO::addThinLTO(BitcodeModule BM, ArrayRef<InputFile::Symbol> Syms,
   for (const InputFile::Symbol &Sym : Syms) {
     assert(!Res.empty());
     const SymbolResolution &R = Res.consume_front();
-
+    auto GUIDIter = IRSpecifiedGUIDs.find(Sym.getIRName());
+    // The bitcode GUID table might not be present if this is an old bitcode
+    // file. For backwards-compatibility, just compute the GUID now in that
+    // case.
+    auto GUID =
+        GUIDIter == IRSpecifiedGUIDs.end()
+            ? GlobalValue::getGUIDAssumingExternalLinkage(
+                  GlobalValue::getGlobalIdentifier(
+                      Sym.getIRName(), GlobalValue::ExternalLinkage, ""))
+            : GUIDIter->second;
     if (!Sym.getIRName().empty() &&
         (R.Prevailing || R.FinalDefinitionInLinkageUnit)) {
-      auto GUID = GlobalValue::getGUIDAssumingExternalLinkage(
-          GlobalValue::getGlobalIdentifier(Sym.getIRName(),
-                                           GlobalValue::ExternalLinkage, ""));
       if (R.Prevailing) {
-        assert(ThinLTO.isPrevailingModuleForGUID(GUID, BMID));
-
+        ThinLTO.setPrevailingModuleForGUID(GUID, BMID);
         // For linker redefined symbols (via --wrap or --defsym) we want to
         // switch the linkage to `weak` to prevent IPOs from happening.
         // Find the summary in the module for this very GV and record the new
         // linkage so that we can switch it when we import the GV.
         if (R.LinkerRedefined)
-          if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID))
+          if (auto *S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID))
             S->setLinkage(GlobalValue::WeakAnyLinkage);
       }
 
       // If the linker resolved the symbol to a local definition then mark it
       // as local in the summary for the module we are adding.
       if (R.FinalDefinitionInLinkageUnit) {
-        if (auto S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID)) {
+        if (auto *S = ThinLTO.CombinedIndex.findSummaryInModule(GUID, BMID)) {
           S->setDSOLocal(true);
         }
       }
@@ -1312,8 +1329,7 @@ Error LTO::run(AddStreamFn AddStream, FileCache Cache) {
     if (Res.second.IRName.empty())
       continue;
 
-    GlobalValue::GUID GUID = GlobalValue::getGUIDAssumingExternalLinkage(
-        GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
+    GlobalValue::GUID GUID = Res.second.getGUID();
 
     if (Res.second.VisibleOutsideSummary && Res.second.Prevailing)
       GUIDPreservedSymbols.insert(GUID);
@@ -2162,8 +2178,7 @@ Error LTO::runThinLTO(AddStreamFn AddStream, FileCache Cache,
     if (Res.second.Partition != GlobalResolution::External ||
         !Res.second.isPrevailingIRSymbol())
       continue;
-    auto GUID = GlobalValue::getGUIDAssumingExternalLinkage(
-        GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
+    auto GUID = Res.second.getGUID();
     // Mark exported unless index-based analysis determined it to be dead.
     if (ThinLTO.CombinedIndex.isGUIDLive(GUID))
       ExportedGUIDs.insert(GUID);
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index 16a42e526eb8a..73697a9d0d446 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -625,12 +625,18 @@ static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
                             const ModuleSummaryIndex &Index) {
   llvm::TimeTraceScope timeScope("Drop dead symbols");
   std::vector<GlobalValue*> DeadGVs;
-  for (auto &GV : Mod.global_values())
-    if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
+
+  for (auto &GV : Mod.global_values()) {
+    auto GUID = GV.getGUIDIfAssigned();
+    if (!GUID)
+      continue;
+
+    if (GlobalValueSummary *GVS = DefinedGlobals.lookup(*GUID))
       if (!Index.isGlobalValueLive(GVS)) {
         DeadGVs.push_back(&GV);
         convertToDeclaration(GV);
       }
+  }
 
   // Now that all dead bodies have been dropped, delete the actual objects
   // themselves when possible.
diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp
index f7db63ef8bf74..9498b3d2bbd0c 100644
--- a/llvm/lib/Passes/PassBuilder.cpp
+++ b/llvm/lib/Passes/PassBuilder.cpp
@@ -353,6 +353,7 @@
 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
 #include "llvm/Transforms/Utils/AddDiscriminators.h"
+#include "llvm/Transforms/Utils/AssignGUID.h"
 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
diff --git a/llvm/lib/Passes/PassBuilderPipelines.cpp b/llvm/lib/Passes/PassBuilderPipelines.cpp
index 9eea552fd263e..d0cf63028e303 100644
--- a/llvm/lib/Passes/PassBuilderPipelines.cpp
+++ b/llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -138,6 +138,7 @@
 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
 #include "llvm/Transforms/Utils/AddDiscriminators.h"
+#include "llvm/Transforms/Utils/AssignGUID.h"
 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
 #include "llvm/Transforms/Utils/CanonicalizeAliases.h"
 #include "llvm/Transforms/Utils/CountVisits.h"
@@ -837,6 +838,7 @@ PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
 void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) {
   MPM.addPass(CanonicalizeAliasesPass());
   MPM.addPass(NameAnonGlobalPass());
+  MPM.addPass(AssignGUIDPass());
 }
 
 void PassBuilder::addPreInlinerPasses(ModulePassManager &MPM,
@@ -1094,6 +1096,7 @@ PassBuilder::buildModuleInlinerPipeline(OptimizationLevel Level,
   if (!UseCtxProfile.empty() && Phase == ThinOrFullLTOPhase::ThinLTOPostLink) {
     MPM.addPass(GlobalOptPass());
     MPM.addPass(GlobalDCEPass());
+    MPM.addPass(AssignGUIDPass());
     MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/false));
   }
 
@@ -1279,10 +1282,8 @@ PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
     // In pre-link, we just want the instrumented IR. We use the contextual
     // profile in the post-thinlink phase.
     // The instrumentation will be removed in post-thinlink after IPO.
-    // FIXME(mtrofin): move AssignGUIDPass if there is agreement to use this
-    // mechanism for GUIDs.
-    MPM.addPass(AssignGUIDPass());
     if (IsCtxProfUse) {
+      MPM.addPass(AssignGUIDPass());
       MPM.addPass(PGOCtxProfFlatteningPass(/*IsPreThinlink=*/true));
       return MPM;
     }
@@ -1294,6 +1295,7 @@ PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
     // unnecessary to collect profiles for non-prevailing copies.
     MPM.addPass(NoinlineNonPrevailing());
     addPostPGOLoopRotation(MPM, Level);
+    MPM.addPass(AssignGUIDPass());
     MPM.addPass(PGOCtxProfLoweringPass());
   } else if (IsColdFuncOnlyInstrGen) {
     addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, /* IsCS */ false,
@@ -1728,6 +1730,8 @@ PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
   if (PTO.DevirtualizeSpeculatively && LTOPhase == ThinOrFullLTOPhase::None) {
     // TODO: explore a better pipeline configuration that can improve
     // compilation time overhead.
+    // FIXME: move this earlier (lots of pass ordering tests will need fixing)
+    MPM.addPass(AssignGUIDPass());
     MPM.addPass(WholeProgramDevirtPass(
         /*ExportSummary*/ nullptr,
         /*ImportSummary*/ nullptr,
diff --git a/llvm/lib/Transforms/IPO/ConstantMerge.cpp b/llvm/lib/Transforms/IPO/ConstantMerge.cpp
index 06e684dbe5a93..480f4c5f68f79 100644
--- a/llvm/lib/Transforms/IPO/ConstantMerge.cpp
+++ b/llvm/lib/Transforms/IPO/ConstantMerge.cpp
@@ -98,9 +98,9 @@ enum class CanMerge { No, Yes };
 static CanMerge makeMergeable(GlobalVariable *Old, GlobalVariable *New) {
   if (!Old->hasGlobalUnnamedAddr() && !New->hasGlobalUnnamedAddr())
     return CanMerge::No;
-  if (Old->hasMetadataOtherThanDebugLoc())
+  if (Old->hasMetadataOtherThanDebugLocAndGuid())
     return CanMerge::No;
-  assert(!New->hasMetadataOtherThanDebugLoc());
+  assert(!New->hasMetadataOtherThanDebugLocAndGuid());
 
   // Merging constants with different comdats means one group cannot in general
   // be dropped independently without the other group now having an invalid
@@ -175,8 +175,8 @@ static bool mergeConstants(Module &M) {
       if (GV.isWeakForLinker())
         continue;
 
-      // Don't touch globals with metadata other then !dbg.
-      if (GV.hasMetadataOtherThanDebugLoc())
+      // Don't touch globals with metadata other than !dbg or !guid.
+      if (GV.hasMetadataOtherThanDebugLocAndGuid())
         continue;
 
       Constant *Init = GV.getInitializer();
diff --git a/llvm/lib/Transforms/IPO/FunctionImport.cpp b/llvm/lib/Transforms/IPO/FunctionImport.cpp
index d305eadc12f35..04da71822906e 100644
--- a/llvm/lib/Transforms/IPO/FunctionImport.cpp
+++ b/llvm/lib/Transforms/IPO/FunctionImport.cpp
@@ -12,6 +12,7 @@
 
 #include "llvm/Transforms/IPO/FunctionImport.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
 #include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SetVector.h"
 #include "llvm/ADT/SmallVector.h"
@@ -1666,14 +1667,22 @@ void llvm::processImportsFiles(
 bool llvm::convertToDeclaration(GlobalValue &GV) {
   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
                     << "\n");
+  MDNode *UniqueID = nullptr;
+  if (auto *GO = dyn_cast<GlobalObject>(&GV))
+    UniqueID = GO->getMetadata(LLVMContext::MD_unique_id);
+
   if (Function *F = dyn_cast<Function>(&GV)) {
     F->deleteBody();
     F->clearMetadata();
+    if (UniqueID)
+      F->setMetadata(LLVMContext::MD_unique_id, UniqueID);
     F->setComdat(nullptr);
   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
     V->setInitializer(nullptr);
     V->setLinkage(GlobalValue::ExternalLinkage);
     V->clearMetadata();
+    if (UniqueID)
+      V->setMetadata(LLVMContext::MD_unique_id, UniqueID);
     V->setComdat(nullptr);
   } else {
     GlobalValue *NewGV;
@@ -1705,7 +1714,7 @@ void llvm::thinLTOFinalizeInModule(Module &TheModule,
   DenseSet<Comdat *> NonPrevailingComdats;
   auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
     // See if the global summary analysis computed a new resolved linkage.
-    const auto &GS = DefinedGlobals.find(GV.getGUID());
+    const auto &GS = DefinedGlobals.find(GV.getGUIDOrFallback());
     if (GS == DefinedGlobals.end())
       return;
 
@@ -1842,7 +1851,7 @@ void llvm::thinLTOInternalizeModule(Module &TheModule,
       return true;
 
     // Lookup the linkage recorded in the summaries during global analysis.
-    auto GS = DefinedGlobals.find(GV.getGUID());
+    auto GS = DefinedGlobals.find(GV.getGUIDOrFallback());
     if (GS == DefinedGlobals.end()) {
       // Must have been promoted (possibly conservatively). Find original
       // name so that we can access the correct summary and see if it can
@@ -1917,7 +1926,7 @@ Expected<bool> FunctionImporter::importFunctions(
   DenseSet<GlobalValue::GUID> MoveSymbolGUIDSet;
   MoveSymbolGUIDSet.insert_range(MoveSymbolGUID);
   for (auto &F : DestModule)
-    if (!F.isDeclaration() && MoveSymbolGUIDSet.contains(F.getGUID()))
+    if (!F.isDeclaration() && MoveSymbolGUIDSet.contains(F.getGUIDOrFallback()))
       F.deleteBody();
 
   IRMover Mover(DestModule);
@@ -1945,7 +1954,7 @@ Expected<bool> FunctionImporter::importFunctions(
       for (Function &F : *SrcModule) {
         if (!F.hasName())
           continue;
-        auto GUID = F.getGUID();
+        auto GUID = F.getGUIDOrFallback();
         auto MaybeImportType = ImportList.getImportType(ModName, GUID);
         bool ImportDefinition =
             MaybeImportType == GlobalValueSummary::Definition;
@@ -1985,7 +1994,7 @@ Expected<bool> FunctionImporter::importFunctions(
       for (GlobalVariable &GV : SrcModule->globals()) {
         if (!GV.hasName())
           continue;
-        auto GUID = GV.getGUID();
+        auto GUID = GV.getGUIDOrFallback();
         auto MaybeImportType = ImportList.getImportType(ModName, GUID);
         bool ImportDefinition =
             MaybeImportType == GlobalValueSummary::Definition;
@@ -2009,7 +2018,7 @@ Expected<bool> FunctionImporter::importFunctions(
       for (GlobalAlias &GA : SrcModule->aliases()) {
         if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
           continue;
-        auto GUID = GA.getGUID();
+        auto GUID = GA.getGUIDOrFallback();
         auto MaybeImportType = ImportList.getImportType(ModName, GUID);
         bool ImportDefinition =
             MaybeImportType == GlobalValueSummary::Definition;
@@ -2029,9 +2038,12 @@ Expected<bool> FunctionImporter::importFunctions(
           if (Error Err = GO->materialize())
             return std::move(Err);
           auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
-          LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << GO->getGUID()
-                            << " " << GO->getName() << " from "
-                            << SrcModule->getSourceFileName() << "\n");
+          assert(Fn);
+          (void)Fn;
+          LLVM_DEBUG(dbgs()
+                     << "Is importing aliasee fn " << GO->getGUIDOrFallback()
+                     << " " << GO->getName() << " from "
+                     << SrcModule->getSourceFileName() << "\n");
           if (EnableImportMetadata || EnableMemProfContextDisambiguation) {
             // Add 'thinlto_src_module' and 'thinlto_src_file' metadata for
             // statistics and debugging.
diff --git a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
index a519f78f2a1a7..6e12cbefcd583 100644
--- a/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
+++ b/llvm/lib/Transforms/IPO/LowerTypeTests.cpp
@@ -1788,9 +1788,7 @@ void LowerTypeTestsModule::buildBitSetsFromFunctionsNative(
     }
 
     if (IsExported) {
-      // TODO: use F->getGUID() once #184065 is relanded.
-      GlobalValue::GUID GUID = GlobalValue::getGUIDAssumingExternalLinkage(
-          GlobalValue::dropLLVMManglingEscape(F->getName()));
+      GlobalValue::GUID GUID = F->getGUID();
       if (IsJumpTableCanonical)
         ExportSummary->cfiFunctionDefs().addSymbolWithThinLTOGUID(F->getName(),
                                                                   GUID);
@@ -2255,22 +2253,28 @@ bool LowerTypeTestsModule::lower() {
           F = nullptr;
         }
 
-        if (!F)
+        if (!F) {
           F = Function::Create(
               FunctionType::get(Type::getVoidTy(M.getContext()), false),
               GlobalVariable::ExternalLinkage,
               M.getDataLayout().getProgramAddressSpace(), FunctionName, &M);
-
+          F->setMetadata(
+              LLVMContext::MD_unique_id,
+              MDTuple::get(M.getContext(), {FuncMD->getOperand(2).get()}));
+        }
         // If the function is available_externally, remove its definition so
         // that it is handled the same way as a declaration. Later we will try
         // to create an alias using this function's linkage, which will fail if
         // the linkage is available_externally. This will also result in us
         // following the code path below to replace the type metadata.
         if (F->hasAvailableExternallyLinkage()) {
+          // Maintain !guid metadata.
+          auto *OrigGUIDMD = F->getMetadata(LLVMContext::MD_unique_id);
           F->setLinkage(GlobalValue::ExternalLinkage);
           F->deleteBody();
           F->setComdat(nullptr);
           F->clearMetadata();
+          F->setMetadata(LLVMContext::MD_unique_id, OrigGUIDMD);
         }
 
         // Update the linkage for extern_weak declarations when a definition
diff --git a/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp b/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
index c14c9b869525d..de05c82d1bd10 100644
--- a/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
+++ b/llvm/lib/Transforms/IPO/ThinLTOBitcodeWriter.cpp
@@ -198,6 +198,8 @@ void simplifyExternals(Module &M) {
                                            AttributeList::FunctionIndex,
                                            F.getAttributes().getFnAttrs()));
     NewF->takeName(&F);
+    NewF->setMetadata(LLVMContext::MD_unique_id,
+                      F.getMetadata(LLVMContext::MD_unique_id));
     F.replaceAllUsesWith(NewF);
     F.eraseFromParent();
   }
@@ -436,9 +438,7 @@ void splitAndWriteThinLTOBitcode(
       Linkage = CFL_Declaration;
     Elts.push_back(ConstantAsMetadata::get(
         llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
-    // TODO: use F->getGUID() once #184065 is relanded.
-    GlobalValue::GUID GUID = GlobalValue::getGUIDAssumingExternalLinkage(
-        GlobalValue::dropLLVMManglingEscape(V->getName()));
+    GlobalValue::GUID GUID = V->getGUID();
     Elts.push_back(ConstantAsMetadata::get(
         llvm::ConstantInt::get(Type::getInt64Ty(Ctx), GUID)));
     append_range(Elts, Types);
diff --git a/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp b/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp
index 8d477b7bdeeba..e4b9e13ca1f1c 100644
--- a/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp
+++ b/llvm/lib/Transforms/IPO/WholeProgramDevirt.cpp
@@ -878,6 +878,7 @@ void llvm::updateVCallVisibilityInModule(
     function_ref<bool(StringRef)> IsVisibleToRegularObj) {
   if (!hasWholeProgramVisibility(WholeProgramVisibilityEnabledInLTO))
     return;
+
   for (GlobalVariable &GV : M.globals()) {
     // Add linkage unit visibility to any variable with type metadata, which are
     // the vtable definitions. We won't have an existing vcall_visibility
diff --git a/llvm/lib/Transforms/Instrumentation/PGOCtxProfFlattening.cpp b/llvm/lib/Transforms/Instrumentation/PGOCtxProfFlattening.cpp
index 32ae14b45764b..42609f29df625 100644
--- a/llvm/lib/Transforms/Instrumentation/PGOCtxProfFlattening.cpp
+++ b/llvm/lib/Transforms/Instrumentation/PGOCtxProfFlattening.cpp
@@ -126,7 +126,7 @@ void annotateIndirectCalls(Module &M, const CtxProfAnalysis::Result &CtxProf) {
   for (auto &F : M) {
     if (F.isDeclaration())
       continue;
-    auto FlatProfIter = FlatIndCalls.find(AssignGUIDPass::getGUID(F));
+    auto FlatProfIter = FlatIndCalls.find(F.getGUID());
     if (FlatProfIter == FlatIndCalls.end())
       continue;
     const auto &FlatProf = FlatProfIter->second;
@@ -179,7 +179,7 @@ PreservedAnalyses PGOCtxProfFlatteningPass::run(Module &M,
            "Function has unreachable basic blocks. The expectation was that "
            "DCE was run before.");
 
-    auto It = FlattenedProfile.find(AssignGUIDPass::getGUID(F));
+    auto It = FlattenedProfile.find(F.getGUID());
     // If this function didn't appear in the contextual profile, it's cold.
     if (It == FlattenedProfile.end())
       clearColdFunctionProfile(F);
diff --git a/llvm/lib/Transforms/Instrumentation/PGOCtxProfLowering.cpp b/llvm/lib/Transforms/Instrumentation/PGOCtxProfLowering.cpp
index de7c1696078db..6a9d10ef5cca0 100644
--- a/llvm/lib/Transforms/Instrumentation/PGOCtxProfLowering.cpp
+++ b/llvm/lib/Transforms/Instrumentation/PGOCtxProfLowering.cpp
@@ -280,8 +280,7 @@ bool CtxInstrumentationLowerer::lowerFunction(Function &F) {
       assert(Mark->getIndex()->isZero());
 
       IRBuilder<> Builder(Mark);
-      Guid = Builder.getInt64(
-          AssignGUIDPass::getGUID(cast<Function>(*Mark->getNameValue())));
+      Guid = Builder.getInt64(cast<Function>(*Mark->getNameValue()).getGUID());
       // The type of the context of this function is now knowable since we have
       // NumCallsites and NumCounters. We declare it here because it's more
       // convenient - we have the Builder.
diff --git a/llvm/lib/Transforms/Scalar/JumpTableToSwitch.cpp b/llvm/lib/Transforms/Scalar/JumpTableToSwitch.cpp
index d5696bc9ea956..12001218801c8 100644
--- a/llvm/lib/Transforms/Scalar/JumpTableToSwitch.cpp
+++ b/llvm/lib/Transforms/Scalar/JumpTableToSwitch.cpp
@@ -12,7 +12,6 @@
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Analysis/ConstantFolding.h"
-#include "llvm/Analysis/CtxProfAnalysis.h"
 #include "llvm/Analysis/DomTreeUpdater.h"
 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
 #include "llvm/Analysis/PostDominators.h"
@@ -215,9 +214,9 @@ PreservedAnalyses JumpTableToSwitchPass::run(Function &F,
   PostDominatorTree *PDT = AM.getCachedResult<PostDominatorTreeAnalysis>(F);
   DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
   bool Changed = false;
-  auto FuncToGuid = [InLTO = this->InLTO](const Function &Fct) {
-    if (Fct.getMetadata(AssignGUIDPass::GUIDMetadataName))
-      return AssignGUIDPass::getGUID(Fct);
+  auto FuncToGuid = [&](const Function &Fct) {
+    if (const auto MaybeGUID = Fct.getGUIDIfAssigned(); MaybeGUID)
+      return *MaybeGUID;
 
     return Function::getGUIDAssumingExternalLinkage(
         getIRPGOFuncName(Fct, InLTO));
diff --git a/llvm/lib/Transforms/Utils/AssignGUID.cpp b/llvm/lib/Transforms/Utils/AssignGUID.cpp
new file mode 100644
index 0000000000000..b05504ad7181a
--- /dev/null
+++ b/llvm/lib/Transforms/Utils/AssignGUID.cpp
@@ -0,0 +1,41 @@
+//===-- AssignGUID.cpp - Unique identifier assignment pass ------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// This file provides a pass which assigns GUID (globally unique identifier)
+// metadata to every GlobalValue in the module, according to its current name,
+// linkage, and originating file. It is idempotent -- if GUID metadata is
+// already present, it does nothing.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Transforms/Utils/AssignGUID.h"
+#include "llvm/Support/Debug.h"
+
+using namespace llvm;
+
+void AssignGUIDPass::runOnModule(Module &M) {
+  for (auto &GV : M.globals()) {
+    if (GV.isDeclaration())
+      continue;
+    GV.assignGUID();
+  }
+  for (auto &F : M.functions()) {
+    if (F.isDeclaration())
+      continue;
+    F.assignGUID();
+  }
+}
+
+void AssignGUIDPass::assignGUIDForMergedGV(GlobalVariable &GV) {
+  // FIXME: merging adds all the guids of the original GVs. We currently drop
+  // that metadata from GV first, but we may want to remember those later, if
+  // we had a motivation for that. In that case, we need some other metadata
+  // to maintain that association.
+  GV.eraseMetadata(LLVMContext::MD_unique_id);
+  GV.assignGUID();
+}
diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt b/llvm/lib/Transforms/Utils/CMakeLists.txt
index 6afd752794484..1c8647eef5d0c 100644
--- a/llvm/lib/Transforms/Utils/CMakeLists.txt
+++ b/llvm/lib/Transforms/Utils/CMakeLists.txt
@@ -2,6 +2,7 @@ add_llvm_component_library(LLVMTransformUtils
   AddDiscriminators.cpp
   AMDGPUEmitPrintf.cpp
   ASanStackFrameLayout.cpp
+  AssignGUID.cpp
   AssumeBundleBuilder.cpp
   BasicBlockUtils.cpp
   BreakCriticalEdges.cpp
diff --git a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
index 1bfeea3b711f9..9656d99f6d473 100644
--- a/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
+++ b/llvm/lib/Transforms/Utils/CallPromotionUtils.cpp
@@ -637,11 +637,11 @@ CallBase *llvm::promoteCallWithIfThenElse(CallBase &CB, Function &Callee,
   IndirectBBIns->setIndex(IndirectID);
   IndirectBBIns->insertInto(&IndirectBB, IndirectBB.getFirstInsertionPt());
 
-  const GlobalValue::GUID CalleeGUID = AssignGUIDPass::getGUID(Callee);
+  const GlobalValue::GUID CalleeGUID = Callee.getGUID();
   const uint32_t NewCountersSize = IndirectID + 1;
 
   auto ProfileUpdater = [&](PGOCtxProfContext &Ctx) {
-    assert(Ctx.guid() == AssignGUIDPass::getGUID(Caller));
+    assert(Ctx.guid() == Caller.getGUID());
     assert(NewCountersSize - 2 == Ctx.counters().size());
     // All the ctx-es belonging to a function must have the same size counters.
     Ctx.resizeCounters(NewCountersSize);
@@ -676,7 +676,6 @@ CallBase *llvm::promoteCallWithIfThenElse(CallBase &CB, Function &Callee,
     // times, and the indirect BB, IndirectCount times
     Ctx.counters()[DirectID] = DirectCount;
     Ctx.counters()[IndirectID] = IndirectCount;
-
   };
   CtxProf.update(ProfileUpdater, Caller);
   return &DirectCall;
diff --git a/llvm/lib/Transforms/Utils/CloneModule.cpp b/llvm/lib/Transforms/Utils/CloneModule.cpp
index 457bb08b76a6c..5e442347d41c6 100644
--- a/llvm/lib/Transforms/Utils/CloneModule.cpp
+++ b/llvm/lib/Transforms/Utils/CloneModule.cpp
@@ -141,17 +141,21 @@ std::unique_ptr<Module> llvm::CloneModule(
   for (const Function &I : M) {
     Function *F = cast<Function>(VMap[&I]);
 
-    if (I.isDeclaration()) {
+    auto CopyMD = [&]() {
       // Copy over metadata for declarations since we're not doing it below in
       // CloneFunctionInto().
       SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
       I.getAllMetadata(MDs);
       for (auto MD : MDs)
         F->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
+    };
+    if (I.isDeclaration()) {
+      CopyMD();
       continue;
     }
 
     if (!ShouldCloneDefinition(&I)) {
+      CopyMD();
       // Skip after setting the correct linkage for an external reference.
       F->setLinkage(GlobalValue::ExternalLinkage);
       // Personality function is not valid on a declaration.
diff --git a/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp b/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp
index d641b33c50133..4f71239cda786 100644
--- a/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp
+++ b/llvm/lib/Transforms/Utils/FunctionImportUtils.cpp
@@ -185,7 +185,7 @@ FunctionImportGlobalProcessing::getLinkage(const GlobalValue *SGV,
     // and/or optimization, but are turned into declarations later
     // during the EliminateAvailableExternally pass.
     if (doImportAsDefinition(SGV) && !isa<GlobalAlias>(SGV))
-      return SymbolsToMove.contains(SGV->getGUID())
+      return SymbolsToMove.contains(SGV->getGUIDOrFallback())
                  ? GlobalValue::ExternalLinkage
                  : GlobalValue::AvailableExternallyLinkage;
     // An imported external declaration stays external.
@@ -261,7 +261,7 @@ void FunctionImportGlobalProcessing::processGlobalForThinLTO(GlobalValue &GV) {
 
   ValueInfo VI;
   if (GV.hasName())
-    VI = ImportIndex.getValueInfo(GV.getGUID());
+    VI = ImportIndex.getValueInfo(GV.getGUIDOrFallback());
 
   // We should always have a ValueInfo (i.e. GV in index) for definitions when
   // we are exporting, and also when importing that value.
diff --git a/llvm/lib/Transforms/Utils/InlineFunction.cpp b/llvm/lib/Transforms/Utils/InlineFunction.cpp
index 1d3f66509b1c5..60dd1cd7929a3 100644
--- a/llvm/lib/Transforms/Utils/InlineFunction.cpp
+++ b/llvm/lib/Transforms/Utils/InlineFunction.cpp
@@ -2491,7 +2491,7 @@ llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
   // Get some preliminary data about the callsite before it might get inlined.
   // Inlining shouldn't delete the callee, but it's cleaner (and low-cost) to
   // get this data upfront and rely less on InlineFunction's behavior.
-  const auto CalleeGUID = AssignGUIDPass::getGUID(Callee);
+  const auto CalleeGUID = Callee.getGUID();
   auto *CallsiteIDIns = CtxProfAnalysis::getCallsiteInstrumentation(CB);
   const auto CallsiteID =
       static_cast<uint32_t>(CallsiteIDIns->getIndex()->getZExtValue());
@@ -2516,7 +2516,7 @@ llvm::InlineFunction(CallBase &CB, InlineFunctionInfo &IFI,
   const uint32_t NewCountersSize = CtxProf.getNumCounters(Caller);
 
   auto Updater = [&](PGOCtxProfContext &Ctx) {
-    assert(Ctx.guid() == AssignGUIDPass::getGUID(Caller));
+    assert(Ctx.guid() == Caller.getGUID());
     const auto &[CalleeCounterMap, CalleeCallsiteMap] = IndicesMaps;
     assert(
         (Ctx.counters().size() +
diff --git a/llvm/test/Assembler/index-value-order.ll b/llvm/test/Assembler/index-value-order.ll
index 9df6d4a46fef2..15ace18647de6 100644
--- a/llvm/test/Assembler/index-value-order.ll
+++ b/llvm/test/Assembler/index-value-order.ll
@@ -11,13 +11,16 @@ target triple = "x86_64-unknown-linux-gnu"
 
 $_ZTSN3FooE = comdat any
 
- at _ZTSN3FooE = linkonce_odr constant [7 x i8] c"N3FooE\00", comdat, align 1
-@"_ZTVN3FooE" = internal unnamed_addr constant { [2 x ptr] } { [2 x ptr] [ptr null, ptr @"_Z3barv"] }, align 8
+ at _ZTSN3FooE = linkonce_odr constant [7 x i8] c"N3FooE\00", comdat, align 1, !guid !0
+@"_ZTVN3FooE" = internal unnamed_addr constant { [2 x ptr] } { [2 x ptr] [ptr null, ptr @"_Z3barv"] }, align 8, !guid !1
 
-define internal i32 @"_Z3barv"() {
+define internal i32 @"_Z3barv"() !guid !2 {
   ret i32 0
 }
 
+!0 = !{i64 0}
+!1 = !{i64 1}
+!2 = !{i64 2}
 ^0 = module: (path: "index-value-order.ll", hash: (0, 0, 0, 0, 0))
 ^9 = gv: (name: "_ZTVN3FooE", summaries: (variable: (module: ^0, flags: (linkage: internal, visibility: default, notEligibleToImport: 0, live: 0, dsoLocal: 1, canAutoHide: 0), varFlags: (readonly: 1, writeonly: 0, constant: 1, vcall_visibility: 0), vTableFuncs: ((virtFunc: ^3, offset: 16)))))
 ^4 = gv: (name: "_ZTSN3FooE", summaries: (variable: (module: ^0, flags: (linkage: linkonce_odr, visibility: default, notEligibleToImport: 0, live: 0, dsoLocal: 0, canAutoHide: 0), varFlags: (readonly: 0, writeonly: 0, constant: 1))))
diff --git a/llvm/test/Bitcode/thinlto-alias.ll b/llvm/test/Bitcode/thinlto-alias.ll
index 4191983055b2c..e6213f61ca8ed 100644
--- a/llvm/test/Bitcode/thinlto-alias.ll
+++ b/llvm/test/Bitcode/thinlto-alias.ll
@@ -13,6 +13,7 @@
 
 ; CHECK: <SOURCE_FILENAME
 ; "main"
+; CHECK-NEXT: <GUIDLIST
 ; CHECK-NEXT: <FUNCTION op0=0 op1=4
 ; "analias"
 ; CHECK-NEXT: <FUNCTION op0=4 op1=7
diff --git a/llvm/test/Bitcode/thinlto-function-summary-callgraph-partial-sample-profile-summary.ll b/llvm/test/Bitcode/thinlto-function-summary-callgraph-partial-sample-profile-summary.ll
index 0c3ab9b208931..cf7190800ed35 100644
--- a/llvm/test/Bitcode/thinlto-function-summary-callgraph-partial-sample-profile-summary.ll
+++ b/llvm/test/Bitcode/thinlto-function-summary-callgraph-partial-sample-profile-summary.ll
@@ -8,6 +8,7 @@
 
 ; CHECK: <SOURCE_FILENAME
 ; "hot_function"
+; CHECK-NEXT: <GUIDLIST
 ; CHECK-NEXT: <FUNCTION op0=0 op1=12
 ; "hot1"
 ; CHECK-NEXT: <FUNCTION op0=12 op1=4
@@ -30,9 +31,9 @@
 ; CHECK-LABEL:       <GLOBALVAL_SUMMARY_BLOCK
 ; CHECK-NEXT:    <VERSION
 ; CHECK-NEXT:    <FLAGS
-; CHECK-NEXT:    <VALUE_GUID {{.*}} op0=27 op1=0 op2=123/>
+; CHECK-NEXT:    <VALUE_GUID {{.*}} op0=28 op1=0 op2=123/>
 ; op4=none1 op6=hot1 op8=cold1 op10=none2 op12=hot2 op14=cold2 op16=none3 op18=hot3 op20=cold3 op22=123
-; CHECK-NEXT:    <PERMODULE_PROFILE {{.*}} op7=7 op8=0 op9=1 op10=3 op11=4 op12=1 op13=8 op14=0 op15=2 op16=3 op17=5 op18=1 op19=9 op20=0 op21=3 op22=3 op23=6 op24=1 op25=27 op26=4/>
+; CHECK-NEXT:    <PERMODULE_PROFILE {{.*}} op7=7 op8=0 op9=1 op10=3 op11=4 op12=1 op13=8 op14=0 op15=2 op16=3 op17=5 op18=1 op19=9 op20=0 op21=3 op22=3 op23=6 op24=1 op25=28 op26=4/>
 ; CHECK-NEXT:    <BLOCK_COUNT op0=4/>
 ; CHECK-NEXT:  </GLOBALVAL_SUMMARY_BLOCK>
 
diff --git a/llvm/test/Bitcode/thinlto-function-summary-callgraph-pgo.ll b/llvm/test/Bitcode/thinlto-function-summary-callgraph-pgo.ll
index ed3c716288d6f..7f5f5ca39c544 100644
--- a/llvm/test/Bitcode/thinlto-function-summary-callgraph-pgo.ll
+++ b/llvm/test/Bitcode/thinlto-function-summary-callgraph-pgo.ll
@@ -11,6 +11,7 @@
 ; RUN: llvm-lto -thinlto-index-stats %p/Inputs/thinlto-function-summary-callgraph-pgo-combined.1.bc  | FileCheck %s --check-prefix=OLD-COMBINED
 
 ; CHECK: <SOURCE_FILENAME
+; CHECK-NEXT: <GUIDLIST
 ; CHECK-NEXT: <FUNCTION
 ; "func"
 ; CHECK-NEXT: <FUNCTION op0=4 op1=4
diff --git a/llvm/test/Bitcode/thinlto-function-summary-callgraph-profile-summary.ll b/llvm/test/Bitcode/thinlto-function-summary-callgraph-profile-summary.ll
index 33288be2d2195..81e204412e909 100644
--- a/llvm/test/Bitcode/thinlto-function-summary-callgraph-profile-summary.ll
+++ b/llvm/test/Bitcode/thinlto-function-summary-callgraph-profile-summary.ll
@@ -27,6 +27,7 @@
 
 ; CHECK: <SOURCE_FILENAME
 ; "hot_function"
+; CHECK-NEXT: <GUIDLIST
 ; CHECK-NEXT: <FUNCTION op0=0 op1=12
 ; "hot1"
 ; CHECK-NEXT: <FUNCTION op0=12 op1=4
@@ -47,9 +48,9 @@
 ; CHECK-LABEL:       <GLOBALVAL_SUMMARY_BLOCK
 ; CHECK-NEXT:    <VERSION
 ; CHECK-NEXT:    <FLAGS
-; CHECK-NEXT:    <VALUE_GUID {{.*}} op0=25 op1=0 op2=123/>
+; CHECK-NEXT:    <VALUE_GUID {{.*}} op0=26 op1=0 op2=123/>
 ; op4=hot1 op6=cold op8=hot2 op10=hot4 op12=none1 op14=hot3 op16=none2 op18=none3 op20=123
-; CHECK-NEXT:    <PERMODULE_PROFILE {{.*}} op7=1 op8=3 op9=5 op10=1 op11=2 op12=3 op13=4 op14=1 op15=6 op16=2 op17=3 op18=3 op19=7 op20=2 op21=8 op22=2 op23=25 op24=4/>
+; CHECK-NEXT:    <PERMODULE_PROFILE {{.*}} op7=1 op8=3 op9=5 op10=1 op11=2 op12=3 op13=4 op14=1 op15=6 op16=2 op17=3 op18=3 op19=7 op20=2 op21=8 op22=2 op23=26 op24=4/>
 ; CHECK-NEXT:  </GLOBALVAL_SUMMARY_BLOCK>
 
 ; CHECK: <STRTAB_BLOCK
diff --git a/llvm/test/Bitcode/thinlto-function-summary-callgraph-sample-profile-summary.ll b/llvm/test/Bitcode/thinlto-function-summary-callgraph-sample-profile-summary.ll
index 2e9b362d39bb4..2f336499440e2 100644
--- a/llvm/test/Bitcode/thinlto-function-summary-callgraph-sample-profile-summary.ll
+++ b/llvm/test/Bitcode/thinlto-function-summary-callgraph-sample-profile-summary.ll
@@ -8,6 +8,7 @@
 
 ; CHECK: <SOURCE_FILENAME
 ; "hot_function"
+; CHECK-NEXT: <GUIDLIST
 ; CHECK-NEXT: <FUNCTION op0=0 op1=12
 ; "hot1"
 ; CHECK-NEXT: <FUNCTION op0=12 op1=4
@@ -30,9 +31,9 @@
 ; CHECK-LABEL:       <GLOBALVAL_SUMMARY_BLOCK
 ; CHECK-NEXT:    <VERSION
 ; CHECK-NEXT:    <FLAGS
-; CHECK-NEXT:    <VALUE_GUID {{.*}} op0=26 op1=0 op2=123/>
+; CHECK-NEXT:    <VALUE_GUID {{.*}} op0=27 op1=0 op2=123/>
 ; op4=none1 op6=hot1 op8=cold1 op10=none2 op12=hot2 op14=cold2 op16=none3 op18=hot3 op20=cold3 op22=123
-; CHECK-NEXT:    <PERMODULE_PROFILE {{.*}} op7=7 op8=0 op9=1 op10=3 op11=4 op12=1 op13=8 op14=0 op15=2 op16=3 op17=5 op18=1 op19=9 op20=0 op21=3 op22=3 op23=6 op24=1 op25=26 op26=4/>
+; CHECK-NEXT:    <PERMODULE_PROFILE {{.*}} op7=7 op8=0 op9=1 op10=3 op11=4 op12=1 op13=8 op14=0 op15=2 op16=3 op17=5 op18=1 op19=9 op20=0 op21=3 op22=3 op23=6 op24=1 op25=27 op26=4/>
 ; CHECK-NEXT:  </GLOBALVAL_SUMMARY_BLOCK>
 
 ; CHECK: <STRTAB_BLOCK
diff --git a/llvm/test/Bitcode/thinlto-function-summary-callgraph.ll b/llvm/test/Bitcode/thinlto-function-summary-callgraph.ll
index becbc4a32dd92..60d04cbc07ca9 100644
--- a/llvm/test/Bitcode/thinlto-function-summary-callgraph.ll
+++ b/llvm/test/Bitcode/thinlto-function-summary-callgraph.ll
@@ -11,6 +11,7 @@
 ; RUN: llvm-lto -thinlto-index-stats %p/Inputs/thinlto-function-summary-callgraph-combined.1.bc  | FileCheck %s --check-prefix=OLD-COMBINED
 
 ; CHECK: <SOURCE_FILENAME
+; CHECK-NEXT: <GUIDLIST
 ; CHECK-NEXT: <GLOBALVAR
 ; CHECK-NEXT: <FUNCTION
 ; "func"
diff --git a/llvm/test/Bitcode/thinlto-function-summary-refgraph.ll b/llvm/test/Bitcode/thinlto-function-summary-refgraph.ll
index a25901a572d30..b8f66676b2ac5 100644
--- a/llvm/test/Bitcode/thinlto-function-summary-refgraph.ll
+++ b/llvm/test/Bitcode/thinlto-function-summary-refgraph.ll
@@ -7,6 +7,7 @@
 
 ; CHECK: <SOURCE_FILENAME
 ; "bar"
+; CHECK-NEXT: <GUIDLIST
 ; CHECK-NEXT: <GLOBALVAR {{.*}} op0=0 op1=3
 ; "globalvar"
 ; CHECK-NEXT: <GLOBALVAR {{.*}} op0=3 op1=9
diff --git a/llvm/test/Bitcode/thinlto-function-summary.ll b/llvm/test/Bitcode/thinlto-function-summary.ll
index 13c6611843d65..dd42471729c2a 100644
--- a/llvm/test/Bitcode/thinlto-function-summary.ll
+++ b/llvm/test/Bitcode/thinlto-function-summary.ll
@@ -3,6 +3,7 @@
 
 ; BC: <SOURCE_FILENAME
 ; "h"
+; BC-NEXT: <GUIDLIST
 ; BC-NEXT: <GLOBALVAR {{.*}} op0=0 op1=1
 ; "foo"
 ; BC-NEXT: <FUNCTION op0=1 op1=3
diff --git a/llvm/test/CodeGen/X86/fat-lto-section.ll b/llvm/test/CodeGen/X86/fat-lto-section.ll
index f3ca8436affb4..ea47e88a5e10b 100644
--- a/llvm/test/CodeGen/X86/fat-lto-section.ll
+++ b/llvm/test/CodeGen/X86/fat-lto-section.ll
@@ -1,5 +1,5 @@
 ;; Ensure that the .llvm.lto section has SHT_EXCLUDE set.
-; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="embed-bitcode<thinlto;emit-summary>" -S \
+; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="assign-guid,embed-bitcode<thinlto;emit-summary>" -S \
 ; RUN:   | llc --mtriple x86_64-unknown-linux-gnu -filetype=obj \
 ; RUN:   | llvm-readelf - --sections \
 ; RUN:   | FileCheck %s --check-prefix=EXCLUDE
diff --git a/llvm/test/LTO/Resolution/X86/not-prevailing-alias.ll b/llvm/test/LTO/Resolution/X86/not-prevailing-alias.ll
index e7c135c2edf93..fc22ca7a6d2c3 100644
--- a/llvm/test/LTO/Resolution/X86/not-prevailing-alias.ll
+++ b/llvm/test/LTO/Resolution/X86/not-prevailing-alias.ll
@@ -7,7 +7,7 @@
 
 ; Check that bar and barAlias were dropped to declarations
 ; RUN: llvm-dis %t2.o.1.1.promote.bc -o - | FileCheck %s --check-prefix=DROP
-; DROP-DAG: declare void @bar()
+; DROP-DAG: declare !guid !{{[0-9]+}} void @bar()
 ; DROP-DAG: declare void @barAlias()
 ; DROP-DAG: @var = external global i32
 ; DROP-DAG: @varAlias = external global i32
diff --git a/llvm/test/LTO/Resolution/X86/not-prevailing-weak-aliasee.ll b/llvm/test/LTO/Resolution/X86/not-prevailing-weak-aliasee.ll
index 7636ea882067d..e13dfaf90f8db 100644
--- a/llvm/test/LTO/Resolution/X86/not-prevailing-weak-aliasee.ll
+++ b/llvm/test/LTO/Resolution/X86/not-prevailing-weak-aliasee.ll
@@ -12,7 +12,7 @@
 ; not live and will also be dropped.
 ; RUN: llvm-dis %t2.o.1.1.promote.bc -o - | FileCheck %s
 ; CHECK: define weak hidden void @__a
-; CHECK: declare hidden void @__b
+; CHECK: declare !guid !{{[0-9]+}} hidden void @__b
 ; CHECK: declare void @b
 
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
diff --git a/llvm/test/Linker/funcimport2.ll b/llvm/test/Linker/funcimport2.ll
index bf8f96b78da01..c1eb7374c47e9 100644
--- a/llvm/test/Linker/funcimport2.ll
+++ b/llvm/test/Linker/funcimport2.ll
@@ -3,7 +3,7 @@
 ; RUN: llvm-lto -thinlto -o %t3 %t1.bc %t2.bc
 ; RUN: llvm-link -import=bar:%t2.bc %t1.bc -summary-index=%t3.thinlto.bc -S | FileCheck %s
 
-; CHECK: define available_externally hidden void @foo() {
+; CHECK: define available_externally hidden void @foo()
 define available_externally hidden void @foo() {
     ret void
 }
diff --git a/llvm/test/Other/new-pm-O0-defaults.ll b/llvm/test/Other/new-pm-O0-defaults.ll
index bac4150caab58..d26149b729cc3 100644
--- a/llvm/test/Other/new-pm-O0-defaults.ll
+++ b/llvm/test/Other/new-pm-O0-defaults.ll
@@ -44,6 +44,7 @@
 ; CHECK-ALLOCTOKEN-NEXT: Running pass: AllocTokenPass
 ; CHECK-PRE-LINK: Running pass: CanonicalizeAliasesPass
 ; CHECK-PRE-LINK-NEXT: Running pass: NameAnonGlobalPass
+; CHECK-PRE-LINK-NEXT: Running pass: AssignGUIDPass
 ; CHECK-THINLTO: Running pass: DropTypeTestsPass
 ; CHECK-THINLTO-NEXT: Running pass: CoroConditionalWrapper
 ; CHECK-THINLTO-NEXT: Running pass: AllocTokenPass
@@ -64,7 +65,7 @@
 ; CHECK-NEXT: Running pass: PrintModulePass
 
 ; Make sure we get the IR back out without changes when we print the module.
-; CHECK-LABEL: define void @foo(i32 %n) local_unnamed_addr {
+; CHECK-LABEL: define void @foo(i32 %n) local_unnamed_addr
 ; CHECK-NEXT: entry:
 ; CHECK-NEXT:   br label %loop
 ; CHECK:      loop:
diff --git a/llvm/test/Other/new-pm-defaults.ll b/llvm/test/Other/new-pm-defaults.ll
index d6e51f451c3a4..914c61110148c 100644
--- a/llvm/test/Other/new-pm-defaults.ll
+++ b/llvm/test/Other/new-pm-defaults.ll
@@ -286,10 +286,11 @@
 ; CHECK-O-NEXT: Running pass: AnnotationRemarksPass on foo
 ; CHECK-LTO-NEXT: Running pass: CanonicalizeAliasesPass
 ; CHECK-LTO-NEXT: Running pass: NameAnonGlobalPass
+; CHECK-LTO-NEXT: Running pass: AssignGUIDPass
 ; CHECK-O-NEXT: Running pass: PrintModulePass
 ;
 ; Make sure we get the IR back out without changes when we print the module.
-; CHECK-O-LABEL: define void @foo(i32 %n) local_unnamed_addr {
+; CHECK-O-LABEL: define void @foo(i32 %n) local_unnamed_addr
 ; CHECK-O-NEXT: entry:
 ; CHECK-O-NEXT:   br label %loop
 ; CHECK-O:      loop:
diff --git a/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll b/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll
index f4245b66b0429..19aec9df79fdd 100644
--- a/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-prelink-defaults.ll
@@ -184,10 +184,11 @@
 ; CHECK-O-NEXT:          Running pass: AnnotationRemarksPass on foo
 ; CHECK-O-NEXT: Running pass: CanonicalizeAliasesPass
 ; CHECK-O-NEXT: Running pass: NameAnonGlobalPass
+; CHECK-O-NEXT: Running pass: AssignGUIDPass
 ; CHECK-O-NEXT: Running pass: PrintModulePass
 
 ; Make sure we get the IR back out without changes when we print the module.
-; CHECK-O-LABEL: define void @foo(i32 %n) local_unnamed_addr {
+; CHECK-O-LABEL: define void @foo(i32 %n) local_unnamed_addr
 ; CHECK-O-NEXT: entry:
 ; CHECK-O-NEXT:   br label %loop
 ; CHECK-O:      loop:
diff --git a/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll b/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
index 87acb355fddc7..4023fbeb49f4c 100644
--- a/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-prelink-pgo-defaults.ll
@@ -187,10 +187,11 @@
 ; CHECK-O-NEXT: Running pass: AnnotationRemarksPass on foo
 ; CHECK-O-NEXT: Running pass: CanonicalizeAliasesPass
 ; CHECK-O-NEXT: Running pass: NameAnonGlobalPass
+; CHECK-O-NEXT: Running pass: AssignGUIDPass
 ; CHECK-O-NEXT: Running pass: PrintModulePass
 
 ; Make sure we get the IR back out without changes when we print the module.
-; CHECK-O-LABEL: define void @foo(i32 %n) local_unnamed_addr {
+; CHECK-O-LABEL: define void @foo(i32 %n) local_unnamed_addr
 ; CHECK-O-NEXT: entry:
 ; CHECK-O-NEXT:   br label %loop
 ; CHECK-O:      loop:
diff --git a/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll b/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
index e5c1453d692eb..0d6f500332902 100644
--- a/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
+++ b/llvm/test/Other/new-pm-thinlto-prelink-samplepgo-defaults.ll
@@ -150,6 +150,7 @@
 ; CHECK-O-NEXT: Running pass: AnnotationRemarksPass on foo
 ; CHECK-O-NEXT: Running pass: CanonicalizeAliasesPass
 ; CHECK-O-NEXT: Running pass: NameAnonGlobalPass
+; CHECK-O-NEXT: Running pass: AssignGUIDPass
 ; CHECK-O-NEXT: Running pass: PrintModulePass
 
 ; Make sure we get the IR back out without changes when we print the module.
diff --git a/llvm/test/ThinLTO/AArch64/aarch64_inline.ll b/llvm/test/ThinLTO/AArch64/aarch64_inline.ll
index 401f66d48c224..edc8505f74716 100644
--- a/llvm/test/ThinLTO/AArch64/aarch64_inline.ll
+++ b/llvm/test/ThinLTO/AArch64/aarch64_inline.ll
@@ -15,7 +15,7 @@
 ; RUN:   -r=%t/main.o,main,plx 2>&1
 ; RUN: llvm-dis %t/t.exe.1.4.opt.bc -o - | FileCheck %s
 
-; CHECK:      define dso_local noundef i32 @main() local_unnamed_addr #0 {
+; CHECK:      define dso_local noundef i32 @main() local_unnamed_addr #0 !guid {{.*}} {
 ; CHECK-NEXT: entry:
 ; CHECK-NEXT:  ret i32 35
 ; CHECK-NEXT: }
diff --git a/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions1.ll b/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions1.ll
index 679b6b3c682b3..2b07c687f8b62 100644
--- a/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions1.ll
+++ b/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions1.ll
@@ -1,6 +1,7 @@
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
 
- at vt1 = constant i32 0, !type !0
+ at vt1 = constant i32 0, !type !0, !guid !1
 
 !0 = !{i32 0, !"typeid1"}
+!1 = !{i64 -5901252123237135102}
diff --git a/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions2.ll b/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions2.ll
index 046983f783cf2..87bd342e96ae5 100644
--- a/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions2.ll
+++ b/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions2.ll
@@ -1,10 +1,12 @@
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
 
- at vt2 = constant ptr @vf2, !type !0
+ at vt2 = constant ptr @vf2, !type !0, !guid !1
 
-define internal i1 @vf2(ptr %this) {
+define internal i1 @vf2(ptr %this) !guid !2 {
   ret i1 0
 }
 
 !0 = !{i32 0, !"typeid2"}
+!1 = !{i64 -4967734856153660966}
+!2 = !{i64 7373133247406063798}
diff --git a/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions3.ll b/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions3.ll
index 8c9a41ecf8f34..f26eedcc25f76 100644
--- a/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions3.ll
+++ b/llvm/test/ThinLTO/X86/Inputs/cache-typeid-resolutions3.ll
@@ -1,15 +1,19 @@
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
 
- at vt2a = constant ptr @vf2a, !type !0
- at vt2b = constant ptr @vf2b, !type !0
+ at vt2a = constant ptr @vf2a, !type !0, !guid !1
+ at vt2b = constant ptr @vf2b, !type !0, !guid !2
 
-define internal i1 @vf2a(ptr %this) {
+define internal i1 @vf2a(ptr %this) !guid !3 {
   ret i1 0
 }
 
-define internal i1 @vf2b(ptr %this) {
+define internal i1 @vf2b(ptr %this) !guid !4 {
   ret i1 1
 }
 
 !0 = !{i32 0, !"typeid2"}
+!1 = !{i64 327052092150035973}
+!2 = !{i64 -3123971987909853701}
+!3 = !{i64 520420412982578150}
+!4 = !{i64 6199549476356213762}
diff --git a/llvm/test/ThinLTO/X86/ctor-dtor-alias.ll b/llvm/test/ThinLTO/X86/ctor-dtor-alias.ll
index f87fc16c933e1..d4b935eafab72 100644
--- a/llvm/test/ThinLTO/X86/ctor-dtor-alias.ll
+++ b/llvm/test/ThinLTO/X86/ctor-dtor-alias.ll
@@ -17,8 +17,8 @@
 ; CHECK: @D1_a = weak_odr dso_local unnamed_addr alias void (ptr), ptr @_ZN1AD1Ev
 ; CHECK: @_ZN1AD1Ev = weak_odr dso_local unnamed_addr alias void (ptr), ptr @_ZN1AD2Ev
 ; CHECK: @D1_a_a = weak_odr dso_local unnamed_addr alias void (ptr), ptr @D1_a
-; CHECK: define weak_odr dso_local void @_ZN1AD2Ev(ptr noundef nonnull %0) unnamed_addr comdat($_ZN1AD5Ev) {
-; CHECK: define available_externally dso_local void @_ZN1AD0Ev(ptr noundef nonnull %0) unnamed_addr {
+; CHECK: define weak_odr dso_local void @_ZN1AD2Ev(ptr noundef nonnull %0) unnamed_addr comdat($_ZN1AD5Ev)
+; CHECK: define available_externally dso_local void @_ZN1AD0Ev(ptr noundef nonnull %0) unnamed_addr
 
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
diff --git a/llvm/test/ThinLTO/X86/ctor-dtor-alias2.ll b/llvm/test/ThinLTO/X86/ctor-dtor-alias2.ll
index 7e79c26e3fb7c..adec2e586f427 100644
--- a/llvm/test/ThinLTO/X86/ctor-dtor-alias2.ll
+++ b/llvm/test/ThinLTO/X86/ctor-dtor-alias2.ll
@@ -26,8 +26,8 @@
 ;; Although D0/D2 in b.bc is non-prevailing, keep D1/D2 as definitions, otherwise
 ;; the output may have an undefined and unsatisfied D1.
 ; CHECK: @_ZN1AIiED1Ev = weak_odr unnamed_addr alias void (ptr), ptr @_ZN1AIiED2Ev
-; CHECK: define weak_odr void @_ZN1AIiED2Ev(ptr noundef nonnull %this) unnamed_addr comdat($_ZN1AIiED5Ev) {
-; CHECK: define available_externally void @_ZN1AIiED0Ev(ptr noundef nonnull %this) unnamed_addr {
+; CHECK: define weak_odr void @_ZN1AIiED2Ev(ptr noundef nonnull %this) unnamed_addr comdat($_ZN1AIiED5Ev)
+; CHECK: define available_externally void @_ZN1AIiED0Ev(ptr noundef nonnull %this) unnamed_addr
 
 ;--- a.ll
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
diff --git a/llvm/test/ThinLTO/X86/deadstrip.ll b/llvm/test/ThinLTO/X86/deadstrip.ll
index 2a3e15f87097e..4a4ef5d818ab7 100644
--- a/llvm/test/ThinLTO/X86/deadstrip.ll
+++ b/llvm/test/ThinLTO/X86/deadstrip.ll
@@ -60,14 +60,14 @@
 ; CHECK-NOT: available_externally {{.*}} @baz()
 ; CHECK: @llvm.global_ctors =
 ; CHECK: define internal void @_GLOBAL__I_a()
-; CHECK: define internal void @bar() {
+; CHECK: define internal void @bar()
 ; CHECK: define internal void @bar_internal()
-; CHECK: define internal void @dead_func() {
+; CHECK: define internal void @dead_func()
 ; CHECK-NOT: available_externally {{.*}} @baz()
 ; LTO2-NOT: available_externally {{.*}} @baz()
 ; LTO2: @llvm.global_ctors =
 ; LTO2: define internal void @_GLOBAL__I_a()
-; LTO2: define internal void @bar() [[ATTR:#[0-9]+]] {
+; LTO2: define internal void @bar() [[ATTR:#[0-9]+]]
 ; LTO2: define internal void @bar_internal()
 ; LTO2-NOT: @dead_func()
 ; LTO2-NOT: available_externally {{.*}} @baz()
@@ -79,7 +79,7 @@
 
 ; Make sure we keep @linkonceodrfuncwithalias in Input/deadstrip.ll alive as it
 ; is reachable from @main.
-; LTO2-CHECK2: define weak_odr dso_local void @linkonceodrfuncwithalias() [[ATTR:#[0-9]+]] {
+; LTO2-CHECK2: define weak_odr dso_local void @linkonceodrfuncwithalias() [[ATTR:#[0-9]+]]
 
 ; We should have eventually removed @baz since it was internalized and unused
 ; CHECK2-NM-NOT: _baz
diff --git a/llvm/test/ThinLTO/X86/devirt_function_alias.ll b/llvm/test/ThinLTO/X86/devirt_function_alias.ll
index 6b88d84a6819d..919fc59a30c3d 100644
--- a/llvm/test/ThinLTO/X86/devirt_function_alias.ll
+++ b/llvm/test/ThinLTO/X86/devirt_function_alias.ll
@@ -6,7 +6,7 @@
 ;; Test pure ThinLTO
 
 ;; Generate unsplit module with summary for ThinLTO index-based WPD.
-; RUN: opt -thinlto-bc -o %t1.o %s
+; RUN: opt -passes=assign-guid -thinlto-bc -o %t1.o %s
 
 ;; Check that we have properly recorded the alias in the vtable summary.
 ; RUN: llvm-dis -o - %t1.o | FileCheck %s --check-prefix SUMMARY
@@ -29,7 +29,7 @@
 ;; Test hybrid Thin/Regular LTO
 
 ;; Generate split module with summary for hybrid Thin/Regular LTO WPD.
-; RUN: opt -thinlto-bc -thinlto-split-lto-unit -o %t3.o %s
+; RUN: opt -passes=assign-guid -thinlto-bc -thinlto-split-lto-unit -o %t3.o %s
 
 ; RUN: llvm-lto2 run %t3.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
@@ -49,7 +49,7 @@
 
 ;; Test Regular LTO
 
-; RUN: opt -o %t5.o %s
+; RUN: opt -passes=assign-guid -o %t5.o %s
 ; RUN: llvm-lto2 run %t5.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t6 \
diff --git a/llvm/test/ThinLTO/X86/devirt_function_alias2.ll b/llvm/test/ThinLTO/X86/devirt_function_alias2.ll
index 491cdfd616a22..3b3208e300aa8 100644
--- a/llvm/test/ThinLTO/X86/devirt_function_alias2.ll
+++ b/llvm/test/ThinLTO/X86/devirt_function_alias2.ll
@@ -6,7 +6,7 @@
 ;; Test pure ThinLTO
 
 ;; Generate unsplit module with summary for ThinLTO index-based WPD.
-; RUN: opt -thinlto-bc -o %t1.o %s
+; RUN: opt -passes=assign-guid -thinlto-bc -o %t1.o %s
 
 ;; Check that we have properly recorded the alias in the vtable summary.
 ; RUN: llvm-dis -o - %t1.o | FileCheck %s --check-prefix SUMMARY
@@ -30,7 +30,7 @@
 ;; Test hybrid Thin/Regular LTO
 
 ;; Generate split module with summary for hybrid Thin/Regular LTO WPD.
-; RUN: opt -thinlto-bc -thinlto-split-lto-unit -o %t3.o %s
+; RUN: opt -passes=assign-guid -thinlto-bc -thinlto-split-lto-unit -o %t3.o %s
 
 ; RUN: llvm-lto2 run %t3.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
@@ -45,7 +45,7 @@
 ; RUN: llvm-dis %t4.1.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR1
 
 ;; Test Regular LTO
-; RUN: opt -o %t5.o %s
+; RUN: opt -passes=assign-guid -o %t5.o %s
 ; RUN: llvm-lto2 run %t5.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t6 \
diff --git a/llvm/test/ThinLTO/X86/devirt_pure_virtual_base.ll b/llvm/test/ThinLTO/X86/devirt_pure_virtual_base.ll
index ea69eedb6e353..caaf0d6b6a2c0 100644
--- a/llvm/test/ThinLTO/X86/devirt_pure_virtual_base.ll
+++ b/llvm/test/ThinLTO/X86/devirt_pure_virtual_base.ll
@@ -2,7 +2,7 @@
 
 ;; Index based WPD
 ;; Generate unsplit module with summary for ThinLTO index-based WPD.
-; RUN: opt --thinlto-bc -o %t1a.o %s
+; RUN: opt -passes=assign-guid --thinlto-bc -o %t1a.o %s
 ; RUN: llvm-lto2 run %t1a.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t3a \
@@ -18,7 +18,7 @@
 
 ;; Hybrid WPD
 ;; Generate split module with summary for hybrid Thin/Regular LTO WPD.
-; RUN: opt --thinlto-bc --thinlto-split-lto-unit -o %t1b.o %s
+; RUN: opt -passes=assign-guid --thinlto-bc --thinlto-split-lto-unit -o %t1b.o %s
 ; RUN: llvm-lto2 run %t1b.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t3b \
@@ -38,7 +38,7 @@
 ; RUN: llvm-dis %t3b.1.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t1c.o %s
+; RUN: opt -passes=assign-guid -o %t1c.o %s
 ; RUN: llvm-lto2 run %t1c.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t3c \
diff --git a/llvm/test/ThinLTO/X86/devirt_vcall_vis_public.ll b/llvm/test/ThinLTO/X86/devirt_vcall_vis_public.ll
index dfb2f8f033d65..6c4ba6376ba11 100644
--- a/llvm/test/ThinLTO/X86/devirt_vcall_vis_public.ll
+++ b/llvm/test/ThinLTO/X86/devirt_vcall_vis_public.ll
@@ -5,7 +5,7 @@
 
 ; Index based WPD
 ; Generate unsplit module with summary for ThinLTO index-based WPD.
-; RUN: opt -thinlto-bc -o %t2.o %s
+; RUN: opt -passes=assign-guid -thinlto-bc -o %t2.o %s
 ; RUN: llvm-lto2 run %t2.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t3 \
@@ -23,7 +23,7 @@
 
 ; Hybrid WPD
 ; Generate split module with summary for hybrid Thin/Regular LTO WPD.
-; RUN: opt -thinlto-bc -thinlto-split-lto-unit -o %t.o %s
+; RUN: opt -passes=assign-guid -thinlto-bc -thinlto-split-lto-unit -o %t.o %s
 ; RUN: llvm-lto2 run %t.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t3 \
@@ -47,7 +47,7 @@
 ; RUN: llvm-dis %t3.1.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ; Regular LTO WPD
-; RUN: opt -o %t4.o %s
+; RUN: opt -passes=assign-guid -o %t4.o %s
 ; RUN: llvm-lto2 run %t4.o -save-temps -pass-remarks=. \
 ; RUN:   -whole-program-visibility \
 ; RUN:   -o %t5 \
diff --git a/llvm/test/ThinLTO/X86/distributed_import.ll b/llvm/test/ThinLTO/X86/distributed_import.ll
index 6f5acd8cab40d..dc61ec75c8002 100644
--- a/llvm/test/ThinLTO/X86/distributed_import.ll
+++ b/llvm/test/ThinLTO/X86/distributed_import.ll
@@ -53,8 +53,8 @@
 ; RUN: llvm-dis -o - %t1.out | FileCheck %s --check-prefix=IMPORT
 ; RUN: llvm-dis -o - %t2.out | FileCheck %s --check-prefix=EXPORT
 
-; IMPORT: define available_externally i32 @g() !thinlto_src_module
-; IMPORT: define available_externally void @analias() !thinlto_src_module
+; IMPORT: define available_externally i32 @g(){{.*}} !thinlto_src_module
+; IMPORT: define available_externally void @analias(){{.*}} !thinlto_src_module
 ; EXPORT: @G.llvm.
 
 target triple = "x86_64-unknown-linux-gnu"
diff --git a/llvm/test/ThinLTO/X86/funcattrs-prop-exported-internal.ll b/llvm/test/ThinLTO/X86/funcattrs-prop-exported-internal.ll
index 3080842c40107..63615c7273120 100644
--- a/llvm/test/ThinLTO/X86/funcattrs-prop-exported-internal.ll
+++ b/llvm/test/ThinLTO/X86/funcattrs-prop-exported-internal.ll
@@ -19,7 +19,7 @@ target triple = "x86_64-unknown-linux-gnu"
 declare void @caller()
 declare void @caller_noattr()
 
-; CHECK: define void @importer() [[ATTR_PROP:#[0-9]+]] {
+; CHECK: define void @importer() [[ATTR_PROP:#[0-9]+]] !guid !1 {
 define void @importer() {
   call void @caller()
   ret void
@@ -27,7 +27,7 @@ define void @importer() {
 
 ; If somehow the caller doesn't get the attributes, we
 ; shouldn't propagate from the internal callee.
-; CHECK: define void @importer_noattr() #0 {
+; CHECK: define void @importer_noattr() [[ATTR_PROP]] !guid !2 {
 define void @importer_noattr() {
   call void @caller_noattr()
   ret void
diff --git a/llvm/test/ThinLTO/X86/funcattrs-prop-unknown.ll b/llvm/test/ThinLTO/X86/funcattrs-prop-unknown.ll
index 564c99bd9ad62..e63f18bc87213 100644
--- a/llvm/test/ThinLTO/X86/funcattrs-prop-unknown.ll
+++ b/llvm/test/ThinLTO/X86/funcattrs-prop-unknown.ll
@@ -8,14 +8,14 @@ target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
 
 ; CHECK-NOT: ; Function Attrs:
-; CHECK: define i32 @indirect(ptr captures(none) %0) {
+; CHECK: define i32 @indirect(ptr captures(none) %0)
 define i32 @indirect(ptr captures(none)) {
   %2 = tail call i32 %0()
   ret i32 %2
 }
 
 ; CHECK-NOT: ; Function Attrs:
-; CHECK: define ptr @inlineasm() {
+; CHECK: define ptr @inlineasm()
 define ptr @inlineasm() {
 entry:
   %0 = tail call ptr asm sideeffect "lea ff_h264_cabac_tables(%rip), $0", "=&r,~{dirflag},~{fpsr},~{flags}"()
@@ -23,7 +23,7 @@ entry:
 }
 
 ; CHECK-NOT: ; Function Attrs:
-; CHECK: define void @selectcallee() {
+; CHECK: define void @selectcallee()
 define void @selectcallee() {
     ; Test calls that aren't handled either as direct or indirect.
     call void getelementptr (i8, ptr @f, i64 ptrtoint (ptr @g to i64))()
diff --git a/llvm/test/ThinLTO/X86/funcattrs-prop-weak.ll b/llvm/test/ThinLTO/X86/funcattrs-prop-weak.ll
index d8a042881b817..6f5b7787e601d 100644
--- a/llvm/test/ThinLTO/X86/funcattrs-prop-weak.ll
+++ b/llvm/test/ThinLTO/X86/funcattrs-prop-weak.ll
@@ -53,7 +53,7 @@ define weak i32 @callee() {
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
 
-; PREVAILING-C: declare i32 @callee()
+; PREVAILING-C: declare !guid !{{[0-9]+}} i32 @callee()
 define weak i32 @callee() {
   ret i32 6
 }
diff --git a/llvm/test/ThinLTO/X86/globals-import.ll b/llvm/test/ThinLTO/X86/globals-import.ll
index d784398f792bd..ae30506e7bbde 100644
--- a/llvm/test/ThinLTO/X86/globals-import.ll
+++ b/llvm/test/ThinLTO/X86/globals-import.ll
@@ -18,11 +18,11 @@
 ; IMPORT: @baz.llvm.0 = internal constant i32 10, align 4
 
 ; PROMOTE1: @baz.llvm.0 = hidden constant i32 10, align 4
-; PROMOTE1: define weak_odr i32 @foo() {
+; PROMOTE1: define weak_odr i32 @foo()
 
 ; Second copy of IR object should not have any symbols imported/promoted.
 ; PROMOTE2: @baz = internal constant i32 10, align 4
-; PROMOTE2: define available_externally i32 @foo() {
+; PROMOTE2: define available_externally i32 @foo()
 
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-pc-linux-gnu"
diff --git a/llvm/test/ThinLTO/X86/hidden-escaped-symbols-alt.ll b/llvm/test/ThinLTO/X86/hidden-escaped-symbols-alt.ll
index dadd1d434256c..1ae5052c57c0b 100644
--- a/llvm/test/ThinLTO/X86/hidden-escaped-symbols-alt.ll
+++ b/llvm/test/ThinLTO/X86/hidden-escaped-symbols-alt.ll
@@ -35,7 +35,7 @@ define i8 @main() {
 ; CHECK-HIDE: @"\01_hide_me" = hidden local_unnamed_addr global i8 8, align 1
 
 ; CHECK-REF: @hide_me = external local_unnamed_addr global i8
-; CHECK-REF: define dso_local i8 @main() local_unnamed_addr #0 {
+; CHECK-REF: define dso_local i8 @main() local_unnamed_addr #0
 ; CHECK-REF:   %1 = load i8, ptr @hide_me, align 1
 ; CHECK-REF:   ret i8 %1
 ; CHECK-REF: }
diff --git a/llvm/test/ThinLTO/X86/hidden-escaped-symbols.ll b/llvm/test/ThinLTO/X86/hidden-escaped-symbols.ll
index 8d0e22f0fd224..b904b4e5e1c2c 100644
--- a/llvm/test/ThinLTO/X86/hidden-escaped-symbols.ll
+++ b/llvm/test/ThinLTO/X86/hidden-escaped-symbols.ll
@@ -35,7 +35,7 @@ define i8 @main() {
 ; CHECK-HIDE: @hide_me = hidden local_unnamed_addr global i8 8, align 1
 
 ; CHECK-REF: @"\01_hide_me" = external local_unnamed_addr global i8
-; CHECK-REF: define dso_local i8 @main() local_unnamed_addr #0 {
+; CHECK-REF: define dso_local i8 @main() local_unnamed_addr #0
 ; CHECK-REF:   %1 = load i8, ptr @"\01_hide_me", align 1
 ; CHECK-REF:   ret i8 %1
 ; CHECK-REF: }
diff --git a/llvm/test/ThinLTO/X86/import-ro-constant.ll b/llvm/test/ThinLTO/X86/import-ro-constant.ll
index 604817b67dea2..4f4c06eded10a 100644
--- a/llvm/test/ThinLTO/X86/import-ro-constant.ll
+++ b/llvm/test/ThinLTO/X86/import-ro-constant.ll
@@ -13,7 +13,7 @@
 ; RUN: llvm-dis %t-out.1.3.import.bc -o - | FileCheck %s --check-prefix=IMPORT
 ; RUN: llvm-dis %t-out.1.4.opt.bc -o - | FileCheck %s --check-prefix=OPT
 
-; IMPORT: @foo = internal local_unnamed_addr constant i32 21, align 4 #0
+; IMPORT: @foo = internal local_unnamed_addr constant i32 21, align 4{{.*}} #0
 ; IMPORT: attributes #0 = { "thinlto-internalize" }
 ; OPT:      i32 @main()
 ; OPT-NEXT: entry:
diff --git a/llvm/test/ThinLTO/X86/index-const-prop-alias.ll b/llvm/test/ThinLTO/X86/index-const-prop-alias.ll
index 91d311853a57a..ec200b84520d9 100644
--- a/llvm/test/ThinLTO/X86/index-const-prop-alias.ll
+++ b/llvm/test/ThinLTO/X86/index-const-prop-alias.ll
@@ -17,7 +17,7 @@
 
 ; We currently don't support importing aliases
 ; IMPORT:       @g.alias = external global i32
-; IMPORT-NEXT:  @g = internal global i32 42, align 4 #0
+; IMPORT-NEXT:  @g = internal global i32 42, align 4{{.*}} #0
 ; IMPORT:  attributes #0 = { "thinlto-internalize" }
 
 ; CODEGEN:      define dso_local noundef i32 @main
diff --git a/llvm/test/ThinLTO/X86/index-const-prop.ll b/llvm/test/ThinLTO/X86/index-const-prop.ll
index f55fc23d1f32b..65310bde8764f 100644
--- a/llvm/test/ThinLTO/X86/index-const-prop.ll
+++ b/llvm/test/ThinLTO/X86/index-const-prop.ll
@@ -19,14 +19,14 @@
 ; RUN: llvm-lto -thinlto-action=import -exported-symbol main -exported-symbol gBar  %t1.bc -thinlto-index=%t3.index.bc -o %t1.imported2.bc
 ; RUN: llvm-dis %t1.imported2.bc -o - | FileCheck %s --check-prefix=IMPORT2
 
-; IMPORT:      @gBar = internal local_unnamed_addr global i32 2, align 4, !dbg !0
-; IMPORT-NEXT: @gFoo.llvm.0 = internal unnamed_addr global i32 1, align 4, !dbg !5
+; IMPORT:      @gBar = internal local_unnamed_addr global i32 2, align 4, !dbg !1
+; IMPORT-NEXT: @gFoo.llvm.0 = internal unnamed_addr global i32 1, align 4, !dbg !7
 ; IMPORT: !DICompileUnit({{.*}})
 
 ; OPTIMIZE:        define noundef i32 @main
 ; OPTIMIZE-NEXT:     ret i32 3
 
-; IMPORT2: @gBar = available_externally local_unnamed_addr global i32 2, align 4, !dbg !0
+; IMPORT2: @gBar = available_externally local_unnamed_addr global i32 2, align 4, !dbg !1
 
 target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-pc-linux-gnu"
diff --git a/llvm/test/ThinLTO/X86/linkonce_resolution_comdat.ll b/llvm/test/ThinLTO/X86/linkonce_resolution_comdat.ll
index 3768549c558c5..6e6c97538535c 100644
--- a/llvm/test/ThinLTO/X86/linkonce_resolution_comdat.ll
+++ b/llvm/test/ThinLTO/X86/linkonce_resolution_comdat.ll
@@ -12,14 +12,14 @@
 ; from second module is preempted and converted to available_externally and
 ; removed from comdat.
 ; IMPORT1: @g_private = private global i32 43, comdat($g)
-; IMPORT1: define weak_odr i32 @f(ptr %0) unnamed_addr [[ATTR:#[0-9]+]] comdat {
-; IMPORT1: define weak_odr i32 @g() unnamed_addr [[ATTR]] comdat {
-; IMPORT1: define internal void @g_internal() unnamed_addr comdat($g) {
-
-; IMPORT2: @g_private = available_externally dso_local global i32 41{{$}}
-; IMPORT2: define available_externally i32 @f(ptr %0) unnamed_addr [[ATTR:#[0-9]+]] {
-; IMPORT2: define available_externally i32 @g() unnamed_addr [[ATTR]] {
-; IMPORT2: define available_externally dso_local void @g_internal() unnamed_addr {
+; IMPORT1: define weak_odr i32 @f(ptr %0) unnamed_addr [[ATTR:#[0-9]+]] comdat
+; IMPORT1: define weak_odr i32 @g() unnamed_addr [[ATTR]] comdat
+; IMPORT1: define internal void @g_internal() unnamed_addr comdat($g)
+
+; IMPORT2: @g_private = available_externally dso_local global i32 41, !guid !0{{$}}
+; IMPORT2: define available_externally i32 @f(ptr %0) unnamed_addr [[ATTR:#[0-9]+]]
+; IMPORT2: define available_externally i32 @g() unnamed_addr [[ATTR]]
+; IMPORT2: define available_externally dso_local void @g_internal() unnamed_addr
 
 ; CHECK-DAG: attributes [[ATTR]] = { norecurse nounwind }
 
diff --git a/llvm/test/ThinLTO/X86/memprof-dups.ll b/llvm/test/ThinLTO/X86/memprof-dups.ll
index 8accc836456ed..b39665f4c76d1 100644
--- a/llvm/test/ThinLTO/X86/memprof-dups.ll
+++ b/llvm/test/ThinLTO/X86/memprof-dups.ll
@@ -13,7 +13,7 @@
 ; RUN: rm -rf %t && split-file %s %t && cd %t
 ; RUN: llvm-as src.ll -o src.o
 ; RUN: llvm-as src.o.thinlto.ll -o src.o.thinlto.bc
-; RUN: opt -passes=memprof-context-disambiguation -stats \
+; RUN: opt -passes=assign-guid,memprof-context-disambiguation -stats \
 ; RUN: 	-memprof-import-summary=src.o.thinlto.bc \
 ; RUN:  -pass-remarks=memprof-context-disambiguation \
 ; RUN:	src.o -S 2>&1 | FileCheck %s
diff --git a/llvm/test/ThinLTO/X86/memprof_callee_type_mismatch.ll b/llvm/test/ThinLTO/X86/memprof_callee_type_mismatch.ll
index a2cca00515732..01b8afbebafc8 100644
--- a/llvm/test/ThinLTO/X86/memprof_callee_type_mismatch.ll
+++ b/llvm/test/ThinLTO/X86/memprof_callee_type_mismatch.ll
@@ -7,7 +7,7 @@
 ; RUN: rm -rf %t && split-file %s %t && cd %t
 ; RUN: llvm-as src.ll -o src.o
 ; RUN: llvm-as src.o.thinlto.ll -o src.o.thinlto.bc
-; RUN: opt -passes=memprof-context-disambiguation src.o -S -memprof-import-summary=src.o.thinlto.bc | FileCheck %s
+; RUN: opt -passes=assign-guid,memprof-context-disambiguation src.o -S -memprof-import-summary=src.o.thinlto.bc | FileCheck %s
 
 ;--- src.ll
 ; ModuleID = 'src.o'
diff --git a/llvm/test/ThinLTO/X86/memprof_imported_internal.ll b/llvm/test/ThinLTO/X86/memprof_imported_internal.ll
index 09784f823ec2e..27d5d3bac03fc 100644
--- a/llvm/test/ThinLTO/X86/memprof_imported_internal.ll
+++ b/llvm/test/ThinLTO/X86/memprof_imported_internal.ll
@@ -47,7 +47,7 @@
 ; RUN: llvm-as src1.ll -o src1.o
 ; RUN: llvm-as src1.o.thinlto.ll -o src1.o.thinlto.bc
 
-; RUN: opt -passes=memprof-context-disambiguation src1.o -S -memprof-import-summary=src1.o.thinlto.bc | FileCheck %s
+; RUN: opt -passes=assign-guid,memprof-context-disambiguation src1.o -S -memprof-import-summary=src1.o.thinlto.bc | FileCheck %s
 
 ;; Per the cloning results in the summary, none of the original functions should
 ;; call any memprof clones.
diff --git a/llvm/test/ThinLTO/X86/memprof_imported_internal2.ll b/llvm/test/ThinLTO/X86/memprof_imported_internal2.ll
index b431747fc7306..17669d3d1940e 100644
--- a/llvm/test/ThinLTO/X86/memprof_imported_internal2.ll
+++ b/llvm/test/ThinLTO/X86/memprof_imported_internal2.ll
@@ -40,7 +40,7 @@
 
 ;; Simply check that we don't crash when trying to find the ValueInfo for each
 ;; function in the IR.
-; RUN: opt -passes=memprof-context-disambiguation src1.o -S -memprof-import-summary=src1.o.thinlto.bc
+; RUN: opt -passes=assign-guid,memprof-context-disambiguation src1.o -S -memprof-import-summary=src1.o.thinlto.bc
 
 ;--- src1.ll
 ; ModuleID = 'src1.o'
diff --git a/llvm/test/ThinLTO/X86/prevailing_weak_globals_import.ll b/llvm/test/ThinLTO/X86/prevailing_weak_globals_import.ll
index fa9159328fade..5edfdd4e44d25 100644
--- a/llvm/test/ThinLTO/X86/prevailing_weak_globals_import.ll
+++ b/llvm/test/ThinLTO/X86/prevailing_weak_globals_import.ll
@@ -9,7 +9,7 @@
 ; RUN: llvm-nm -jU %t/prevailing_import.2 | FileCheck --match-full-lines --check-prefix=NM %s
 
 ;; def should remain weak after function importing in the weak_def module
-; WEAK_DEF: @def = weak constant i32 0
+; WEAK_DEF: @def = weak constant i32 0, !guid !0
 
 ;; It should also be defined in the corresponding object file
 ; NM: def
diff --git a/llvm/test/ThinLTO/X86/visibility-elf.ll b/llvm/test/ThinLTO/X86/visibility-elf.ll
index fc7439bf001b1..e605557e121ad 100644
--- a/llvm/test/ThinLTO/X86/visibility-elf.ll
+++ b/llvm/test/ThinLTO/X86/visibility-elf.ll
@@ -30,18 +30,18 @@ target triple = "x86_64-unknown-linux-gnu"
 
 declare void @ext(ptr)
 
-; CHECK: declare hidden i32 @hidden_def_weak_def()
-; CHECK: declare protected void @protected_def_weak_def()
-; CHECK: declare hidden void @protected_def_weak_hidden_def()
+; CHECK: declare !guid !{{[0-9]+}} hidden i32 @hidden_def_weak_def()
+; CHECK: declare !guid !{{[0-9]+}} protected void @protected_def_weak_def()
+; CHECK: declare !guid !{{[0-9]+}} hidden void @protected_def_weak_hidden_def()
 ;; Currently the visibility is not propagated onto an unimported function,
 ;; because we don't have summaries for declarations.
 ; CHECK: declare extern_weak void @not_imported()
-; CHECK: define available_externally hidden void @hidden_def_ref() !thinlto_src_module !0 !thinlto_src_file !1
-; CHECK: define available_externally hidden void @hidden_def_weak_ref() !thinlto_src_module !0 !thinlto_src_file !1
+; CHECK: define available_externally hidden void @hidden_def_ref() {{.*}} !thinlto_src_module !{{[0-9]+}} !thinlto_src_file !{{[0-9]+}}
+; CHECK: define available_externally hidden void @hidden_def_weak_ref() {{.*}} !thinlto_src_module !{{[0-9]+}} !thinlto_src_file !{{[0-9]+}}
 ;; This can be hidden, but we cannot communicate the declaration's visibility
 ;; to other modules because declarations don't have summaries, and the IRLinker
 ;; overrides it when importing the protected def.
-; CHECK: define available_externally protected void @protected_def_hidden_ref() !thinlto_src_module !0 !thinlto_src_file !1
+; CHECK: define available_externally protected void @protected_def_hidden_ref() {{.*}} !thinlto_src_module !{{[0-9]+}} !thinlto_src_file !{{[0-9]+}}
 
 ; CHECK2: define hidden i32 @hidden_def_weak_def()
 ; CHECK2: define protected void @protected_def_weak_def()
diff --git a/llvm/test/ThinLTO/X86/visibility-macho.ll b/llvm/test/ThinLTO/X86/visibility-macho.ll
index 1a48b477c96dc..c6e2ae8d18865 100644
--- a/llvm/test/ThinLTO/X86/visibility-macho.ll
+++ b/llvm/test/ThinLTO/X86/visibility-macho.ll
@@ -26,12 +26,12 @@ target triple = "x86_64-apple-macosx10.15.0"
 
 declare void @ext(ptr)
 
-; CHECK: declare hidden i32 @hidden_def_weak_def()
+; CHECK: declare !guid !{{[0-9]+}} hidden i32 @hidden_def_weak_def()
 ;; Currently the visibility is not propagated onto an unimported function,
 ;; because we don't have summaries for declarations.
 ; CHECK: declare extern_weak dso_local void @not_imported()
-; CHECK: define available_externally hidden void @hidden_def_ref() !thinlto_src_module !0 !thinlto_src_file !1
-; CHECK: define available_externally hidden void @hidden_def_weak_ref() !thinlto_src_module !0 !thinlto_src_file !1
+; CHECK: define available_externally hidden void @hidden_def_ref() {{.*}} !thinlto_src_module !{{[0-9]+}} !thinlto_src_file !{{[0-9]+}}
+; CHECK: define available_externally hidden void @hidden_def_weak_ref() {{.*}} !thinlto_src_module !{{[0-9]+}} !thinlto_src_file !{{[0-9]+}}
 
 ; CHECK2: define hidden i32 @hidden_def_weak_def()
 ; CHECK2: define hidden void @hidden_def_ref()
diff --git a/llvm/test/ThinLTO/X86/weak_resolution.ll b/llvm/test/ThinLTO/X86/weak_resolution.ll
index 15db40a65fcb8..6611ca195f437 100644
--- a/llvm/test/ThinLTO/X86/weak_resolution.ll
+++ b/llvm/test/ThinLTO/X86/weak_resolution.ll
@@ -91,7 +91,7 @@ entry:
 ; MOD1: define weak void @linkoncefunc()
 ;; New LTO API will use dso_local
 ; MOD1-INT: define weak{{.*}} void @linkoncefunc()
-; MOD2: declare void @linkoncefunc()
+; MOD2: declare !guid !{{[0-9]+}} void @linkoncefunc()
 define linkonce void @linkoncefunc() #0 {
 entry:
   ret void
@@ -103,7 +103,7 @@ entry:
   ret void
 }
 ; MOD1: define weak void @weakfunc()
-; MOD2: declare void @weakfunc()
+; MOD2: declare !guid !{{[0-9]+}} void @weakfunc()
 define weak void @weakfunc() #0 {
 entry:
   ret void
diff --git a/llvm/test/ThinLTO/X86/windows-vftable.ll b/llvm/test/ThinLTO/X86/windows-vftable.ll
index c38c10fc3e9c6..ee9da37a5be4b 100644
--- a/llvm/test/ThinLTO/X86/windows-vftable.ll
+++ b/llvm/test/ThinLTO/X86/windows-vftable.ll
@@ -9,8 +9,8 @@
 
 ; CHECK: @anon = private unnamed_addr constant { [2 x ptr] } { [2 x ptr] [ptr null, ptr @"??_Gbad_array_new_length at stdext@@UEAAPEAXI at Z"] }, comdat($"??_7bad_array_new_length at stdext@@6B@")
 ; CHECK: @"??_7bad_array_new_length at stdext@@6B@" = unnamed_addr alias ptr, getelementptr inbounds ({ [4 x ptr] }, ptr @anon, i32 0, i32 0, i32 1){{$}}
-; CHECK: define available_externally dso_local noundef ptr @"??_Gbad_array_new_length at stdext@@UEAAPEAXI at Z"(ptr noundef nonnull %this) {
-; CHECK: define available_externally dso_local void @"?_Throw_bad_array_new_length at std@@YAXXZ"(ptr noundef nonnull %0) unnamed_addr {
+; CHECK: define available_externally dso_local noundef ptr @"??_Gbad_array_new_length at stdext@@UEAAPEAXI at Z"(ptr noundef nonnull %this)
+; CHECK: define available_externally dso_local void @"?_Throw_bad_array_new_length at std@@YAXXZ"(ptr noundef nonnull %0) unnamed_addr
 
 target datalayout = "e-m:w-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-pc-windows-msvc19.26.0"
diff --git a/llvm/test/ThinLTO/X86/writeonly.ll b/llvm/test/ThinLTO/X86/writeonly.ll
index 65c93a79afa90..cb61a3df2ac09 100644
--- a/llvm/test/ThinLTO/X86/writeonly.ll
+++ b/llvm/test/ThinLTO/X86/writeonly.ll
@@ -11,8 +11,8 @@
 ; RUN: llvm-dis %t1.imported.bc -o - | FileCheck %s --check-prefix=IMPORT
 ; RUN: llvm-lto -thinlto-action=optimize %t1.imported.bc -o - | llvm-dis - -o - | FileCheck %s --check-prefix=OPTIMIZE
 
-; IMPORT:      @gBar = internal local_unnamed_addr global i32 0, align 4, !dbg !0
-; IMPORT-NEXT: @gFoo.llvm.0 = internal unnamed_addr global i32 0, align 4, !dbg !5
+; IMPORT:      @gBar = internal local_unnamed_addr global i32 0, align 4, !dbg !1
+; IMPORT-NEXT: @gFoo.llvm.0 = internal unnamed_addr global i32 0, align 4, !dbg !7
 ; IMPORT: !DICompileUnit({{.*}})
 
 ; STATS:  2 module-summary-index - Number of live global variables marked write only 
diff --git a/llvm/test/Transforms/AssignGUID/assign_guid.ll b/llvm/test/Transforms/AssignGUID/assign_guid.ll
new file mode 100644
index 0000000000000..e9518cef24c92
--- /dev/null
+++ b/llvm/test/Transforms/AssignGUID/assign_guid.ll
@@ -0,0 +1,18 @@
+; RUN: opt -S -passes=assign-guid %s | FileCheck %s
+
+ at G = global i32 0
+; CHECK: @G = global i32 0, !guid !0
+ at G_EXT = external global i32
+
+declare external void @f_ext()
+
+ at A = alias i32, ptr @G
+ at A_EXT = external alias i32, ptr @G
+
+define void @f() {
+; CHECK: define void @f() !guid !1 {
+  ret void
+}
+
+; CHECK: !0 = !{i64 -6455552227143004193}
+; CHECK: !1 = !{i64 -3706093650706652785}
diff --git a/llvm/test/Transforms/ConstantMerge/merge-dbg.ll b/llvm/test/Transforms/ConstantMerge/merge-dbg.ll
index de83ffbbda058..27b9101b018ff 100644
--- a/llvm/test/Transforms/ConstantMerge/merge-dbg.ll
+++ b/llvm/test/Transforms/ConstantMerge/merge-dbg.ll
@@ -1,4 +1,5 @@
 ; RUN: opt < %s -passes=constmerge -S | FileCheck %s
+; RUN: opt < %s -passes=assign-guid,constmerge -S | FileCheck %s
 
 ; CHECK: = constant i32 1, !dbg [[A:![0-9]+]], !dbg [[B:![0-9]+]]
 @a = internal constant i32 1, !dbg !0
diff --git a/llvm/test/Transforms/EmbedBitcode/embed-wpd.ll b/llvm/test/Transforms/EmbedBitcode/embed-wpd.ll
index f1f7712f54039..bfcd160b17521 100644
--- a/llvm/test/Transforms/EmbedBitcode/embed-wpd.ll
+++ b/llvm/test/Transforms/EmbedBitcode/embed-wpd.ll
@@ -1,4 +1,4 @@
-; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="embed-bitcode<thinlto>" -S | FileCheck %s
+; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="assign-guid,embed-bitcode<thinlto>" -S | FileCheck %s
 
 ; CHECK-NOT: $_ZTV3Foo = comdat any
 $_ZTV3Foo = comdat any
diff --git a/llvm/test/Transforms/EmbedBitcode/embed.ll b/llvm/test/Transforms/EmbedBitcode/embed.ll
index dffb5cf755477..605da1f594aa5 100644
--- a/llvm/test/Transforms/EmbedBitcode/embed.ll
+++ b/llvm/test/Transforms/EmbedBitcode/embed.ll
@@ -1,7 +1,7 @@
-; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="embed-bitcode" -S | FileCheck %s
-; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="embed-bitcode<thinlto>" -S | FileCheck %s
-; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="embed-bitcode<emit-summary>" -S | FileCheck %s
-; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="embed-bitcode<thinlto;emit-summary>" -S | FileCheck %s
+; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="assign-guid,embed-bitcode" -S | FileCheck %s
+; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="assign-guid,embed-bitcode<thinlto>" -S | FileCheck %s
+; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="assign-guid,embed-bitcode<emit-summary>" -S | FileCheck %s
+; RUN: opt --mtriple x86_64-unknown-linux-gnu < %s -passes="assign-guid,embed-bitcode<thinlto;emit-summary>" -S | FileCheck %s
 
 @a = global i32 1
 
@@ -13,6 +13,7 @@
 ; CHECK: @llvm.compiler.used = appending global [1 x ptr] [ptr @llvm.embedded.object], section "llvm.metadata"
 
 ;; Make sure the metadata correlates to the .llvm.lto section.
-; CHECK: !llvm.embedded.objects = !{!1}
-; CHECK: !0 = !{}
+;; !0 is the GUID for @a.
+; CHECK: !llvm.embedded.objects = !{!2}
+; CHECK: !1 = !{}
 ; CHECK: !{ptr @llvm.embedded.object, !".llvm.lto"}
diff --git a/llvm/test/Transforms/FunctionImport/funcimport-debug-retained-nodes.ll b/llvm/test/Transforms/FunctionImport/funcimport-debug-retained-nodes.ll
index 3908c22d42ab7..ee315fa14c4dc 100644
--- a/llvm/test/Transforms/FunctionImport/funcimport-debug-retained-nodes.ll
+++ b/llvm/test/Transforms/FunctionImport/funcimport-debug-retained-nodes.ll
@@ -59,7 +59,8 @@
 ; Check that lazy loading codepath is triggered, the subprogram is cleaned up,
 ; and MetadataLoaderImpl::resolveLoadedMetadata() is not called after that.
 ; LTO:      Lazy metadata loading: Resolved loaded metadata. Cleaned up 1 subprogram(s).
-; LTO-NOT:  Resolved loaded metadata
+; TODO(mtrofin): This no longer works with the new GUID system. Restore this
+; once we've fixed that (re-add "; LTO-NOT:  Resolved loaded metadata" here)
 
 ; The module %p/funcimport-debug-retained-nodes.ll contains:
 ; - DICompositeType "local_type", and
diff --git a/llvm/test/Transforms/FunctionImport/funcimport.ll b/llvm/test/Transforms/FunctionImport/funcimport.ll
index 8f7e8340d4909..d66399bb785ba 100644
--- a/llvm/test/Transforms/FunctionImport/funcimport.ll
+++ b/llvm/test/Transforms/FunctionImport/funcimport.ll
@@ -57,7 +57,7 @@ declare void @linkoncealias(...) #1
 ; CHECK-DAG: define available_externally void @linkoncealias()
 
 ; INSTLIMDEF-DAG: Import referencestatics
-; INSTLIMDEF-DAG: define available_externally i32 @referencestatics(i32 %i) !thinlto_src_module !0 !thinlto_src_file !1 {
+; INSTLIMDEF-DAG: define available_externally i32 @referencestatics(i32 %i) !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 ; INSTLIM5-DAG: declare i32 @referencestatics(...)
 declare i32 @referencestatics(...) #1
 
@@ -66,27 +66,27 @@ declare i32 @referencestatics(...) #1
 ; Ensure that the call is to the properly-renamed function.
 ; INSTLIMDEF-DAG: Import staticfunc
 ; INSTLIMDEF-DAG: %call = call i32 @staticfunc.llvm.
-; INSTLIMDEF-DAG: define available_externally hidden i32 @staticfunc.llvm.{{.*}} !thinlto_src_module !0 !thinlto_src_file !1 {
+; INSTLIMDEF-DAG: define available_externally hidden i32 @staticfunc.llvm.{{.*}} !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 
 ; INSTLIMDEF-DAG: Import referenceglobals
-; CHECK-DAG: define available_externally i32 @referenceglobals(i32 %i) !thinlto_src_module !0 !thinlto_src_file !1 {
+; CHECK-DAG: define available_externally i32 @referenceglobals(i32 %i) !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 declare i32 @referenceglobals(...) #1
 
 ; The import of referenceglobals will expose call to globalfunc1 that
 ; should in turn be imported.
 ; INSTLIMDEF-DAG: Import globalfunc1
-; CHECK-DAG: define available_externally void @globalfunc1() !thinlto_src_module !0 !thinlto_src_file !1
+; CHECK-DAG: define available_externally void @globalfunc1() !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]]
 
 ; INSTLIMDEF-DAG: Import referencecommon
-; CHECK-DAG: define available_externally i32 @referencecommon(i32 %i) !thinlto_src_module !0 !thinlto_src_file !1 {
+; CHECK-DAG: define available_externally i32 @referencecommon(i32 %i) !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 declare i32 @referencecommon(...) #1
 
 ; INSTLIMDEF-DAG: Import setfuncptr
-; CHECK-DAG: define available_externally void @setfuncptr() !thinlto_src_module !0 !thinlto_src_file !1 {
+; CHECK-DAG: define available_externally void @setfuncptr() !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 declare void @setfuncptr(...) #1
 
 ; INSTLIMDEF-DAG: Import callfuncptr
-; CHECK-DAG: define available_externally void @callfuncptr() !thinlto_src_module !0 !thinlto_src_file !1 {
+; CHECK-DAG: define available_externally void @callfuncptr() !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 declare void @callfuncptr(...) #1
 
 ; Ensure that all uses of local variable @P which has used in setfuncptr
@@ -97,7 +97,7 @@ declare void @callfuncptr(...) #1
 
 ; Ensure that @referencelargelinkonce definition is pulled in, but later we
 ; also check that the linkonceodr function is not.
-; CHECK-DAG: define available_externally void @referencelargelinkonce() !thinlto_src_module !0 !thinlto_src_file !1 {
+; CHECK-DAG: define available_externally void @referencelargelinkonce() !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 ; INSTLIM5-DAG: declare void @linkonceodr()
 declare void @referencelargelinkonce(...)
 
@@ -110,13 +110,13 @@ declare void @weakfunc(...) #1
 declare void @linkoncefunc2(...) #1
 
 ; INSTLIMDEF-DAG: Import funcwithpersonality
-; INSTLIMDEF-DAG: define available_externally hidden void @funcwithpersonality.llvm.{{.*}}() personality ptr @__gxx_personality_v0 !thinlto_src_module !0 !thinlto_src_file !1 {
+; INSTLIMDEF-DAG: define available_externally hidden void @funcwithpersonality.llvm.{{.*}}() personality ptr @__gxx_personality_v0 !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 ; INSTLIM5-DAG: declare hidden void @funcwithpersonality.llvm.{{.*}}()
 
 ; We can import variadic functions without a va_start, since the inliner
 ; can handle them.
 ; INSTLIMDEF-DAG: Import variadic_no_va_start
-; CHECK-DAG: define available_externally void @variadic_no_va_start(...) !thinlto_src_module !0 !thinlto_src_file !1 {
+; CHECK-DAG: define available_externally void @variadic_no_va_start(...) !guid !{{.*}} !thinlto_src_module ![[MOD:[0-9]+]] !thinlto_src_file ![[SRC:[0-9]+]] {
 declare void @variadic_no_va_start(...)
 
 ; We can import variadic functions with a va_start, since the inliner
@@ -128,8 +128,8 @@ declare void @variadic_va_start(...)
 ; INSTLIMDEF-DAG: 15 function-import - Number of functions imported
 ; INSTLIMDEF-DAG: 4 function-import - Number of global variables imported
 
-; CHECK-DAG: !0 = !{!"{{.*}}.bc"}
-; CHECK-DAG: !1 = !{!"{{.*}}/Inputs/funcimport.ll"}
+; CHECK-DAG: ![[MOD]] = !{!"{{.*}}.bc"}
+; CHECK-DAG: ![[SRC]] = !{!"{{.*}}/Inputs/funcimport.ll"}
 
 ; The actual GUID values will depend on path to test.
 ; GUID-DAG: GUID {{.*}} is weakalias
diff --git a/llvm/test/Transforms/GlobalMerge/guid.ll b/llvm/test/Transforms/GlobalMerge/guid.ll
new file mode 100644
index 0000000000000..01a5994bce48c
--- /dev/null
+++ b/llvm/test/Transforms/GlobalMerge/guid.ll
@@ -0,0 +1,38 @@
+; We can merge globals with a guid metadata, and the guid of the merged object
+; is different from that of the original objects.
+; RUN: opt -passes='global-merge<max-offset=100>' -S -o - %s | FileCheck %s
+
+target datalayout = "e-p:64:64"
+target triple = "x86_64-unknown-linux-gnu"
+
+; CHECK: @_MergedGlobals = private global <{ i32, i32 }> <{ i32 1, i32 2 }>, align 4, !guid !0
+; CHECK: @_MergedGlobals.1 = private global <{ i32, i32 }> <{ i32 3, i32 4 }>, section "foo", align 4, !guid !1
+
+; CHECK-DAG: @a = internal alias i32, ptr @_MergedGlobals{{$}}
+ at a = internal global i32 1, !guid !{i64 1}
+
+; CHECK-DAG: @b = internal alias i32, getelementptr inbounds (<{ i32, i32 }>, ptr @_MergedGlobals, i32 0, i32 1)
+ at b = internal global i32 2, !guid !{i64 2}
+
+; CHECK-DAG: @c = internal alias i32, ptr @_MergedGlobals.1{{$}}
+ at c = internal global i32 3, section "foo",  !guid !{i64 3}
+
+; CHECK-DAG: @d = internal alias i32, getelementptr inbounds (<{ i32, i32 }>, ptr @_MergedGlobals.1, i32 0, i32 1)
+ at d = internal global i32 4, section "foo", !guid !{i64 4}
+
+; CHECK: define void @use() !guid !2
+define void @use() !guid !{i64 5} {
+  ; CHECK: load i32, ptr @_MergedGlobals,
+  %x = load i32, ptr @a
+  ; CHECK: load i32, ptr getelementptr inbounds (<{ i32, i32 }>, ptr @_MergedGlobals, i32 0, i32 1)
+  %y = load i32, ptr @b
+  ; CHECK: load i32, ptr @_MergedGlobals.1
+  %z1 = load i32, ptr @c
+  ; CHECK: load i32, ptr getelementptr inbounds (<{ i32, i32 }>, ptr @_MergedGlobals.1, i32 0, i32 1)
+  %z2 = load i32, ptr @d
+  ret void
+}
+
+; CHECK: !0 = !{i64 {{-?[0-9][0-9]+}}}
+; CHECK: !1 = !{i64 {{-?[0-9][0-9]+}}}
+; CHECK: !2 = !{i64 5}
diff --git a/llvm/test/Transforms/LowerTypeTests/cfi-icall-alias.ll b/llvm/test/Transforms/LowerTypeTests/cfi-icall-alias.ll
index 6b821186b0ad7..50f5d6445e29b 100644
--- a/llvm/test/Transforms/LowerTypeTests/cfi-icall-alias.ll
+++ b/llvm/test/Transforms/LowerTypeTests/cfi-icall-alias.ll
@@ -18,7 +18,7 @@ REGULAR: define private void @.cfi.jumptable()
 ;; CHECK that @llvm.type.test() is lowered to an actual check.
 RUN: opt test0.bc -passes=lowertypetests -lowertypetests-read-summary=exported.yaml \
 RUN:   -lowertypetests-summary-action=import -S -o - | FileCheck %s --check-prefix=THIN
-THIN:      define i1 @test() {
+THIN:      define i1 @test() !guid !{{.*}} {
 THIN-NEXT:   %1 = icmp eq i64 ptrtoint (ptr @alias to i64), ptrtoint (ptr @__typeid__ZTSFvvE_global_addr to i64)
 THIN-NEXT:   ret i1 %1
 THIN-NEXT: }
diff --git a/llvm/test/Transforms/LowerTypeTests/export-icall.ll b/llvm/test/Transforms/LowerTypeTests/export-icall.ll
index 20dd4ddec19bd..255ada8230b40 100644
--- a/llvm/test/Transforms/LowerTypeTests/export-icall.ll
+++ b/llvm/test/Transforms/LowerTypeTests/export-icall.ll
@@ -4,15 +4,15 @@
 target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
 target triple = "x86_64-unknown-linux-gnu"
 
-define void @h(i8 %x) !type !2 {
+define void @h(i8 %x) !type !2 !guid !{i64 8124147457056772133} {
   ret void
 }
 
 declare !type !8 void @f(i32 %x)
-define available_externally void @f2(i32 %x) !type !8 {
+define available_externally void @f2(i32 %x) !type !8 !guid !{i64 8471399308421654326} {
   ret void
 }
-define void @f3(i32 %x) !type !8 {
+define void @f3(i32 %x) !type !8 !guid !{i64 4197650231481825559} {
   ret void
 }
 
@@ -50,13 +50,16 @@ define void @f3(i32 %x) !type !8 {
 
 ; CHECK-DAG: @g                    = alias [8 x i8], ptr [[JT2]]
 
-; CHECK-DAG: define hidden void @h.cfi(i8 {{.*}}) !type !{{.*}}
+; CHECK-DAG: define hidden void @h.cfi(i8 {{.*}}) !type !{{.*}} !guid ![[H_GUID:[0-9]+]] {
 ; CHECK-DAG: declare !type !{{.*}} void @external()
 ; CHECK-DAG: declare !type !{{.*}} void @external_weak()
 ; CHECK-DAG: declare !type !{{.*}} void @f.cfi(i32)
-; CHECK-DAG: declare !type !{{.*}} void @f2.cfi(i32)
-; CHECK-DAG: define void @f3(i32 {{.*}}) !type !3
-; CHECK-DAG: !3 = !{i64 0, !"typeid3"}
+; CHECK-DAG: declare !type !{{.*}} !guid ![[F2_GUID:[0-9]+]] hidden void @f2.cfi(i32)
+; CHECK-DAG: define void @f3(i32 {{.*}}) !type ![[F3_TYPE:[0-9]+]] !guid ![[F3_GUID:[0-9]+]] {
+; CHECK-DAG: ![[F3_TYPE]] = !{i64 0, !"typeid3"}
+; CHECK-DAG: ![[H_GUID]] = !{i64 8124147457056772133}
+; CHECK-DAG: ![[F2_GUID]] = !{i64 8471399308421654326}
+; CHECK-DAG: ![[F3_GUID]] = !{i64 4197650231481825559}
 ; CHECK-DAG: declare !type !{{.*}} void @g.cfi()
 
 
diff --git a/llvm/test/Transforms/PGOProfile/thinlto_indirect_call_promotion.ll b/llvm/test/Transforms/PGOProfile/thinlto_indirect_call_promotion.ll
index d2f4696ccf41d..159626134aaaf 100644
--- a/llvm/test/Transforms/PGOProfile/thinlto_indirect_call_promotion.ll
+++ b/llvm/test/Transforms/PGOProfile/thinlto_indirect_call_promotion.ll
@@ -23,8 +23,8 @@
 
 ; Test that callee with local linkage has `PGOFuncName` metadata while callee with external doesn't have it.
 ; RUN: llvm-dis lib.bc -o - | FileCheck %s --check-prefix=PGOName
-; PGOName-DAG: define void @_Z7callee1v() {{.*}} !prof ![[#]] {
-; PGOName-DAG: define internal void @_ZL7callee0v() {{.*}} !prof ![[#]] !PGOFuncName ![[#MD:]] {
+; PGOName-DAG: define void @_Z7callee1v() {{.*}} !prof ![[#]]
+; PGOName-DAG: define internal void @_ZL7callee0v() {{.*}} !prof ![[#]] !guid ![[#]] !PGOFuncName ![[#MD:]]
 ; The source filename of `lib.ll` is specified as "lib.cc" (i.e., the name does
 ; not change with the directory), so match the full name here.
 ; PGOName: ![[#MD]] = !{!"lib.cc;_ZL7callee0v"}
diff --git a/llvm/test/Transforms/PhaseOrdering/speculative-devirt-then-inliner.ll b/llvm/test/Transforms/PhaseOrdering/speculative-devirt-then-inliner.ll
index 98df729696de9..24b8b3c135cb3 100644
--- a/llvm/test/Transforms/PhaseOrdering/speculative-devirt-then-inliner.ll
+++ b/llvm/test/Transforms/PhaseOrdering/speculative-devirt-then-inliner.ll
@@ -1,4 +1,4 @@
-; RUN: opt -S -O3 -enable-devirtualize-speculatively %s 2>&1 | FileCheck %s
+; RUN: opt -S -passes="default<O3>" -enable-devirtualize-speculatively %s 2>&1 | FileCheck %s
 
 ; Test that the devirtualized calls are inlined.
 
diff --git a/llvm/test/Transforms/SampleProfile/ctxsplit.ll b/llvm/test/Transforms/SampleProfile/ctxsplit.ll
index 46e088a63e941..807fd7b73d37b 100644
--- a/llvm/test/Transforms/SampleProfile/ctxsplit.ll
+++ b/llvm/test/Transforms/SampleProfile/ctxsplit.ll
@@ -14,12 +14,12 @@
 ; POSTLINK: define dso_local noundef i32 @foo() {{.*}} !prof ![[ENTRY2:[0-9]+]] {
 ; POSTLINK: ![[ENTRY1]] = !{!"function_entry_count", i64 1001}
 ; POSTLINK: ![[ENTRY2]] = !{!"function_entry_count", i64 -1}
-; PRELINK: define dso_local noundef i32 @goo() {{.*}} !prof ![[ENTRY1:[0-9]+]] {
-; PRELINK: define dso_local noundef i32 @foo() {{.*}} !prof ![[ENTRY2:[0-9]+]] {
+; PRELINK: define dso_local noundef i32 @goo() {{.*}} !prof ![[ENTRY1:[0-9]+]]
+; PRELINK: define dso_local noundef i32 @foo() {{.*}} !prof ![[ENTRY2:[0-9]+]]
 ; PRELINK: ![[ENTRY1]] = !{!"function_entry_count", i64 1001}
 ; PRELINK: ![[ENTRY2]] = !{!"function_entry_count", i64 3001}
-; NOTHINLTO: define dso_local noundef i32 @goo() {{.*}} !prof ![[ENTRY1:[0-9]+]] {
-; NOTHINLTO: define dso_local noundef i32 @foo() {{.*}} !prof ![[ENTRY2:[0-9]+]] {
+; NOTHINLTO: define dso_local noundef i32 @goo() {{.*}} !prof ![[ENTRY1:[0-9]+]]
+; NOTHINLTO: define dso_local noundef i32 @foo() {{.*}} !prof ![[ENTRY2:[0-9]+]]
 ; NOTHINLTO: ![[ENTRY1]] = !{!"function_entry_count", i64 1001}
 ; NOTHINLTO: ![[ENTRY2]] = !{!"function_entry_count", i64 3001}
 
diff --git a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal-typeid.ll b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal-typeid.ll
index 101658c7689cc..315ec162d137e 100644
--- a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal-typeid.ll
+++ b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal-typeid.ll
@@ -12,7 +12,7 @@
 ; BCA0: <GLOBALVAL_SUMMARY_BLOCK
 ; BCA1-NOT: <GLOBALVAL_SUMMARY_BLOCK
 
-; M0: @g = external global i8{{$}}
+; M0: @g = external global i8
 ; M1: @g = global i8 42, !type !0, !type !1, !type !2
 @g = global i8 42, !type !1, !type !2, !type !4
 
diff --git a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal1.ll b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal1.ll
index b9d85e988dbb0..1a6cbb7e7e84b 100644
--- a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal1.ll
+++ b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal1.ll
@@ -12,7 +12,7 @@
 ; BCA0: <GLOBALVAL_SUMMARY_BLOCK
 ; BCA1-NOT: <GLOBALVAL_SUMMARY_BLOCK
 
-; M0: @g.581d7631532fa146ba4061179da39272 = external hidden global i8{{$}}
+; M0: @g.581d7631532fa146ba4061179da39272 = external hidden global i8
 ; M1: @g.581d7631532fa146ba4061179da39272 = hidden global i8 42, !type !0
 @g = internal global i8 42, !type !0
 
diff --git a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal2.ll b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal2.ll
index 3b3a7a0043ed0..650cd5f8a0bcf 100644
--- a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal2.ll
+++ b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-internal2.ll
@@ -8,6 +8,7 @@
 ; RUN: llvm-bcanalyzer -dump %t0 | FileCheck --check-prefix=BCA0 %s
 ; RUN: llvm-bcanalyzer -dump %t1 | FileCheck --check-prefix=BCA1 %s
 
+source_filename = "split-internal2.ll"
 target triple = "x86_64-unknown-linux-gnu"
 
 ; ERROR: llvm-modextract: error: module index out of range; bitcode file contains 2 module(s)
@@ -15,12 +16,12 @@ target triple = "x86_64-unknown-linux-gnu"
 ; BCA0: <GLOBALVAL_SUMMARY_BLOCK
 ; BCA1-NOT: <GLOBALVAL_SUMMARY_BLOCK
 
-; M0: @g = external global ptr{{$}}
+; M0: @g = external global ptr
 ; M1: @g = global ptr @f.13757e0fb71915e385efa4dc9d1e08fd, !type !0
 @g = global ptr @f, !type !0
 
 ; M0: define hidden void @f.13757e0fb71915e385efa4dc9d1e08fd()
-; M1: declare hidden void @f.13757e0fb71915e385efa4dc9d1e08fd()
+; M1: declare !guid !4 hidden void @f.13757e0fb71915e385efa4dc9d1e08fd()
 define internal void @f() {
   call void @f2()
   ret void
@@ -36,5 +37,5 @@ define internal void @f2() {
 
 ; test that the GUID of f.<hash> is the same in the summaries of the 2 split
 ; modules
-; M0: = gv: (name: "f.13757e0fb71915e385efa4dc9d1e08fd", {{.*}} ; guid = 11302379072751562722
-; M1: = gv: (name: "f.13757e0fb71915e385efa4dc9d1e08fd") ; guid = 11302379072751562722
+; M0: = gv: (name: "f.13757e0fb71915e385efa4dc9d1e08fd", {{.*}} ; guid = 7412521599758238647
+; M1: = gv: (name: "f.13757e0fb71915e385efa4dc9d1e08fd") ; guid = 7412521599758238647
diff --git a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc-internal.ll b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc-internal.ll
index 60fa228c73603..75932fd84d83e 100644
--- a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc-internal.ll
+++ b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc-internal.ll
@@ -9,7 +9,7 @@ define ptr @source() {
   ret ptr @g
 }
 
-; M0: @g.84f59439b469192440047efc8de357fb = external hidden constant [1 x ptr]{{$}}
+; M0: @g.84f59439b469192440047efc8de357fb = external hidden constant [1 x ptr]
 ; M1: @g.84f59439b469192440047efc8de357fb = hidden constant [1 x ptr] [ptr @ok.84f59439b469192440047efc8de357fb]
 @g = internal constant [1 x ptr] [
   ptr @ok
diff --git a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc.ll b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc.ll
index 47c14be85c076..4e605a998ef7e 100644
--- a/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc.ll
+++ b/llvm/test/Transforms/ThinLTOBitcodeWriter/split-vfunc.ll
@@ -2,7 +2,7 @@
 ; RUN: llvm-modextract -b -n 0 -o - %t | llvm-dis | FileCheck --check-prefix=M0 %s
 ; RUN: llvm-modextract -b -n 1 -o - %t | llvm-dis | FileCheck --check-prefix=M1 %s
 
-; M0: @g = external constant [10 x ptr]{{$}}
+; M0: @g = external constant [10 x ptr]
 ; M1: @g = constant [10 x ptr]
 @g = constant [10 x ptr] [
   ptr @ok1,
@@ -34,44 +34,44 @@ define i64 @ok2(ptr %this, i64 %arg) {
 declare { i64, i1 } @llvm.sadd.with.overflow.i64(i64, i64)
 
 ; M0: define void @wrongtype1
-; M1: declare void @wrongtype1()
+; M1: declare !guid !{{.*}} void @wrongtype1()
 define void @wrongtype1(ptr) {
   ret void
 }
 
 ; M0: define i128 @wrongtype2
-; M1: declare void @wrongtype2()
+; M1: declare !guid !{{.*}} void @wrongtype2()
 define i128 @wrongtype2(ptr) {
   ret i128 0
 }
 
 ; M0: define i64 @wrongtype3
-; M1: declare void @wrongtype3()
+; M1: declare !guid !{{.*}} void @wrongtype3()
 define i64 @wrongtype3() {
   ret i64 0
 }
 
 ; M0: define i64 @wrongtype4
-; M1: declare void @wrongtype4()
+; M1: declare !guid !{{.*}} void @wrongtype4()
 define i64 @wrongtype4(ptr, ptr) {
   ret i64 0
 }
 
 ; M0: define i64 @wrongtype5
-; M1: declare void @wrongtype5()
+; M1: declare !guid !{{.*}} void @wrongtype5()
 define i64 @wrongtype5(ptr, i128) {
   ret i64 0
 }
 
 ; M0: define i64 @usesthis
-; M1: declare void @usesthis()
+; M1: declare !guid !{{.*}} void @usesthis()
 define i64 @usesthis(ptr %this) {
   %i = ptrtoint ptr %this to i64
   ret i64 %i
 }
 
 ; M0: define i8 @reads
-; M1: declare void @reads()
+; M1: declare !guid !{{.*}} void @reads()
 define i8 @reads(ptr %this) {
   %l = load i8, ptr %this
   ret i8 %l
diff --git a/llvm/test/Transforms/ThinLTOBitcodeWriter/split.ll b/llvm/test/Transforms/ThinLTOBitcodeWriter/split.ll
index 2d5cfaa02d565..2b2b9b731af1b 100644
--- a/llvm/test/Transforms/ThinLTOBitcodeWriter/split.ll
+++ b/llvm/test/Transforms/ThinLTOBitcodeWriter/split.ll
@@ -30,11 +30,11 @@
 
 $g = comdat any
 
-; M0: @g = external global i8{{$}}
+; M0: @g = external global i8
 ; M1: @g = global i8 42, comdat, !type !0
 @g = global i8 42, comdat, !type !0
 
-; M0: @g1 = external global i8{{$}}
+; M0: @g1 = external global i8
 ; M1: @g1 = global i8 43, !type !0
 @g1 = global i8 43, !type !0
 
diff --git a/llvm/test/Transforms/ThinLTOBitcodeWriter/unsplittable.ll b/llvm/test/Transforms/ThinLTOBitcodeWriter/unsplittable.ll
index c961179fd3d07..430071d617777 100644
--- a/llvm/test/Transforms/ThinLTOBitcodeWriter/unsplittable.ll
+++ b/llvm/test/Transforms/ThinLTOBitcodeWriter/unsplittable.ll
@@ -21,7 +21,7 @@
 ; CHECK: @llvm.global_ctors = appending global
 @llvm.global_ctors = appending global [1 x { i32, ptr, ptr }] [{ i32, ptr, ptr } { i32 65535, ptr @f, ptr null }]
 
-; CHECK: @g = internal global i8 42, !type !0
+; CHECK: @g = internal global i8 42, !type !1
 @g = internal global i8 42, !type !0
 
 declare void @sink(ptr)
diff --git a/llvm/test/Transforms/WholeProgramDevirt/branch-funnel-profile.ll b/llvm/test/Transforms/WholeProgramDevirt/branch-funnel-profile.ll
index f1a28ca8d681c..1b694812a42b5 100644
--- a/llvm/test/Transforms/WholeProgramDevirt/branch-funnel-profile.ll
+++ b/llvm/test/Transforms/WholeProgramDevirt/branch-funnel-profile.ll
@@ -6,28 +6,28 @@
 ; RUN: opt -passes=wholeprogramdevirt -whole-program-visibility -wholeprogramdevirt-summary-action=export -wholeprogramdevirt-read-summary=%S/Inputs/export.yaml -wholeprogramdevirt-write-summary=%t -S -o - %s | FileCheck --check-prefixes=RETP %s
 ; RUN: opt -passes='wholeprogramdevirt,default<O3>' -whole-program-visibility -wholeprogramdevirt-summary-action=export -wholeprogramdevirt-read-summary=%S/Inputs/export.yaml -wholeprogramdevirt-write-summary=%t  -S -o - %s | FileCheck --check-prefixes=O3 %s
 
-; RETP: define hidden void @__typeid_typeid1_0_branch_funnel(ptr nest %0, ...) !prof !11
-; RETP: define hidden void @__typeid_typeid1_rv_0_branch_funnel(ptr nest %0, ...) !prof !11
-; RETP: define internal void @branch_funnel(ptr nest %0, ...) !prof !10
-; RETP: define internal void @branch_funnel.1(ptr nest %0, ...) !prof !10 
-; RETP: !10 = !{!"function_entry_count", i64 1000}
-; RETP: !11 = !{!"function_entry_count", i64 3000}
-
-; NORETP: define hidden void @__typeid_typeid1_0_branch_funnel(ptr nest %0, ...) !prof !11
-; NORETP: define hidden void @__typeid_typeid1_rv_0_branch_funnel(ptr nest %0, ...) !prof !11
-; NORETP: define internal void @branch_funnel(ptr nest %0, ...) !prof !11
-; NORETP: define internal void @branch_funnel.1(ptr nest %0, ...) !prof !11
-; NORETP: !11 = !{!"unknown", !"wholeprogramdevirt"}
-
-; O3: define hidden void @__typeid_typeid1_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof !11
-; O3: define hidden void @__typeid_typeid1_rv_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof !11
-; O3: define internal void @branch_funnel(ptr nest %0, ...) unnamed_addr #5 !prof !10
-; O3: define internal void @branch_funnel.1(ptr nest %0, ...) unnamed_addr #5 !prof !10
-; O3: define hidden void @__typeid_typeid3_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof !12
-; O3: define hidden void @__typeid_typeid3_rv_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof !12
-; O3: !10 = !{!"function_entry_count", i64 1000}
-; O3: !11 = !{!"function_entry_count", i64 3000}
-; O3: !12 = !{!"unknown", !"wholeprogramdevirt"}
+; RETP: define hidden void @__typeid_typeid1_0_branch_funnel(ptr nest %0, ...) !prof ![[PROF1:[0-9]+]]
+; RETP: define hidden void @__typeid_typeid1_rv_0_branch_funnel(ptr nest %0, ...) !prof ![[PROF1]]
+; RETP: define internal void @branch_funnel(ptr nest %0, ...) !prof ![[PROF2:[0-9]+]]
+; RETP: define internal void @branch_funnel.1(ptr nest %0, ...) !prof ![[PROF2]]
+; RETP: ![[PROF2]] = !{!"function_entry_count", i64 1000}
+; RETP: ![[PROF1]] = !{!"function_entry_count", i64 3000}
+
+; NORETP: define hidden void @__typeid_typeid1_0_branch_funnel(ptr nest %0, ...) !prof ![[PROF1:[0-9]+]]
+; NORETP: define hidden void @__typeid_typeid1_rv_0_branch_funnel(ptr nest %0, ...) !prof ![[PROF1]]
+; NORETP: define internal void @branch_funnel(ptr nest %0, ...) !prof ![[PROF1]]
+; NORETP: define internal void @branch_funnel.1(ptr nest %0, ...) !prof ![[PROF1]]
+; NORETP: ![[PROF1]] = !{!"unknown", !"wholeprogramdevirt"}
+
+; O3: define hidden void @__typeid_typeid1_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof ![[PROF1:[0-9]+]]
+; O3: define hidden void @__typeid_typeid1_rv_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof ![[PROF1]]
+; O3: define internal void @branch_funnel(ptr nest %0, ...) unnamed_addr #5 !prof ![[PROF2:[0-9]+]]
+; O3: define internal void @branch_funnel.1(ptr nest %0, ...) unnamed_addr #5 !prof ![[PROF2]]
+; O3: define hidden void @__typeid_typeid3_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof ![[PROF3:[0-9]+]]
+; O3: define hidden void @__typeid_typeid3_rv_0_branch_funnel(ptr nest %0, ...) local_unnamed_addr #5 !prof ![[PROF3]]
+; O3: ![[PROF2]] = !{!"function_entry_count", i64 1000}
+; O3: ![[PROF1]] = !{!"function_entry_count", i64 3000}
+; O3: ![[PROF3]] = !{!"unknown", !"wholeprogramdevirt"}
 
 target datalayout = "e-p:64:64"
 target triple = "x86_64-unknown-linux-gnu"
diff --git a/llvm/test/Transforms/WholeProgramDevirt/export-single-impl.ll b/llvm/test/Transforms/WholeProgramDevirt/export-single-impl.ll
index c27b4b34ac04e..d58adeecae9ab 100644
--- a/llvm/test/Transforms/WholeProgramDevirt/export-single-impl.ll
+++ b/llvm/test/Transforms/WholeProgramDevirt/export-single-impl.ll
@@ -81,12 +81,12 @@ define void @vf2(ptr) {
   ret void
 }
 
-; CHECK: define hidden void @vf3.llvm.merged(ptr %0) {
+; CHECK: define hidden void @vf3.llvm.merged(ptr %0)
 define internal void @vf3(ptr) {
   ret void
 }
 
-; CHECK: define hidden void @vf4.llvm.merged(ptr %0) comdat {
+; CHECK: define hidden void @vf4.llvm.merged(ptr %0) comdat
 define internal void @vf4(ptr) comdat {
   ret void
 }
diff --git a/llvm/test/Transforms/WholeProgramDevirt/export-vcp.ll b/llvm/test/Transforms/WholeProgramDevirt/export-vcp.ll
index a81df69395a20..c38e5a06c0547 100644
--- a/llvm/test/Transforms/WholeProgramDevirt/export-vcp.ll
+++ b/llvm/test/Transforms/WholeProgramDevirt/export-vcp.ll
@@ -60,10 +60,10 @@ target datalayout = "e-p:64:64"
 ; CHECK: [[CVT3D:.*]] = private constant { [8 x i8], ptr, [0 x i8] } { [8 x i8] c"\00\00\00\00\00\00\00\01", ptr @vf1i1, [0 x i8] zeroinitializer }, !type !0
 @vt3d = constant ptr @vf1i1, !type !0
 
-; CHECK: [[CVT4A:.*]] = private constant { [8 x i8], ptr, [0 x i8] } { [8 x i8] c"\00\00\00\00\01\00\00\00", ptr @vf1i32, [0 x i8] zeroinitializer }, !type !1
+; CHECK: [[CVT4A:.*]] = private constant { [8 x i8], ptr, [0 x i8] } { [8 x i8] c"\00\00\00\00\01\00\00\00", ptr @vf1i32, [0 x i8] zeroinitializer }, !type !5
 @vt4a = constant ptr @vf1i32, !type !1
 
-; CHECK: [[CVT4B:.*]] = private constant { [8 x i8], ptr, [0 x i8] } { [8 x i8] c"\00\00\00\00\02\00\00\00", ptr @vf2i32, [0 x i8] zeroinitializer }, !type !1
+; CHECK: [[CVT4B:.*]] = private constant { [8 x i8], ptr, [0 x i8] } { [8 x i8] c"\00\00\00\00\02\00\00\00", ptr @vf2i32, [0 x i8] zeroinitializer }, !type !5
 @vt4b = constant ptr @vf2i32, !type !1
 
 ; X86: @__typeid_typeid3_0_12_24_bit = hidden alias i8, inttoptr (i32 1 to ptr)
@@ -94,7 +94,7 @@ define i32 @vf2i32(ptr %this, i32, i32) readnone {
 }
 
 ; CHECK: !0 = !{i32 8, !"typeid3"}
-; CHECK: !1 = !{i32 8, !"typeid4"}
+; CHECK: !5 = !{i32 8, !"typeid4"}
 
 !0 = !{i32 0, !"typeid3"}
 !1 = !{i32 0, !"typeid4"}
diff --git a/llvm/test/tools/gold/X86/devirt_vcall_vis_export_dynamic.ll b/llvm/test/tools/gold/X86/devirt_vcall_vis_export_dynamic.ll
index 1976f8f539fd6..2e6a6f0769ef8 100644
--- a/llvm/test/tools/gold/X86/devirt_vcall_vis_export_dynamic.ll
+++ b/llvm/test/tools/gold/X86/devirt_vcall_vis_export_dynamic.ll
@@ -26,7 +26,7 @@
 ; RUN: llvm-dis %t.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t4.o %s
+; RUN: opt -passes=assign-guid -o %t4.o %s
 ; RUN: %gold -m elf_x86_64 -plugin %llvmshlibdir/LLVMgold%shlibext \
 ; RUN:   --plugin-opt=whole-program-visibility \
 ; RUN:   --plugin-opt=save-temps \
@@ -92,7 +92,7 @@
 ; RUN:   --export-dynamic 2>&1 | FileCheck /dev/null --implicit-check-not single-impl --allow-empty
 
 ;; Regular LTO WPD
-; RUN: opt -relocation-model=pic -o %t5.o %s
+; RUN: opt -passes=assign-guid -relocation-model=pic -o %t5.o %s
 ; RUN: %gold -m elf_x86_64 -plugin %llvmshlibdir/LLVMgold%shlibext \
 ; RUN: 	 %t5.o -o %t5.so -shared
 ; RUN: %gold -m elf_x86_64 -plugin %llvmshlibdir/LLVMgold%shlibext \
diff --git a/llvm/test/tools/gold/X86/devirt_vcall_vis_public.ll b/llvm/test/tools/gold/X86/devirt_vcall_vis_public.ll
index 4e84a21ebfdfe..a97d59b8b1856 100644
--- a/llvm/test/tools/gold/X86/devirt_vcall_vis_public.ll
+++ b/llvm/test/tools/gold/X86/devirt_vcall_vis_public.ll
@@ -21,7 +21,7 @@
 ; RUN: llvm-dis %t.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t4.o %s
+; RUN: opt -passes=assign-guid -o %t4.o %s
 ; RUN: %gold -m elf_x86_64 -plugin %llvmshlibdir/LLVMgold%shlibext \
 ; RUN:   --plugin-opt=whole-program-visibility \
 ; RUN:   --plugin-opt=save-temps \
diff --git a/llvm/test/tools/gold/X86/devirt_vcall_vis_shared_def.ll b/llvm/test/tools/gold/X86/devirt_vcall_vis_shared_def.ll
index 2a3cfdcfa03bd..6d05598e8b302 100644
--- a/llvm/test/tools/gold/X86/devirt_vcall_vis_shared_def.ll
+++ b/llvm/test/tools/gold/X86/devirt_vcall_vis_shared_def.ll
@@ -26,8 +26,8 @@
 ; RUN: llvm-dis %t1b.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t1c.o %s
-; RUN: opt -o %t2c.o %S/Inputs/devirt_vcall_vis_shared_def.ll
+; RUN: opt -passes=assign-guid -o %t1c.o %s
+; RUN: opt -passes=assign-guid -o %t2c.o %S/Inputs/devirt_vcall_vis_shared_def.ll
 ; RUN: %gold -m elf_x86_64 -plugin %llvmshlibdir/LLVMgold%shlibext \
 ; RUN:   --plugin-opt=whole-program-visibility \
 ; RUN:   --plugin-opt=save-temps \
diff --git a/llvm/test/tools/gold/X86/thinlto_weak_library.ll b/llvm/test/tools/gold/X86/thinlto_weak_library.ll
index 6c193197699dc..6f91ca2c79e28 100644
--- a/llvm/test/tools/gold/X86/thinlto_weak_library.ll
+++ b/llvm/test/tools/gold/X86/thinlto_weak_library.ll
@@ -24,7 +24,7 @@
 ; copy of f() (and didn't simply convert to available_externally, which
 ; would incorrectly enable inlining).
 ; RUN: llvm-dis %t2.o.1.promote.bc -o - | FileCheck %s
-; CHECK: declare i32 @f()
+; CHECK: declare !guid !{{[0-9]+}} i32 @f()
 
 ; ModuleID = 'thinlto_weak_library.c'
 source_filename = "thinlto_weak_library.c"
diff --git a/llvm/test/tools/gold/X86/thinlto_weak_resolution.ll b/llvm/test/tools/gold/X86/thinlto_weak_resolution.ll
index cab79b1d4975f..a9727fde7ac76 100644
--- a/llvm/test/tools/gold/X86/thinlto_weak_resolution.ll
+++ b/llvm/test/tools/gold/X86/thinlto_weak_resolution.ll
@@ -80,7 +80,7 @@ entry:
   ret void
 }
 ; IMPORT: define weak void @linkoncefunc()
-; IMPORT2: declare void @linkoncefunc()
+; IMPORT2: declare !guid !{{[0-9]+}} void @linkoncefunc()
 define linkonce void @linkoncefunc() #0 {
 entry:
   ret void
@@ -92,7 +92,7 @@ entry:
   ret void
 }
 ; IMPORT: define weak void @weakfunc()
-; IMPORT2: declare void @weakfunc()
+; IMPORT2: declare !guid !{{[0-9]+}} void @weakfunc()
 define weak void @weakfunc() #0 {
 entry:
   ret void
diff --git a/llvm/test/tools/gold/X86/v1.16/devirt_vcall_vis_export_dynamic.ll b/llvm/test/tools/gold/X86/v1.16/devirt_vcall_vis_export_dynamic.ll
index 82880a2483fa2..65e2fd0ed7555 100644
--- a/llvm/test/tools/gold/X86/v1.16/devirt_vcall_vis_export_dynamic.ll
+++ b/llvm/test/tools/gold/X86/v1.16/devirt_vcall_vis_export_dynamic.ll
@@ -25,7 +25,7 @@
 ; RUN: llvm-dis %t.o.4.opt.bc -o - | FileCheck %s --check-prefix=CHECK-IR
 
 ;; Regular LTO WPD
-; RUN: opt -o %t4.o %s
+; RUN: opt -passes=assign-guid -o %t4.o %s
 ; RUN: %gold -m elf_x86_64 -plugin %llvmshlibdir/LLVMgold%shlibext \
 ; RUN:   --plugin-opt=whole-program-visibility \
 ; RUN:   --plugin-opt=save-temps \
diff --git a/llvm/tools/llvm-link/llvm-link.cpp b/llvm/tools/llvm-link/llvm-link.cpp
index f9fac9032039c..e49082f2d7bfb 100644
--- a/llvm/tools/llvm-link/llvm-link.cpp
+++ b/llvm/tools/llvm-link/llvm-link.cpp
@@ -363,8 +363,9 @@ static bool importFunctions(const char *argv0, Module &DestModule) {
     // definition, so make the import type definition directly.
     // FIXME: A follow-up patch should add test coverage for import declaration
     // in `llvm-link` CLI (e.g., by introducing a new command line option).
+    const auto GUID = F->getGUIDOrFallback();
     ImportList.addDefinition(
-        FileNameStringCache.insert(FileName).first->getKey(), F->getGUID());
+        FileNameStringCache.insert(FileName).first->getKey(), GUID);
   }
   auto CachedModuleLoader = [&](StringRef Identifier) {
     return ModuleLoaderCache.takeModule(std::string(Identifier));
diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp
index c303048137648..f72f3ef524974 100644
--- a/llvm/tools/opt/NewPMDriver.cpp
+++ b/llvm/tools/opt/NewPMDriver.cpp
@@ -41,6 +41,7 @@
 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
 #include "llvm/Transforms/Scalar/LoopPassManager.h"
+#include "llvm/Transforms/Utils/AssignGUID.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include "llvm/Transforms/Utils/ProfileVerify.h"
 
@@ -527,14 +528,21 @@ bool llvm::runPassPipeline(
   case OK_NoOutput:
     break; // No output pass needed.
   case OK_OutputAssembly:
+    if (EmitSummaryIndex) {
+      MPM.addPass(AssignGUIDPass());
+    }
     MPM.addPass(PrintModulePass(
         Out->os(), "", ShouldPreserveAssemblyUseListOrder, EmitSummaryIndex));
     break;
   case OK_OutputBitcode:
+    if (EmitSummaryIndex) {
+      MPM.addPass(AssignGUIDPass());
+    }
     MPM.addPass(BitcodeWriterPass(Out->os(), ShouldPreserveBitcodeUseListOrder,
                                   EmitSummaryIndex, EmitModuleHash));
     break;
   case OK_OutputThinLTOBitcode:
+    MPM.addPass(AssignGUIDPass());
     MPM.addPass(ThinLTOBitcodeWriterPass(
         Out->os(), ThinLTOLinkOut ? &ThinLTOLinkOut->os() : nullptr,
         ShouldPreserveBitcodeUseListOrder));
diff --git a/llvm/tools/opt/optdriver.cpp b/llvm/tools/opt/optdriver.cpp
index 3119db716d509..a178643f6cc82 100644
--- a/llvm/tools/opt/optdriver.cpp
+++ b/llvm/tools/opt/optdriver.cpp
@@ -57,6 +57,7 @@
 #include "llvm/TargetParser/SubtargetFeature.h"
 #include "llvm/TargetParser/Triple.h"
 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
+#include "llvm/Transforms/Utils/AssignGUID.h"
 #include "llvm/Transforms/Utils/Cloning.h"
 #include "llvm/Transforms/Utils/Debugify.h"
 #include <algorithm>
@@ -624,6 +625,12 @@ optMain(int argc, char **argv,
     return 1;
   }
 
+  // Manually assign GUIDs -- updateVCallVisibilityInModule accesses GUIDs, and
+  // there's no way to specify it in the pass pipeline since this runs before
+  // any pass given on the command line.
+  if (hasWholeProgramVisibility(/*WholeProgramVisibilityEnabledInLTO=*/false))
+    AssignGUIDPass::runOnModule(*M);
+
   // Enable testing of whole program devirtualization on this module by invoking
   // the facility for updating public visibility to linkage unit visibility when
   // specified by an internal option. This is normally done during LTO which is



More information about the cfe-commits mailing list