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