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