https://github.com/maryammo updated 
https://github.com/llvm/llvm-project/pull/234368

>From 335ba834d2fbfaf5eb736fd0c317e25860423d7f Mon Sep 17 00:00:00 2001
From: Maryam Moghadas <[email protected]>
Date: Tue, 20 Oct 2026 20:01:57 +0000
Subject: [PATCH 1/4] [Clang][z/OS] Add CSECT option and pragma

---
 clang/docs/LanguageExtensions.md              |  28 +++++
 clang/include/clang/AST/ASTContext.h          |   4 +
 clang/include/clang/Basic/CodeGenOptions.h    |   3 +
 .../clang/Basic/DiagnosticSemaKinds.td        |   4 +
 clang/include/clang/Basic/TokenKinds.def      |   3 +
 clang/include/clang/Options/Options.td        |   5 +
 clang/include/clang/Parse/Parser.h            |   5 +
 clang/include/clang/Sema/Sema.h               |   4 +
 clang/lib/CodeGen/CodeGenModule.cpp           |  22 ++++
 clang/lib/Driver/ToolChains/Clang.cpp         |  25 ++++
 clang/lib/Frontend/CompilerInvocation.cpp     |  10 ++
 clang/lib/Parse/ParsePragma.cpp               | 110 ++++++++++++++++++
 clang/lib/Parse/Parser.cpp                    |   3 +
 clang/lib/Sema/SemaAttr.cpp                   |  20 ++++
 .../CodeGen/SystemZ/zos-csect-option-pragma.c |  29 +++++
 clang/test/CodeGen/SystemZ/zos-csect-option.c |  19 +++
 .../CodeGen/SystemZ/zos-csect-pragma-diag.c   |  13 +++
 clang/test/CodeGen/SystemZ/zos-csect-pragma.c |  11 ++
 18 files changed, 318 insertions(+)
 create mode 100644 clang/test/CodeGen/SystemZ/zos-csect-option-pragma.c
 create mode 100644 clang/test/CodeGen/SystemZ/zos-csect-option.c
 create mode 100644 clang/test/CodeGen/SystemZ/zos-csect-pragma-diag.c
 create mode 100644 clang/test/CodeGen/SystemZ/zos-csect-pragma.c

diff --git a/clang/docs/LanguageExtensions.md b/clang/docs/LanguageExtensions.md
index cf453ac2e3b69b..55b776501cf27e 100644
--- a/clang/docs/LanguageExtensions.md
+++ b/clang/docs/LanguageExtensions.md
@@ -5707,6 +5707,34 @@ ASM strings. See
 [String literal encoding in ASM 
statements](#string-literal-encoding-in-asm-statements)
 for details.
 
+#### z/OS CSECT pragma
+
+Clang supports the `#pragma csect` directive to control CSECT (control 
+section) names in the output object module on z/OS.
+
+The `#pragma csect` directive, which must appear at file scope, sets the CSECT
+name for the code or static section:
+   
+```c
+#pragma csect(code, "name")
+#pragma csect(static, "name")
+```
+
+The name specified on `#pragma csect` overrides the generated name that
+`-mcsect` would have created for the section. When `-mno-csect` is used, the
+name specified on `#pragma csect` is still used for that section.
+
+There can be at most one `#pragma csect` directive for each section type
+(code or static) per translation unit; duplicates are warned and ignored.
+
+The code and static section names set by `#pragma csect` must be different;
+using the same name for both results in an error.
+
+`#pragma csect(test, "name")` is accepted and ignored. This is done to avoid
+messages when porting XL code.
+
+The names must follow the CSECT name rules described in the "CSECT Options"
+section of the User's Manual.
 
 ## Extensions for Static Analysis
 
diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index 9ad16898b32563..ba699455064849 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -3978,6 +3978,10 @@ OPT_LIST(V)
 
   llvm::StringMap<SectionInfo> SectionInfos;
 
+  /// Names set by '#pragma csect(code/static, "name")' on z/OS.
+  std::string PragmaCsectStatic;
+  std::string PragmaCsectCode;
+
   /// Return a new OMPTraitInfo object owned by this context.
   OMPTraitInfo &getNewOMPTraitInfo();
 
diff --git a/clang/include/clang/Basic/CodeGenOptions.h 
b/clang/include/clang/Basic/CodeGenOptions.h
index 4f1875d8c0bd47..e11a72274decaf 100644
--- a/clang/include/clang/Basic/CodeGenOptions.h
+++ b/clang/include/clang/Basic/CodeGenOptions.h
@@ -633,6 +633,9 @@ class CodeGenOptions : public CodeGenOptionsBase {
   /// If threshold option is not specified, it is disabled by default.
   std::optional<uint64_t> DiagnosticsHotnessThreshold = 0;
 
+  /// Specifies the csect name (qualifier & basename) on z/OS.
+  std::optional<std::string> CsectName;
+
   /// The maximum percentage profiling weights can deviate from the expected
   /// values in order to be included in misexpect diagnostics.
   std::optional<uint32_t> DiagnosticsMisExpectTolerance = 0;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index ddf1d325ac3bc2..498b208310299f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1300,6 +1300,10 @@ def note_surrounding_namespace_starts_here : Note<
 def warn_failed_to_resolve_pragma : Warning<
   "failed to resolve '#pragma %0' to a declaration">,
   InGroup<IgnoredPragmas>;
+def warn_duplicate_pragma : Warning<"duplicate '#pragma %0' is ignored">,
+  InGroup<IgnoredPragmas>;
+def err_conflicting_pragma : Error<
+  "external name '%0' in pragma %1 conflicts with another csect name">;
 def warn_pragma_not_applied : Warning<
   "#pragma %0 is applicable to symbols with external linkage only; "
   "not applied to %1">,
diff --git a/clang/include/clang/Basic/TokenKinds.def 
b/clang/include/clang/Basic/TokenKinds.def
index 802947e31cbc18..2dabce81acdba7 100644
--- a/clang/include/clang/Basic/TokenKinds.def
+++ b/clang/include/clang/Basic/TokenKinds.def
@@ -902,6 +902,9 @@ PRAGMA_ANNOTATION(pragma_attribute)
 // Annotation for C/C++ #pragma export(ident)
 PRAGMA_ANNOTATION(pragma_export)
 
+// Annotation for #pragma csect(ident, str lit)
+PRAGMA_ANNOTATION(pragma_csect)
+
 // Annotation for the riscv pragma directives - #pragma clang riscv intrinsic 
...
 PRAGMA_ANNOTATION(pragma_riscv)
 
diff --git a/clang/include/clang/Options/Options.td 
b/clang/include/clang/Options/Options.td
index e07b7cbe112797..6b65af184cbdd3 100644
--- a/clang/include/clang/Options/Options.td
+++ b/clang/include/clang/Options/Options.td
@@ -5673,6 +5673,11 @@ def march_EQ : Joined<["-"], "march=">, Group<m_Group>,
   Flags<[TargetSpecific]>, Visibility<[ClangOption, CLOption, DXCOption, 
FlangOption]>,
   HelpText<"For a list of available architectures for the target use 
'-mcpu=help'">;
 def mzos_target_EQ : Joined<["-"], "mzos-target=">, Group<m_Group>, 
Visibility<[ClangOption, CC1Option]>, HelpText<"Set the z/OS release of the 
runtime environment">;
+def mcsect_EQ : Joined<["-"], "mcsect=">, Group<m_Group>, 
Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Set CSECT names in the output object module">;
+def mcsect : Flag<["-"], "mcsect">, Group<m_Group>, Visibility<[ClangOption, 
CC1Option]>, Alias<mcsect_EQ>;
+def mno_csect : Flag<["-"], "mno-csect">, Group<m_Group>, 
Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Do not set CSECT names in the output object module">;
 def masm_EQ : Joined<["-"], "masm=">, Group<m_Group>, Visibility<[ClangOption, 
FlangOption]>;
 def inline_asm_EQ : Joined<["-"], "inline-asm=">, Group<m_Group>,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/include/clang/Parse/Parser.h 
b/clang/include/clang/Parse/Parser.h
index 946f63765ca388..c8ede7db5d056b 100644
--- a/clang/include/clang/Parse/Parser.h
+++ b/clang/include/clang/Parse/Parser.h
@@ -7200,6 +7200,7 @@ class Parser : public CodeCompletionHandler {
   std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler;
   std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler;
   std::unique_ptr<PragmaHandler> ExportHandler;
+  std::unique_ptr<PragmaHandler> CsectHandler;
   std::unique_ptr<PragmaHandler> RISCVPragmaHandler;
 
   /// Initialize all pragma handlers.
@@ -7327,6 +7328,10 @@ class Parser : public CodeCompletionHandler {
   /// #pragma export ...
   void HandlePragmaExport();
 
+  /// Handle the annotation token produced for
+  /// #pragma csect(...)
+  void HandlePragmaCsect();
+
   ///@}
 
   //
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 0d13ea4c74ebf5..2446c787ffd2bd 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2409,6 +2409,10 @@ class Sema final : public SemaBase {
   void ActOnPragmaExport(IdentifierInfo *IdentId, SourceLocation ExportNameLoc,
                          Scope *curScope);
 
+  /// ActOnPragmaCsect - called on well-formed '\#pragma csect'
+  void ActOnPragmaCsect(StringRef SectionKind, SourceLocation SectionLoc,
+                        StringRef SectionName);
+
   /// Only called on function definitions; if there is a pragma in scope
   /// with the effect of a range-based optnone, consider marking the function
   /// with attribute optnone.
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index f0ea493e172229..16b679af30da07 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -1570,6 +1570,28 @@ void CodeGenModule::Release() {
     // Multiple modes will be supported here.
     getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode",
                               llvm::MDString::get(VMContext, "ascii"));
+
+    if (!Context.PragmaCsectCode.empty()) {
+      getModule().addModuleFlag(
+          llvm::Module::Error, "zos_csect_code",
+          llvm::MDString::get(VMContext, Context.PragmaCsectCode));
+    } else if (getCodeGenOpts().CsectName) {
+      getModule().addModuleFlag(
+          llvm::Module::Error, "zos_csect_code",
+          llvm::MDString::get(VMContext,
+                              StringRef(*(getCodeGenOpts().CsectName) + "C")));
+    }
+
+    if (!Context.PragmaCsectStatic.empty()) {
+      getModule().addModuleFlag(
+          llvm::Module::Error, "zos_csect_static",
+          llvm::MDString::get(VMContext, Context.PragmaCsectStatic));
+    } else if (getCodeGenOpts().CsectName) {
+      getModule().addModuleFlag(
+          llvm::Module::Error, "zos_csect_static",
+          llvm::MDString::get(VMContext,
+                              StringRef(*(getCodeGenOpts().CsectName) + "S")));
+    }
   }
 
   llvm::Triple T = Context.getTargetInfo().getTriple();
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 5f6338ab12ed59..bd6e3a0cded327 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5979,6 +5979,31 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
     }
   }
 
+  if (RawTriple.isOSzOS()) {
+    if (Args.hasFlag(options::OPT_mcsect_EQ, options::OPT_mno_csect, false)) {
+      SmallString<256> CsectArg("-mcsect=");
+      StringRef Qualifier;
+      if (const Arg *A = Args.getLastArg(options::OPT_mcsect_EQ))
+        Qualifier = A->getValue();
+      if (!Qualifier.empty()) {
+        CsectArg += Qualifier;
+        CsectArg += "#";
+      }
+
+      SmallString<64> OutputName;
+      if (Arg *OutputOpt = Args.getLastArg(options::OPT_o))
+        OutputName = OutputOpt->getValue();
+      else if (Output.isFilename())
+        OutputName = Output.getFilename();
+
+      CsectArg += llvm::sys::path::stem(OutputName);
+      CsectArg += "#";
+      CmdArgs.push_back(Args.MakeArgString(CsectArg));
+    } else {
+      CmdArgs.push_back("-mno-csect");
+    }
+  }
+
   llvm::Reloc::Model RelocationModel;
   unsigned PICLevel;
   bool IsPIE;
diff --git a/clang/lib/Frontend/CompilerInvocation.cpp 
b/clang/lib/Frontend/CompilerInvocation.cpp
index 9af6f6c41eb756..3f474210432c5f 100644
--- a/clang/lib/Frontend/CompilerInvocation.cpp
+++ b/clang/lib/Frontend/CompilerInvocation.cpp
@@ -1846,6 +1846,11 @@ void CompilerInvocationBase::GenerateCodeGenArgs(const 
CodeGenOptions &Opts,
     break;
   }
 
+  if (Opts.CsectName)
+    GenerateArg(Consumer, OPT_mcsect_EQ, Twine(*Opts.CsectName));
+  else
+    GenerateArg(Consumer, OPT_mno_csect);
+
   if (Opts.StaticClosure)
     GenerateArg(Consumer, OPT_static_libclosure);
 }
@@ -2349,6 +2354,11 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions 
&Opts, ArgList &Args,
   if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
     Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
 
+  if (Args.hasFlag(OPT_mcsect_EQ, OPT_mno_csect, false)) {
+    const Arg *A = Args.getLastArg(OPT_mcsect_EQ);
+    Opts.CsectName = A->getValue();
+  }
+
   Opts.StaticClosure = Args.hasArg(options::OPT_static_libclosure);
 
   if (!Opts.HLSLRecordCommandLine.empty()) {
diff --git a/clang/lib/Parse/ParsePragma.cpp b/clang/lib/Parse/ParsePragma.cpp
index dd05bd3c21442a..3795890d93d59c 100644
--- a/clang/lib/Parse/ParsePragma.cpp
+++ b/clang/lib/Parse/ParsePragma.cpp
@@ -395,6 +395,12 @@ struct PragmaExportHandler : public PragmaHandler {
                     Token &FirstToken) override;
 };
 
+struct PragmaCsectHandler : public PragmaHandler {
+  PragmaCsectHandler() : PragmaHandler("csect") {}
+  void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
+                    Token &Tok) override;
+};
+
 struct PragmaRISCVHandler : public PragmaHandler {
   PragmaRISCVHandler(Sema &Actions)
       : PragmaHandler("riscv"), Actions(Actions) {}
@@ -562,6 +568,8 @@ void Parser::initializePragmaHandlers() {
   if (getLangOpts().ZOSExt) {
     ExportHandler = std::make_unique<PragmaExportHandler>();
     PP.AddPragmaHandler(ExportHandler.get());
+    CsectHandler = std::make_unique<PragmaCsectHandler>();
+    PP.AddPragmaHandler(CsectHandler.get());
   }
 
   if (getTargetInfo().getTriple().isRISCV()) {
@@ -702,6 +710,8 @@ void Parser::resetPragmaHandlers() {
   if (getLangOpts().ZOSExt) {
     PP.RemovePragmaHandler(ExportHandler.get());
     ExportHandler.reset();
+    PP.RemovePragmaHandler(CsectHandler.get());
+    CsectHandler.reset();
   }
 
   if (getTargetInfo().getTriple().isRISCV()) {
@@ -1477,6 +1487,19 @@ void Parser::HandlePragmaExport() {
   zOSHandlePragmaHelper(tok::annot_pragma_export);
 }
 
+void Parser::HandlePragmaCsect() {
+  assert(Tok.is(tok::annot_pragma_csect));
+  StringRef *SectionName = static_cast<StringRef *>(Tok.getAnnotationValue());
+  assert(SectionName);
+  SourceLocation PragmaLoc = Tok.getLocation();
+
+  ConsumeAnnotationToken();
+
+  llvm::StringRef SectionKind = Tok.getIdentifierInfo()->getName();
+  ConsumeToken();
+  Actions.ActOnPragmaCsect(SectionKind, PragmaLoc, *SectionName);
+}
+
 static std::string PragmaLoopHintString(Token PragmaName, Token Option) {
   StringRef Str = PragmaName.getIdentifierInfo()->getName();
   std::string ClangLoopStr("clang loop ");
@@ -4272,3 +4295,90 @@ void PragmaRISCVHandler::HandlePragma(Preprocessor &PP,
   else if (II->isStr("andes_vector"))
     Actions.RISCV().DeclareAndesVectorBuiltins = true;
 }
+
+/// Handle #pragma csect.
+void PragmaCsectHandler::HandlePragma(Preprocessor &PP,
+                                      PragmaIntroducer Introducer, Token &Tok) 
{
+  SourceLocation CSectLoc = Tok.getLocation();
+
+  PP.Lex(Tok);
+  if (Tok.isNot(tok::l_paren)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_lparen) << "csect";
+    return;
+  }
+
+  PP.LexUnexpandedToken(Tok);
+  bool ValidPragma = false;
+  bool AcceptAndIgnore = false;
+  switch (Tok.getKind()) {
+  case tok::kw_static:
+    ValidPragma = true;
+    break;
+  case tok::identifier: {
+    assert(Tok.getIdentifierInfo());
+    StringRef Section = Tok.getIdentifierInfo()->getName();
+    AcceptAndIgnore = Section.equals_insensitive("test");
+    if (AcceptAndIgnore || Section.equals_insensitive("code") ||
+        Section.equals_insensitive("static"))
+      ValidPragma = true;
+    break;
+  }
+  default:
+    break;
+  }
+  if (!ValidPragma) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_identifier)
+        << "csect";
+    return;
+  }
+  Token SectionKind = Tok;
+
+  PP.Lex(Tok);
+  if (Tok.isNot(tok::comma)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_comma) << "csect";
+    return;
+  }
+
+  PP.Lex(Tok);
+  if (Tok.isNot(tok::string_literal)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_string) << "csect";
+    return;
+  }
+
+  std::string SectionName;
+  if (!PP.FinishLexStringLiteral(Tok, SectionName, "pragma csect",
+                                 /*AllowMacroExpansion*/ false)) {
+    return;
+  }
+
+  if (Tok.isNot(tok::r_paren)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_expected_rparen) << "csect";
+    return;
+  }
+
+  PP.Lex(Tok);
+  if (Tok.isNot(tok::eod)) {
+    PP.Diag(Tok.getLocation(), diag::warn_pragma_extra_tokens_at_eol)
+        << "csect";
+    return;
+  }
+
+  if (AcceptAndIgnore) {
+    // accept and ignore #pragma csect(test, "STRING LITERAL");
+    return;
+  }
+
+  auto *SectionNameRef = new (PP.getPreprocessorAllocator())
+      StringRef(StringRef(SectionName).copy(PP.getPreprocessorAllocator()));
+
+  MutableArrayRef<Token> Toks(PP.getPreprocessorAllocator().Allocate<Token>(2),
+                              2);
+  Toks[0].startToken();
+  Toks[0].setKind(tok::annot_pragma_csect);
+  Toks[0].setLocation(CSectLoc);
+  Toks[0].setAnnotationValue(static_cast<void *>(SectionNameRef));
+  Toks[1] = SectionKind;
+
+  PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
+                      /*IsReinject=*/false);
+}
diff --git a/clang/lib/Parse/Parser.cpp b/clang/lib/Parse/Parser.cpp
index fbfc632c47e45b..c88176574356ba 100644
--- a/clang/lib/Parse/Parser.cpp
+++ b/clang/lib/Parse/Parser.cpp
@@ -821,6 +821,9 @@ Parser::ParseExternalDeclaration(ParsedAttributes &Attrs,
   case tok::annot_pragma_export:
     HandlePragmaExport();
     return nullptr;
+  case tok::annot_pragma_csect:
+    HandlePragmaCsect();
+    return nullptr;
   case tok::semi:
     // Either a C++11 empty-declaration or attribute-declaration.
     SingleDecl =
diff --git a/clang/lib/Sema/SemaAttr.cpp b/clang/lib/Sema/SemaAttr.cpp
index e5253e2a311747..7ed4dc34dabfa7 100644
--- a/clang/lib/Sema/SemaAttr.cpp
+++ b/clang/lib/Sema/SemaAttr.cpp
@@ -1714,3 +1714,23 @@ bool Sema::checkCommonAttributeFeatures(QualType T, 
const ParsedAttr &A,
                                         bool SkipArgCountCheck) {
   return ::checkCommonAttributeFeatures(*this, T, A, SkipArgCountCheck);
 }
+
+void Sema::ActOnPragmaCsect(StringRef SectionKind, SourceLocation SectionLoc,
+                            StringRef SectionName) {
+  if (SectionKind.equals_insensitive("static")) {
+    if (!Context.PragmaCsectStatic.empty())
+      Diag(SectionLoc, diag::warn_duplicate_pragma) << "csect";
+    else if (Context.PragmaCsectCode == SectionName)
+      Diag(SectionLoc, diag::err_conflicting_pragma) << SectionName << "csect";
+    else
+      Context.PragmaCsectStatic = SectionName.str();
+  } else if (SectionKind.equals_insensitive("code")) {
+    if (!Context.PragmaCsectCode.empty())
+      Diag(SectionLoc, diag::warn_duplicate_pragma) << "csect";
+    else if (Context.PragmaCsectStatic == SectionName)
+      Diag(SectionLoc, diag::err_conflicting_pragma) << SectionName << "csect";
+    else
+      Context.PragmaCsectCode = SectionName.str();
+  } else
+    llvm_unreachable("invalid Csect kind");
+}
diff --git a/clang/test/CodeGen/SystemZ/zos-csect-option-pragma.c 
b/clang/test/CodeGen/SystemZ/zos-csect-option-pragma.c
new file mode 100644
index 00000000000000..76d1c78902f19b
--- /dev/null
+++ b/clang/test/CodeGen/SystemZ/zos-csect-option-pragma.c
@@ -0,0 +1,29 @@
+// REQUIRES: systemz-registered-target
+
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos %s -o outputfile2.ll && 
cat outputfile2.ll | FileCheck %s --check-prefix=CHECK-NOCSECT
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect %s -o 
outputfile2.ll && cat outputfile2.ll | FileCheck %s
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect= %s -o 
outputfile2.ll && cat outputfile2.ll | FileCheck %s
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect=abc %s -o 
outputfile2.ll && cat outputfile2.ll | FileCheck %s 
--check-prefix=CHECK-QUALIFIER
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mno-csect %s -o 
outputfile2.ll && cat outputfile2.ll | FileCheck %s --check-prefix=CHECK-NOCSECT
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect %s && cat 
zos-csect-option-pragma.ll | FileCheck %s --check-prefix=CHECK-NOOUTFILE
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect= %s && cat 
zos-csect-option-pragma.ll | FileCheck %s --check-prefix=CHECK-NOOUTFILE
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect=cde %s && cat 
zos-csect-option-pragma.ll | FileCheck %s 
--check-prefix=CHECK-NOOUTFILE-QUALIFIER
+
+#pragma csect(code, "csectcode")
+
+int main() { return 0; }
+
+// CHECK: !{i32 1, !"zos_csect_code", !"csectcode"}
+// CHECK: !{i32 1, !"zos_csect_static", !"outputfile2#S"}
+
+// CHECK-QUALIFIER: !{i32 1, !"zos_csect_code", !"csectcode"}
+// CHECK-QUALIFIER: !{i32 1, !"zos_csect_static", !"abc#outputfile2#S"}
+
+// CHECK-NOCSECT: !{i32 1, !"zos_csect_code", !"csectcode"}
+// CHECK-NOCSECT-NOT: zos_csect_static
+
+// CHECK-NOOUTFILE: !{i32 1, !"zos_csect_code", !"csectcode"}
+// CHECK-NOOUTFILE: !{i32 1, !"zos_csect_static", !"zos-csect-option-pragma#S"}
+
+// CHECK-NOOUTFILE-QUALIFIER: !{i32 1, !"zos_csect_code", !"csectcode"}
+// CHECK-NOOUTFILE-QUALIFIER: !{i32 1, !"zos_csect_static", 
!"cde#zos-csect-option-pragma#S"}
diff --git a/clang/test/CodeGen/SystemZ/zos-csect-option.c 
b/clang/test/CodeGen/SystemZ/zos-csect-option.c
new file mode 100644
index 00000000000000..a515099949a53a
--- /dev/null
+++ b/clang/test/CodeGen/SystemZ/zos-csect-option.c
@@ -0,0 +1,19 @@
+// REQUIRES: systemz-registered-target
+
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos %s -o outputfile.ll && 
cat outputfile.ll | FileCheck %s --check-prefix=CHECK-NOCSECT
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect= %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect=abc %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s --check-prefix=CHECK-QUALIFIER
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mno-csect %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s --check-prefix=CHECK-NOCSECT
+// RUN: %clang -S -emit-llvm --target=s390x-linux-gnu %s -o outputfile.ll && 
cat outputfile.ll | FileCheck %s --check-prefix=CHECK-NOCSECT
+
+int main() { return 0; }
+
+// CHECK: !{i32 1, !"zos_csect_code", !"outputfile#C"}
+// CHECK: !{i32 1, !"zos_csect_static", !"outputfile#S"}
+
+// CHECK-QUALIFIER: !{i32 1, !"zos_csect_code", !"abc#outputfile#C"}
+// CHECK-QUALIFIER: !{i32 1, !"zos_csect_static", !"abc#outputfile#S"}
+
+// CHECK-NOCSECT-NOT: zos_csect_code
+// CHECK-NOCSECT-NOT: zos_csect_static
diff --git a/clang/test/CodeGen/SystemZ/zos-csect-pragma-diag.c 
b/clang/test/CodeGen/SystemZ/zos-csect-pragma-diag.c
new file mode 100644
index 00000000000000..390140756af30e
--- /dev/null
+++ b/clang/test/CodeGen/SystemZ/zos-csect-pragma-diag.c
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -triple s390x-none-zos -fzos-extensions %s -verify
+
+#pragma csect(code, "abc")
+#pragma csect(code, "csectcode") // expected-warning {{duplicate '#pragma 
csect' is ignored}}
+#pragma csect(static, "abc") // expected-error {{external name 'abc' in pragma 
csect conflicts with another csect name}}
+
+#pragma csect(static, "csectstatic")
+#pragma csect(test,"csecttest")
+#pragma csect(xyz,"csectxyz") // expected-warning {{expected identifier in 
'#pragma csect' - ignored}}
+
+int main() { return 0; }
+
+void def() {}
diff --git a/clang/test/CodeGen/SystemZ/zos-csect-pragma.c 
b/clang/test/CodeGen/SystemZ/zos-csect-pragma.c
new file mode 100644
index 00000000000000..c7f7af16db8179
--- /dev/null
+++ b/clang/test/CodeGen/SystemZ/zos-csect-pragma.c
@@ -0,0 +1,11 @@
+// REQUIRES: systemz-registered-target
+
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos %s -o - | FileCheck %s
+
+#pragma csect(code, "codecsect")
+#pragma csect(static, "staticcsect")
+
+int main() { return 0; }
+
+// CHECK: !{i32 1, !"zos_csect_code", !"codecsect"}
+// CHECK: !{i32 1, !"zos_csect_static", !"staticcsect"}

>From 2c9f8a20e52b84f2aa5f6393642099f03f67c61b Mon Sep 17 00:00:00 2001
From: Maryam Moghadas <[email protected]>
Date: Tue, 27 Oct 2026 16:21:03 +0000
Subject: [PATCH 2/4] Address review comments on CSECT docs

---
 clang/docs/UsersManual.md | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)

diff --git a/clang/docs/UsersManual.md b/clang/docs/UsersManual.md
index fa316bded946de..931d56ed6355d1 100644
--- a/clang/docs/UsersManual.md
+++ b/clang/docs/UsersManual.md
@@ -5234,6 +5234,29 @@ mapping of default visibility to an explicit shared 
object export
   export behavior similar to ELF platforms where all entities with default
   visibility are exported.
 
+#### z/OS
+
+##### CSECT Options
+
+Clang supports the `-mcsect`, `-mcsect=<qualifier>`, and `-mno-csect` options
+to control CSECT (control section) names in the output object module on z/OS.
+
+When `-mcsect` or `-mcsect=<qualifier>` is specified the CSECT names for the
+output object module will be:
+
+`qualifier#basename#suffix`
+
+Where:
+
+- `qualifier` is the `<qualifier>` specified by `-mcsect=<qualifier>`. If
+  `qualifier` is empty, the syntax becomes just `basename#suffix`.
+- `basename` is the output file name with path information and the right-most
+  extension information removed.
+- `suffix` is `C` for the code section and `S` for the static section.
+
+`-mno-csect` is the default. `-mcsect` is the same as `-mcsect=` with an empty
+qualifier.
+
 (spir-v)=
 
 ### SPIR-V support

>From 617a41c03f4e745d3b5aed1629e11cb015ba9178 Mon Sep 17 00:00:00 2001
From: Maryam Moghadas <[email protected]>
Date: Thu, 12 Nov 2026 19:47:51 +0000
Subject: [PATCH 3/4] Handle -o - for -mcsect and document CSECT name rules

---
 clang/docs/UsersManual.md                     | 14 +++++++++++++-
 clang/lib/Driver/ToolChains/Clang.cpp         |  5 ++++-
 clang/test/CodeGen/SystemZ/zos-csect-option.c |  4 ++++
 3 files changed, 21 insertions(+), 2 deletions(-)

diff --git a/clang/docs/UsersManual.md b/clang/docs/UsersManual.md
index 931d56ed6355d1..9b6f48bafb5cfc 100644
--- a/clang/docs/UsersManual.md
+++ b/clang/docs/UsersManual.md
@@ -5251,12 +5251,24 @@ Where:
 - `qualifier` is the `<qualifier>` specified by `-mcsect=<qualifier>`. If
   `qualifier` is empty, the syntax becomes just `basename#suffix`.
 - `basename` is the output file name with path information and the right-most
-  extension information removed.
+  extension information removed. If the output is standard output (`-o -`),
+  `basename` is `@stdout@`.
 - `suffix` is `C` for the code section and `S` for the static section.
 
 `-mno-csect` is the default. `-mcsect` is the same as `-mcsect=` with an empty
 qualifier.
 
+CSECT names, whether generated by `-mcsect` or set by `#pragma csect`, must
+follow these rules:
+
+- The first character must be a letter (`A`-`Z`, `a`-`z`), `_`, `$`, `#`, or
+  `@`.
+- The other characters may be letters, digits, or those same characters.
+- No other special characters, spaces, or double-byte characters are allowed.
+
+The compiler does not diagnose names that do not follow these rules. The
+behavior is undefined if the rules are not followed.
+
 (spir-v)=
 
 ### SPIR-V support
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index bd6e3a0cded327..12daf56647e0e4 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -5996,7 +5996,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
       else if (Output.isFilename())
         OutputName = Output.getFilename();
 
-      CsectArg += llvm::sys::path::stem(OutputName);
+      if (OutputName == "-")
+        CsectArg += "@stdout@";
+      else
+        CsectArg += llvm::sys::path::stem(OutputName);
       CsectArg += "#";
       CmdArgs.push_back(Args.MakeArgString(CsectArg));
     } else {
diff --git a/clang/test/CodeGen/SystemZ/zos-csect-option.c 
b/clang/test/CodeGen/SystemZ/zos-csect-option.c
index a515099949a53a..e3cb160178473a 100644
--- a/clang/test/CodeGen/SystemZ/zos-csect-option.c
+++ b/clang/test/CodeGen/SystemZ/zos-csect-option.c
@@ -4,6 +4,7 @@
 // RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s
 // RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect= %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s
 // RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect=abc %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s --check-prefix=CHECK-QUALIFIER
+// RUN: %clang -S -emit-llvm --target=s390x-none-zos -mcsect %s -o - | 
FileCheck %s --check-prefix=CHECK-STDOUT
 // RUN: %clang -S -emit-llvm --target=s390x-none-zos -mno-csect %s -o 
outputfile.ll && cat outputfile.ll | FileCheck %s --check-prefix=CHECK-NOCSECT
 // RUN: %clang -S -emit-llvm --target=s390x-linux-gnu %s -o outputfile.ll && 
cat outputfile.ll | FileCheck %s --check-prefix=CHECK-NOCSECT
 
@@ -15,5 +16,8 @@ int main() { return 0; }
 // CHECK-QUALIFIER: !{i32 1, !"zos_csect_code", !"abc#outputfile#C"}
 // CHECK-QUALIFIER: !{i32 1, !"zos_csect_static", !"abc#outputfile#S"}
 
+// CHECK-STDOUT: !{i32 1, !"zos_csect_code", !"@stdout@#C"}
+// CHECK-STDOUT: !{i32 1, !"zos_csect_static", !"@stdout@#S"}
+
 // CHECK-NOCSECT-NOT: zos_csect_code
 // CHECK-NOCSECT-NOT: zos_csect_static

>From ab7b4d15760c3789861030499b86a17e38e4cb4c Mon Sep 17 00:00:00 2001
From: Maryam Moghadas <[email protected]>
Date: Thu, 19 Nov 2026 20:42:33 +0000
Subject: [PATCH 4/4] Serialize #pragma csect names in PCH

---
 .../include/clang/Serialization/ASTBitCodes.h |  3 +++
 clang/include/clang/Serialization/ASTReader.h |  4 ++++
 clang/include/clang/Serialization/ASTWriter.h |  1 +
 clang/lib/Serialization/ASTReader.cpp         | 15 +++++++++++++++
 clang/lib/Serialization/ASTWriter.cpp         | 13 +++++++++++++
 clang/test/PCH/zos-csect-pch.c                | 19 +++++++++++++++++++
 6 files changed, 55 insertions(+)
 create mode 100644 clang/test/PCH/zos-csect-pch.c

diff --git a/clang/include/clang/Serialization/ASTBitCodes.h 
b/clang/include/clang/Serialization/ASTBitCodes.h
index 04cc0c5af89d15..a4255983c39b2f 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -754,6 +754,9 @@ enum ASTRecordTypes {
 
   /// Record code for the OpenMP 'requires' directives seen in the TU.
   OMP_REQUIRES_DECLS = 81,
+
+  /// Record code for the names set by '#pragma csect' on z/OS.
+  ZOS_CSECT_PRAGMA_OPTIONS = 82,
 };
 
 /// Record types used within a source manager block.
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 275383d40cf808..11f7160fbb0a1b 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -1058,6 +1058,10 @@ class ASTReader : public ExternalPreprocessorSource,
   /// The RISC-V intrinsic pragma(including RVV, SiFive and Andes).
   SmallVector<bool, 3> RISCVVecIntrinsicPragma;
 
+  /// The z/OS '#pragma csect(code/static, "name")'.
+  std::string PragmaCsectCode;
+  std::string PragmaCsectStatic;
+
 private:
   struct ImportedSubmodule {
     serialization::SubmoduleID ID;
diff --git a/clang/include/clang/Serialization/ASTWriter.h 
b/clang/include/clang/Serialization/ASTWriter.h
index 576eb863959291..46125e1c30a784 100644
--- a/clang/include/clang/Serialization/ASTWriter.h
+++ b/clang/include/clang/Serialization/ASTWriter.h
@@ -646,6 +646,7 @@ class ASTWriter : public ASTDeserializationListener,
   void WriteOptimizePragmaOptions(Sema &SemaRef);
   void WriteMSStructPragmaOptions(Sema &SemaRef);
   void WriteMSPointersToMembersPragmaOptions(Sema &SemaRef);
+  void WriteZOSCsectPragmaOptions(Sema &SemaRef);
   void WritePackPragmaOptions(Sema &SemaRef);
   void WriteFloatControlPragmaOptions(Sema &SemaRef);
   void WriteDeclsWithEffectsToVerify(Sema &SemaRef);
diff --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index db04c06f3cee73..dc10aa4746f951 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -4621,6 +4621,13 @@ llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
       PragmaMSStructState = Record[0];
       break;
 
+    case ZOS_CSECT_PRAGMA_OPTIONS: {
+      unsigned Idx = 0;
+      PragmaCsectCode = ReadString(Record, Idx);
+      PragmaCsectStatic = ReadString(Record, Idx);
+      break;
+    }
+
     case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
       if (Record.size() != 2)
         return llvm::createStringError(
@@ -9443,6 +9450,14 @@ void ASTReader::UpdateSema() {
             PragmaMSPointersToMembersState,
         PointersToMembersPragmaLocation);
   }
+  // Apply the '#pragma csect' names from the PCH once, then clear them.
+  if (!PragmaCsectCode.empty())
+    SemaObj->ActOnPragmaCsect("code", SourceLocation(), PragmaCsectCode);
+  if (!PragmaCsectStatic.empty())
+    SemaObj->ActOnPragmaCsect("static", SourceLocation(), PragmaCsectStatic);
+  PragmaCsectCode.clear();
+  PragmaCsectStatic.clear();
+
   SemaObj->CUDA().ForceHostDeviceDepth = ForceHostDeviceDepth;
   if (!RISCVVecIntrinsicPragma.empty()) {
     assert(RISCVVecIntrinsicPragma.size() == 3 &&
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 3ae7ac0e8c9fa0..cbe0b01fd6af97 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -987,6 +987,7 @@ void ASTWriter::WriteBlockInfoBlock() {
   RECORD(PP_UNSAFE_BUFFER_USAGE);
   RECORD(VTABLES_TO_EMIT);
   RECORD(RISCV_VECTOR_INTRINSICS_PRAGMA);
+  RECORD(ZOS_CSECT_PRAGMA_OPTIONS);
 
   // SourceManager Block.
   BLOCK(SOURCE_MANAGER_BLOCK);
@@ -5275,6 +5276,17 @@ void ASTWriter::WriteMSStructPragmaOptions(Sema 
&SemaRef) {
   Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
 }
 
+/// Write the names set by 'pragma csect' at the end of the module.
+void ASTWriter::WriteZOSCsectPragmaOptions(Sema &SemaRef) {
+  const ASTContext &Ctx = SemaRef.Context;
+  if (Ctx.PragmaCsectCode.empty() && Ctx.PragmaCsectStatic.empty())
+    return;
+  RecordData Record;
+  AddString(Ctx.PragmaCsectCode, Record);
+  AddString(Ctx.PragmaCsectStatic, Record);
+  Stream.EmitRecord(ZOS_CSECT_PRAGMA_OPTIONS, Record);
+}
+
 /// Write the state of 'pragma pointers_to_members' at the end of the
 //module.
 void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
@@ -6412,6 +6424,7 @@ ASTFileSignature ASTWriter::WriteASTCore(Sema *SemaPtr, 
StringRef isysroot,
       WriteOptimizePragmaOptions(*SemaPtr);
       WriteMSStructPragmaOptions(*SemaPtr);
       WriteMSPointersToMembersPragmaOptions(*SemaPtr);
+      WriteZOSCsectPragmaOptions(*SemaPtr);
     }
     WritePackPragmaOptions(*SemaPtr);
     WriteFloatControlPragmaOptions(*SemaPtr);
diff --git a/clang/test/PCH/zos-csect-pch.c b/clang/test/PCH/zos-csect-pch.c
new file mode 100644
index 00000000000000..1cbacfe1c02889
--- /dev/null
+++ b/clang/test/PCH/zos-csect-pch.c
@@ -0,0 +1,19 @@
+// REQUIRES: systemz-registered-target
+
+// RUN: %clang_cc1 -triple s390x-ibm-zos -emit-pch -o %t %s
+// RUN: %clang_cc1 -triple s390x-ibm-zos -include-pch %t -emit-llvm %s -o - | 
FileCheck %s
+
+#ifndef HEADER
+#define HEADER
+#pragma csect(code, "codecsect")
+#pragma csect(static, "staticcsect")
+
+#else
+
+int main() { return 0; }
+
+// CHECK: define {{.*}} @main()
+// CHECK: !{i32 1, !"zos_csect_code", !"codecsect"}
+// CHECK: !{i32 1, !"zos_csect_static", !"staticcsect"}
+
+#endif

_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to