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