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 // Flang's intermediate representations. 273 if (dashX.isUnknown()) 274 dashX = llvm::StringSwitch<InputKind>(xValue) 275 .Case("ir", Language::LLVM_IR) 276 .Case("fir", Language::MLIR) 277 .Case("mlir", Language::MLIR) 278 .Default(Language::Unknown); 279 280 if (dashX.isUnknown()) 281 diags.Report(clang::diag::err_drv_invalid_value) 282 << a->getAsString(args) << a->getValue(); 283 } 284 285 // Collect the input files and save them in our instance of FrontendOptions. 286 std::vector<std::string> inputs = 287 args.getAllArgValues(clang::driver::options::OPT_INPUT); 288 opts.inputs.clear(); 289 if (inputs.empty()) 290 // '-' is the default input if none is given. 291 inputs.push_back("-"); 292 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 293 InputKind ik = dashX; 294 if (ik.isUnknown()) { 295 ik = FrontendOptions::getInputKindForExtension( 296 llvm::StringRef(inputs[i]).rsplit('.').second); 297 if (ik.isUnknown()) 298 ik = Language::Unknown; 299 if (i == 0) 300 dashX = ik; 301 } 302 303 opts.inputs.emplace_back(std::move(inputs[i]), ik); 304 } 305 306 // Set fortranForm based on options -ffree-form and -ffixed-form. 307 if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form, 308 clang::driver::options::OPT_ffree_form)) { 309 opts.fortranForm = 310 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 311 ? FortranForm::FixedForm 312 : FortranForm::FreeForm; 313 } 314 315 // Set fixedFormColumns based on -ffixed-line-length=<value> 316 if (const auto *arg = 317 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 318 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 319 std::int64_t columns = -1; 320 if (argValue == "none") { 321 columns = 0; 322 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 323 columns = -1; 324 } 325 if (columns < 0) { 326 diags.Report(clang::diag::err_drv_negative_columns) 327 << arg->getOption().getName() << arg->getValue(); 328 } else if (columns == 0) { 329 opts.fixedFormColumns = 1000000; 330 } else if (columns < 7) { 331 diags.Report(clang::diag::err_drv_small_columns) 332 << arg->getOption().getName() << arg->getValue() << "7"; 333 } else { 334 opts.fixedFormColumns = columns; 335 } 336 } 337 338 // -f{no-}implicit-none 339 opts.features.Enable( 340 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 341 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 342 clang::driver::options::OPT_fno_implicit_none, false)); 343 344 // -f{no-}backslash 345 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 346 args.hasFlag(clang::driver::options::OPT_fbackslash, 347 clang::driver::options::OPT_fno_backslash, false)); 348 349 // -f{no-}logical-abbreviations 350 opts.features.Enable(Fortran::common::LanguageFeature::LogicalAbbreviations, 351 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 352 clang::driver::options::OPT_fno_logical_abbreviations, false)); 353 354 // -f{no-}xor-operator 355 opts.features.Enable(Fortran::common::LanguageFeature::XOROperator, 356 args.hasFlag(clang::driver::options::OPT_fxor_operator, 357 clang::driver::options::OPT_fno_xor_operator, false)); 358 359 // -fno-automatic 360 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 361 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 362 } 363 364 if (args.hasArg( 365 clang::driver::options::OPT_falternative_parameter_statement)) { 366 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 367 } 368 if (const llvm::opt::Arg *arg = 369 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 370 llvm::StringRef argValue = arg->getValue(); 371 if (argValue == "utf-8") { 372 opts.encoding = Fortran::parser::Encoding::UTF_8; 373 } else if (argValue == "latin-1") { 374 opts.encoding = Fortran::parser::Encoding::LATIN_1; 375 } else { 376 diags.Report(clang::diag::err_drv_invalid_value) 377 << arg->getAsString(args) << argValue; 378 } 379 } 380 381 setUpFrontendBasedOnAction(opts); 382 opts.dashX = dashX; 383 384 return diags.getNumErrors() == numErrorsBefore; 385 } 386 387 // Generate the path to look for intrinsic modules 388 static std::string getIntrinsicDir() { 389 // TODO: Find a system independent API 390 llvm::SmallString<128> driverPath; 391 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 392 llvm::sys::path::remove_filename(driverPath); 393 driverPath.append("/../include/flang/"); 394 return std::string(driverPath); 395 } 396 397 // Generate the path to look for OpenMP headers 398 static std::string getOpenMPHeadersDir() { 399 llvm::SmallString<128> includePath; 400 includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 401 llvm::sys::path::remove_filename(includePath); 402 includePath.append("/../include/flang/OpenMP/"); 403 return std::string(includePath); 404 } 405 406 /// Parses all preprocessor input arguments and populates the preprocessor 407 /// options accordingly. 408 /// 409 /// \param [in] opts The preprocessor options instance 410 /// \param [out] args The list of input arguments 411 static void parsePreprocessorArgs( 412 Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) { 413 // Add macros from the command line. 414 for (const auto *currentArg : args.filtered( 415 clang::driver::options::OPT_D, clang::driver::options::OPT_U)) { 416 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 417 opts.addMacroDef(currentArg->getValue()); 418 } else { 419 opts.addMacroUndef(currentArg->getValue()); 420 } 421 } 422 423 // Add the ordered list of -I's. 424 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 425 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 426 427 // Prepend the ordered list of -intrinsic-modules-path 428 // to the default location to search. 429 for (const auto *currentArg : 430 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 431 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 432 433 // -cpp/-nocpp 434 if (const auto *currentArg = args.getLastArg( 435 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 436 opts.macrosFlag = 437 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 438 ? PPMacrosFlag::Include 439 : PPMacrosFlag::Exclude; 440 441 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 442 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 443 } 444 445 /// Parses all semantic related arguments and populates the variables 446 /// options accordingly. Returns false if new errors are generated. 447 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 448 clang::DiagnosticsEngine &diags) { 449 unsigned numErrorsBefore = diags.getNumErrors(); 450 451 // -J/module-dir option 452 auto moduleDirList = 453 args.getAllArgValues(clang::driver::options::OPT_module_dir); 454 // User can only specify -J/-module-dir once 455 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 456 if (moduleDirList.size() > 1) { 457 const unsigned diagID = 458 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 459 "Only one '-module-dir/-J' option allowed"); 460 diags.Report(diagID); 461 } 462 if (moduleDirList.size() == 1) 463 res.setModuleDir(moduleDirList[0]); 464 465 // -fdebug-module-writer option 466 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 467 res.setDebugModuleDir(true); 468 } 469 470 // -module-suffix 471 if (const auto *moduleSuffix = 472 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 473 res.setModuleFileSuffix(moduleSuffix->getValue()); 474 } 475 476 // -f{no-}analyzed-objects-for-unparse 477 res.setUseAnalyzedObjectsForUnparse(args.hasFlag( 478 clang::driver::options::OPT_fanalyzed_objects_for_unparse, 479 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 480 481 return diags.getNumErrors() == numErrorsBefore; 482 } 483 484 /// Parses all diagnostics related arguments and populates the variables 485 /// options accordingly. Returns false if new errors are generated. 486 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 487 clang::DiagnosticsEngine &diags) { 488 unsigned numErrorsBefore = diags.getNumErrors(); 489 490 // -Werror option 491 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 492 // this has to change when other -W<opt>'s are supported. 493 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 494 if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) 495 .equals("error")) { 496 res.setWarnAsErr(true); 497 } else { 498 const unsigned diagID = 499 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 500 "Only `-Werror` is supported currently."); 501 diags.Report(diagID); 502 } 503 } 504 505 return diags.getNumErrors() == numErrorsBefore; 506 } 507 508 /// Parses all Dialect related arguments and populates the variables 509 /// options accordingly. Returns false if new errors are generated. 510 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 511 clang::DiagnosticsEngine &diags) { 512 unsigned numErrorsBefore = diags.getNumErrors(); 513 514 // -fdefault* family 515 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 516 res.getDefaultKinds().set_defaultRealKind(8); 517 res.getDefaultKinds().set_doublePrecisionKind(16); 518 } 519 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 520 res.getDefaultKinds().set_defaultIntegerKind(8); 521 res.getDefaultKinds().set_subscriptIntegerKind(8); 522 res.getDefaultKinds().set_sizeIntegerKind(8); 523 } 524 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 525 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 526 // -fdefault-double-8 has to be used with -fdefault-real-8 527 // to be compatible with gfortran 528 const unsigned diagID = 529 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 530 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 531 diags.Report(diagID); 532 } 533 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 534 res.getDefaultKinds().set_doublePrecisionKind(8); 535 } 536 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 537 res.getDefaultKinds().set_sizeIntegerKind(8); 538 539 // -fopenmp and -fopenacc 540 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 541 res.getFrontendOpts().features.Enable( 542 Fortran::common::LanguageFeature::OpenACC); 543 } 544 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 545 res.getFrontendOpts().features.Enable( 546 Fortran::common::LanguageFeature::OpenMP); 547 } 548 549 // -pedantic 550 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 551 res.setEnableConformanceChecks(); 552 } 553 // -std=f2018 (currently this implies -pedantic) 554 // TODO: Set proper options when more fortran standards 555 // are supported. 556 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 557 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 558 // We only allow f2018 as the given standard 559 if (standard.equals("f2018")) { 560 res.setEnableConformanceChecks(); 561 } else { 562 const unsigned diagID = 563 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 564 "Only -std=f2018 is allowed currently."); 565 diags.Report(diagID); 566 } 567 } 568 return diags.getNumErrors() == numErrorsBefore; 569 } 570 571 bool CompilerInvocation::createFromArgs( 572 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 573 clang::DiagnosticsEngine &diags) { 574 575 bool success = true; 576 577 // Set the default triple for this CompilerInvocation. This might be 578 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 579 // below). 580 // NOTE: Like in Clang, it would be nice to use option marshalling 581 // for this so that the entire logic for setting-up the triple is in one 582 // place. 583 res.getTargetOpts().triple = 584 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 585 586 // Parse the arguments 587 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 588 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 589 unsigned missingArgIndex, missingArgCount; 590 llvm::opt::InputArgList args = opts.ParseArgs( 591 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 592 593 // Check for missing argument error. 594 if (missingArgCount) { 595 diags.Report(clang::diag::err_drv_missing_argument) 596 << args.getArgString(missingArgIndex) << missingArgCount; 597 success = false; 598 } 599 600 // Issue errors on unknown arguments 601 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 602 auto argString = a->getAsString(args); 603 std::string nearest; 604 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 605 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 606 else 607 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 608 << argString << nearest; 609 success = false; 610 } 611 612 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 613 parseTargetArgs(res.getTargetOpts(), args); 614 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 615 success &= parseSemaArgs(res, args, diags); 616 success &= parseDialectArgs(res, args, diags); 617 success &= parseDiagArgs(res, args, diags); 618 res.frontendOpts.llvmArgs = 619 args.getAllArgValues(clang::driver::options::OPT_mllvm); 620 621 res.frontendOpts.mlirArgs = 622 args.getAllArgValues(clang::driver::options::OPT_mmlir); 623 624 return success; 625 } 626 627 void CompilerInvocation::collectMacroDefinitions() { 628 auto &ppOpts = this->getPreprocessorOpts(); 629 630 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 631 llvm::StringRef macro = ppOpts.macros[i].first; 632 bool isUndef = ppOpts.macros[i].second; 633 634 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 635 llvm::StringRef macroName = macroPair.first; 636 llvm::StringRef macroBody = macroPair.second; 637 638 // For an #undef'd macro, we only care about the name. 639 if (isUndef) { 640 parserOpts.predefinitions.emplace_back(macroName.str(), 641 std::optional<std::string>{}); 642 continue; 643 } 644 645 // For a #define'd macro, figure out the actual definition. 646 if (macroName.size() == macro.size()) 647 macroBody = "1"; 648 else { 649 // Note: GCC drops anything following an end-of-line character. 650 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 651 macroBody = macroBody.substr(0, end); 652 } 653 parserOpts.predefinitions.emplace_back( 654 macroName, std::optional<std::string>(macroBody.str())); 655 } 656 } 657 658 void CompilerInvocation::setDefaultFortranOpts() { 659 auto &fortranOptions = getFortranOpts(); 660 661 std::vector<std::string> searchDirectories{"."s}; 662 fortranOptions.searchDirectories = searchDirectories; 663 664 // Add the location of omp_lib.h to the search directories. Currently this is 665 // identical to the modules' directory. 666 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 667 668 fortranOptions.isFixedForm = false; 669 } 670 671 // TODO: When expanding this method, consider creating a dedicated API for 672 // this. Also at some point we will need to differentiate between different 673 // targets and add dedicated predefines for each. 674 void CompilerInvocation::setDefaultPredefinitions() { 675 auto &fortranOptions = getFortranOpts(); 676 const auto &frontendOptions = getFrontendOpts(); 677 678 // Populate the macro list with version numbers and other predefinitions. 679 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 680 fortranOptions.predefinitions.emplace_back( 681 "__flang_major__", FLANG_VERSION_MAJOR_STRING); 682 fortranOptions.predefinitions.emplace_back( 683 "__flang_minor__", FLANG_VERSION_MINOR_STRING); 684 fortranOptions.predefinitions.emplace_back( 685 "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING); 686 687 // Add predefinitions based on extensions enabled 688 if (frontendOptions.features.IsEnabled( 689 Fortran::common::LanguageFeature::OpenACC)) { 690 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 691 } 692 if (frontendOptions.features.IsEnabled( 693 Fortran::common::LanguageFeature::OpenMP)) { 694 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 695 } 696 } 697 698 void CompilerInvocation::setFortranOpts() { 699 auto &fortranOptions = getFortranOpts(); 700 const auto &frontendOptions = getFrontendOpts(); 701 const auto &preprocessorOptions = getPreprocessorOpts(); 702 auto &moduleDirJ = getModuleDir(); 703 704 if (frontendOptions.fortranForm != FortranForm::Unknown) { 705 fortranOptions.isFixedForm = 706 frontendOptions.fortranForm == FortranForm::FixedForm; 707 } 708 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 709 710 fortranOptions.features = frontendOptions.features; 711 fortranOptions.encoding = frontendOptions.encoding; 712 713 // Adding search directories specified by -I 714 fortranOptions.searchDirectories.insert( 715 fortranOptions.searchDirectories.end(), 716 preprocessorOptions.searchDirectoriesFromDashI.begin(), 717 preprocessorOptions.searchDirectoriesFromDashI.end()); 718 719 // Add the ordered list of -intrinsic-modules-path 720 fortranOptions.searchDirectories.insert( 721 fortranOptions.searchDirectories.end(), 722 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 723 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 724 725 // Add the default intrinsic module directory 726 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 727 728 // Add the directory supplied through -J/-module-dir to the list of search 729 // directories 730 if (moduleDirJ.compare(".") != 0) 731 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 732 733 if (frontendOptions.instrumentedParse) 734 fortranOptions.instrumentedParse = true; 735 736 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 737 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 738 739 if (getEnableConformanceChecks()) { 740 fortranOptions.features.WarnOnAllNonstandard(); 741 } 742 } 743 744 void CompilerInvocation::setSemanticsOpts( 745 Fortran::parser::AllCookedSources &allCookedSources) { 746 const auto &fortranOptions = getFortranOpts(); 747 748 semanticsContext = std::make_unique<semantics::SemanticsContext>( 749 getDefaultKinds(), fortranOptions.features, allCookedSources); 750 751 semanticsContext->set_moduleDirectory(getModuleDir()) 752 .set_searchDirectories(fortranOptions.searchDirectories) 753 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 754 .set_warnOnNonstandardUsage(getEnableConformanceChecks()) 755 .set_warningsAreErrors(getWarnAsErr()) 756 .set_moduleFileSuffix(getModuleFileSuffix()); 757 } 758