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