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