diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td b/clang/include/clang/Basic/DiagnosticParseKinds.td index c724136a7fdaf..888c0ce16c922 100644 --- a/clang/include/clang/Basic/DiagnosticParseKinds.td +++ b/clang/include/clang/Basic/DiagnosticParseKinds.td @@ -1365,6 +1365,9 @@ def err_pragma_comment_unknown_kind : Error<"unknown kind of pragma comment">; // PS4 recognizes only #pragma comment(lib) def warn_pragma_comment_ignored : Warning<"'#pragma comment %0' ignored">, InGroup; +def warn_pragma_comment_once : Warning<"'#pragma comment %0' " + "can be specified only once per translation unit - ignored">, + InGroup; // - #pragma detect_mismatch def err_pragma_detect_mismatch_malformed : Error< "pragma detect_mismatch is malformed; it requires two comma-separated " diff --git a/clang/include/clang/Basic/PragmaKinds.h b/clang/include/clang/Basic/PragmaKinds.h index 42f049f7323d2..52ca58855d460 100644 --- a/clang/include/clang/Basic/PragmaKinds.h +++ b/clang/include/clang/Basic/PragmaKinds.h @@ -17,7 +17,8 @@ enum PragmaMSCommentKind { PCK_Lib, // #pragma comment(lib, ...) PCK_Compiler, // #pragma comment(compiler, ...) PCK_ExeStr, // #pragma comment(exestr, ...) - PCK_User // #pragma comment(user, ...) + PCK_User, // #pragma comment(user, ...) + PCK_Copyright // #pragma comment(copyright, ...) }; enum PragmaMSStructKind { diff --git a/clang/lib/AST/TextNodeDumper.cpp b/clang/lib/AST/TextNodeDumper.cpp index 8f7fe3bea4e8f..cc4aa7d4820e1 100644 --- a/clang/lib/AST/TextNodeDumper.cpp +++ b/clang/lib/AST/TextNodeDumper.cpp @@ -2523,6 +2523,9 @@ void TextNodeDumper::VisitPragmaCommentDecl(const PragmaCommentDecl *D) { case PCK_User: OS << "user"; break; + case PCK_Copyright: + OS << "copyright"; + break; } StringRef Arg = D->getArg(); if (!Arg.empty()) diff --git a/clang/lib/CodeGen/CodeGenModule.cpp b/clang/lib/CodeGen/CodeGenModule.cpp index f6f7f22a09004..4bd63afac4ed5 100644 --- a/clang/lib/CodeGen/CodeGenModule.cpp +++ b/clang/lib/CodeGen/CodeGenModule.cpp @@ -41,6 +41,7 @@ #include "clang/Basic/CodeGenOptions.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/Module.h" +#include "clang/Basic/PragmaKinds.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/Version.h" @@ -1555,6 +1556,12 @@ void CodeGenModule::Release() { EmitBackendOptionsMetadata(getCodeGenOpts()); + // Emit copyright metadata + if (CopyrightCommentInTU) { + auto *NMD = getModule().getOrInsertNamedMetadata("loadtime.copyright.comment"); + NMD->addOperand(CopyrightCommentInTU); + } + // If there is device offloading code embed it in the host now. EmbedObject(&getModule(), CodeGenOpts, *getFileSystem(), getDiags()); @@ -3317,6 +3324,24 @@ void CodeGenModule::AddDependentLib(StringRef Lib) { LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); } +/// Process the #pragma comment(copyright, "copyright string ") +/// and create llvm metadata for the copyright +void CodeGenModule::ProcessPragmaComment(PragmaMSCommentKind Kind, + StringRef Comment) { + + if (!getTriple().isOSAIX() || Kind != PCK_Copyright) + return; + + assert( + !CopyrightCommentInTU && + "Only one copyright comment should be present in the Translation Unit"); + // Create llvm metadata with the comment string + auto &C = getLLVMContext(); + llvm::Metadata *Ops[] = {llvm::MDString::get(C, Comment.str())}; + auto *Node = llvm::MDNode::get(C, Ops); + CopyrightCommentInTU = Node; +} + /// Add link options implied by the given module, including modules /// it depends on, using a postorder walk. static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, @@ -7453,6 +7478,12 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) { case PCK_Lib: AddDependentLib(PCD->getArg()); break; + case PCK_Copyright: + // Skip pragmas deserialized from modules/PCHs + if (PCD->isFromASTFile()) + break; + ProcessPragmaComment(PCD->getCommentKind(), PCD->getArg()); + break; case PCK_Compiler: case PCK_ExeStr: case PCK_User: diff --git a/clang/lib/CodeGen/CodeGenModule.h b/clang/lib/CodeGen/CodeGenModule.h index 3971b296b3f80..beb851f2708ee 100644 --- a/clang/lib/CodeGen/CodeGenModule.h +++ b/clang/lib/CodeGen/CodeGenModule.h @@ -587,6 +587,10 @@ class CodeGenModule : public CodeGenTypeCache { /// A vector of metadata strings for dependent libraries for ELF. SmallVector ELFDependentLibraries; + /// Single module-level copyright comment (if any). + /// We only ever accept one per TU. + llvm::MDNode *CopyrightCommentInTU = nullptr; + /// @name Cache for Objective-C runtime types /// @{ @@ -1458,6 +1462,8 @@ class CodeGenModule : public CodeGenTypeCache { /// Appends a dependent lib to the appropriate metadata value. void AddDependentLib(StringRef Lib); + /// Process pragma comment + void ProcessPragmaComment(PragmaMSCommentKind Kind, StringRef Comment); llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD); diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp index 98933811265e8..a9e4e8ec280de 100644 --- a/clang/lib/Parse/ParsePragma.cpp +++ b/clang/lib/Parse/ParsePragma.cpp @@ -236,6 +236,7 @@ struct PragmaCommentHandler : public PragmaHandler { private: Sema &Actions; + bool SeenCopyrightInTU = false; // TU-scoped }; struct PragmaDetectMismatchHandler : public PragmaHandler { @@ -473,7 +474,8 @@ void Parser::initializePragmaHandlers() { PP.AddPragmaHandler(OpenACCHandler.get()); if (getLangOpts().MicrosoftExt || - getTargetInfo().getTriple().isOSBinFormatELF()) { + getTargetInfo().getTriple().isOSBinFormatELF() || + getTargetInfo().getTriple().isOSAIX()) { MSCommentHandler = std::make_unique(Actions); PP.AddPragmaHandler(MSCommentHandler.get()); } @@ -595,7 +597,8 @@ void Parser::resetPragmaHandlers() { OpenACCHandler.reset(); if (getLangOpts().MicrosoftExt || - getTargetInfo().getTriple().isOSBinFormatELF()) { + getTargetInfo().getTriple().isOSBinFormatELF() || + getTargetInfo().getTriple().isOSAIX()) { PP.RemovePragmaHandler(MSCommentHandler.get()); MSCommentHandler.reset(); } @@ -3201,13 +3204,26 @@ void PragmaCommentHandler::HandlePragma(Preprocessor &PP, // Verify that this is one of the 5 explicitly listed options. IdentifierInfo *II = Tok.getIdentifierInfo(); PragmaMSCommentKind Kind = - llvm::StringSwitch(II->getName()) - .Case("linker", PCK_Linker) - .Case("lib", PCK_Lib) - .Case("compiler", PCK_Compiler) - .Case("exestr", PCK_ExeStr) - .Case("user", PCK_User) - .Default(PCK_Unknown); + llvm::StringSwitch(II->getName()) + .Case("linker", PCK_Linker) + .Case("lib", PCK_Lib) + .Case("compiler", PCK_Compiler) + .Case("exestr", PCK_ExeStr) + .Case("user", PCK_User) + .Case("copyright", PCK_Copyright) + .Default(PCK_Unknown); + + // Restrict copyright to AIX targets only + if (!PP.getTargetInfo().getTriple().isOSAIX()) { + switch (Kind) { + case PCK_Copyright: + Kind = PCK_Unknown; + break; + default: + break; + } + } + if (Kind == PCK_Unknown) { PP.Diag(Tok.getLocation(), diag::err_pragma_comment_unknown_kind); return; @@ -3219,6 +3235,16 @@ void PragmaCommentHandler::HandlePragma(Preprocessor &PP, return; } + // On AIX, pragma comment copyright can each appear only once in a TU. + if (Kind == PCK_Copyright) { + if (SeenCopyrightInTU) { + PP.Diag(Tok.getLocation(), diag::warn_pragma_comment_once) + << II->getName(); + return; + } + SeenCopyrightInTU = true; + } + // Read the optional string if present. PP.Lex(Tok); std::string ArgumentString; @@ -3245,6 +3271,10 @@ void PragmaCommentHandler::HandlePragma(Preprocessor &PP, return; } + // Accept and ignore well-formed copyright with empty string. + if (Kind == PCK_Copyright && ArgumentString.empty()) + return; + // If the pragma is lexically sound, notify any interested PPCallbacks. if (PP.getPPCallbacks()) PP.getPPCallbacks()->PragmaComment(CommentLoc, II, ArgumentString); diff --git a/clang/test/CodeGen/PowerPC/pragma-comment-copyright-aix-modules.cpp b/clang/test/CodeGen/PowerPC/pragma-comment-copyright-aix-modules.cpp new file mode 100644 index 0000000000000..e1fc99796f867 --- /dev/null +++ b/clang/test/CodeGen/PowerPC/pragma-comment-copyright-aix-modules.cpp @@ -0,0 +1,26 @@ +// RUN: split-file %s %t + +// Build the module interface to a PCM +// RUN: %clang_cc1 -std=c++20 -triple powerpc-ibm-aix \ +// RUN: -emit-module-interface %t/copymod.cppm -o %t/copymod.pcm + +// verify that module interface emit copyright string when compiled to assembly +// RUN: %clang_cc1 -std=c++20 -triple powerpc-ibm-aix -S %t/copymod.cppm -o - \ +// RUN: | FileCheck %s --check-prefix=CHECK-MOD +// CHECK-MOD: .string "module me" + +// Compile an importing TU that uses the prebuilt module and verify that it +// does NOT re-emit the module's copyright string. +// RUN: %clang_cc1 -std=c++20 -triple powerpc-ibm-aix \ +// RUN: -fprebuilt-module-path=%t -S %t/importmod.cc -o - \ +// RUN: | FileCheck %s +// CHECK-NOT: .string "module me" + +//--- copymod.cppm +export module copymod; +#pragma comment(copyright, "module me") +export inline void f() {} + +//--- importmod.cc +import copymod; +void g() { f(); } diff --git a/clang/test/CodeGen/PowerPC/pragma-comment-copyright-aix.c b/clang/test/CodeGen/PowerPC/pragma-comment-copyright-aix.c new file mode 100644 index 0000000000000..5ace127629dda --- /dev/null +++ b/clang/test/CodeGen/PowerPC/pragma-comment-copyright-aix.c @@ -0,0 +1,34 @@ +// RUN: %clang_cc1 %s -triple powerpc-ibm-aix -O0 -disable-llvm-passes -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 %s -triple powerpc64-ibm-aix -O0 -disable-llvm-passes -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 %s -triple powerpc-ibm-aix -verify +// RUN: %clang_cc1 %s -triple powerpc64-ibm-aix -verify +// RUN: %clang_cc1 %s -DTEST_EMPTY_COPYRIGHT -triple powerpc-ibm-aix -verify + +// RUN: %clang_cc1 %s -x c++ -triple powerpc-ibm-aix -O0 -disable-llvm-passes -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 %s -x c++ -triple powerpc64-ibm-aix -O0 -disable-llvm-passes -emit-llvm -o - | FileCheck %s +// RUN: %clang_cc1 %s -x c++ -triple powerpc-ibm-aix -verify +// RUN: %clang_cc1 %s -x c++ -triple powerpc64-ibm-aix -verify +// RUN: %clang_cc1 %s -x c++ -DTEST_EMPTY_COPYRIGHT -triple powerpc-ibm-aix -verify + +#ifndef TEST_EMPTY_COPYRIGHT +// Test basic pragma comment types +#pragma comment(copyright, "@(#) Copyright") + +// Test duplicate copyright - should warn and ignore +#pragma comment(copyright, "Duplicate Copyright") // expected-warning {{'#pragma comment copyright' can be specified only once per translation unit - ignored}} + +int main() { return 0; } + +// Check that both metadata sections are present +// CHECK: !loadtime.copyright.comment = !{![[copyright:[0-9]+]]} + +// Check individual metadata content +// CHECK: ![[copyright]] = !{!"@(#) Copyright"} + +#else +// Test empty copyright string - valid with no warning +#pragma comment(copyright, "") // expected-no-diagnostics + +int main() { return 0; } + +#endif \ No newline at end of file diff --git a/llvm/include/llvm/Transforms/Utils/CopyrightMetadataPass.h b/llvm/include/llvm/Transforms/Utils/CopyrightMetadataPass.h new file mode 100644 index 0000000000000..38b9d724905f9 --- /dev/null +++ b/llvm/include/llvm/Transforms/Utils/CopyrightMetadataPass.h @@ -0,0 +1,25 @@ +//===-- CopyrightMetadataPass.h - Lower AIX copyright metadata -*- 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 +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_TRANSFORMS_UTILS_COPYRIGHTMETADATAPASS_H +#define LLVM_TRANSFORMS_UTILS_COPYRIGHTMETADATAPASS_H + +#include "llvm/IR/PassManager.h" + +namespace llvm { +class CopyrightMetadataPass : public PassInfoMixin { +public: + PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM); + + static bool isRequired() { return true; } +}; + + +} // namespace llvm + +#endif // LLVM_TRANSFORMS_UTILS_COPYRIGHTMETADATAPASS_H \ No newline at end of file diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp index c234623caecf9..705580634f14b 100644 --- a/llvm/lib/Passes/PassBuilder.cpp +++ b/llvm/lib/Passes/PassBuilder.cpp @@ -346,6 +346,7 @@ #include "llvm/Transforms/Utils/BreakCriticalEdges.h" #include "llvm/Transforms/Utils/CanonicalizeAliases.h" #include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h" +#include "llvm/Transforms/Utils/CopyrightMetadataPass.h" #include "llvm/Transforms/Utils/CountVisits.h" #include "llvm/Transforms/Utils/DXILUpgrade.h" #include "llvm/Transforms/Utils/Debugify.h" diff --git a/llvm/lib/Passes/PassBuilderPipelines.cpp b/llvm/lib/Passes/PassBuilderPipelines.cpp index 256cf9d4cd1ce..a17ac863a533e 100644 --- a/llvm/lib/Passes/PassBuilderPipelines.cpp +++ b/llvm/lib/Passes/PassBuilderPipelines.cpp @@ -134,6 +134,7 @@ #include "llvm/Transforms/Utils/AddDiscriminators.h" #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" #include "llvm/Transforms/Utils/CanonicalizeAliases.h" +#include "llvm/Transforms/Utils/CopyrightMetadataPass.h" #include "llvm/Transforms/Utils/CountVisits.h" #include "llvm/Transforms/Utils/EntryExitInstrumenter.h" #include "llvm/Transforms/Utils/ExtraPassManager.h" @@ -1446,6 +1447,9 @@ PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level, const bool LTOPreLink = isLTOPreLink(LTOPhase); ModulePassManager MPM; + // Process copyright metadata early, before any optimizations + MPM.addPass(CopyrightMetadataPass()); + // Run partial inlining pass to partially inline functions that have // large bodies. if (RunPartialInlining) @@ -2219,6 +2223,9 @@ PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level, ModulePassManager MPM; + // Process copyright metadata at O0 before any other transformations + MPM.addPass(CopyrightMetadataPass()); + // Perform pseudo probe instrumentation in O0 mode. This is for the // consistency between different build modes. For example, a LTO build can be // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in diff --git a/llvm/lib/Passes/PassRegistry.def b/llvm/lib/Passes/PassRegistry.def index f0e7d36f78aab..f523707f083ca 100644 --- a/llvm/lib/Passes/PassRegistry.def +++ b/llvm/lib/Passes/PassRegistry.def @@ -60,6 +60,7 @@ MODULE_PASS("check-debugify", NewPMCheckDebugifyPass()) MODULE_PASS("constmerge", ConstantMergePass()) MODULE_PASS("coro-cleanup", CoroCleanupPass()) MODULE_PASS("coro-early", CoroEarlyPass()) +MODULE_PASS("copyright-metadata", CopyrightMetadataPass()) MODULE_PASS("cross-dso-cfi", CrossDSOCFIPass()) MODULE_PASS("ctx-instr-gen", PGOInstrumentationGen(PGOInstrumentationType::CTXPROF)) diff --git a/llvm/lib/Transforms/Utils/CMakeLists.txt b/llvm/lib/Transforms/Utils/CMakeLists.txt index f367ca2fdf56b..13643e9f411b9 100644 --- a/llvm/lib/Transforms/Utils/CMakeLists.txt +++ b/llvm/lib/Transforms/Utils/CMakeLists.txt @@ -17,6 +17,7 @@ add_llvm_component_library(LLVMTransformUtils CodeLayout.cpp CodeMoverUtils.cpp ControlFlowUtils.cpp + CopyrightMetadataPass.cpp CtorUtils.cpp CountVisits.cpp Debugify.cpp diff --git a/llvm/lib/Transforms/Utils/CopyrightMetadataPass.cpp b/llvm/lib/Transforms/Utils/CopyrightMetadataPass.cpp new file mode 100644 index 0000000000000..edba4b479df06 --- /dev/null +++ b/llvm/lib/Transforms/Utils/CopyrightMetadataPass.cpp @@ -0,0 +1,160 @@ +//===-- CopyrightMetadataPass.cpp - Lower copyright metadata -------------===// +// +// 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 +// +//===---------------------------------------------------------------------===// +// +// CopyrightMetadataPass pass lowers module-level copyright metadata emitted by +// Clang: +// +// !loadtime.copyright.comment = !{!"Copyright ..."} +// +// into concrete, translation-unit–local globals to ensure that copyright +// strings: +// - survive all optimization and LTO pipelines, +// - are not removed by linker garbage collection, and +// - remain visible in the final XCOFF binary. +// +// For each module (translation unit), the pass performs the following: +// +// 1. Creates a null-terminated, internal constant string global +// (`__loadtime_copyright_str`) containing the copyright text in +// `__copyright_comment` section. +// +// 2. Marks the string in `llvm.used` so it cannot be dropped by +// optimization or LTO. +// +// 3. Attaches `!implicit.ref` metadata referencing the string to every +// defined function in the module. The PowerPC AIX backend recognizes +// this metadata and emits a `.ref` directive from the function to the +// string, creating a concrete relocation that prevents the linker from +// discarding it (as long as the referencing symbol is kept). +// +// Input IR: +// !loadtime.copyright.comment = !{!"Copyright"} +// Output IR: +// @__loadtime_copyright_str = internal constant [N x i8] c"Copyright\00", +// section "__copyright_comment" +// @llvm.used = appending global [1 x ptr] [ptr @__loadtime_copyright_str] +// +// define i32 @func() !implicit.ref !5 { ... } +// !5 = !{ptr @__loadtime_copyright_str} +// +// The copyright string is placed in the "__copyright_comment" section (mapped to +// an XCOFF csect with [RO] storage class), making it easily identifiable in +// object files and executables. The R_REF relocation prevents the linker +// from discarding this section during garbage collection. Copyright string (if +// kept by the linker) is expected to be loaded at run time. +//===----------------------------------------------------------------------===// + +#include "llvm/Transforms/Utils/CopyrightMetadataPass.h" + +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/IR/Attributes.h" +#include "llvm/IR/Constants.h" +#include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/Function.h" +#include "llvm/IR/GlobalValue.h" +#include "llvm/IR/GlobalVariable.h" +#include "llvm/IR/MDBuilder.h" +#include "llvm/IR/Metadata.h" +#include "llvm/IR/Module.h" +#include "llvm/IR/Type.h" +#include "llvm/IR/Value.h" +#include "llvm/Passes/PassBuilder.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/Debug.h" +#include "llvm/TargetParser/Triple.h" +#include "llvm/Transforms/Utils/ModuleUtils.h" + +#define DEBUG_TYPE "copyright-metadata" + +using namespace llvm; + +static cl::opt + DisableCopyrightMetadata("disable-copyright-metadata", cl::ReallyHidden, + cl::desc("Disable copyright metadata pass."), + cl::init(false)); + +static bool isAIXTriple(const Module &M) { + return Triple(M.getTargetTriple()).isOSAIX(); +} + +PreservedAnalyses CopyrightMetadataPass::run(Module &M, + ModuleAnalysisManager &AM) { + if (DisableCopyrightMetadata || !isAIXTriple(M)) + return PreservedAnalyses::all(); + + LLVMContext &Ctx = M.getContext(); + + // Single-metadata: !loadtime.copyright.comment = !{!0} + // Each operand node is expected to have one MDString operand. + NamedMDNode *MD = M.getNamedMetadata("loadtime.copyright.comment"); + if (!MD || MD->getNumOperands() == 0) + return PreservedAnalyses::all(); + + // At this point we are guarateed that one TU contains a single copyright + // metadata entry. Create TU-local string global for that metadata entry. + MDNode *MdNode = MD->getOperand(0); + if (!MdNode || MdNode->getNumOperands() == 0) + return PreservedAnalyses::all(); + + auto *MdString = dyn_cast_or_null(MdNode->getOperand(0)); + if (!MdString) + return PreservedAnalyses::all(); + + StringRef Text = MdString->getString(); + if (Text.empty()) + return PreservedAnalyses::all(); + + // 1. Create a single NULL-terminated string global + Constant *StrInit = ConstantDataArray::getString(Ctx, Text, /*AddNull=*/true); + + // Internal, constant, TU-local — avoids duplicate symbol issues across TUs. + auto *StrGV = new GlobalVariable(M, StrInit->getType(), + /*isConstant=*/true, + GlobalValue::InternalLinkage, StrInit, + /*Name=*/"__loadtime_copyright_str"); + // Set unnamed_addr to allow the linker to merge identical strings + StrGV->setUnnamedAddr(GlobalValue::UnnamedAddr::Global); + StrGV->setAlignment(Align(1)); + // Place in the "__copyright_comment" section. + // Backend maps this to an appropriate XCOFF csect (typically [RO]) + // The section will appear in assembly as: + // .csect __copyright_comment[RO],2 + StrGV->setSection("__copyright_comment"); + + // 2. Add the string to llvm.used to prevent LLVM optimization/LTO passes from + // removing it. + appendToUsed(M, {StrGV}); + + // 3. Attach !implicit ref to every defined function + // Create a metadata node pointing to the copyright string: + // !N = !{ptr @__loadtime_copyright_str} + Metadata *Ops[] = {ConstantAsMetadata::get(StrGV)}; + MDNode *ImplicitRefMD = MDNode::get(Ctx, Ops); + + // Lambda to attach implicit.ref metadata to a function. + // The backend will translate this into .ref assembly directives. + auto AddImplicitRef = [&](Function &F) { + if (F.isDeclaration()) + return; + // Attach the implicit.ref metadata to the function + F.setMetadata("implicit.ref", ImplicitRefMD); + LLVM_DEBUG(dbgs() << "[copyright] attached implicit.ref to function: " + << F.getName() << "\n"); + }; + + // Process all functions in the module + for (Function &F : M) + AddImplicitRef(F); + + // Cleanup the processed metadata. + MD->eraseFromParent(); + LLVM_DEBUG(dbgs() << "[copyright] created string and anchor for module\n"); + + return PreservedAnalyses::all(); +} diff --git a/llvm/test/Transforms/CopyrightMetadata/copyright-metadata.ll b/llvm/test/Transforms/CopyrightMetadata/copyright-metadata.ll new file mode 100644 index 0000000000000..53140489a34f2 --- /dev/null +++ b/llvm/test/Transforms/CopyrightMetadata/copyright-metadata.ll @@ -0,0 +1,59 @@ +; RUN: opt -passes=copyright-metadata -S %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-O0 + +; Verify that copyright-metadata is enabled by default on all opt pipelines. +; RUN: opt --O0 -S %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-O0 +; RUN: opt --O1 -S %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-ON +; RUN: opt --O2 -S %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-ON +; RUN: opt --O3 -S %s -o - | FileCheck %s --check-prefixes=CHECK,CHECK-ON + +; Verify that CopyrightMetadataPass lowers !loadtime.copyright.comment +; into concrete, translation-unit–local globals. +; +; For each module (translation unit), the pass performs the following: +; +; 1. Creates a null-terminated, internal constant string global +; (`__loadtime_copyright_str`) containing the copyright text in +; `__copyright_comment` section. +; +; 2. Marks the string in `llvm.used` so it cannot be dropped by +; optimization or LTO. +; +; 3. Attaches `!implicit.ref` metadata referencing the string to every +; defined function in the module. The PowerPC AIX backend recognizes +; this metadata and emits a `.ref` directive from the function to the +; string, creating a concrete relocation that prevents the linker from +; discarding it (as long as the referencing symbol is kept). + +target triple = "powerpc-ibm-aix" + +define void @f0() { +entry: + ret void +} +define i32 @main() { +entry: + ret i32 0 +} + +!llvm.module.flags = !{!0} +!0 = !{i32 1, !"wchar_size", i32 2} + +!loadtime.copyright.comment = !{!1} +!1 = !{!"@(#) Copyright IBM 2025"} + + +; ---- Globals-------------------------------------------- +; CHECK: @__loadtime_copyright_str = internal unnamed_addr constant [24 x i8] c"@(#) Copyright IBM 2025\00", section "__copyright_comment", align 1 +; Preservation in llvm.used sets +; CHECK-NEXT: @llvm.used = appending global [1 x ptr] [ptr @__loadtime_copyright_str], section "llvm.metadata" +; CHECK-NOT: ![[copyright:[0-9]+]] = !{!"@(#) Copyright IBM 2025"} + +; Function has an implicit ref MD pointing at the string: +; CHECK-O0: define void @f0() !implicit.ref ![[MD:[0-9]+]] +; CHECK-ON: define void @f0() local_unnamed_addr #0 !implicit.ref ![[MD:[0-9]+]] +; CHECK-O0: define i32 @main() !implicit.ref ![[MD]] +; CHECK-ON: define noundef i32 @main() local_unnamed_addr #0 !implicit.ref ![[MD]] + +; Verify metadata content +; CHECK-O0: ![[MD]] = !{ptr @__loadtime_copyright_str} +; CHECK-ON: ![[MD]] = !{ptr @__loadtime_copyright_str} \ No newline at end of file