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