diff --git a/clang/include/clang/Driver/Driver.h b/clang/include/clang/Driver/Driver.h --- a/clang/include/clang/Driver/Driver.h +++ b/clang/include/clang/Driver/Driver.h @@ -301,7 +301,7 @@ StringRef CustomResourceDir = ""); Driver(StringRef ClangExecutable, StringRef TargetTriple, - DiagnosticsEngine &Diags, + DiagnosticsEngine &Diags, std::string Title = "clang LLVM compiler", IntrusiveRefCntPtr VFS = nullptr); /// @name Accessors diff --git a/clang/include/clang/Driver/Options.h b/clang/include/clang/Driver/Options.h --- a/clang/include/clang/Driver/Options.h +++ b/clang/include/clang/Driver/Options.h @@ -34,7 +34,8 @@ CC1AsOption = (1 << 11), NoDriverOption = (1 << 12), LinkOption = (1 << 13), - Ignored = (1 << 14), + FlangOption = (1 << 14), + Ignored = (1 << 15), }; enum ID { diff --git a/clang/include/clang/Driver/Options.td b/clang/include/clang/Driver/Options.td --- a/clang/include/clang/Driver/Options.td +++ b/clang/include/clang/Driver/Options.td @@ -56,6 +56,10 @@ // be used), add this flag. def LinkOption : OptionFlag; +// FlangOption - This is considered a "core" Flang option, available in +// flang mode +def FlangOption : OptionFlag; + // A short name to show in documentation. The name will be interpreted as rST. class DocName { string DocName = name; } @@ -2069,7 +2073,7 @@ Flags<[DriverOption]>, HelpText<"Restore the default behavior of not embedding source text in DWARF debug sections">; def headerpad__max__install__names : Joined<["-"], "headerpad_max_install_names">; -def help : Flag<["-", "--"], "help">, Flags<[CC1Option,CC1AsOption]>, +def help : Flag<["-", "--"], "help">, Flags<[CC1Option,CC1AsOption,FlangOption]>, HelpText<"Display available options">; def ibuiltininc : Flag<["-"], "ibuiltininc">, HelpText<"Enable builtin #include directories even when -nostdinc is used " @@ -3012,7 +3016,7 @@ def _serialize_diags : Separate<["-", "--"], "serialize-diagnostics">, Flags<[DriverOption]>, HelpText<"Serialize compiler diagnostics to a file">; // We give --version different semantics from -version. -def _version : Flag<["--"], "version">, Flags<[CoreOption, CC1Option]>, +def _version : Flag<["--"], "version">, Flags<[CoreOption, CC1Option,FlangOption]>, HelpText<"Print version information">; def _signed_char : Flag<["--"], "signed-char">, Alias; def _std : Separate<["--"], "std">, Alias; diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp --- a/clang/lib/Driver/Driver.cpp +++ b/clang/lib/Driver/Driver.cpp @@ -121,12 +121,12 @@ } Driver::Driver(StringRef ClangExecutable, StringRef TargetTriple, - DiagnosticsEngine &Diags, + DiagnosticsEngine &Diags, std::string Title, IntrusiveRefCntPtr VFS) : Diags(Diags), VFS(std::move(VFS)), Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None), ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), - DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr), + DriverTitle(Title), CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr), CCCPrintBindings(false), CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false), CCGenDiagnostics(false), @@ -1566,6 +1566,14 @@ if (!ShowHidden) ExcludedFlagsBitmask |= HelpHidden; + if (Mode == DriverMode::FlangMode) { + ExcludedFlagsBitmask |= options::CLOption; + ExcludedFlagsBitmask |= options::CC1AsOption; + ExcludedFlagsBitmask |= options::CC1Option; + IncludedFlagsBitmask |= options::FlangOption; + } else + ExcludedFlagsBitmask |= options::FlangOption; + std::string Usage = llvm::formatv("{0} [options] file...", Name).str(); getOpts().PrintHelp(llvm::outs(), Usage.c_str(), DriverTitle.c_str(), IncludedFlagsBitmask, ExcludedFlagsBitmask, @@ -1573,6 +1581,10 @@ } void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { + if (IsFlangMode()) { + OS << "Flang experimental driver (flang-new)" << '\n'; + return; + } // FIXME: The following handlers should use a callback mechanism, we don't // know what the client would like to do. OS << getClangFullVersion() << '\n'; diff --git a/clang/lib/Driver/ToolChains/Flang.cpp b/clang/lib/Driver/ToolChains/Flang.cpp --- a/clang/lib/Driver/ToolChains/Flang.cpp +++ b/clang/lib/Driver/ToolChains/Flang.cpp @@ -69,11 +69,13 @@ CmdArgs.push_back(Input.getFilename()); const auto& D = C.getDriver(); - const char* Exec = Args.MakeArgString(D.GetProgramPath("flang", TC)); + // flang-new is a experimental binary for the new flang driver + // TODO:Replace by flang when the new driver is fully functional + const char *Exec = Args.MakeArgString(D.GetProgramPath("flang-new", TC)); C.addCommand(std::make_unique( JA, *this, ResponseFileSupport::AtFileUTF8(), Exec, CmdArgs, Inputs)); } -Flang::Flang(const ToolChain &TC) : Tool("flang", "flang frontend", TC) {} +Flang::Flang(const ToolChain &TC) : Tool("flang-new", "flang frontend", TC) {} Flang::~Flang() {} diff --git a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp --- a/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp +++ b/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp @@ -40,8 +40,8 @@ Args.push_back("-fsyntax-only"); // FIXME: We shouldn't have to pass in the path info. - driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), - *Diags, VFS); + driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), *Diags, + "clang LLVM compiler", VFS); // Don't check that inputs exist, they may have been remapped. TheDriver.setCheckInputsExist(false); diff --git a/clang/lib/Tooling/Tooling.cpp b/clang/lib/Tooling/Tooling.cpp --- a/clang/lib/Tooling/Tooling.cpp +++ b/clang/lib/Tooling/Tooling.cpp @@ -78,7 +78,7 @@ IntrusiveRefCntPtr VFS) { driver::Driver *CompilerDriver = new driver::Driver(BinaryName, llvm::sys::getDefaultTargetTriple(), - *Diagnostics, std::move(VFS)); + *Diagnostics, "clang LLVM compiler", std::move(VFS)); CompilerDriver->setTitle("clang_based_tool"); return CompilerDriver; } diff --git a/clang/test/Driver/flang/flang.f90 b/clang/test/Driver/flang/flang.f90 --- a/clang/test/Driver/flang/flang.f90 +++ b/clang/test/Driver/flang/flang.f90 @@ -13,7 +13,7 @@ ! * (no type specified, resulting in an object file) ! All invocations should begin with flang -fc1, consume up to here. -! ALL-LABEL: "{{[^"]*}}flang" "-fc1" +! ALL-LABEL: "{{[^"]*}}flang-new" "-fc1" ! Check that f90 files are not treated as "previously preprocessed" ! ... in --driver-mode=flang. diff --git a/clang/test/Driver/flang/flang_ucase.F90 b/clang/test/Driver/flang/flang_ucase.F90 --- a/clang/test/Driver/flang/flang_ucase.F90 +++ b/clang/test/Driver/flang/flang_ucase.F90 @@ -13,7 +13,7 @@ ! * (no type specified, resulting in an object file) ! All invocations should begin with flang -fc1, consume up to here. -! ALL-LABEL: "{{[^"]*}}flang" "-fc1" +! ALL-LABEL: "{{[^"]*}}flang-new" "-fc1" ! Check that f90 files are not treated as "previously preprocessed" ! ... in --driver-mode=flang. diff --git a/clang/test/Driver/flang/multiple-inputs-mixed.f90 b/clang/test/Driver/flang/multiple-inputs-mixed.f90 --- a/clang/test/Driver/flang/multiple-inputs-mixed.f90 +++ b/clang/test/Driver/flang/multiple-inputs-mixed.f90 @@ -1,7 +1,7 @@ ! Check that flang can handle mixed C and fortran inputs. ! RUN: %clang --driver-mode=flang -### -fsyntax-only %S/Inputs/one.f90 %S/Inputs/other.c 2>&1 | FileCheck --check-prefixes=CHECK-SYNTAX-ONLY %s -! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang{{[^"/]*}}" "-fc1" +! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new{{[^"/]*}}" "-fc1" ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/one.f90" ! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}clang{{[^"/]*}}" "-cc1" ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/other.c" diff --git a/clang/test/Driver/flang/multiple-inputs.f90 b/clang/test/Driver/flang/multiple-inputs.f90 --- a/clang/test/Driver/flang/multiple-inputs.f90 +++ b/clang/test/Driver/flang/multiple-inputs.f90 @@ -1,7 +1,7 @@ ! Check that flang driver can handle multiple inputs at once. ! RUN: %clang --driver-mode=flang -### -fsyntax-only %S/Inputs/one.f90 %S/Inputs/two.f90 2>&1 | FileCheck --check-prefixes=CHECK-SYNTAX-ONLY %s -! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang" "-fc1" +! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new" "-fc1" ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/one.f90" -! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang" "-fc1" +! CHECK-SYNTAX-ONLY-LABEL: "{{[^"]*}}flang-new" "-fc1" ! CHECK-SYNTAX-ONLY: "{{[^"]*}}/Inputs/two.f90" diff --git a/clang/unittests/Driver/SanitizerArgsTest.cpp b/clang/unittests/Driver/SanitizerArgsTest.cpp --- a/clang/unittests/Driver/SanitizerArgsTest.cpp +++ b/clang/unittests/Driver/SanitizerArgsTest.cpp @@ -57,7 +57,7 @@ new DiagnosticIDs, Opts, new TextDiagnosticPrinter(llvm::errs(), Opts.get())); DriverInstance.emplace(ClangBinary, "x86_64-unknown-linux-gnu", Diags, - prepareFS(ExtraFiles)); + "clang LLVM compiler", prepareFS(ExtraFiles)); std::vector Args = {ClangBinary}; for (const auto &A : ExtraArgs) diff --git a/clang/unittests/Driver/ToolChainTest.cpp b/clang/unittests/Driver/ToolChainTest.cpp --- a/clang/unittests/Driver/ToolChainTest.cpp +++ b/clang/unittests/Driver/ToolChainTest.cpp @@ -35,7 +35,7 @@ IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); Driver TheDriver("/bin/clang", "arm-linux-gnueabihf", Diags, - InMemoryFileSystem); + "clang LLVM compiler", InMemoryFileSystem); const char *EmptyFiles[] = { "foo.cpp", @@ -89,7 +89,7 @@ IntrusiveRefCntPtr InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); Driver TheDriver("/home/test/bin/clang", "arm-linux-gnueabi", Diags, - InMemoryFileSystem); + "clang LLVM compiler", InMemoryFileSystem); const char *EmptyFiles[] = { "foo.cpp", "/home/test/lib/gcc/arm-linux-gnueabi/4.6.1/crtbegin.o", @@ -130,13 +130,13 @@ new llvm::vfs::InMemoryFileSystem); Driver CCDriver("/home/test/bin/clang", "arm-linux-gnueabi", Diags, - InMemoryFileSystem); + "clang LLVM compiler", InMemoryFileSystem); CCDriver.setCheckInputsExist(false); Driver CXXDriver("/home/test/bin/clang++", "arm-linux-gnueabi", Diags, - InMemoryFileSystem); + "clang LLVM compiler", InMemoryFileSystem); CXXDriver.setCheckInputsExist(false); Driver CLDriver("/home/test/bin/clang-cl", "arm-linux-gnueabi", Diags, - InMemoryFileSystem); + "clang LLVM compiler", InMemoryFileSystem); CLDriver.setCheckInputsExist(false); std::unique_ptr CC(CCDriver.BuildCompilation( diff --git a/flang/CMakeLists.txt b/flang/CMakeLists.txt --- a/flang/CMakeLists.txt +++ b/flang/CMakeLists.txt @@ -17,6 +17,7 @@ endif() option(LINK_WITH_FIR "Link driver with FIR and LLVM" ON) +option(BUILD_FLANG_NEW_DRIVER "Build the flang driver frontend" OFF) # Flang requires C++17. set(CMAKE_CXX_STANDARD 17) @@ -70,6 +71,7 @@ include(HandleLLVMOptions) include(VersionFromVCS) + if(LINK_WITH_FIR) include(TableGen) find_package(MLIR REQUIRED CONFIG) @@ -192,6 +194,14 @@ endif() endif() +if(BUILD_FLANG_NEW_DRIVER) + # TODO:Removed when clangDriver and clangBasics are not in clang/lib + set(CLANG_INCLUDE_DIR ${LLVM_MAIN_SRC_DIR}/../clang/include ) + set(CLANG_TABLEGEN_OUTPUT_DIR ${CMAKE_BINARY_DIR}/tools/clang/include) + include_directories(SYSTEM ${CLANG_INCLUDE_DIR}) + include_directories(SYSTEM ${CLANG_TABLEGEN_OUTPUT_DIR}) +endif() + if(LINK_WITH_FIR) # tco tool and FIR lib output directories set(LLVM_RUNTIME_OUTPUT_INTDIR ${CMAKE_BINARY_DIR}/bin) diff --git a/flang/include/flang/Frontend/CompilerInstance.h b/flang/include/flang/Frontend/CompilerInstance.h new file mode 100644 --- /dev/null +++ b/flang/include/flang/Frontend/CompilerInstance.h @@ -0,0 +1,99 @@ +//===-- CompilerInstance.h - Clang Compiler Instance ------------*- 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_FLANG_FRONTEND_COMPILERINSTANCE_H +#define LLVM_FLANG_FRONTEND_COMPILERINSTANCE_H + +#include "flang/Frontend/CompilerInvocation.h" + +#include +#include + +namespace flang { + +class CompilerInstance { + + /// The options used in this compiler instance. + std::shared_ptr Invocation; + + // The diagnostics engine instance. + llvm::IntrusiveRefCntPtr Diagnostics; + +public: + explicit CompilerInstance(); + + ~CompilerInstance(); + CompilerInvocation &getInvocation() { + assert(Invocation && "Compiler instance has no invocation!"); + return *Invocation; + }; + /// } + /// @name Forwarding Methods + /// { + + clang::DiagnosticOptions &getDiagnosticOpts() { + return Invocation->getDiagnosticOpts(); + } + const clang::DiagnosticOptions &getDiagnosticOpts() const { + return Invocation->getDiagnosticOpts(); + } + + FrontendOptions &getFrontendOpts() { return Invocation->getFrontendOpts(); } + const FrontendOptions &getFrontendOpts() const { + return Invocation->getFrontendOpts(); + } + + /// } + /// @name Diagnostics Engine + /// { + + bool hasDiagnostics() const { return Diagnostics != nullptr; } + + /// Get the current diagnostics engine. + clang::DiagnosticsEngine &getDiagnostics() const { + assert(Diagnostics && "Compiler instance has no diagnostics!"); + return *Diagnostics; + } + + /// setDiagnostics - Replace the current diagnostics engine. + void setDiagnostics(clang::DiagnosticsEngine *Value); + + clang::DiagnosticConsumer &getDiagnosticClient() const { + assert(Diagnostics && Diagnostics->getClient() && + "Compiler instance has no diagnostic client!"); + return *Diagnostics->getClient(); + } + + /// } + /// @name Construction Utility Methods + /// { + + /// Create a DiagnosticsEngine object with a the TextDiagnosticPrinter. + /// + /// If no diagnostic client is provided, this creates a + /// DiagnosticConsumer that is owned by the returned diagnostic + /// object, if using directly the caller is responsible for + /// releasing the returned DiagnosticsEngine's client eventually. + /// + /// \param Opts - The diagnostic options; note that the created text + /// diagnostic object contains a reference to these options. + /// + /// \param Client If non-NULL, a diagnostic client that will be + /// attached to (and, then, owned by) the returned DiagnosticsEngine + /// object. + /// + /// \return The new object on success, or null on failure. + void createDiagnostics( + clang::DiagnosticConsumer *Client = nullptr, bool ShouldOwnClient = true); + + static clang::IntrusiveRefCntPtr createDiagnostics( + clang::DiagnosticOptions *Opts, + clang::DiagnosticConsumer *Client = nullptr, bool ShouldOwnClient = true); +}; + +} // end namespace flang +#endif // LLVM_FLANG_FRONTEND_COMPILERINSTANCE_H diff --git a/flang/include/flang/Frontend/CompilerInvocation.h b/flang/include/flang/Frontend/CompilerInvocation.h new file mode 100644 --- /dev/null +++ b/flang/include/flang/Frontend/CompilerInvocation.h @@ -0,0 +1,53 @@ +//===- CompilerInvocation.h - Compiler Invocation Helper Data ---*- 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_FLANG_FRONTEND_COMPILERINVOCATION_H +#define LLVM_FLANG_FRONTEND_COMPILERINVOCATION_H + +#include "flang/Frontend/FrontendOptions.h" +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticOptions.h" + +namespace flang { +class CompilerInvocationBase { +public: + /// Options controlling the diagnostic engine.$ + llvm::IntrusiveRefCntPtr DiagnosticOpts; + + CompilerInvocationBase(); + CompilerInvocationBase(const CompilerInvocationBase &X); + ~CompilerInvocationBase(); + + clang::DiagnosticOptions &getDiagnosticOpts() { + return *DiagnosticOpts.get(); + } + const clang::DiagnosticOptions &getDiagnosticOpts() const { + return *DiagnosticOpts.get(); + } +}; + +class CompilerInvocation : public CompilerInvocationBase { + /// Options controlling the frontend itself. + FrontendOptions FrontendOpts; + +public: + CompilerInvocation() = default; + + FrontendOptions &getFrontendOpts() { return FrontendOpts; } + const FrontendOptions &getFrontendOpts() const { return FrontendOpts; } + + /// Create a compiler invocation from a list of input options. + /// \returns true on success. + /// \returns false if an error was encountered while parsing the arguments + /// \param [out] Res - The resulting invocation. + static bool CreateFromArgs(CompilerInvocation &Res, + llvm::ArrayRef CommandLineArgs, + clang::DiagnosticsEngine &Diags); +}; + +} // end namespace flang +#endif // LLVM_FLANG_FRONTEND_COMPILERINVOCATION_H diff --git a/flang/include/flang/Frontend/FrontendOptions.h b/flang/include/flang/Frontend/FrontendOptions.h new file mode 100644 --- /dev/null +++ b/flang/include/flang/Frontend/FrontendOptions.h @@ -0,0 +1,72 @@ +//===- FrontendOptions.h ----------------------------------------*- 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_FLANG_FRONTEND_FRONTENDOPTIONS_H +#define LLVM_FLANG_FRONTEND_FRONTENDOPTIONS_H + +#include +#include +namespace flang { + +enum class Language : uint8_t { + Unknown, + + /// LLVM IR: we accept this so that we can run the optimizer on it, + /// and compile it to assembly or object code. + LLVM_IR, + + ///@{ Languages that the frontend can parse and compile. + Fortran, + ///@} +}; + +/// The kind of a file that we've been handed as an input. +class InputKind { +private: + Language Lang; + unsigned Fmt : 3; + unsigned Preprocessed : 1; + +public: + /// The input file format. + enum Format { Source, ModuleMap, Precompiled }; + + constexpr InputKind( + Language L = Language::Unknown, Format F = Source, bool PP = false) + : Lang(L), Fmt(F), Preprocessed(PP) {} + + Language getLanguage() const { return static_cast(Lang); } + Format getFormat() const { return static_cast(Fmt); } + bool isPreprocessed() const { return Preprocessed; } + + /// Is the input kind fully-unknown? + bool isUnknown() const { return Lang == Language::Unknown && Fmt == Source; } + + InputKind getPreprocessed() const { + return InputKind(getLanguage(), getFormat(), true); + } + + InputKind withFormat(Format F) const { + return InputKind(getLanguage(), F, isPreprocessed()); + } +}; + +/// FrontendOptions - Options for controlling the behavior of the frontend. +class FrontendOptions { +public: + /// Show the -help text. + unsigned ShowHelp : 1; + + /// Show the -version text. + unsigned ShowVersion : 1; + +public: + FrontendOptions() : ShowHelp(false), ShowVersion(false) {} +}; +} // namespace flang + +#endif // LLVM_FLANG_FRONTEND_FRONTENDOPTIONS_H diff --git a/flang/include/flang/FrontendTool/Utils.h b/flang/include/flang/FrontendTool/Utils.h new file mode 100644 --- /dev/null +++ b/flang/include/flang/FrontendTool/Utils.h @@ -0,0 +1,32 @@ + +//===--- Utils.h - Misc utilities for the flang front-end --------*- 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 header contains miscellaneous utilities for various front-end actions +// which were split from Frontend to minimise Frontend's dependencies. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_FLANG_FRONTENDTOOL_UTILS_H +#define LLVM_FLANG_FRONTENDTOOL_UTILS_H + +#include + +namespace flang { + +class CompilerInstance; + +/// ExecuteCompilerInvocation - Execute the given actions described by the +/// compiler invocation object in the given compiler instance. +/// +/// \return - True on success. +bool ExecuteCompilerInvocation(CompilerInstance *Flang); + +} // end namespace flang + +#endif // LLVM_FLANG_FRONTENDTOOL_UTILS_H diff --git a/flang/lib/CMakeLists.txt b/flang/lib/CMakeLists.txt --- a/flang/lib/CMakeLists.txt +++ b/flang/lib/CMakeLists.txt @@ -5,6 +5,11 @@ add_subdirectory(Parser) add_subdirectory(Semantics) +if(BUILD_FLANG_NEW_DRIVER) + add_subdirectory(Frontend) + add_subdirectory(FrontendTool) +endif() + if(LINK_WITH_FIR) add_subdirectory(Optimizer) endif() diff --git a/flang/lib/Frontend/CMakeLists.txt b/flang/lib/Frontend/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/flang/lib/Frontend/CMakeLists.txt @@ -0,0 +1,22 @@ + +add_library(flangFrontend + CompilerInstance.cpp + CompilerInvocation.cpp + FrontendOptions.cpp +) + +# ClangFrontend was added to help Diagnostic error +# Further work may be required +target_link_libraries(flangFrontend + LLVMOption + LLVMSupport + clangBasic + clangDriver + clangFrontend +) + +install (TARGETS flangFrontend + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin +) diff --git a/flang/lib/Frontend/CompilerInstance.cpp b/flang/lib/Frontend/CompilerInstance.cpp new file mode 100644 --- /dev/null +++ b/flang/lib/Frontend/CompilerInstance.cpp @@ -0,0 +1,42 @@ +//===--- CompilerInstance.cpp ---------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#include "flang/Frontend/CompilerInstance.h" +#include "flang/Frontend/CompilerInvocation.h" +#include "clang/Frontend/TextDiagnosticPrinter.h" +#include "llvm/Support/raw_ostream.h" + +using namespace flang; + +CompilerInstance::CompilerInstance() : Invocation(new CompilerInvocation()) {} + +CompilerInstance::~CompilerInstance() = default; + +void CompilerInstance::createDiagnostics( + clang::DiagnosticConsumer *Client, bool ShouldOwnClient) { + Diagnostics = + createDiagnostics(&getDiagnosticOpts(), Client, ShouldOwnClient); +} + +clang::IntrusiveRefCntPtr +CompilerInstance::createDiagnostics(clang::DiagnosticOptions *Opts, + clang::DiagnosticConsumer *Client, bool ShouldOwnClient) { + clang::IntrusiveRefCntPtr DiagID( + new clang::DiagnosticIDs()); + clang::IntrusiveRefCntPtr Diags( + new clang::DiagnosticsEngine(DiagID, Opts)); + + // Create the diagnostic client for reporting errors or for + // implementing -verify. + if (Client) { + Diags->setClient(Client, ShouldOwnClient); + } else + Diags->setClient(new clang::TextDiagnosticPrinter(llvm::errs(), Opts)); + + return Diags; +} diff --git a/flang/lib/Frontend/CompilerInvocation.cpp b/flang/lib/Frontend/CompilerInvocation.cpp new file mode 100644 --- /dev/null +++ b/flang/lib/Frontend/CompilerInvocation.cpp @@ -0,0 +1,94 @@ +//===- CompilerInvocation.cpp ---------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#include "flang/Frontend/CompilerInvocation.h" +#include "clang/Basic/AllDiagnostics.h" +#include "clang/Basic/DiagnosticDriver.h" +#include "clang/Basic/DiagnosticOptions.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Driver/Options.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/Option/Arg.h" +#include "llvm/Option/ArgList.h" +#include "llvm/Option/OptTable.h" +#include "llvm/Support/raw_ostream.h" + +using namespace flang; + +//===----------------------------------------------------------------------===// +// Initialization. +//===----------------------------------------------------------------------===// +CompilerInvocationBase::CompilerInvocationBase() + : DiagnosticOpts(new clang::DiagnosticOptions()) {} + +CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X) + : DiagnosticOpts(new clang::DiagnosticOptions(X.getDiagnosticOpts())) {} + +CompilerInvocationBase::~CompilerInvocationBase() = default; + +static InputKind ParseFrontendArgs(FrontendOptions &Opts, + llvm::opt::ArgList &Args, clang::DiagnosticsEngine &Diags) { + if (const llvm::opt::Arg *A = + Args.getLastArg(clang::driver::options::OPT_Action_Group)) { + switch (A->getOption().getID()) { + default: { + // Happens when no option is passed to the driver + llvm::errs() << "Unknown Option"; + Diags.Report(clang::diag::err_drv_invalid_value) << "Unknown" + << "Options"; + InputKind DashX(Language::Unknown); + return DashX; + } + } + } + + Opts.ShowHelp = Args.hasArg(clang::driver::options::OPT_help); + Opts.ShowVersion = Args.hasArg(clang::driver::options::OPT_version); + + InputKind DashX(Language::Unknown); + if (const llvm::opt::Arg *A = + Args.getLastArg(clang::driver::options::OPT_x)) { + llvm::StringRef XValue = A->getValue(); + // Principal languages. + DashX = llvm::StringSwitch(XValue) + .Case("f90", Language::Fortran) + .Default(Language::Unknown); + + // Some special cases cannot be combined with suffixes. + if (DashX.isUnknown()) + DashX = llvm::StringSwitch(XValue) + .Case("ir", Language::LLVM_IR) + .Default(Language::Unknown); + if (DashX.isUnknown()) + Diags.Report(clang::diag::err_drv_invalid_value) + << A->getAsString(Args) << A->getValue(); + } + + return DashX; +} + +bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, + llvm::ArrayRef CommandLineArgs, + clang::DiagnosticsEngine &Diags) { + + bool Success = true; + + // Parse the arguments. + const llvm::opt::OptTable &Opts = clang::driver::getDriverOptTable(); + const unsigned IncludedFlagsBitmask = + clang::driver::options::CC1Option | clang::driver::options::FlangOption; + unsigned MissingArgIndex, MissingArgCount; + llvm::opt::InputArgList Args = Opts.ParseArgs( + CommandLineArgs, MissingArgIndex, MissingArgCount, IncludedFlagsBitmask); + + InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags); + (void)DashX; + + return Success; +} diff --git a/flang/lib/Frontend/FrontendOptions.cpp b/flang/lib/Frontend/FrontendOptions.cpp new file mode 100644 --- /dev/null +++ b/flang/lib/Frontend/FrontendOptions.cpp @@ -0,0 +1,9 @@ +//===- FrontendOptions.cpp ------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#include "flang/Frontend/FrontendOptions.h" diff --git a/flang/lib/FrontendTool/CMakeLists.txt b/flang/lib/FrontendTool/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/flang/lib/FrontendTool/CMakeLists.txt @@ -0,0 +1,16 @@ +add_library(flangFrontendTool + ExecuteCompilerInvocation.cpp + ) + +target_link_libraries(flangFrontendTool + LLVMOption + LLVMSupport + clangBasic + clangDriver +) + +install (TARGETS flangFrontendTool + ARCHIVE DESTINATION lib + LIBRARY DESTINATION lib + RUNTIME DESTINATION bin +) diff --git a/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp b/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp new file mode 100644 --- /dev/null +++ b/flang/lib/FrontendTool/ExecuteCompilerInvocation.cpp @@ -0,0 +1,42 @@ +//===--- ExecuteCompilerInvocation.cpp ------------------------------------===// +// +// 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 holds ExecuteCompilerInvocation(). It is split into its own file to +// minimize the impact of pulling in essentially everything else in Clang. +// +//===----------------------------------------------------------------------===// + +#include "flang/Frontend/CompilerInstance.h" +#include "clang/Driver/Options.h" +#include "llvm/Option/OptTable.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/raw_ostream.h" + +using namespace flang; +namespace flang { +bool ExecuteCompilerInvocation(CompilerInstance *Flang) { + // Honor -help. + if (Flang->getFrontendOpts().ShowHelp) { + clang::driver::getDriverOptTable().PrintHelp(llvm::outs(), + "flang-new -fc1 [options] file...", "LLVM 'Flang' Compiler:", + /*Include=*/clang::driver::options::FlangOption, + /*Exclude=*/0, /*ShowAllAliases=*/false); + return true; + } + // Honor -version. + // + // FIXME: Use a better -version message? + if (Flang->getFrontendOpts().ShowVersion) { + llvm::cl::PrintVersionMessage(); + return true; + } + + return true; +} + +} // namespace flang diff --git a/flang/test/CMakeLists.txt b/flang/test/CMakeLists.txt --- a/flang/test/CMakeLists.txt +++ b/flang/test/CMakeLists.txt @@ -37,6 +37,10 @@ list(APPEND FLANG_TEST_DEPENDS tco) endif() +if (BUILD_FLANG_NEW_DRIVER) + list(APPEND FLANG_TEST_DEPENDS flang-new) +endif() + if (FLANG_INCLUDE_TESTS) if (FLANG_GTEST_AVAIL) list(APPEND FLANG_TEST_DEPENDS FlangUnitTests) diff --git a/flang/test/Flang-Driver/driver-error-cc1.c b/flang/test/Flang-Driver/driver-error-cc1.c new file mode 100644 --- /dev/null +++ b/flang/test/Flang-Driver/driver-error-cc1.c @@ -0,0 +1,6 @@ +! Test invalid frontend argument for the driver +! Use c file to call flang-new -cc1 + +! RUN: %flang-new %s 2>&1 | FileCheck %s + +! CHECK:error: unknown integrated tool '-cc1'. Valid tools include '-fc1'. diff --git a/flang/test/Flang-Driver/driver-error-cc1.cpp b/flang/test/Flang-Driver/driver-error-cc1.cpp new file mode 100644 --- /dev/null +++ b/flang/test/Flang-Driver/driver-error-cc1.cpp @@ -0,0 +1,6 @@ +! Test invalid frontend argument for the driver +! Use cpp file to call flang-new -cc1 + +! RUN: %flang-new %s 2>&1 | FileCheck %s + +! CHECK:error: unknown integrated tool '-cc1'. Valid tools include '-fc1'. diff --git a/flang/test/Flang-Driver/driver-error-diagnostic.f90 b/flang/test/Flang-Driver/driver-error-diagnostic.f90 new file mode 100644 --- /dev/null +++ b/flang/test/Flang-Driver/driver-error-diagnostic.f90 @@ -0,0 +1,7 @@ +! Test driver 'flang-new' error diagnostic messages + +! RUN: not %flang-new --versiona 2>&1 | FileCheck %s +! RUN: not %flang-new --helps 2>&1 | FileCheck %s + +! CHECK:error: unsupported option +! CHECK-NEXT:error: no input files diff --git a/flang/test/Flang-Driver/driver-help.f90 b/flang/test/Flang-Driver/driver-help.f90 new file mode 100644 --- /dev/null +++ b/flang/test/Flang-Driver/driver-help.f90 @@ -0,0 +1,12 @@ +! Test flang driver 'flang-new' and flang frontend driver 'flang-new -fc1' help screen + +! RUN: %flang-new -help 2>&1 | FileCheck %s +! RUN: %flang-new -fc1 -help 2>&1 | FileCheck %s + +! CHECK:OVERVIEW: LLVM 'Flang' Compiler: +! CHECK-EMPTY: +! CHECK-NEXT:USAGE: flang-new +! CHECK-EMPTY: +! CHECK-NEXT:OPTIONS: +! CHECK-NEXT: -help Display available options +! CHECK-NEXT: --version Print version information \ No newline at end of file diff --git a/flang/test/Flang-Driver/driver-version.f90 b/flang/test/Flang-Driver/driver-version.f90 new file mode 100644 --- /dev/null +++ b/flang/test/Flang-Driver/driver-version.f90 @@ -0,0 +1,5 @@ +! Test driver 'flang-new' print version + +! RUN: %flang-new --version 2>&1 | FileCheck %s + +! CHECK:Flang experimental driver (flang-new) diff --git a/flang/test/lit.cfg.py b/flang/test/lit.cfg.py --- a/flang/test/lit.cfg.py +++ b/flang/test/lit.cfg.py @@ -25,7 +25,7 @@ config.test_format = lit.formats.ShTest(not llvm_config.use_lit_shell) # suffixes: A list of file extensions to treat as test files. -config.suffixes = ['.f', '.F', '.ff','.FOR', '.for', '.f77', '.f90', '.F90', +config.suffixes = ['.c', '.cpp', '.f', '.F', '.ff','.FOR', '.for', '.f77', '.f90', '.F90', '.ff90', '.f95', '.F95', '.ff95', '.fpp', '.FPP', '.cuf', '.CUF', '.f18', '.F18', '.fir' ] @@ -36,7 +36,11 @@ # excludes: A list of directories to exclude from the testsuite. The 'Inputs' # subdirectories contain auxiliary inputs for various tests in their parent # directories. -config.excludes = ['Inputs', 'CMakeLists.txt', 'README.txt', 'LICENSE.txt'] +# exclude the tests for flang_new driver while there are two drivers +if config.include_flang_new_driver_test == "OFF": + config.excludes = ['Inputs', 'CMakeLists.txt', 'README.txt', 'LICENSE.txt', 'Flang-Driver'] +else : + config.excludes = ['Inputs', 'CMakeLists.txt', 'README.txt', 'LICENSE.txt'] # test_source_root: The root path where tests are located. config.test_source_root = os.path.dirname(__file__) @@ -57,6 +61,7 @@ # For each occurrence of a flang tool name, replace it with the full path to # the build directory holding that tool. tools = [ + ToolSubst('%flang-new', command=FindTool('flang-new'), unresolved='ignore'), ToolSubst('%f18', command=FindTool('f18'), extra_args=["-intrinsic-module-directory "+config.flang_intrinsic_modules_dir], unresolved='fatal') diff --git a/flang/test/lit.site.cfg.py.in b/flang/test/lit.site.cfg.py.in --- a/flang/test/lit.site.cfg.py.in +++ b/flang/test/lit.site.cfg.py.in @@ -10,6 +10,9 @@ config.flang_llvm_tools_dir = "@CMAKE_BINARY_DIR@/bin" config.python_executable = "@PYTHON_EXECUTABLE@" +# controld the regression test for flang-new driver +config.include_flang_new_driver_test="@BUILD_FLANG_NEW_DRIVER@" + # Support substitution of the tools_dir with user parameters. This is # used when we can't determine the tool dir at configuration time. try: diff --git a/flang/tools/CMakeLists.txt b/flang/tools/CMakeLists.txt --- a/flang/tools/CMakeLists.txt +++ b/flang/tools/CMakeLists.txt @@ -7,6 +7,9 @@ #===------------------------------------------------------------------------===# add_subdirectory(f18) +if(BUILD_FLANG_NEW_DRIVER) + add_subdirectory(flang-driver) +endif() if(LINK_WITH_FIR) add_subdirectory(tco) endif() diff --git a/flang/tools/flang-driver/CMakeLists.txt b/flang/tools/flang-driver/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/flang/tools/flang-driver/CMakeLists.txt @@ -0,0 +1,26 @@ +# Infrastructure to build flang driver entry point. Flang driver depends on +# LLVM libraries. + +# Set your project compile flags. +link_directories(${LLVM_LIBRARY_DIR}) + +add_executable(flang-new + driver.cpp + fc1_main.cpp +) + +# Link against LLVM and Clang libraries +target_link_libraries(flang-new + PRIVATE + ${LLVM_COMMON_LIBS} + flangFrontend + flangFrontendTool + clangDriver + clangBasic + clangFrontend + LLVMSupport + LLVMTarget + LLVMOption +) + +install(TARGETS flang-new DESTINATION bin) diff --git a/flang/tools/flang-driver/driver.cpp b/flang/tools/flang-driver/driver.cpp new file mode 100644 --- /dev/null +++ b/flang/tools/flang-driver/driver.cpp @@ -0,0 +1,105 @@ +//===-- main.cpp - Flang Driver -----------------------------------------===// +// +// 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 is the entry point to the flang driver; it is a thin wrapper +// for functionality in the Driver flang library. +// +//===----------------------------------------------------------------------===// +// ClangFrontend was added to help Diagnostic error +// Further work may be required +#include "clang/Driver/Driver.h" +#include "clang/Basic/Diagnostic.h" +#include "clang/Basic/DiagnosticIDs.h" +#include "clang/Basic/DiagnosticOptions.h" +#include "clang/Driver/Compilation.h" +#include "clang/Frontend/TextDiagnosticPrinter.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/IntrusiveRefCntPtr.h" +#include "llvm/Option/ArgList.h" +#include "llvm/Support/Host.h" +#include "llvm/Support/InitLLVM.h" +#include "llvm/Support/VirtualFileSystem.h" + +// main frontend method. Lives inside fc1_main.cpp +extern int fc1_main( + llvm::ArrayRef Argv, const char *Argv0, void *MainAddr); + +std::string GetExecutablePath(const char *Argv0) { + // This just needs to be some symbol in the binary + void *P = (void *)(intptr_t)GetExecutablePath; + return llvm::sys::fs::getMainExecutable(Argv0, P); +} + +// This lets us create the DiagnosticsEngine with a properly-filled-out +// DiagnosticOptions instance +static clang::DiagnosticOptions *CreateAndPopulateDiagOpts( + llvm::ArrayRef argv) { + auto *DiagOpts = new clang::DiagnosticOptions; + return DiagOpts; +} + +static int ExecuteFC1Tool(llvm::SmallVectorImpl &ArgV) { + llvm::StringRef Tool = ArgV[1]; + void *GetExecutablePathVP = (void *)(intptr_t)GetExecutablePath; + if (Tool == "-fc1") + return fc1_main(makeArrayRef(ArgV).slice(2), ArgV[0], GetExecutablePathVP); + + // Reject unknown tools. + // ATM it only supports fc1. Any fc1[*] is rejected. + llvm::errs() << "error: unknown integrated tool '" << Tool << "'. " + << "Valid tools include '-fc1'.\n"; + return 1; +} + +int main(int argc_, const char **argv_) { + + // Initialize variables to call the driver + llvm::InitLLVM X(argc_, argv_); + llvm::SmallVector argv(argv_, argv_ + argc_); + + clang::driver::ParsedClangName TargetandMode("flang", "--driver-mode=flang"); + std::string DriverPath = GetExecutablePath(argv[0]); + + // Check if flang-new is in frontend mode + auto FirstArg = std::find_if( + argv.begin() + 1, argv.end(), [](const char *A) { return A != nullptr; }); + if (FirstArg != argv.end()) { + // Something went wrong, unsupported code path. + // Exit early (return 1). + if (llvm::StringRef(argv[1]).startswith("-cc1")) { + llvm::errs() << "error: unknown integrated tool '" << argv[1] << "'. " + << "Valid tools include '-fc1'.\n"; + return 1; + } + // Call flang-new frontend + if (llvm::StringRef(argv[1]).startswith("-fc1")) { + return ExecuteFC1Tool(argv); + } + } + + // Do driver tasks. Not in the frontend mode. + + // Create DiagnosticsEngine + llvm::IntrusiveRefCntPtr DiagOpts = + CreateAndPopulateDiagOpts(argv); + llvm::IntrusiveRefCntPtr DiagID( + new clang::DiagnosticIDs()); + clang::TextDiagnosticPrinter *DiagClient = + new clang::TextDiagnosticPrinter(llvm::errs(), &*DiagOpts); + clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagClient); + + // Prepare driver and run + clang::driver::Driver TheDriver(DriverPath, + llvm::sys::getDefaultTargetTriple(), Diags, "LLVM 'Flang' Compiler:"); + TheDriver.setTargetAndMode(TargetandMode); + std::unique_ptr C( + TheDriver.BuildCompilation(argv)); + llvm::SmallVector, 4> + FailingCommands; + return TheDriver.ExecuteCompilation(*C, FailingCommands); +} diff --git a/flang/tools/flang-driver/fc1_main.cpp b/flang/tools/flang-driver/fc1_main.cpp new file mode 100644 --- /dev/null +++ b/flang/tools/flang-driver/fc1_main.cpp @@ -0,0 +1,57 @@ +//===-- fc1_main.cpp - Flang FC1 Compiler Frontend ------------------------===// +// +// 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 is the entry point to the flang -fc1 functionality, which implements the +// core compiler functionality along with a number of additional tools for +// demonstration and testing purposes. +// +//===----------------------------------------------------------------------===// + +#include "flang/Frontend/CompilerInstance.h" +#include "flang/Frontend/CompilerInvocation.h" +#include "flang/FrontendTool/Utils.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Frontend/TextDiagnosticBuffer.h" +#include "llvm/Option/Arg.h" +#include "llvm/Option/ArgList.h" +#include "llvm/Option/OptTable.h" +#include "llvm/Support/Process.h" +#include "llvm/Support/Signals.h" +#include "llvm/Support/raw_ostream.h" + +#include + +using namespace flang; + +int fc1_main( + llvm::ArrayRef Argv, const char *Argv0, void *MainAddr) { + + // Create DiagnosticsEngine + llvm::IntrusiveRefCntPtr DiagID( + new clang::DiagnosticIDs()); + llvm::IntrusiveRefCntPtr DiagOpts = + new clang::DiagnosticOptions(); + clang::TextDiagnosticBuffer *DiagsBuffer = new clang::TextDiagnosticBuffer; + clang::DiagnosticsEngine Diags(DiagID, &*DiagOpts, DiagsBuffer); + + // Create compiler instance compiler invocation to have a frontend + std::unique_ptr Flang(new CompilerInstance()); + + // Diagnostics engine for the frontend. + Flang->createDiagnostics(); + if (!Flang->hasDiagnostics()) + return 1; + + bool Success = + CompilerInvocation::CreateFromArgs(Flang->getInvocation(), Argv, Diags); + + // Execute the frontend actions. + { Success = ExecuteCompilerInvocation(Flang.get()); } + + return !Success; +} diff --git a/flang/unittests/CMakeLists.txt b/flang/unittests/CMakeLists.txt --- a/flang/unittests/CMakeLists.txt +++ b/flang/unittests/CMakeLists.txt @@ -22,3 +22,7 @@ add_subdirectory(Evaluate) add_subdirectory(Runtime) add_subdirectory(Lower) + +if (BUILD_FLANG_NEW_DRIVER) +add_subdirectory(Frontend) +endif() diff --git a/flang/unittests/Frontend/CMakeLists.txt b/flang/unittests/Frontend/CMakeLists.txt new file mode 100644 --- /dev/null +++ b/flang/unittests/Frontend/CMakeLists.txt @@ -0,0 +1,10 @@ +add_flang_unittest(FlangFrontendTests + CompilerInstanceTest.cpp +) + +target_link_libraries(FlangFrontendTests + PRIVATE + LLVMSupport + clangBasic + flangFrontend + flangFrontendTool) diff --git a/flang/unittests/Frontend/CompilerInstanceTest.cpp b/flang/unittests/Frontend/CompilerInstanceTest.cpp new file mode 100644 --- /dev/null +++ b/flang/unittests/Frontend/CompilerInstanceTest.cpp @@ -0,0 +1,52 @@ +//===- unittests/Frontend/CompilerInstanceTest.cpp - CI tests -------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#include "flang/Frontend/CompilerInstance.h" +#include "gtest/gtest.h" +#include "flang/Frontend/CompilerInvocation.h" +#include "clang/Basic/DiagnosticOptions.h" +#include "clang/Driver/Options.h" +#include "clang/Frontend/TextDiagnosticPrinter.h" +#include "llvm/Support/raw_ostream.h" + +#include +using namespace llvm; +using namespace flang; + +namespace { + +TEST(CompilerInstance, AllowDiagnosticLogWithUnownedDiagnosticConsumer) { + // 1. Set-up a basic DiagnosticConsumer + std::string DiagnosticOutput; + llvm::raw_string_ostream DiagnosticsOS(DiagnosticOutput); + auto DiagPrinter = std::make_unique( + DiagnosticsOS, new clang::DiagnosticOptions()); + + // 2. Create a CompilerInstance (to manage a DiagnosticEngine) + CompilerInstance CompInst; + + // 3. Set-up DiagnosticOptions + auto DiagOpts = new clang::DiagnosticOptions(); + // Tell the diagnostics engine to emit the diagnostic log to STDERR. This + // ensures that a chained diagnostic consumer is created so that the test can + // exercise the unowned diagnostic consumer in a chained consumer. + DiagOpts->DiagnosticLogFile = "-"; + + // 4. Create a DiagnosticEngine with an unowned consumer + IntrusiveRefCntPtr Diags = + CompInst.createDiagnostics( + DiagOpts, DiagPrinter.get(), /*ShouldOwnClient=*/false); + + // 5. Report a diagnostic + Diags->Report(clang::diag::err_expected) << "no crash"; + + // 6. Verify that the reported diagnostic wasn't lost and did end up in the + // output stream + ASSERT_EQ(DiagnosticsOS.str(), "error: expected no crash\n"); +} +} // namespace diff --git a/llvm/lib/Option/OptTable.cpp b/llvm/lib/Option/OptTable.cpp --- a/llvm/lib/Option/OptTable.cpp +++ b/llvm/lib/Option/OptTable.cpp @@ -612,7 +612,19 @@ unsigned Flags = getInfo(Id).Flags; if (FlagsToInclude && !(Flags & FlagsToInclude)) continue; - if (Flags & FlagsToExclude) + // If `Flags` is in both the Exclude set and in the Include set - display + // it. + if ((Flags & FlagsToExclude) && !(Flags & FlagsToInclude)) + continue; + + // If `Flags` is empty (i.e. it's an option without any flags) then this is + // a Clang-only option. If: + // * we _are not_ in Flang Mode (FlagsToExclude contains FlangMode), then + // display it. + // * we _are_ in Flang mode (FlagsToExclude does not contain FlangMode), + // don't display it. + if (!Flags && + (FlagsToExclude & /*clang::driver::options::FlangMode*/ (1 << 14))) continue; // If an alias doesn't have a help text, show a help text for the aliased