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