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/Common/Fortran-features.h" 11 #include "flang/Frontend/PreprocessorOptions.h" 12 #include "flang/Semantics/semantics.h" 13 #include "flang/Version.inc" 14 #include "clang/Basic/AllDiagnostics.h" 15 #include "clang/Basic/DiagnosticDriver.h" 16 #include "clang/Basic/DiagnosticOptions.h" 17 #include "clang/Driver/DriverDiagnostic.h" 18 #include "clang/Driver/Options.h" 19 #include "llvm/ADT/StringRef.h" 20 #include "llvm/ADT/StringSwitch.h" 21 #include "llvm/Option/Arg.h" 22 #include "llvm/Option/ArgList.h" 23 #include "llvm/Option/OptTable.h" 24 #include "llvm/Support/FileSystem.h" 25 #include "llvm/Support/FileUtilities.h" 26 #include "llvm/Support/Process.h" 27 #include "llvm/Support/raw_ostream.h" 28 #include <memory> 29 30 using namespace Fortran::frontend; 31 32 //===----------------------------------------------------------------------===// 33 // Initialization. 34 //===----------------------------------------------------------------------===// 35 CompilerInvocationBase::CompilerInvocationBase() 36 : diagnosticOpts_(new clang::DiagnosticOptions()), 37 preprocessorOpts_(new PreprocessorOptions()) {} 38 39 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 40 : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())), 41 preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {} 42 43 CompilerInvocationBase::~CompilerInvocationBase() = default; 44 45 //===----------------------------------------------------------------------===// 46 // Deserialization (from args) 47 //===----------------------------------------------------------------------===// 48 static bool parseShowColorsArgs( 49 const llvm::opt::ArgList &args, bool defaultColor) { 50 // Color diagnostics default to auto ("on" if terminal supports) in the driver 51 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 52 // Support both clang's -f[no-]color-diagnostics and gcc's 53 // -f[no-]diagnostics-colors[=never|always|auto]. 54 enum { 55 Colors_On, 56 Colors_Off, 57 Colors_Auto 58 } ShowColors = defaultColor ? Colors_Auto : Colors_Off; 59 60 for (auto *a : args) { 61 const llvm::opt::Option &O = a->getOption(); 62 if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) || 63 O.matches(clang::driver::options::OPT_fdiagnostics_color)) { 64 ShowColors = Colors_On; 65 } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) || 66 O.matches(clang::driver::options::OPT_fno_diagnostics_color)) { 67 ShowColors = Colors_Off; 68 } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 69 llvm::StringRef value(a->getValue()); 70 if (value == "always") 71 ShowColors = Colors_On; 72 else if (value == "never") 73 ShowColors = Colors_Off; 74 else if (value == "auto") 75 ShowColors = Colors_Auto; 76 } 77 } 78 79 return ShowColors == Colors_On || 80 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()); 81 } 82 83 bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts, 84 llvm::opt::ArgList &args, bool defaultDiagColor) { 85 opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor); 86 87 return true; 88 } 89 90 // Tweak the frontend configuration based on the frontend action 91 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 92 assert(opts.programAction_ != Fortran::frontend::InvalidAction && 93 "Fortran frontend action not set!"); 94 95 if (opts.programAction_ == DebugDumpParsingLog) 96 opts.instrumentedParse_ = true; 97 98 if (opts.programAction_ == DebugDumpProvenance || 99 opts.programAction_ == Fortran::frontend::GetDefinition) 100 opts.needProvenanceRangeToCharBlockMappings_ = true; 101 } 102 103 static bool ParseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 104 clang::DiagnosticsEngine &diags) { 105 unsigned numErrorsBefore = diags.getNumErrors(); 106 107 // By default the frontend driver creates a ParseSyntaxOnly action. 108 opts.programAction_ = ParseSyntaxOnly; 109 110 // Identify the action (i.e. opts.ProgramAction) 111 if (const llvm::opt::Arg *a = 112 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 113 switch (a->getOption().getID()) { 114 default: { 115 llvm_unreachable("Invalid option in group!"); 116 } 117 case clang::driver::options::OPT_test_io: 118 opts.programAction_ = InputOutputTest; 119 break; 120 case clang::driver::options::OPT_E: 121 opts.programAction_ = PrintPreprocessedInput; 122 break; 123 case clang::driver::options::OPT_fsyntax_only: 124 opts.programAction_ = ParseSyntaxOnly; 125 break; 126 case clang::driver::options::OPT_emit_obj: 127 opts.programAction_ = EmitObj; 128 break; 129 case clang::driver::options::OPT_fdebug_unparse: 130 opts.programAction_ = DebugUnparse; 131 break; 132 case clang::driver::options::OPT_fdebug_unparse_no_sema: 133 opts.programAction_ = DebugUnparseNoSema; 134 break; 135 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 136 opts.programAction_ = DebugUnparseWithSymbols; 137 break; 138 case clang::driver::options::OPT_fdebug_dump_symbols: 139 opts.programAction_ = DebugDumpSymbols; 140 break; 141 case clang::driver::options::OPT_fdebug_dump_parse_tree: 142 opts.programAction_ = DebugDumpParseTree; 143 break; 144 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 145 opts.programAction_ = DebugDumpParseTreeNoSema; 146 break; 147 case clang::driver::options::OPT_fdebug_dump_provenance: 148 opts.programAction_ = DebugDumpProvenance; 149 break; 150 case clang::driver::options::OPT_fdebug_dump_parsing_log: 151 opts.programAction_ = DebugDumpParsingLog; 152 break; 153 case clang::driver::options::OPT_fdebug_measure_parse_tree: 154 opts.programAction_ = DebugMeasureParseTree; 155 break; 156 case clang::driver::options::OPT_fdebug_pre_fir_tree: 157 opts.programAction_ = DebugPreFIRTree; 158 break; 159 case clang::driver::options::OPT_fget_symbols_sources: 160 opts.programAction_ = GetSymbolsSources; 161 break; 162 case clang::driver::options::OPT_fget_definition: 163 opts.programAction_ = GetDefinition; 164 break; 165 case clang::driver::options::OPT_init_only: 166 opts.programAction_ = InitOnly; 167 break; 168 169 // TODO: 170 // case clang::driver::options::OPT_emit_llvm: 171 // case clang::driver::options::OPT_emit_llvm_only: 172 // case clang::driver::options::OPT_emit_codegen_only: 173 // case clang::driver::options::OPT_emit_module: 174 // (...) 175 } 176 177 // Parse the values provided with `-fget-definition` (there should be 3 178 // integers) 179 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 180 clang::driver::options::OPT_fget_definition) { 181 unsigned optVals[3] = {0, 0, 0}; 182 183 for (unsigned i = 0; i < 3; i++) { 184 llvm::StringRef val = a->getValue(i); 185 186 if (val.getAsInteger(10, optVals[i])) { 187 // A non-integer was encountered - that's an error. 188 diags.Report(clang::diag::err_drv_invalid_value) 189 << a->getOption().getName() << val; 190 break; 191 } 192 } 193 opts.getDefVals_.line = optVals[0]; 194 opts.getDefVals_.startColumn = optVals[1]; 195 opts.getDefVals_.endColumn = optVals[2]; 196 } 197 } 198 199 opts.outputFile_ = args.getLastArgValue(clang::driver::options::OPT_o); 200 opts.showHelp_ = args.hasArg(clang::driver::options::OPT_help); 201 opts.showVersion_ = args.hasArg(clang::driver::options::OPT_version); 202 203 // Get the input kind (from the value passed via `-x`) 204 InputKind dashX(Language::Unknown); 205 if (const llvm::opt::Arg *a = 206 args.getLastArg(clang::driver::options::OPT_x)) { 207 llvm::StringRef XValue = a->getValue(); 208 // Principal languages. 209 dashX = llvm::StringSwitch<InputKind>(XValue) 210 .Case("f90", Language::Fortran) 211 .Default(Language::Unknown); 212 213 // Some special cases cannot be combined with suffixes. 214 if (dashX.IsUnknown()) 215 dashX = llvm::StringSwitch<InputKind>(XValue) 216 .Case("ir", Language::LLVM_IR) 217 .Default(Language::Unknown); 218 219 if (dashX.IsUnknown()) 220 diags.Report(clang::diag::err_drv_invalid_value) 221 << a->getAsString(args) << a->getValue(); 222 } 223 224 // Collect the input files and save them in our instance of FrontendOptions. 225 std::vector<std::string> inputs = 226 args.getAllArgValues(clang::driver::options::OPT_INPUT); 227 opts.inputs_.clear(); 228 if (inputs.empty()) 229 // '-' is the default input if none is given. 230 inputs.push_back("-"); 231 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 232 InputKind ik = dashX; 233 if (ik.IsUnknown()) { 234 ik = FrontendOptions::GetInputKindForExtension( 235 llvm::StringRef(inputs[i]).rsplit('.').second); 236 if (ik.IsUnknown()) 237 ik = Language::Unknown; 238 if (i == 0) 239 dashX = ik; 240 } 241 242 opts.inputs_.emplace_back(std::move(inputs[i]), ik); 243 } 244 245 // Set fortranForm_ based on options -ffree-form and -ffixed-form. 246 if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form, 247 clang::driver::options::OPT_ffree_form)) { 248 opts.fortranForm_ = 249 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 250 ? FortranForm::FixedForm 251 : FortranForm::FreeForm; 252 } 253 254 // Set fixedFormColumns_ based on -ffixed-line-length=<value> 255 if (const auto *arg = 256 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 257 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 258 std::int64_t columns = -1; 259 if (argValue == "none") { 260 columns = 0; 261 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 262 columns = -1; 263 } 264 if (columns < 0) { 265 diags.Report(clang::diag::err_drv_negative_columns) 266 << arg->getOption().getName() << arg->getValue(); 267 } else if (columns == 0) { 268 opts.fixedFormColumns_ = 1000000; 269 } else if (columns < 7) { 270 diags.Report(clang::diag::err_drv_small_columns) 271 << arg->getOption().getName() << arg->getValue() << "7"; 272 } else { 273 opts.fixedFormColumns_ = columns; 274 } 275 } 276 277 if (const llvm::opt::Arg *arg = 278 args.getLastArg(clang::driver::options::OPT_fimplicit_none, 279 clang::driver::options::OPT_fno_implicit_none)) { 280 opts.features_.Enable( 281 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 282 arg->getOption().matches(clang::driver::options::OPT_fimplicit_none)); 283 } 284 if (const llvm::opt::Arg *arg = 285 args.getLastArg(clang::driver::options::OPT_fbackslash, 286 clang::driver::options::OPT_fno_backslash)) { 287 opts.features_.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 288 arg->getOption().matches(clang::driver::options::OPT_fbackslash)); 289 } 290 if (const llvm::opt::Arg *arg = 291 args.getLastArg(clang::driver::options::OPT_flogical_abbreviations, 292 clang::driver::options::OPT_fno_logical_abbreviations)) { 293 opts.features_.Enable( 294 Fortran::common::LanguageFeature::LogicalAbbreviations, 295 arg->getOption().matches( 296 clang::driver::options::OPT_flogical_abbreviations)); 297 } 298 if (const llvm::opt::Arg *arg = 299 args.getLastArg(clang::driver::options::OPT_fxor_operator, 300 clang::driver::options::OPT_fno_xor_operator)) { 301 opts.features_.Enable(Fortran::common::LanguageFeature::XOROperator, 302 arg->getOption().matches(clang::driver::options::OPT_fxor_operator)); 303 } 304 if (args.hasArg( 305 clang::driver::options::OPT_falternative_parameter_statement)) { 306 opts.features_.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 307 } 308 if (const llvm::opt::Arg *arg = 309 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 310 llvm::StringRef argValue = arg->getValue(); 311 if (argValue == "utf-8") { 312 opts.encoding_ = Fortran::parser::Encoding::UTF_8; 313 } else if (argValue == "latin-1") { 314 opts.encoding_ = Fortran::parser::Encoding::LATIN_1; 315 } else { 316 diags.Report(clang::diag::err_drv_invalid_value) 317 << arg->getAsString(args) << argValue; 318 } 319 } 320 321 setUpFrontendBasedOnAction(opts); 322 opts.dashX_ = dashX; 323 324 return diags.getNumErrors() == numErrorsBefore; 325 } 326 327 // Generate the path to look for intrinsic modules 328 static std::string getIntrinsicDir() { 329 // TODO: Find a system independent API 330 llvm::SmallString<128> driverPath; 331 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 332 llvm::sys::path::remove_filename(driverPath); 333 driverPath.append("/../include/flang/"); 334 return std::string(driverPath); 335 } 336 337 /// Parses all preprocessor input arguments and populates the preprocessor 338 /// options accordingly. 339 /// 340 /// \param [in] opts The preprocessor options instance 341 /// \param [out] args The list of input arguments 342 static void parsePreprocessorArgs( 343 Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) { 344 // Add macros from the command line. 345 for (const auto *currentArg : args.filtered( 346 clang::driver::options::OPT_D, clang::driver::options::OPT_U)) { 347 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 348 opts.addMacroDef(currentArg->getValue()); 349 } else { 350 opts.addMacroUndef(currentArg->getValue()); 351 } 352 } 353 354 // Add the ordered list of -I's. 355 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 356 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 357 358 // Prepend the ordered list of -intrinsic-modules-path 359 // to the default location to search. 360 for (const auto *currentArg : 361 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 362 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 363 364 // -cpp/-nocpp 365 if (const auto *currentArg = args.getLastArg( 366 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 367 opts.macrosFlag_ = 368 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 369 ? PPMacrosFlag::Include 370 : PPMacrosFlag::Exclude; 371 } 372 373 /// Parses all semantic related arguments and populates the variables 374 /// options accordingly. Returns false if new errors are generated. 375 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 376 clang::DiagnosticsEngine &diags) { 377 unsigned numErrorsBefore = diags.getNumErrors(); 378 379 // -J/module-dir option 380 auto moduleDirList = 381 args.getAllArgValues(clang::driver::options::OPT_module_dir); 382 // User can only specify -J/-module-dir once 383 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 384 if (moduleDirList.size() > 1) { 385 const unsigned diagID = 386 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 387 "Only one '-module-dir/-J' option allowed"); 388 diags.Report(diagID); 389 } 390 if (moduleDirList.size() == 1) 391 res.SetModuleDir(moduleDirList[0]); 392 393 // -fdebug-module-writer option 394 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 395 res.SetDebugModuleDir(true); 396 } 397 398 // -module-suffix 399 if (const auto *moduleSuffix = 400 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 401 res.SetModuleFileSuffix(moduleSuffix->getValue()); 402 } 403 404 return diags.getNumErrors() == numErrorsBefore; 405 } 406 407 /// Parses all diagnostics related arguments and populates the variables 408 /// options accordingly. Returns false if new errors are generated. 409 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 410 clang::DiagnosticsEngine &diags) { 411 unsigned numErrorsBefore = diags.getNumErrors(); 412 413 // -Werror option 414 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 415 // this has to change when other -W<opt>'s are supported. 416 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 417 if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) 418 .equals("error")) { 419 res.SetWarnAsErr(true); 420 } else { 421 const unsigned diagID = 422 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 423 "Only `-Werror` is supported currently."); 424 diags.Report(diagID); 425 } 426 } 427 428 return diags.getNumErrors() == numErrorsBefore; 429 } 430 431 /// Parses all Dialect related arguments and populates the variables 432 /// options accordingly. Returns false if new errors are generated. 433 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 434 clang::DiagnosticsEngine &diags) { 435 unsigned numErrorsBefore = diags.getNumErrors(); 436 437 // -fdefault* family 438 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 439 res.defaultKinds().set_defaultRealKind(8); 440 res.defaultKinds().set_doublePrecisionKind(16); 441 } 442 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 443 res.defaultKinds().set_defaultIntegerKind(8); 444 res.defaultKinds().set_subscriptIntegerKind(8); 445 res.defaultKinds().set_sizeIntegerKind(8); 446 } 447 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 448 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 449 // -fdefault-double-8 has to be used with -fdefault-real-8 450 // to be compatible with gfortran 451 const unsigned diagID = 452 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 453 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 454 diags.Report(diagID); 455 } 456 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 457 res.defaultKinds().set_doublePrecisionKind(8); 458 } 459 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 460 res.defaultKinds().set_sizeIntegerKind(8); 461 462 // -fopenmp and -fopenacc 463 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 464 res.frontendOpts().features_.Enable( 465 Fortran::common::LanguageFeature::OpenACC); 466 } 467 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 468 res.frontendOpts().features_.Enable( 469 Fortran::common::LanguageFeature::OpenMP); 470 } 471 472 // -pedantic 473 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 474 res.set_EnableConformanceChecks(); 475 } 476 // -std=f2018 (currently this implies -pedantic) 477 // TODO: Set proper options when more fortran standards 478 // are supported. 479 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 480 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 481 // We only allow f2018 as the given standard 482 if (standard.equals("f2018")) { 483 res.set_EnableConformanceChecks(); 484 } else { 485 const unsigned diagID = 486 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 487 "Only -std=f2018 is allowed currently."); 488 diags.Report(diagID); 489 } 490 } 491 return diags.getNumErrors() == numErrorsBefore; 492 } 493 494 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res, 495 llvm::ArrayRef<const char *> commandLineArgs, 496 clang::DiagnosticsEngine &diags) { 497 498 bool success = true; 499 500 // Parse the arguments 501 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 502 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 503 unsigned missingArgIndex, missingArgCount; 504 llvm::opt::InputArgList args = opts.ParseArgs( 505 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 506 507 // Check for missing argument error. 508 if (missingArgCount) { 509 diags.Report(clang::diag::err_drv_missing_argument) 510 << args.getArgString(missingArgIndex) << missingArgCount; 511 success = false; 512 } 513 514 // Issue errors on unknown arguments 515 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 516 auto argString = a->getAsString(args); 517 std::string nearest; 518 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 519 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 520 else 521 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 522 << argString << nearest; 523 success = false; 524 } 525 526 success &= ParseFrontendArgs(res.frontendOpts(), args, diags); 527 parsePreprocessorArgs(res.preprocessorOpts(), args); 528 success &= parseSemaArgs(res, args, diags); 529 success &= parseDialectArgs(res, args, diags); 530 success &= parseDiagArgs(res, args, diags); 531 532 return success; 533 } 534 535 void CompilerInvocation::collectMacroDefinitions() { 536 auto &ppOpts = this->preprocessorOpts(); 537 538 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 539 llvm::StringRef macro = ppOpts.macros[i].first; 540 bool isUndef = ppOpts.macros[i].second; 541 542 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 543 llvm::StringRef macroName = macroPair.first; 544 llvm::StringRef macroBody = macroPair.second; 545 546 // For an #undef'd macro, we only care about the name. 547 if (isUndef) { 548 parserOpts_.predefinitions.emplace_back( 549 macroName.str(), std::optional<std::string>{}); 550 continue; 551 } 552 553 // For a #define'd macro, figure out the actual definition. 554 if (macroName.size() == macro.size()) 555 macroBody = "1"; 556 else { 557 // Note: GCC drops anything following an end-of-line character. 558 llvm::StringRef::size_type End = macroBody.find_first_of("\n\r"); 559 macroBody = macroBody.substr(0, End); 560 } 561 parserOpts_.predefinitions.emplace_back( 562 macroName, std::optional<std::string>(macroBody.str())); 563 } 564 } 565 566 void CompilerInvocation::SetDefaultFortranOpts() { 567 auto &fortranOptions = fortranOpts(); 568 569 // These defaults are based on the defaults in f18/f18.cpp. 570 std::vector<std::string> searchDirectories{"."s}; 571 fortranOptions.searchDirectories = searchDirectories; 572 fortranOptions.isFixedForm = false; 573 } 574 575 // TODO: When expanding this method, consider creating a dedicated API for 576 // this. Also at some point we will need to differentiate between different 577 // targets and add dedicated predefines for each. 578 void CompilerInvocation::setDefaultPredefinitions() { 579 auto &fortranOptions = fortranOpts(); 580 const auto &frontendOptions = frontendOpts(); 581 582 // Populate the macro list with version numbers and other predefinitions. 583 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 584 fortranOptions.predefinitions.emplace_back( 585 "__flang_major__", FLANG_VERSION_MAJOR_STRING); 586 fortranOptions.predefinitions.emplace_back( 587 "__flang_minor__", FLANG_VERSION_MINOR_STRING); 588 fortranOptions.predefinitions.emplace_back( 589 "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING); 590 591 // Add predefinitions based on extensions enabled 592 if (frontendOptions.features_.IsEnabled( 593 Fortran::common::LanguageFeature::OpenACC)) { 594 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 595 } 596 if (frontendOptions.features_.IsEnabled( 597 Fortran::common::LanguageFeature::OpenMP)) { 598 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 599 } 600 } 601 602 void CompilerInvocation::setFortranOpts() { 603 auto &fortranOptions = fortranOpts(); 604 const auto &frontendOptions = frontendOpts(); 605 const auto &preprocessorOptions = preprocessorOpts(); 606 auto &moduleDirJ = moduleDir(); 607 608 if (frontendOptions.fortranForm_ != FortranForm::Unknown) { 609 fortranOptions.isFixedForm = 610 frontendOptions.fortranForm_ == FortranForm::FixedForm; 611 } 612 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns_; 613 614 fortranOptions.features = frontendOptions.features_; 615 fortranOptions.encoding = frontendOptions.encoding_; 616 617 // Adding search directories specified by -I 618 fortranOptions.searchDirectories.insert( 619 fortranOptions.searchDirectories.end(), 620 preprocessorOptions.searchDirectoriesFromDashI.begin(), 621 preprocessorOptions.searchDirectoriesFromDashI.end()); 622 623 // Add the ordered list of -intrinsic-modules-path 624 fortranOptions.searchDirectories.insert( 625 fortranOptions.searchDirectories.end(), 626 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 627 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 628 629 // Add the default intrinsic module directory at the end 630 fortranOptions.searchDirectories.emplace_back(getIntrinsicDir()); 631 632 // Add the directory supplied through -J/-module-dir to the list of search 633 // directories 634 if (moduleDirJ.compare(".") != 0) 635 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 636 637 if (frontendOptions.instrumentedParse_) 638 fortranOptions.instrumentedParse = true; 639 640 if (frontendOptions.needProvenanceRangeToCharBlockMappings_) 641 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 642 643 if (enableConformanceChecks()) { 644 fortranOptions.features.WarnOnAllNonstandard(); 645 } 646 } 647 648 void CompilerInvocation::setSemanticsOpts( 649 Fortran::parser::AllCookedSources &allCookedSources) { 650 const auto &fortranOptions = fortranOpts(); 651 652 semanticsContext_ = std::make_unique<semantics::SemanticsContext>( 653 defaultKinds(), fortranOptions.features, allCookedSources); 654 655 semanticsContext_->set_moduleDirectory(moduleDir()) 656 .set_searchDirectories(fortranOptions.searchDirectories) 657 .set_warnOnNonstandardUsage(enableConformanceChecks()) 658 .set_warningsAreErrors(warnAsErr()) 659 .set_moduleFileSuffix(moduleFileSuffix()); 660 } 661