xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision 87dfd5e012e147f4bfa3a9a4564e9cbc167278ff)
1 //===- CompilerInvocation.cpp ---------------------------------------------===//
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 #include "flang/Frontend/CompilerInvocation.h"
10 #include "flang/Frontend/PreprocessorOptions.h"
11 #include "clang/Basic/AllDiagnostics.h"
12 #include "clang/Basic/DiagnosticDriver.h"
13 #include "clang/Basic/DiagnosticOptions.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Options.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/Option/Arg.h"
19 #include "llvm/Option/ArgList.h"
20 #include "llvm/Option/OptTable.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace Fortran::frontend;
25 
26 //===----------------------------------------------------------------------===//
27 // Initialization.
28 //===----------------------------------------------------------------------===//
29 CompilerInvocationBase::CompilerInvocationBase()
30     : diagnosticOpts_(new clang::DiagnosticOptions()),
31       preprocessorOpts_(new PreprocessorOptions()) {}
32 
33 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
34     : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())),
35       preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {}
36 
37 CompilerInvocationBase::~CompilerInvocationBase() = default;
38 
39 //===----------------------------------------------------------------------===//
40 // Deserialization (from args)
41 //===----------------------------------------------------------------------===//
42 static bool parseShowColorsArgs(
43     const llvm::opt::ArgList &args, bool defaultColor) {
44   // Color diagnostics default to auto ("on" if terminal supports) in the driver
45   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
46   // Support both clang's -f[no-]color-diagnostics and gcc's
47   // -f[no-]diagnostics-colors[=never|always|auto].
48   enum {
49     Colors_On,
50     Colors_Off,
51     Colors_Auto
52   } ShowColors = defaultColor ? Colors_Auto : Colors_Off;
53 
54   for (auto *a : args) {
55     const llvm::opt::Option &O = a->getOption();
56     if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) ||
57         O.matches(clang::driver::options::OPT_fdiagnostics_color)) {
58       ShowColors = Colors_On;
59     } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) ||
60         O.matches(clang::driver::options::OPT_fno_diagnostics_color)) {
61       ShowColors = Colors_Off;
62     } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
63       llvm::StringRef value(a->getValue());
64       if (value == "always")
65         ShowColors = Colors_On;
66       else if (value == "never")
67         ShowColors = Colors_Off;
68       else if (value == "auto")
69         ShowColors = Colors_Auto;
70     }
71   }
72 
73   return ShowColors == Colors_On ||
74       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors());
75 }
76 
77 bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts,
78     llvm::opt::ArgList &args, bool defaultDiagColor) {
79   opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor);
80 
81   return true;
82 }
83 
84 static InputKind ParseFrontendArgs(FrontendOptions &opts,
85     llvm::opt::ArgList &args, clang::DiagnosticsEngine &diags) {
86   // Identify the action (i.e. opts.ProgramAction)
87   if (const llvm::opt::Arg *a =
88           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
89     switch (a->getOption().getID()) {
90     default: {
91       llvm_unreachable("Invalid option in group!");
92     }
93     case clang::driver::options::OPT_test_io:
94       opts.programAction_ = InputOutputTest;
95       break;
96     case clang::driver::options::OPT_E:
97       opts.programAction_ = PrintPreprocessedInput;
98       break;
99     case clang::driver::options::OPT_fsyntax_only:
100       opts.programAction_ = ParseSyntaxOnly;
101       break;
102     case clang::driver::options::OPT_emit_obj:
103       opts.programAction_ = EmitObj;
104       break;
105 
106       // TODO:
107       // case calng::driver::options::OPT_emit_llvm:
108       // case clang::driver::options::OPT_emit_llvm_only:
109       // case clang::driver::options::OPT_emit_codegen_only:
110       // case clang::driver::options::OPT_emit_module:
111       // (...)
112     }
113   }
114 
115   opts.outputFile_ = args.getLastArgValue(clang::driver::options::OPT_o);
116   opts.showHelp_ = args.hasArg(clang::driver::options::OPT_help);
117   opts.showVersion_ = args.hasArg(clang::driver::options::OPT_version);
118 
119   // Get the input kind (from the value passed via `-x`)
120   InputKind dashX(Language::Unknown);
121   if (const llvm::opt::Arg *a =
122           args.getLastArg(clang::driver::options::OPT_x)) {
123     llvm::StringRef XValue = a->getValue();
124     // Principal languages.
125     dashX = llvm::StringSwitch<InputKind>(XValue)
126                 .Case("f90", Language::Fortran)
127                 .Default(Language::Unknown);
128 
129     // Some special cases cannot be combined with suffixes.
130     if (dashX.IsUnknown())
131       dashX = llvm::StringSwitch<InputKind>(XValue)
132                   .Case("ir", Language::LLVM_IR)
133                   .Default(Language::Unknown);
134 
135     if (dashX.IsUnknown())
136       diags.Report(clang::diag::err_drv_invalid_value)
137           << a->getAsString(args) << a->getValue();
138   }
139 
140   // Collect the input files and save them in our instance of FrontendOptions.
141   std::vector<std::string> inputs =
142       args.getAllArgValues(clang::driver::options::OPT_INPUT);
143   opts.inputs_.clear();
144   if (inputs.empty())
145     // '-' is the default input if none is given.
146     inputs.push_back("-");
147   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
148     InputKind ik = dashX;
149     if (ik.IsUnknown()) {
150       ik = FrontendOptions::GetInputKindForExtension(
151           llvm::StringRef(inputs[i]).rsplit('.').second);
152       if (ik.IsUnknown())
153         ik = Language::Unknown;
154       if (i == 0)
155         dashX = ik;
156     }
157 
158     opts.inputs_.emplace_back(std::move(inputs[i]), ik);
159   }
160   return dashX;
161 }
162 
163 /// Parses all preprocessor input arguments and populates the preprocessor
164 /// options accordingly.
165 ///
166 /// \param [in] opts The preprocessor options instance
167 /// \param [out] args The list of input arguments
168 static void parsePreprocessorArgs(
169     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
170   // Add macros from the command line.
171   for (const auto *currentArg : args.filtered(
172            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
173     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
174       opts.addMacroDef(currentArg->getValue());
175     } else {
176       opts.addMacroUndef(currentArg->getValue());
177     }
178   }
179 
180   // Add the ordered list of -I's.
181   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
182     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
183 }
184 
185 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
186     llvm::ArrayRef<const char *> commandLineArgs,
187     clang::DiagnosticsEngine &diags) {
188 
189   bool success = true;
190 
191   // Parse the arguments
192   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
193   const unsigned includedFlagsBitmask =
194       clang::driver::options::FC1Option;
195   unsigned missingArgIndex, missingArgCount;
196   llvm::opt::InputArgList args = opts.ParseArgs(
197       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
198 
199   // Issue errors on unknown arguments
200   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
201     auto argString = a->getAsString(args);
202     std::string nearest;
203     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
204       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
205     else
206       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
207           << argString << nearest;
208     success = false;
209   }
210 
211   // Parse the frontend args
212   ParseFrontendArgs(res.frontendOpts(), args, diags);
213   // Parse the preprocessor args
214   parsePreprocessorArgs(res.preprocessorOpts(), args);
215 
216   return success;
217 }
218 
219 /// Collect the macro definitions provided by the given preprocessor
220 /// options into the parser options.
221 ///
222 /// \param [in] ppOpts The preprocessor options
223 /// \param [out] opts The fortran options
224 static void collectMacroDefinitions(
225     const PreprocessorOptions &ppOpts, Fortran::parser::Options &opts) {
226   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
227     llvm::StringRef macro = ppOpts.macros[i].first;
228     bool isUndef = ppOpts.macros[i].second;
229 
230     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
231     llvm::StringRef macroName = macroPair.first;
232     llvm::StringRef macroBody = macroPair.second;
233 
234     // For an #undef'd macro, we only care about the name.
235     if (isUndef) {
236       opts.predefinitions.emplace_back(
237           macroName.str(), std::optional<std::string>{});
238       continue;
239     }
240 
241     // For a #define'd macro, figure out the actual definition.
242     if (macroName.size() == macro.size())
243       macroBody = "1";
244     else {
245       // Note: GCC drops anything following an end-of-line character.
246       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
247       macroBody = macroBody.substr(0, End);
248     }
249     opts.predefinitions.emplace_back(
250         macroName, std::optional<std::string>(macroBody.str()));
251   }
252 }
253 
254 void CompilerInvocation::SetDefaultFortranOpts() {
255   auto &fortranOptions = fortranOpts();
256 
257   // These defaults are based on the defaults in f18/f18.cpp.
258   std::vector<std::string> searchDirectories{"."s};
259   fortranOptions.searchDirectories = searchDirectories;
260   fortranOptions.isFixedForm = false;
261 }
262 
263 void CompilerInvocation::setFortranOpts() {
264   auto &fortranOptions = fortranOpts();
265   const auto &preprocessorOptions = preprocessorOpts();
266 
267   collectMacroDefinitions(preprocessorOptions, fortranOptions);
268 
269   fortranOptions.searchDirectories.insert(
270       fortranOptions.searchDirectories.end(),
271       preprocessorOptions.searchDirectoriesFromDashI.begin(),
272       preprocessorOptions.searchDirectoriesFromDashI.end());
273 }
274