1257b2971SCaroline Concatto //===- CompilerInvocation.cpp ---------------------------------------------===//
2257b2971SCaroline Concatto //
3257b2971SCaroline Concatto // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4257b2971SCaroline Concatto // See https://llvm.org/LICENSE.txt for license information.
5257b2971SCaroline Concatto // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6257b2971SCaroline Concatto //
7257b2971SCaroline Concatto //===----------------------------------------------------------------------===//
8257b2971SCaroline Concatto 
9257b2971SCaroline Concatto #include "flang/Frontend/CompilerInvocation.h"
106d48a1a5SFaris Rehman #include "flang/Common/Fortran-features.h"
117809fa20SFaris Rehman #include "flang/Frontend/PreprocessorOptions.h"
126d48a1a5SFaris Rehman #include "flang/Semantics/semantics.h"
13197d9a55SFaris Rehman #include "flang/Version.inc"
14257b2971SCaroline Concatto #include "clang/Basic/AllDiagnostics.h"
15257b2971SCaroline Concatto #include "clang/Basic/DiagnosticDriver.h"
16257b2971SCaroline Concatto #include "clang/Basic/DiagnosticOptions.h"
17257b2971SCaroline Concatto #include "clang/Driver/DriverDiagnostic.h"
18257b2971SCaroline Concatto #include "clang/Driver/Options.h"
19257b2971SCaroline Concatto #include "llvm/ADT/StringRef.h"
20257b2971SCaroline Concatto #include "llvm/ADT/StringSwitch.h"
21257b2971SCaroline Concatto #include "llvm/Option/Arg.h"
22257b2971SCaroline Concatto #include "llvm/Option/ArgList.h"
23257b2971SCaroline Concatto #include "llvm/Option/OptTable.h"
248d51d37eSAndrzej Warzynski #include "llvm/Support/Process.h"
25257b2971SCaroline Concatto #include "llvm/Support/raw_ostream.h"
266d48a1a5SFaris Rehman #include <memory>
27257b2971SCaroline Concatto 
28257b2971SCaroline Concatto using namespace Fortran::frontend;
29257b2971SCaroline Concatto 
30257b2971SCaroline Concatto //===----------------------------------------------------------------------===//
31257b2971SCaroline Concatto // Initialization.
32257b2971SCaroline Concatto //===----------------------------------------------------------------------===//
33257b2971SCaroline Concatto CompilerInvocationBase::CompilerInvocationBase()
347809fa20SFaris Rehman     : diagnosticOpts_(new clang::DiagnosticOptions()),
357809fa20SFaris Rehman       preprocessorOpts_(new PreprocessorOptions()) {}
36257b2971SCaroline Concatto 
37257b2971SCaroline Concatto CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
387809fa20SFaris Rehman     : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())),
397809fa20SFaris Rehman       preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {}
40257b2971SCaroline Concatto 
41257b2971SCaroline Concatto CompilerInvocationBase::~CompilerInvocationBase() = default;
42257b2971SCaroline Concatto 
43257b2971SCaroline Concatto //===----------------------------------------------------------------------===//
44257b2971SCaroline Concatto // Deserialization (from args)
45257b2971SCaroline Concatto //===----------------------------------------------------------------------===//
468d51d37eSAndrzej Warzynski static bool parseShowColorsArgs(
478d51d37eSAndrzej Warzynski     const llvm::opt::ArgList &args, bool defaultColor) {
488d51d37eSAndrzej Warzynski   // Color diagnostics default to auto ("on" if terminal supports) in the driver
498d51d37eSAndrzej Warzynski   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
508d51d37eSAndrzej Warzynski   // Support both clang's -f[no-]color-diagnostics and gcc's
518d51d37eSAndrzej Warzynski   // -f[no-]diagnostics-colors[=never|always|auto].
528d51d37eSAndrzej Warzynski   enum {
538d51d37eSAndrzej Warzynski     Colors_On,
548d51d37eSAndrzej Warzynski     Colors_Off,
558d51d37eSAndrzej Warzynski     Colors_Auto
568d51d37eSAndrzej Warzynski   } ShowColors = defaultColor ? Colors_Auto : Colors_Off;
578d51d37eSAndrzej Warzynski 
588d51d37eSAndrzej Warzynski   for (auto *a : args) {
598d51d37eSAndrzej Warzynski     const llvm::opt::Option &O = a->getOption();
608d51d37eSAndrzej Warzynski     if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) ||
618d51d37eSAndrzej Warzynski         O.matches(clang::driver::options::OPT_fdiagnostics_color)) {
628d51d37eSAndrzej Warzynski       ShowColors = Colors_On;
638d51d37eSAndrzej Warzynski     } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) ||
648d51d37eSAndrzej Warzynski         O.matches(clang::driver::options::OPT_fno_diagnostics_color)) {
658d51d37eSAndrzej Warzynski       ShowColors = Colors_Off;
668d51d37eSAndrzej Warzynski     } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
678d51d37eSAndrzej Warzynski       llvm::StringRef value(a->getValue());
688d51d37eSAndrzej Warzynski       if (value == "always")
698d51d37eSAndrzej Warzynski         ShowColors = Colors_On;
708d51d37eSAndrzej Warzynski       else if (value == "never")
718d51d37eSAndrzej Warzynski         ShowColors = Colors_Off;
728d51d37eSAndrzej Warzynski       else if (value == "auto")
738d51d37eSAndrzej Warzynski         ShowColors = Colors_Auto;
748d51d37eSAndrzej Warzynski     }
758d51d37eSAndrzej Warzynski   }
768d51d37eSAndrzej Warzynski 
778d51d37eSAndrzej Warzynski   return ShowColors == Colors_On ||
788d51d37eSAndrzej Warzynski       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors());
798d51d37eSAndrzej Warzynski }
808d51d37eSAndrzej Warzynski 
818d51d37eSAndrzej Warzynski bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts,
828d51d37eSAndrzej Warzynski     llvm::opt::ArgList &args, bool defaultDiagColor) {
838d51d37eSAndrzej Warzynski   opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor);
848d51d37eSAndrzej Warzynski 
858d51d37eSAndrzej Warzynski   return true;
868d51d37eSAndrzej Warzynski }
878d51d37eSAndrzej Warzynski 
88523d7bc6SAndrzej Warzynski // Tweak the frontend configuration based on the frontend action
89523d7bc6SAndrzej Warzynski static void setUpFrontendBasedOnAction(FrontendOptions &opts) {
90523d7bc6SAndrzej Warzynski   assert(opts.programAction_ != Fortran::frontend::InvalidAction &&
91523d7bc6SAndrzej Warzynski       "Fortran frontend action not set!");
92523d7bc6SAndrzej Warzynski 
93523d7bc6SAndrzej Warzynski   if (opts.programAction_ == DebugDumpParsingLog)
94523d7bc6SAndrzej Warzynski     opts.instrumentedParse_ = true;
95523d7bc6SAndrzej Warzynski }
96523d7bc6SAndrzej Warzynski 
97257b2971SCaroline Concatto static InputKind ParseFrontendArgs(FrontendOptions &opts,
98257b2971SCaroline Concatto     llvm::opt::ArgList &args, clang::DiagnosticsEngine &diags) {
99760e6c4cSAndrzej Warzynski 
100760e6c4cSAndrzej Warzynski   // By default the frontend driver creates a ParseSyntaxOnly action.
101760e6c4cSAndrzej Warzynski   opts.programAction_ = ParseSyntaxOnly;
102760e6c4cSAndrzej Warzynski 
103257b2971SCaroline Concatto   // Identify the action (i.e. opts.ProgramAction)
104257b2971SCaroline Concatto   if (const llvm::opt::Arg *a =
105257b2971SCaroline Concatto           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
106257b2971SCaroline Concatto     switch (a->getOption().getID()) {
107257b2971SCaroline Concatto     default: {
108257b2971SCaroline Concatto       llvm_unreachable("Invalid option in group!");
109257b2971SCaroline Concatto     }
1104c5906cfSCaroline Concatto     case clang::driver::options::OPT_test_io:
1114c5906cfSCaroline Concatto       opts.programAction_ = InputOutputTest;
1124c5906cfSCaroline Concatto       break;
113d28de0d7SCaroline Concatto     case clang::driver::options::OPT_E:
114d28de0d7SCaroline Concatto       opts.programAction_ = PrintPreprocessedInput;
115d28de0d7SCaroline Concatto       break;
1167d246cb1SAndrzej Warzynski     case clang::driver::options::OPT_fsyntax_only:
1177d246cb1SAndrzej Warzynski       opts.programAction_ = ParseSyntaxOnly;
1187d246cb1SAndrzej Warzynski       break;
119e5cdb6c5SAndrzej Warzynski     case clang::driver::options::OPT_emit_obj:
120e5cdb6c5SAndrzej Warzynski       opts.programAction_ = EmitObj;
121e5cdb6c5SAndrzej Warzynski       break;
12296d229c9SAndrzej Warzynski     case clang::driver::options::OPT_fdebug_unparse:
12396d229c9SAndrzej Warzynski       opts.programAction_ = DebugUnparse;
12496d229c9SAndrzej Warzynski       break;
12596d229c9SAndrzej Warzynski     case clang::driver::options::OPT_fdebug_unparse_with_symbols:
12696d229c9SAndrzej Warzynski       opts.programAction_ = DebugUnparseWithSymbols;
12796d229c9SAndrzej Warzynski       break;
1284bd08dabSFaris Rehman     case clang::driver::options::OPT_fdebug_dump_symbols:
1294bd08dabSFaris Rehman       opts.programAction_ = DebugDumpSymbols;
1304bd08dabSFaris Rehman       break;
1314bd08dabSFaris Rehman     case clang::driver::options::OPT_fdebug_dump_parse_tree:
1324bd08dabSFaris Rehman       opts.programAction_ = DebugDumpParseTree;
1334bd08dabSFaris Rehman       break;
1344bd08dabSFaris Rehman     case clang::driver::options::OPT_fdebug_dump_provenance:
1354bd08dabSFaris Rehman       opts.programAction_ = DebugDumpProvenance;
1364bd08dabSFaris Rehman       break;
137523d7bc6SAndrzej Warzynski     case clang::driver::options::OPT_fdebug_dump_parsing_log:
138523d7bc6SAndrzej Warzynski       opts.programAction_ = DebugDumpParsingLog;
139523d7bc6SAndrzej Warzynski       break;
140529f7181SFaris Rehman     case clang::driver::options::OPT_fdebug_measure_parse_tree:
141529f7181SFaris Rehman       opts.programAction_ = DebugMeasureParseTree;
142529f7181SFaris Rehman       break;
143529f7181SFaris Rehman     case clang::driver::options::OPT_fdebug_pre_fir_tree:
144529f7181SFaris Rehman       opts.programAction_ = DebugPreFIRTree;
145529f7181SFaris Rehman       break;
146*eefda605SAndrzej Warzynski     case clang::driver::options::OPT_fget_symbols_sources:
147*eefda605SAndrzej Warzynski       opts.programAction_ = GetSymbolsSources;
148*eefda605SAndrzej Warzynski       break;
149d28de0d7SCaroline Concatto 
150257b2971SCaroline Concatto       // TODO:
151257b2971SCaroline Concatto       // case calng::driver::options::OPT_emit_llvm:
152257b2971SCaroline Concatto       // case clang::driver::options::OPT_emit_llvm_only:
153257b2971SCaroline Concatto       // case clang::driver::options::OPT_emit_codegen_only:
154257b2971SCaroline Concatto       // case clang::driver::options::OPT_emit_module:
155257b2971SCaroline Concatto       // (...)
156257b2971SCaroline Concatto     }
157257b2971SCaroline Concatto   }
158257b2971SCaroline Concatto 
1594c5906cfSCaroline Concatto   opts.outputFile_ = args.getLastArgValue(clang::driver::options::OPT_o);
160257b2971SCaroline Concatto   opts.showHelp_ = args.hasArg(clang::driver::options::OPT_help);
161257b2971SCaroline Concatto   opts.showVersion_ = args.hasArg(clang::driver::options::OPT_version);
162257b2971SCaroline Concatto 
163257b2971SCaroline Concatto   // Get the input kind (from the value passed via `-x`)
164257b2971SCaroline Concatto   InputKind dashX(Language::Unknown);
165257b2971SCaroline Concatto   if (const llvm::opt::Arg *a =
166257b2971SCaroline Concatto           args.getLastArg(clang::driver::options::OPT_x)) {
167257b2971SCaroline Concatto     llvm::StringRef XValue = a->getValue();
168257b2971SCaroline Concatto     // Principal languages.
169257b2971SCaroline Concatto     dashX = llvm::StringSwitch<InputKind>(XValue)
170257b2971SCaroline Concatto                 .Case("f90", Language::Fortran)
171257b2971SCaroline Concatto                 .Default(Language::Unknown);
172257b2971SCaroline Concatto 
173257b2971SCaroline Concatto     // Some special cases cannot be combined with suffixes.
174257b2971SCaroline Concatto     if (dashX.IsUnknown())
175257b2971SCaroline Concatto       dashX = llvm::StringSwitch<InputKind>(XValue)
176257b2971SCaroline Concatto                   .Case("ir", Language::LLVM_IR)
177257b2971SCaroline Concatto                   .Default(Language::Unknown);
178257b2971SCaroline Concatto 
179257b2971SCaroline Concatto     if (dashX.IsUnknown())
180257b2971SCaroline Concatto       diags.Report(clang::diag::err_drv_invalid_value)
181257b2971SCaroline Concatto           << a->getAsString(args) << a->getValue();
182257b2971SCaroline Concatto   }
183257b2971SCaroline Concatto 
1844c5906cfSCaroline Concatto   // Collect the input files and save them in our instance of FrontendOptions.
1854c5906cfSCaroline Concatto   std::vector<std::string> inputs =
1864c5906cfSCaroline Concatto       args.getAllArgValues(clang::driver::options::OPT_INPUT);
1874c5906cfSCaroline Concatto   opts.inputs_.clear();
1884c5906cfSCaroline Concatto   if (inputs.empty())
1894c5906cfSCaroline Concatto     // '-' is the default input if none is given.
1904c5906cfSCaroline Concatto     inputs.push_back("-");
1914c5906cfSCaroline Concatto   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
1924c5906cfSCaroline Concatto     InputKind ik = dashX;
1934c5906cfSCaroline Concatto     if (ik.IsUnknown()) {
1944c5906cfSCaroline Concatto       ik = FrontendOptions::GetInputKindForExtension(
1954c5906cfSCaroline Concatto           llvm::StringRef(inputs[i]).rsplit('.').second);
1964c5906cfSCaroline Concatto       if (ik.IsUnknown())
1974c5906cfSCaroline Concatto         ik = Language::Unknown;
1984c5906cfSCaroline Concatto       if (i == 0)
1994c5906cfSCaroline Concatto         dashX = ik;
2004c5906cfSCaroline Concatto     }
2014c5906cfSCaroline Concatto 
2024c5906cfSCaroline Concatto     opts.inputs_.emplace_back(std::move(inputs[i]), ik);
2034c5906cfSCaroline Concatto   }
2043a1513c1SFaris Rehman 
2053a1513c1SFaris Rehman   // Set fortranForm_ based on options -ffree-form and -ffixed-form.
2063a1513c1SFaris Rehman   if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form,
2073a1513c1SFaris Rehman           clang::driver::options::OPT_ffree_form)) {
2083a1513c1SFaris Rehman     opts.fortranForm_ =
2093a1513c1SFaris Rehman         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
2103a1513c1SFaris Rehman         ? FortranForm::FixedForm
2113a1513c1SFaris Rehman         : FortranForm::FreeForm;
2123a1513c1SFaris Rehman   }
2133a1513c1SFaris Rehman 
2143a1513c1SFaris Rehman   // Set fixedFormColumns_ based on -ffixed-line-length=<value>
2153a1513c1SFaris Rehman   if (const auto *arg =
2163a1513c1SFaris Rehman           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
2173a1513c1SFaris Rehman     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
2183a1513c1SFaris Rehman     std::int64_t columns = -1;
2193a1513c1SFaris Rehman     if (argValue == "none") {
2203a1513c1SFaris Rehman       columns = 0;
2213a1513c1SFaris Rehman     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
2223a1513c1SFaris Rehman       columns = -1;
2233a1513c1SFaris Rehman     }
2243a1513c1SFaris Rehman     if (columns < 0) {
2253a1513c1SFaris Rehman       diags.Report(clang::diag::err_drv_invalid_value_with_suggestion)
2263a1513c1SFaris Rehman           << arg->getOption().getName() << arg->getValue()
2273a1513c1SFaris Rehman           << "value must be 'none' or a non-negative integer";
2283a1513c1SFaris Rehman     } else if (columns == 0) {
2293a1513c1SFaris Rehman       opts.fixedFormColumns_ = 1000000;
2303a1513c1SFaris Rehman     } else if (columns < 7) {
2313a1513c1SFaris Rehman       diags.Report(clang::diag::err_drv_invalid_value_with_suggestion)
2323a1513c1SFaris Rehman           << arg->getOption().getName() << arg->getValue()
2333a1513c1SFaris Rehman           << "value must be at least seven";
2343a1513c1SFaris Rehman     } else {
2353a1513c1SFaris Rehman       opts.fixedFormColumns_ = columns;
2363a1513c1SFaris Rehman     }
2373a1513c1SFaris Rehman   }
2386d48a1a5SFaris Rehman 
23910826ea7SFaris Rehman   if (const llvm::opt::Arg *arg =
24010826ea7SFaris Rehman           args.getLastArg(clang::driver::options::OPT_fimplicit_none,
24110826ea7SFaris Rehman               clang::driver::options::OPT_fno_implicit_none)) {
24210826ea7SFaris Rehman     opts.features_.Enable(
24310826ea7SFaris Rehman         Fortran::common::LanguageFeature::ImplicitNoneTypeAlways,
24410826ea7SFaris Rehman         arg->getOption().matches(clang::driver::options::OPT_fimplicit_none));
24510826ea7SFaris Rehman   }
24610826ea7SFaris Rehman   if (const llvm::opt::Arg *arg =
24710826ea7SFaris Rehman           args.getLastArg(clang::driver::options::OPT_fbackslash,
24810826ea7SFaris Rehman               clang::driver::options::OPT_fno_backslash)) {
24910826ea7SFaris Rehman     opts.features_.Enable(Fortran::common::LanguageFeature::BackslashEscapes,
25010826ea7SFaris Rehman         arg->getOption().matches(clang::driver::options::OPT_fbackslash));
25110826ea7SFaris Rehman   }
25210826ea7SFaris Rehman   if (const llvm::opt::Arg *arg =
25310826ea7SFaris Rehman           args.getLastArg(clang::driver::options::OPT_flogical_abbreviations,
25410826ea7SFaris Rehman               clang::driver::options::OPT_fno_logical_abbreviations)) {
25510826ea7SFaris Rehman     opts.features_.Enable(
25610826ea7SFaris Rehman         Fortran::common::LanguageFeature::LogicalAbbreviations,
25710826ea7SFaris Rehman         arg->getOption().matches(
25810826ea7SFaris Rehman             clang::driver::options::OPT_flogical_abbreviations));
25910826ea7SFaris Rehman   }
26010826ea7SFaris Rehman   if (const llvm::opt::Arg *arg =
26110826ea7SFaris Rehman           args.getLastArg(clang::driver::options::OPT_fxor_operator,
26210826ea7SFaris Rehman               clang::driver::options::OPT_fno_xor_operator)) {
26310826ea7SFaris Rehman     opts.features_.Enable(Fortran::common::LanguageFeature::XOROperator,
26410826ea7SFaris Rehman         arg->getOption().matches(clang::driver::options::OPT_fxor_operator));
26510826ea7SFaris Rehman   }
26610826ea7SFaris Rehman   if (args.hasArg(
26710826ea7SFaris Rehman           clang::driver::options::OPT_falternative_parameter_statement)) {
26810826ea7SFaris Rehman     opts.features_.Enable(Fortran::common::LanguageFeature::OldStyleParameter);
26910826ea7SFaris Rehman   }
27010826ea7SFaris Rehman   if (const llvm::opt::Arg *arg =
27110826ea7SFaris Rehman           args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) {
27210826ea7SFaris Rehman     llvm::StringRef argValue = arg->getValue();
27310826ea7SFaris Rehman     if (argValue == "utf-8") {
27410826ea7SFaris Rehman       opts.encoding_ = Fortran::parser::Encoding::UTF_8;
27510826ea7SFaris Rehman     } else if (argValue == "latin-1") {
27610826ea7SFaris Rehman       opts.encoding_ = Fortran::parser::Encoding::LATIN_1;
27710826ea7SFaris Rehman     } else {
27810826ea7SFaris Rehman       diags.Report(clang::diag::err_drv_invalid_value)
27910826ea7SFaris Rehman           << arg->getAsString(args) << argValue;
28010826ea7SFaris Rehman     }
28110826ea7SFaris Rehman   }
282523d7bc6SAndrzej Warzynski 
283523d7bc6SAndrzej Warzynski   setUpFrontendBasedOnAction(opts);
284523d7bc6SAndrzej Warzynski 
285257b2971SCaroline Concatto   return dashX;
286257b2971SCaroline Concatto }
287257b2971SCaroline Concatto 
2887809fa20SFaris Rehman /// Parses all preprocessor input arguments and populates the preprocessor
2897809fa20SFaris Rehman /// options accordingly.
2907809fa20SFaris Rehman ///
2917809fa20SFaris Rehman /// \param [in] opts The preprocessor options instance
2927809fa20SFaris Rehman /// \param [out] args The list of input arguments
2937809fa20SFaris Rehman static void parsePreprocessorArgs(
2947809fa20SFaris Rehman     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
2957809fa20SFaris Rehman   // Add macros from the command line.
2967809fa20SFaris Rehman   for (const auto *currentArg : args.filtered(
2977809fa20SFaris Rehman            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
2987809fa20SFaris Rehman     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
2997809fa20SFaris Rehman       opts.addMacroDef(currentArg->getValue());
3007809fa20SFaris Rehman     } else {
3017809fa20SFaris Rehman       opts.addMacroUndef(currentArg->getValue());
3027809fa20SFaris Rehman     }
3037809fa20SFaris Rehman   }
30487dfd5e0SFaris Rehman 
30587dfd5e0SFaris Rehman   // Add the ordered list of -I's.
30687dfd5e0SFaris Rehman   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
30787dfd5e0SFaris Rehman     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
3087809fa20SFaris Rehman }
3097809fa20SFaris Rehman 
310985a42fdSArnamoy Bhattacharyya /// Parses all semantic related arguments and populates the variables
311985a42fdSArnamoy Bhattacharyya /// options accordingly.
3121fd4beecSArnamoy Bhattacharyya static void parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
313985a42fdSArnamoy Bhattacharyya     clang::DiagnosticsEngine &diags) {
314985a42fdSArnamoy Bhattacharyya 
3151fd4beecSArnamoy Bhattacharyya   // -J/module-dir option
316985a42fdSArnamoy Bhattacharyya   auto moduleDirList =
317985a42fdSArnamoy Bhattacharyya       args.getAllArgValues(clang::driver::options::OPT_module_dir);
318985a42fdSArnamoy Bhattacharyya   // User can only specify -J/-module-dir once
319985a42fdSArnamoy Bhattacharyya   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
320985a42fdSArnamoy Bhattacharyya   if (moduleDirList.size() > 1) {
321985a42fdSArnamoy Bhattacharyya     const unsigned diagID =
322985a42fdSArnamoy Bhattacharyya         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
323985a42fdSArnamoy Bhattacharyya             "Only one '-module-dir/-J' option allowed");
324985a42fdSArnamoy Bhattacharyya     diags.Report(diagID);
325985a42fdSArnamoy Bhattacharyya   }
326985a42fdSArnamoy Bhattacharyya   if (moduleDirList.size() == 1)
3271fd4beecSArnamoy Bhattacharyya     res.SetModuleDir(moduleDirList[0]);
3281fd4beecSArnamoy Bhattacharyya 
3291fd4beecSArnamoy Bhattacharyya   // -fdebug-module-writer option
3301fd4beecSArnamoy Bhattacharyya   if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) {
3311fd4beecSArnamoy Bhattacharyya     res.SetDebugModuleDir(true);
3321fd4beecSArnamoy Bhattacharyya   }
333985a42fdSArnamoy Bhattacharyya }
334985a42fdSArnamoy Bhattacharyya 
335ab971c29SArnamoy Bhattacharyya /// Parses all Dialect related arguments and populates the variables
336ab971c29SArnamoy Bhattacharyya /// options accordingly.
337ab971c29SArnamoy Bhattacharyya static void parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args,
338ab971c29SArnamoy Bhattacharyya     clang::DiagnosticsEngine &diags) {
339ab971c29SArnamoy Bhattacharyya 
340ab971c29SArnamoy Bhattacharyya   // -fdefault* family
341ab971c29SArnamoy Bhattacharyya   if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
342ab971c29SArnamoy Bhattacharyya     res.defaultKinds().set_defaultRealKind(8);
343ab971c29SArnamoy Bhattacharyya     res.defaultKinds().set_doublePrecisionKind(16);
344ab971c29SArnamoy Bhattacharyya   }
345ab971c29SArnamoy Bhattacharyya   if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) {
346ab971c29SArnamoy Bhattacharyya     res.defaultKinds().set_defaultIntegerKind(8);
347ab971c29SArnamoy Bhattacharyya     res.defaultKinds().set_subscriptIntegerKind(8);
348ab971c29SArnamoy Bhattacharyya     res.defaultKinds().set_sizeIntegerKind(8);
349ab971c29SArnamoy Bhattacharyya   }
350ab971c29SArnamoy Bhattacharyya   if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) {
351ab971c29SArnamoy Bhattacharyya     if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) {
352ab971c29SArnamoy Bhattacharyya       // -fdefault-double-8 has to be used with -fdefault-real-8
353ab971c29SArnamoy Bhattacharyya       // to be compatible with gfortran
354ab971c29SArnamoy Bhattacharyya       const unsigned diagID =
355ab971c29SArnamoy Bhattacharyya           diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
356ab971c29SArnamoy Bhattacharyya               "Use of `-fdefault-double-8` requires `-fdefault-real-8`");
357ab971c29SArnamoy Bhattacharyya       diags.Report(diagID);
358ab971c29SArnamoy Bhattacharyya     }
359ab971c29SArnamoy Bhattacharyya     // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html
360ab971c29SArnamoy Bhattacharyya     res.defaultKinds().set_doublePrecisionKind(8);
361ab971c29SArnamoy Bhattacharyya   }
362ab971c29SArnamoy Bhattacharyya   if (args.hasArg(clang::driver::options::OPT_flarge_sizes))
363ab971c29SArnamoy Bhattacharyya     res.defaultKinds().set_sizeIntegerKind(8);
364ab971c29SArnamoy Bhattacharyya 
365ab971c29SArnamoy Bhattacharyya   // -fopenmp and -fopenacc
366ab971c29SArnamoy Bhattacharyya   if (args.hasArg(clang::driver::options::OPT_fopenacc)) {
367ab971c29SArnamoy Bhattacharyya     res.frontendOpts().features_.Enable(
368ab971c29SArnamoy Bhattacharyya         Fortran::common::LanguageFeature::OpenACC);
369ab971c29SArnamoy Bhattacharyya   }
370ab971c29SArnamoy Bhattacharyya   if (args.hasArg(clang::driver::options::OPT_fopenmp)) {
371ab971c29SArnamoy Bhattacharyya     res.frontendOpts().features_.Enable(
372ab971c29SArnamoy Bhattacharyya         Fortran::common::LanguageFeature::OpenMP);
373ab971c29SArnamoy Bhattacharyya   }
374ab971c29SArnamoy Bhattacharyya   return;
375ab971c29SArnamoy Bhattacharyya }
376ab971c29SArnamoy Bhattacharyya 
377257b2971SCaroline Concatto bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
378257b2971SCaroline Concatto     llvm::ArrayRef<const char *> commandLineArgs,
379257b2971SCaroline Concatto     clang::DiagnosticsEngine &diags) {
380257b2971SCaroline Concatto 
381257b2971SCaroline Concatto   bool success = true;
382257b2971SCaroline Concatto 
383257b2971SCaroline Concatto   // Parse the arguments
384257b2971SCaroline Concatto   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
3858e3adda8SFaris Rehman   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
386257b2971SCaroline Concatto   unsigned missingArgIndex, missingArgCount;
387257b2971SCaroline Concatto   llvm::opt::InputArgList args = opts.ParseArgs(
388257b2971SCaroline Concatto       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
389257b2971SCaroline Concatto 
390257b2971SCaroline Concatto   // Issue errors on unknown arguments
391257b2971SCaroline Concatto   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
392257b2971SCaroline Concatto     auto argString = a->getAsString(args);
393257b2971SCaroline Concatto     std::string nearest;
394257b2971SCaroline Concatto     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
395257b2971SCaroline Concatto       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
396257b2971SCaroline Concatto     else
397257b2971SCaroline Concatto       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
398257b2971SCaroline Concatto           << argString << nearest;
399257b2971SCaroline Concatto     success = false;
400257b2971SCaroline Concatto   }
401257b2971SCaroline Concatto 
402257b2971SCaroline Concatto   // Parse the frontend args
4039ffb5b04SAndrzej Warzynski   ParseFrontendArgs(res.frontendOpts(), args, diags);
4047809fa20SFaris Rehman   // Parse the preprocessor args
4057809fa20SFaris Rehman   parsePreprocessorArgs(res.preprocessorOpts(), args);
406985a42fdSArnamoy Bhattacharyya   // Parse semantic args
4071fd4beecSArnamoy Bhattacharyya   parseSemaArgs(res, args, diags);
408ab971c29SArnamoy Bhattacharyya   // Parse dialect arguments
409ab971c29SArnamoy Bhattacharyya   parseDialectArgs(res, args, diags);
410257b2971SCaroline Concatto 
411257b2971SCaroline Concatto   return success;
412257b2971SCaroline Concatto }
413d28de0d7SCaroline Concatto 
4147809fa20SFaris Rehman /// Collect the macro definitions provided by the given preprocessor
4157809fa20SFaris Rehman /// options into the parser options.
4167809fa20SFaris Rehman ///
4177809fa20SFaris Rehman /// \param [in] ppOpts The preprocessor options
4187809fa20SFaris Rehman /// \param [out] opts The fortran options
4197809fa20SFaris Rehman static void collectMacroDefinitions(
4207809fa20SFaris Rehman     const PreprocessorOptions &ppOpts, Fortran::parser::Options &opts) {
4217809fa20SFaris Rehman   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
4227809fa20SFaris Rehman     llvm::StringRef macro = ppOpts.macros[i].first;
4237809fa20SFaris Rehman     bool isUndef = ppOpts.macros[i].second;
4247809fa20SFaris Rehman 
4257809fa20SFaris Rehman     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
4267809fa20SFaris Rehman     llvm::StringRef macroName = macroPair.first;
4277809fa20SFaris Rehman     llvm::StringRef macroBody = macroPair.second;
4287809fa20SFaris Rehman 
4297809fa20SFaris Rehman     // For an #undef'd macro, we only care about the name.
4307809fa20SFaris Rehman     if (isUndef) {
4317809fa20SFaris Rehman       opts.predefinitions.emplace_back(
4327809fa20SFaris Rehman           macroName.str(), std::optional<std::string>{});
4337809fa20SFaris Rehman       continue;
4347809fa20SFaris Rehman     }
4357809fa20SFaris Rehman 
4367809fa20SFaris Rehman     // For a #define'd macro, figure out the actual definition.
4377809fa20SFaris Rehman     if (macroName.size() == macro.size())
4387809fa20SFaris Rehman       macroBody = "1";
4397809fa20SFaris Rehman     else {
4407809fa20SFaris Rehman       // Note: GCC drops anything following an end-of-line character.
4417809fa20SFaris Rehman       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
4427809fa20SFaris Rehman       macroBody = macroBody.substr(0, End);
4437809fa20SFaris Rehman     }
4447809fa20SFaris Rehman     opts.predefinitions.emplace_back(
4457809fa20SFaris Rehman         macroName, std::optional<std::string>(macroBody.str()));
4467809fa20SFaris Rehman   }
4477809fa20SFaris Rehman }
4487809fa20SFaris Rehman 
449d28de0d7SCaroline Concatto void CompilerInvocation::SetDefaultFortranOpts() {
4506bbbe4a5SAndrzej Warzynski   auto &fortranOptions = fortranOpts();
451d28de0d7SCaroline Concatto 
452d28de0d7SCaroline Concatto   // These defaults are based on the defaults in f18/f18.cpp.
453d28de0d7SCaroline Concatto   std::vector<std::string> searchDirectories{"."s};
454d28de0d7SCaroline Concatto   fortranOptions.searchDirectories = searchDirectories;
455d28de0d7SCaroline Concatto   fortranOptions.isFixedForm = false;
4560feff71eSAndrzej Warzynski }
4570feff71eSAndrzej Warzynski 
4580feff71eSAndrzej Warzynski // TODO: When expanding this method, consider creating a dedicated API for
4590feff71eSAndrzej Warzynski // this. Also at some point we will need to differentiate between different
4600feff71eSAndrzej Warzynski // targets and add dedicated predefines for each.
4610feff71eSAndrzej Warzynski void CompilerInvocation::setDefaultPredefinitions() {
4620feff71eSAndrzej Warzynski   auto &fortranOptions = fortranOpts();
4630feff71eSAndrzej Warzynski   const auto &frontendOptions = frontendOpts();
464197d9a55SFaris Rehman 
465197d9a55SFaris Rehman   // Populate the macro list with version numbers and other predefinitions.
466197d9a55SFaris Rehman   fortranOptions.predefinitions.emplace_back("__flang__", "1");
467197d9a55SFaris Rehman   fortranOptions.predefinitions.emplace_back(
468197d9a55SFaris Rehman       "__flang_major__", FLANG_VERSION_MAJOR_STRING);
469197d9a55SFaris Rehman   fortranOptions.predefinitions.emplace_back(
470197d9a55SFaris Rehman       "__flang_minor__", FLANG_VERSION_MINOR_STRING);
471197d9a55SFaris Rehman   fortranOptions.predefinitions.emplace_back(
472197d9a55SFaris Rehman       "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING);
4736d48a1a5SFaris Rehman 
4746d48a1a5SFaris Rehman   // Add predefinitions based on extensions enabled
4756d48a1a5SFaris Rehman   if (frontendOptions.features_.IsEnabled(
4766d48a1a5SFaris Rehman           Fortran::common::LanguageFeature::OpenACC)) {
4776d48a1a5SFaris Rehman     fortranOptions.predefinitions.emplace_back("_OPENACC", "202011");
4786d48a1a5SFaris Rehman   }
4796d48a1a5SFaris Rehman   if (frontendOptions.features_.IsEnabled(
4806d48a1a5SFaris Rehman           Fortran::common::LanguageFeature::OpenMP)) {
4816d48a1a5SFaris Rehman     fortranOptions.predefinitions.emplace_back("_OPENMP", "201511");
4826d48a1a5SFaris Rehman   }
4836d48a1a5SFaris Rehman }
4846d48a1a5SFaris Rehman 
4857809fa20SFaris Rehman void CompilerInvocation::setFortranOpts() {
4867809fa20SFaris Rehman   auto &fortranOptions = fortranOpts();
4873a1513c1SFaris Rehman   const auto &frontendOptions = frontendOpts();
4887809fa20SFaris Rehman   const auto &preprocessorOptions = preprocessorOpts();
489985a42fdSArnamoy Bhattacharyya   auto &moduleDirJ = moduleDir();
4907809fa20SFaris Rehman 
4913a1513c1SFaris Rehman   if (frontendOptions.fortranForm_ != FortranForm::Unknown) {
4923a1513c1SFaris Rehman     fortranOptions.isFixedForm =
4933a1513c1SFaris Rehman         frontendOptions.fortranForm_ == FortranForm::FixedForm;
4943a1513c1SFaris Rehman   }
4953a1513c1SFaris Rehman   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns_;
4963a1513c1SFaris Rehman 
4976d48a1a5SFaris Rehman   fortranOptions.features = frontendOptions.features_;
49810826ea7SFaris Rehman   fortranOptions.encoding = frontendOptions.encoding_;
4996d48a1a5SFaris Rehman 
5007809fa20SFaris Rehman   collectMacroDefinitions(preprocessorOptions, fortranOptions);
50187dfd5e0SFaris Rehman 
50287dfd5e0SFaris Rehman   fortranOptions.searchDirectories.insert(
50387dfd5e0SFaris Rehman       fortranOptions.searchDirectories.end(),
50487dfd5e0SFaris Rehman       preprocessorOptions.searchDirectoriesFromDashI.begin(),
50587dfd5e0SFaris Rehman       preprocessorOptions.searchDirectoriesFromDashI.end());
506985a42fdSArnamoy Bhattacharyya 
507985a42fdSArnamoy Bhattacharyya   // Add the directory supplied through -J/-module-dir to the list of search
508985a42fdSArnamoy Bhattacharyya   // directories
509985a42fdSArnamoy Bhattacharyya   if (moduleDirJ.compare(".") != 0)
510985a42fdSArnamoy Bhattacharyya     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
511523d7bc6SAndrzej Warzynski 
512523d7bc6SAndrzej Warzynski   if (frontendOptions.instrumentedParse_)
513523d7bc6SAndrzej Warzynski     fortranOptions.instrumentedParse = true;
514985a42fdSArnamoy Bhattacharyya }
515985a42fdSArnamoy Bhattacharyya 
516985a42fdSArnamoy Bhattacharyya void CompilerInvocation::setSemanticsOpts(
5176d48a1a5SFaris Rehman     Fortran::parser::AllCookedSources &allCookedSources) {
5186d48a1a5SFaris Rehman   const auto &fortranOptions = fortranOpts();
5196d48a1a5SFaris Rehman 
5206d48a1a5SFaris Rehman   semanticsContext_ = std::make_unique<semantics::SemanticsContext>(
521ab971c29SArnamoy Bhattacharyya       defaultKinds(), fortranOptions.features, allCookedSources);
5226d48a1a5SFaris Rehman 
5231fd4beecSArnamoy Bhattacharyya   semanticsContext_->set_moduleDirectory(moduleDir())
524985a42fdSArnamoy Bhattacharyya       .set_searchDirectories(fortranOptions.searchDirectories);
5257809fa20SFaris Rehman }
526