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(const llvm::opt::ArgList &args, 57 bool defaultColor = true) { 58 // Color diagnostics default to auto ("on" if terminal supports) in the 59 // compiler driver `flang-new` but default to off in the frontend driver 60 // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color. 61 // Support both clang's -f[no-]color-diagnostics and gcc's 62 // -f[no-]diagnostics-colors[=never|always|auto]. 63 enum { 64 Colors_On, 65 Colors_Off, 66 Colors_Auto 67 } showColors = defaultColor ? Colors_Auto : Colors_Off; 68 69 for (auto *a : args) { 70 const llvm::opt::Option &opt = a->getOption(); 71 if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) { 72 showColors = Colors_On; 73 } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) { 74 showColors = Colors_Off; 75 } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 76 llvm::StringRef value(a->getValue()); 77 if (value == "always") 78 showColors = Colors_On; 79 else if (value == "never") 80 showColors = Colors_Off; 81 else if (value == "auto") 82 showColors = Colors_Auto; 83 } 84 } 85 86 return showColors == Colors_On || 87 (showColors == Colors_Auto && 88 llvm::sys::Process::StandardErrHasColors()); 89 } 90 91 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts, 92 llvm::opt::ArgList &args) { 93 opts.ShowColors = parseShowColorsArgs(args); 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 // Default to off for `flang-new -fc1`. 506 res.getFrontendOpts().showColors = 507 parseShowColorsArgs(args, /*defaultDiagColor=*/false); 508 509 return diags.getNumErrors() == numErrorsBefore; 510 } 511 512 /// Parses all Dialect related arguments and populates the variables 513 /// options accordingly. Returns false if new errors are generated. 514 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 515 clang::DiagnosticsEngine &diags) { 516 unsigned numErrorsBefore = diags.getNumErrors(); 517 518 // -fdefault* family 519 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 520 res.getDefaultKinds().set_defaultRealKind(8); 521 res.getDefaultKinds().set_doublePrecisionKind(16); 522 } 523 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 524 res.getDefaultKinds().set_defaultIntegerKind(8); 525 res.getDefaultKinds().set_subscriptIntegerKind(8); 526 res.getDefaultKinds().set_sizeIntegerKind(8); 527 } 528 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 529 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 530 // -fdefault-double-8 has to be used with -fdefault-real-8 531 // to be compatible with gfortran 532 const unsigned diagID = 533 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 534 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 535 diags.Report(diagID); 536 } 537 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 538 res.getDefaultKinds().set_doublePrecisionKind(8); 539 } 540 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 541 res.getDefaultKinds().set_sizeIntegerKind(8); 542 543 // -fopenmp and -fopenacc 544 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 545 res.getFrontendOpts().features.Enable( 546 Fortran::common::LanguageFeature::OpenACC); 547 } 548 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 549 res.getFrontendOpts().features.Enable( 550 Fortran::common::LanguageFeature::OpenMP); 551 } 552 553 // -pedantic 554 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 555 res.setEnableConformanceChecks(); 556 } 557 // -std=f2018 (currently this implies -pedantic) 558 // TODO: Set proper options when more fortran standards 559 // are supported. 560 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 561 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 562 // We only allow f2018 as the given standard 563 if (standard.equals("f2018")) { 564 res.setEnableConformanceChecks(); 565 } else { 566 const unsigned diagID = 567 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 568 "Only -std=f2018 is allowed currently."); 569 diags.Report(diagID); 570 } 571 } 572 return diags.getNumErrors() == numErrorsBefore; 573 } 574 575 bool CompilerInvocation::createFromArgs( 576 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 577 clang::DiagnosticsEngine &diags) { 578 579 bool success = true; 580 581 // Set the default triple for this CompilerInvocation. This might be 582 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 583 // below). 584 // NOTE: Like in Clang, it would be nice to use option marshalling 585 // for this so that the entire logic for setting-up the triple is in one 586 // place. 587 res.getTargetOpts().triple = 588 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 589 590 // Parse the arguments 591 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 592 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 593 unsigned missingArgIndex, missingArgCount; 594 llvm::opt::InputArgList args = opts.ParseArgs( 595 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 596 597 // Check for missing argument error. 598 if (missingArgCount) { 599 diags.Report(clang::diag::err_drv_missing_argument) 600 << args.getArgString(missingArgIndex) << missingArgCount; 601 success = false; 602 } 603 604 // Issue errors on unknown arguments 605 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 606 auto argString = a->getAsString(args); 607 std::string nearest; 608 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 609 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 610 else 611 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 612 << argString << nearest; 613 success = false; 614 } 615 616 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 617 parseTargetArgs(res.getTargetOpts(), args); 618 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 619 success &= parseSemaArgs(res, args, diags); 620 success &= parseDialectArgs(res, args, diags); 621 success &= parseDiagArgs(res, args, diags); 622 res.frontendOpts.llvmArgs = 623 args.getAllArgValues(clang::driver::options::OPT_mllvm); 624 625 res.frontendOpts.mlirArgs = 626 args.getAllArgValues(clang::driver::options::OPT_mmlir); 627 628 return success; 629 } 630 631 void CompilerInvocation::collectMacroDefinitions() { 632 auto &ppOpts = this->getPreprocessorOpts(); 633 634 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 635 llvm::StringRef macro = ppOpts.macros[i].first; 636 bool isUndef = ppOpts.macros[i].second; 637 638 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 639 llvm::StringRef macroName = macroPair.first; 640 llvm::StringRef macroBody = macroPair.second; 641 642 // For an #undef'd macro, we only care about the name. 643 if (isUndef) { 644 parserOpts.predefinitions.emplace_back(macroName.str(), 645 std::optional<std::string>{}); 646 continue; 647 } 648 649 // For a #define'd macro, figure out the actual definition. 650 if (macroName.size() == macro.size()) 651 macroBody = "1"; 652 else { 653 // Note: GCC drops anything following an end-of-line character. 654 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 655 macroBody = macroBody.substr(0, end); 656 } 657 parserOpts.predefinitions.emplace_back( 658 macroName, std::optional<std::string>(macroBody.str())); 659 } 660 } 661 662 void CompilerInvocation::setDefaultFortranOpts() { 663 auto &fortranOptions = getFortranOpts(); 664 665 std::vector<std::string> searchDirectories{"."s}; 666 fortranOptions.searchDirectories = searchDirectories; 667 668 // Add the location of omp_lib.h to the search directories. Currently this is 669 // identical to the modules' directory. 670 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 671 672 fortranOptions.isFixedForm = false; 673 } 674 675 // TODO: When expanding this method, consider creating a dedicated API for 676 // this. Also at some point we will need to differentiate between different 677 // targets and add dedicated predefines for each. 678 void CompilerInvocation::setDefaultPredefinitions() { 679 auto &fortranOptions = getFortranOpts(); 680 const auto &frontendOptions = getFrontendOpts(); 681 682 // Populate the macro list with version numbers and other predefinitions. 683 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 684 fortranOptions.predefinitions.emplace_back( 685 "__flang_major__", FLANG_VERSION_MAJOR_STRING); 686 fortranOptions.predefinitions.emplace_back( 687 "__flang_minor__", FLANG_VERSION_MINOR_STRING); 688 fortranOptions.predefinitions.emplace_back( 689 "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING); 690 691 // Add predefinitions based on extensions enabled 692 if (frontendOptions.features.IsEnabled( 693 Fortran::common::LanguageFeature::OpenACC)) { 694 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 695 } 696 if (frontendOptions.features.IsEnabled( 697 Fortran::common::LanguageFeature::OpenMP)) { 698 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 699 } 700 } 701 702 void CompilerInvocation::setFortranOpts() { 703 auto &fortranOptions = getFortranOpts(); 704 const auto &frontendOptions = getFrontendOpts(); 705 const auto &preprocessorOptions = getPreprocessorOpts(); 706 auto &moduleDirJ = getModuleDir(); 707 708 if (frontendOptions.fortranForm != FortranForm::Unknown) { 709 fortranOptions.isFixedForm = 710 frontendOptions.fortranForm == FortranForm::FixedForm; 711 } 712 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 713 714 fortranOptions.features = frontendOptions.features; 715 fortranOptions.encoding = frontendOptions.encoding; 716 717 // Adding search directories specified by -I 718 fortranOptions.searchDirectories.insert( 719 fortranOptions.searchDirectories.end(), 720 preprocessorOptions.searchDirectoriesFromDashI.begin(), 721 preprocessorOptions.searchDirectoriesFromDashI.end()); 722 723 // Add the ordered list of -intrinsic-modules-path 724 fortranOptions.searchDirectories.insert( 725 fortranOptions.searchDirectories.end(), 726 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 727 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 728 729 // Add the default intrinsic module directory 730 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 731 732 // Add the directory supplied through -J/-module-dir to the list of search 733 // directories 734 if (moduleDirJ.compare(".") != 0) 735 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 736 737 if (frontendOptions.instrumentedParse) 738 fortranOptions.instrumentedParse = true; 739 740 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 741 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 742 743 if (getEnableConformanceChecks()) { 744 fortranOptions.features.WarnOnAllNonstandard(); 745 } 746 } 747 748 void CompilerInvocation::setSemanticsOpts( 749 Fortran::parser::AllCookedSources &allCookedSources) { 750 const auto &fortranOptions = getFortranOpts(); 751 752 semanticsContext = std::make_unique<semantics::SemanticsContext>( 753 getDefaultKinds(), fortranOptions.features, allCookedSources); 754 755 semanticsContext->set_moduleDirectory(getModuleDir()) 756 .set_searchDirectories(fortranOptions.searchDirectories) 757 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 758 .set_warnOnNonstandardUsage(getEnableConformanceChecks()) 759 .set_warningsAreErrors(getWarnAsErr()) 760 .set_moduleFileSuffix(getModuleFileSuffix()); 761 } 762