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