xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision e5cdb6c56edf656d03f57c5c285cfa8c6b7b6f57)
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 
181 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
182     llvm::ArrayRef<const char *> commandLineArgs,
183     clang::DiagnosticsEngine &diags) {
184 
185   bool success = true;
186 
187   // Parse the arguments
188   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
189   const unsigned includedFlagsBitmask =
190       clang::driver::options::FC1Option;
191   unsigned missingArgIndex, missingArgCount;
192   llvm::opt::InputArgList args = opts.ParseArgs(
193       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
194 
195   // Issue errors on unknown arguments
196   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
197     auto argString = a->getAsString(args);
198     std::string nearest;
199     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
200       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
201     else
202       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
203           << argString << nearest;
204     success = false;
205   }
206 
207   // Parse the frontend args
208   ParseFrontendArgs(res.frontendOpts(), args, diags);
209   // Parse the preprocessor args
210   parsePreprocessorArgs(res.preprocessorOpts(), args);
211 
212   return success;
213 }
214 
215 /// Collect the macro definitions provided by the given preprocessor
216 /// options into the parser options.
217 ///
218 /// \param [in] ppOpts The preprocessor options
219 /// \param [out] opts The fortran options
220 static void collectMacroDefinitions(
221     const PreprocessorOptions &ppOpts, Fortran::parser::Options &opts) {
222   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
223     llvm::StringRef macro = ppOpts.macros[i].first;
224     bool isUndef = ppOpts.macros[i].second;
225 
226     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
227     llvm::StringRef macroName = macroPair.first;
228     llvm::StringRef macroBody = macroPair.second;
229 
230     // For an #undef'd macro, we only care about the name.
231     if (isUndef) {
232       opts.predefinitions.emplace_back(
233           macroName.str(), std::optional<std::string>{});
234       continue;
235     }
236 
237     // For a #define'd macro, figure out the actual definition.
238     if (macroName.size() == macro.size())
239       macroBody = "1";
240     else {
241       // Note: GCC drops anything following an end-of-line character.
242       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
243       macroBody = macroBody.substr(0, End);
244     }
245     opts.predefinitions.emplace_back(
246         macroName, std::optional<std::string>(macroBody.str()));
247   }
248 }
249 
250 void CompilerInvocation::SetDefaultFortranOpts() {
251   auto &fortranOptions = fortranOpts();
252 
253   // These defaults are based on the defaults in f18/f18.cpp.
254   std::vector<std::string> searchDirectories{"."s};
255   fortranOptions.searchDirectories = searchDirectories;
256   fortranOptions.isFixedForm = false;
257 }
258 
259 void CompilerInvocation::setFortranOpts() {
260   auto &fortranOptions = fortranOpts();
261   const auto &preprocessorOptions = preprocessorOpts();
262 
263   collectMacroDefinitions(preprocessorOptions, fortranOptions);
264 }
265