[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / flang / tools / flang-driver / driver.cpp
blob99fa66b0dc8e266a84fac7227fbf6b104b65ab24
1 //===-- driver.cpp - Flang Driver -----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This is the entry point to the flang driver; it is a thin wrapper
10 // for functionality in the Driver flang library.
12 //===----------------------------------------------------------------------===//
14 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/
16 //===----------------------------------------------------------------------===//
18 #include "clang/Driver/Driver.h"
19 #include "flang/Frontend/CompilerInvocation.h"
20 #include "flang/Frontend/TextDiagnosticPrinter.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticIDs.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Driver/Compilation.h"
25 #include "llvm/ADT/ArrayRef.h"
26 #include "llvm/ADT/IntrusiveRefCntPtr.h"
27 #include "llvm/Option/ArgList.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/InitLLVM.h"
30 #include "llvm/Support/VirtualFileSystem.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/TargetParser/Host.h"
33 #include <stdlib.h>
35 // main frontend method. Lives inside fc1_main.cpp
36 extern int fc1_main(llvm::ArrayRef<const char *> argv, const char *argv0);
38 std::string getExecutablePath(const char *argv0) {
39 // This just needs to be some symbol in the binary
40 void *p = (void *)(intptr_t)getExecutablePath;
41 return llvm::sys::fs::getMainExecutable(argv0, p);
44 // This lets us create the DiagnosticsEngine with a properly-filled-out
45 // DiagnosticOptions instance
46 static clang::DiagnosticOptions *
47 createAndPopulateDiagOpts(llvm::ArrayRef<const char *> argv) {
48 auto *diagOpts = new clang::DiagnosticOptions;
50 // Ignore missingArgCount and the return value of ParseDiagnosticArgs.
51 // Any errors that would be diagnosed here will also be diagnosed later,
52 // when the DiagnosticsEngine actually exists.
53 unsigned missingArgIndex, missingArgCount;
54 llvm::opt::InputArgList args = clang::driver::getDriverOptTable().ParseArgs(
55 argv.slice(1), missingArgIndex, missingArgCount,
56 llvm::opt::Visibility(clang::driver::options::FlangOption));
58 (void)Fortran::frontend::parseDiagnosticArgs(*diagOpts, args);
60 return diagOpts;
63 static int executeFC1Tool(llvm::SmallVectorImpl<const char *> &argV) {
64 llvm::StringRef tool = argV[1];
65 if (tool == "-fc1")
66 return fc1_main(llvm::ArrayRef(argV).slice(2), argV[0]);
68 // Reject unknown tools.
69 // ATM it only supports fc1. Any fc1[*] is rejected.
70 llvm::errs() << "error: unknown integrated tool '" << tool << "'. "
71 << "Valid tools include '-fc1'.\n";
72 return 1;
75 static void ExpandResponseFiles(llvm::StringSaver &saver,
76 llvm::SmallVectorImpl<const char *> &args) {
77 // We're defaulting to the GNU syntax, since we don't have a CL mode.
78 llvm::cl::TokenizerCallback tokenizer = &llvm::cl::TokenizeGNUCommandLine;
79 llvm::cl::ExpansionContext ExpCtx(saver.getAllocator(), tokenizer);
80 if (llvm::Error Err = ExpCtx.expandResponseFiles(args)) {
81 llvm::errs() << toString(std::move(Err)) << '\n';
85 int main(int argc, const char **argv) {
87 // Initialize variables to call the driver
88 llvm::InitLLVM x(argc, argv);
89 llvm::SmallVector<const char *, 256> args(argv, argv + argc);
91 clang::driver::ParsedClangName targetandMode("flang", "--driver-mode=flang");
92 std::string driverPath = getExecutablePath(args[0]);
94 llvm::BumpPtrAllocator a;
95 llvm::StringSaver saver(a);
96 ExpandResponseFiles(saver, args);
98 // Check if flang-new is in the frontend mode
99 auto firstArg = std::find_if(args.begin() + 1, args.end(),
100 [](const char *a) { return a != nullptr; });
101 if (firstArg != args.end()) {
102 if (llvm::StringRef(args[1]).startswith("-cc1")) {
103 llvm::errs() << "error: unknown integrated tool '" << args[1] << "'. "
104 << "Valid tools include '-fc1'.\n";
105 return 1;
107 // Call flang-new frontend
108 if (llvm::StringRef(args[1]).startswith("-fc1")) {
109 return executeFC1Tool(args);
113 // Not in the frontend mode - continue in the compiler driver mode.
115 // Create DiagnosticsEngine for the compiler driver
116 llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagOpts =
117 createAndPopulateDiagOpts(args);
118 llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID(
119 new clang::DiagnosticIDs());
120 Fortran::frontend::TextDiagnosticPrinter *diagClient =
121 new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), &*diagOpts);
123 diagClient->setPrefix(
124 std::string(llvm::sys::path::stem(getExecutablePath(args[0]))));
126 clang::DiagnosticsEngine diags(diagID, &*diagOpts, diagClient);
128 // Prepare the driver
129 clang::driver::Driver theDriver(driverPath,
130 llvm::sys::getDefaultTargetTriple(), diags,
131 "flang LLVM compiler");
132 theDriver.setTargetAndMode(targetandMode);
133 std::unique_ptr<clang::driver::Compilation> c(
134 theDriver.BuildCompilation(args));
135 llvm::SmallVector<std::pair<int, const clang::driver::Command *>, 4>
136 failingCommands;
138 // Set the environment variable, FLANG_COMPILER_OPTIONS_STRING, to contain all
139 // the compiler options. This is intended for the frontend driver,
140 // flang-new -fc1, to enable the implementation of the COMPILER_OPTIONS
141 // intrinsic. To this end, the frontend driver requires the list of the
142 // original compiler options, which is not available through other means.
143 // TODO: This way of passing information between the compiler and frontend
144 // drivers is discouraged. We should find a better way not involving env
145 // variables.
146 std::string compilerOptsGathered;
147 llvm::raw_string_ostream os(compilerOptsGathered);
148 for (int i = 0; i < argc; ++i) {
149 os << argv[i];
150 if (i < argc - 1) {
151 os << ' ';
154 #ifdef _WIN32
155 _putenv_s("FLANG_COMPILER_OPTIONS_STRING", compilerOptsGathered.c_str());
156 #else
157 setenv("FLANG_COMPILER_OPTIONS_STRING", compilerOptsGathered.c_str(), 1);
158 #endif
160 // Run the driver
161 int res = 1;
162 bool isCrash = false;
163 res = theDriver.ExecuteCompilation(*c, failingCommands);
165 for (const auto &p : failingCommands) {
166 int commandRes = p.first;
167 const clang::driver::Command *failingCommand = p.second;
168 if (!res)
169 res = commandRes;
171 // If result status is < 0 (e.g. when sys::ExecuteAndWait returns -1),
172 // then the driver command signalled an error. On Windows, abort will
173 // return an exit code of 3. In these cases, generate additional diagnostic
174 // information if possible.
175 isCrash = commandRes < 0;
176 #ifdef _WIN32
177 isCrash |= commandRes == 3;
178 #endif
179 if (isCrash) {
180 theDriver.generateCompilationDiagnostics(*c, *failingCommand);
181 break;
185 diags.getClient()->finish();
187 // If we have multiple failing commands, we return the result of the first
188 // failing command.
189 return res;