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/Frontend/Debug/Options.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/Path.h" 35 #include "llvm/Support/Process.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include "llvm/TargetParser/Host.h" 38 #include "llvm/TargetParser/Triple.h" 39 #include <memory> 40 #include <optional> 41 42 using namespace Fortran::frontend; 43 44 //===----------------------------------------------------------------------===// 45 // Initialization. 46 //===----------------------------------------------------------------------===// 47 CompilerInvocationBase::CompilerInvocationBase() 48 : diagnosticOpts(new clang::DiagnosticOptions()), 49 preprocessorOpts(new PreprocessorOptions()) {} 50 51 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 52 : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())), 53 preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {} 54 55 CompilerInvocationBase::~CompilerInvocationBase() = default; 56 57 //===----------------------------------------------------------------------===// 58 // Deserialization (from args) 59 //===----------------------------------------------------------------------===// 60 static bool parseShowColorsArgs(const llvm::opt::ArgList &args, 61 bool defaultColor = true) { 62 // Color diagnostics default to auto ("on" if terminal supports) in the 63 // compiler driver `flang-new` but default to off in the frontend driver 64 // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color. 65 // Support both clang's -f[no-]color-diagnostics and gcc's 66 // -f[no-]diagnostics-colors[=never|always|auto]. 67 enum { 68 Colors_On, 69 Colors_Off, 70 Colors_Auto 71 } showColors = defaultColor ? Colors_Auto : Colors_Off; 72 73 for (auto *a : args) { 74 const llvm::opt::Option &opt = a->getOption(); 75 if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) { 76 showColors = Colors_On; 77 } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) { 78 showColors = Colors_Off; 79 } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 80 llvm::StringRef value(a->getValue()); 81 if (value == "always") 82 showColors = Colors_On; 83 else if (value == "never") 84 showColors = Colors_Off; 85 else if (value == "auto") 86 showColors = Colors_Auto; 87 } 88 } 89 90 return showColors == Colors_On || 91 (showColors == Colors_Auto && 92 llvm::sys::Process::StandardErrHasColors()); 93 } 94 95 /// Extracts the optimisation level from \a args. 96 static unsigned getOptimizationLevel(llvm::opt::ArgList &args, 97 clang::DiagnosticsEngine &diags) { 98 unsigned defaultOpt = llvm::CodeGenOpt::None; 99 100 if (llvm::opt::Arg *a = 101 args.getLastArg(clang::driver::options::OPT_O_Group)) { 102 if (a->getOption().matches(clang::driver::options::OPT_O0)) 103 return llvm::CodeGenOpt::None; 104 105 assert(a->getOption().matches(clang::driver::options::OPT_O)); 106 107 return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt, 108 diags); 109 } 110 111 return defaultOpt; 112 } 113 114 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts, 115 llvm::opt::ArgList &args) { 116 opts.ShowColors = parseShowColorsArgs(args); 117 118 return true; 119 } 120 121 static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts, 122 llvm::opt::ArgList &args, 123 clang::DiagnosticsEngine &diags) { 124 using DebugInfoKind = llvm::codegenoptions::DebugInfoKind; 125 if (llvm::opt::Arg *arg = 126 args.getLastArg(clang::driver::options::OPT_debug_info_kind_EQ)) { 127 std::optional<DebugInfoKind> val = 128 llvm::StringSwitch<std::optional<DebugInfoKind>>(arg->getValue()) 129 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly) 130 .Case("line-directives-only", 131 llvm::codegenoptions::DebugDirectivesOnly) 132 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor) 133 .Case("limited", llvm::codegenoptions::LimitedDebugInfo) 134 .Case("standalone", llvm::codegenoptions::FullDebugInfo) 135 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo) 136 .Default(std::nullopt); 137 if (!val.has_value()) { 138 diags.Report(clang::diag::err_drv_invalid_value) 139 << arg->getAsString(args) << arg->getValue(); 140 return false; 141 } 142 opts.setDebugInfo(val.value()); 143 if (val != llvm::codegenoptions::DebugLineTablesOnly && 144 val != llvm::codegenoptions::NoDebugInfo) { 145 const auto debugWarning = diags.getCustomDiagID( 146 clang::DiagnosticsEngine::Warning, "Unsupported debug option: %0"); 147 diags.Report(debugWarning) << arg->getValue(); 148 } 149 } 150 return true; 151 } 152 153 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts, 154 llvm::opt::ArgList &args, 155 clang::DiagnosticsEngine &diags) { 156 opts.OptimizationLevel = getOptimizationLevel(args, diags); 157 158 if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager, 159 clang::driver::options::OPT_fno_debug_pass_manager, false)) 160 opts.DebugPassManager = 1; 161 162 if (args.hasFlag(clang::driver::options::OPT_fstack_arrays, 163 clang::driver::options::OPT_fno_stack_arrays, false)) { 164 opts.StackArrays = 1; 165 } 166 if (args.hasFlag(clang::driver::options::OPT_floop_versioning, 167 clang::driver::options::OPT_fno_loop_versioning, false)) { 168 opts.LoopVersioning = 1; 169 } 170 171 for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ)) 172 opts.LLVMPassPlugins.push_back(a->getValue()); 173 174 // -fembed-offload-object option 175 for (auto *a : 176 args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ)) 177 opts.OffloadObjects.push_back(a->getValue()); 178 179 // -flto=full/thin option. 180 if (const llvm::opt::Arg *a = 181 args.getLastArg(clang::driver::options::OPT_flto_EQ)) { 182 llvm::StringRef s = a->getValue(); 183 assert((s == "full" || s == "thin") && "Unknown LTO mode."); 184 if (s == "full") 185 opts.PrepareForFullLTO = true; 186 else 187 opts.PrepareForThinLTO = true; 188 } 189 190 if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ)) 191 opts.SaveTempsDir = a->getValue(); 192 193 // -mrelocation-model option. 194 if (const llvm::opt::Arg *a = 195 args.getLastArg(clang::driver::options::OPT_mrelocation_model)) { 196 llvm::StringRef modelName = a->getValue(); 197 auto relocModel = 198 llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(modelName) 199 .Case("static", llvm::Reloc::Static) 200 .Case("pic", llvm::Reloc::PIC_) 201 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC) 202 .Case("ropi", llvm::Reloc::ROPI) 203 .Case("rwpi", llvm::Reloc::RWPI) 204 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 205 .Default(std::nullopt); 206 if (relocModel.has_value()) 207 opts.setRelocationModel(*relocModel); 208 else 209 diags.Report(clang::diag::err_drv_invalid_value) 210 << a->getAsString(args) << modelName; 211 } 212 213 // -pic-level and -pic-is-pie option. 214 if (int picLevel = getLastArgIntValue( 215 args, clang::driver::options::OPT_pic_level, 0, diags)) { 216 if (picLevel > 2) 217 diags.Report(clang::diag::err_drv_invalid_value) 218 << args.getLastArg(clang::driver::options::OPT_pic_level) 219 ->getAsString(args) 220 << picLevel; 221 222 opts.PICLevel = picLevel; 223 if (args.hasArg(clang::driver::options::OPT_pic_is_pie)) 224 opts.IsPIE = 1; 225 } 226 227 // This option is compatible with -f[no-]underscoring in gfortran. 228 if (args.hasFlag(clang::driver::options::OPT_fno_underscoring, 229 clang::driver::options::OPT_funderscoring, false)) { 230 opts.Underscoring = 0; 231 } 232 } 233 234 /// Parses all target input arguments and populates the target 235 /// options accordingly. 236 /// 237 /// \param [in] opts The target options instance to update 238 /// \param [in] args The list of input arguments (from the compiler invocation) 239 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { 240 if (const llvm::opt::Arg *a = 241 args.getLastArg(clang::driver::options::OPT_triple)) 242 opts.triple = a->getValue(); 243 244 if (const llvm::opt::Arg *a = 245 args.getLastArg(clang::driver::options::OPT_target_cpu)) 246 opts.cpu = a->getValue(); 247 248 for (const llvm::opt::Arg *currentArg : 249 args.filtered(clang::driver::options::OPT_target_feature)) 250 opts.featuresAsWritten.emplace_back(currentArg->getValue()); 251 } 252 253 // Tweak the frontend configuration based on the frontend action 254 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 255 if (opts.programAction == DebugDumpParsingLog) 256 opts.instrumentedParse = true; 257 258 if (opts.programAction == DebugDumpProvenance || 259 opts.programAction == Fortran::frontend::GetDefinition) 260 opts.needProvenanceRangeToCharBlockMappings = true; 261 } 262 263 /// Parse the argument specified for the -fconvert=<value> option 264 static std::optional<const char *> parseConvertArg(const char *s) { 265 return llvm::StringSwitch<std::optional<const char *>>(s) 266 .Case("unknown", "UNKNOWN") 267 .Case("native", "NATIVE") 268 .Case("little-endian", "LITTLE_ENDIAN") 269 .Case("big-endian", "BIG_ENDIAN") 270 .Case("swap", "SWAP") 271 .Default(std::nullopt); 272 } 273 274 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 275 clang::DiagnosticsEngine &diags) { 276 unsigned numErrorsBefore = diags.getNumErrors(); 277 278 // By default the frontend driver creates a ParseSyntaxOnly action. 279 opts.programAction = ParseSyntaxOnly; 280 281 // Treat multiple action options as an invocation error. Note that `clang 282 // -cc1` does accept multiple action options, but will only consider the 283 // rightmost one. 284 if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) { 285 const unsigned diagID = diags.getCustomDiagID( 286 clang::DiagnosticsEngine::Error, "Only one action option is allowed"); 287 diags.Report(diagID); 288 return false; 289 } 290 291 // Identify the action (i.e. opts.ProgramAction) 292 if (const llvm::opt::Arg *a = 293 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 294 switch (a->getOption().getID()) { 295 default: { 296 llvm_unreachable("Invalid option in group!"); 297 } 298 case clang::driver::options::OPT_test_io: 299 opts.programAction = InputOutputTest; 300 break; 301 case clang::driver::options::OPT_E: 302 opts.programAction = PrintPreprocessedInput; 303 break; 304 case clang::driver::options::OPT_fsyntax_only: 305 opts.programAction = ParseSyntaxOnly; 306 break; 307 case clang::driver::options::OPT_emit_mlir: 308 opts.programAction = EmitMLIR; 309 break; 310 case clang::driver::options::OPT_emit_llvm: 311 opts.programAction = EmitLLVM; 312 break; 313 case clang::driver::options::OPT_emit_llvm_bc: 314 opts.programAction = EmitLLVMBitcode; 315 break; 316 case clang::driver::options::OPT_emit_obj: 317 opts.programAction = EmitObj; 318 break; 319 case clang::driver::options::OPT_S: 320 opts.programAction = EmitAssembly; 321 break; 322 case clang::driver::options::OPT_fdebug_unparse: 323 opts.programAction = DebugUnparse; 324 break; 325 case clang::driver::options::OPT_fdebug_unparse_no_sema: 326 opts.programAction = DebugUnparseNoSema; 327 break; 328 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 329 opts.programAction = DebugUnparseWithSymbols; 330 break; 331 case clang::driver::options::OPT_fdebug_dump_symbols: 332 opts.programAction = DebugDumpSymbols; 333 break; 334 case clang::driver::options::OPT_fdebug_dump_parse_tree: 335 opts.programAction = DebugDumpParseTree; 336 break; 337 case clang::driver::options::OPT_fdebug_dump_pft: 338 opts.programAction = DebugDumpPFT; 339 break; 340 case clang::driver::options::OPT_fdebug_dump_all: 341 opts.programAction = DebugDumpAll; 342 break; 343 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 344 opts.programAction = DebugDumpParseTreeNoSema; 345 break; 346 case clang::driver::options::OPT_fdebug_dump_provenance: 347 opts.programAction = DebugDumpProvenance; 348 break; 349 case clang::driver::options::OPT_fdebug_dump_parsing_log: 350 opts.programAction = DebugDumpParsingLog; 351 break; 352 case clang::driver::options::OPT_fdebug_measure_parse_tree: 353 opts.programAction = DebugMeasureParseTree; 354 break; 355 case clang::driver::options::OPT_fdebug_pre_fir_tree: 356 opts.programAction = DebugPreFIRTree; 357 break; 358 case clang::driver::options::OPT_fget_symbols_sources: 359 opts.programAction = GetSymbolsSources; 360 break; 361 case clang::driver::options::OPT_fget_definition: 362 opts.programAction = GetDefinition; 363 break; 364 case clang::driver::options::OPT_init_only: 365 opts.programAction = InitOnly; 366 break; 367 368 // TODO: 369 // case clang::driver::options::OPT_emit_llvm: 370 // case clang::driver::options::OPT_emit_llvm_only: 371 // case clang::driver::options::OPT_emit_codegen_only: 372 // case clang::driver::options::OPT_emit_module: 373 // (...) 374 } 375 376 // Parse the values provided with `-fget-definition` (there should be 3 377 // integers) 378 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 379 clang::driver::options::OPT_fget_definition) { 380 unsigned optVals[3] = {0, 0, 0}; 381 382 for (unsigned i = 0; i < 3; i++) { 383 llvm::StringRef val = a->getValue(i); 384 385 if (val.getAsInteger(10, optVals[i])) { 386 // A non-integer was encountered - that's an error. 387 diags.Report(clang::diag::err_drv_invalid_value) 388 << a->getOption().getName() << val; 389 break; 390 } 391 } 392 opts.getDefVals.line = optVals[0]; 393 opts.getDefVals.startColumn = optVals[1]; 394 opts.getDefVals.endColumn = optVals[2]; 395 } 396 } 397 398 // Parsing -load <dsopath> option and storing shared object path 399 if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) { 400 opts.plugins.push_back(a->getValue()); 401 } 402 403 // Parsing -plugin <name> option and storing plugin name and setting action 404 if (const llvm::opt::Arg *a = 405 args.getLastArg(clang::driver::options::OPT_plugin)) { 406 opts.programAction = PluginAction; 407 opts.actionName = a->getValue(); 408 } 409 410 opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); 411 opts.showHelp = args.hasArg(clang::driver::options::OPT_help); 412 opts.showVersion = args.hasArg(clang::driver::options::OPT_version); 413 414 // Get the input kind (from the value passed via `-x`) 415 InputKind dashX(Language::Unknown); 416 if (const llvm::opt::Arg *a = 417 args.getLastArg(clang::driver::options::OPT_x)) { 418 llvm::StringRef xValue = a->getValue(); 419 // Principal languages. 420 dashX = llvm::StringSwitch<InputKind>(xValue) 421 // Flang does not differentiate between pre-processed and not 422 // pre-processed inputs. 423 .Case("f95", Language::Fortran) 424 .Case("f95-cpp-input", Language::Fortran) 425 .Default(Language::Unknown); 426 427 // Flang's intermediate representations. 428 if (dashX.isUnknown()) 429 dashX = llvm::StringSwitch<InputKind>(xValue) 430 .Case("ir", Language::LLVM_IR) 431 .Case("fir", Language::MLIR) 432 .Case("mlir", Language::MLIR) 433 .Default(Language::Unknown); 434 435 if (dashX.isUnknown()) 436 diags.Report(clang::diag::err_drv_invalid_value) 437 << a->getAsString(args) << a->getValue(); 438 } 439 440 // Collect the input files and save them in our instance of FrontendOptions. 441 std::vector<std::string> inputs = 442 args.getAllArgValues(clang::driver::options::OPT_INPUT); 443 opts.inputs.clear(); 444 if (inputs.empty()) 445 // '-' is the default input if none is given. 446 inputs.push_back("-"); 447 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 448 InputKind ik = dashX; 449 if (ik.isUnknown()) { 450 ik = FrontendOptions::getInputKindForExtension( 451 llvm::StringRef(inputs[i]).rsplit('.').second); 452 if (ik.isUnknown()) 453 ik = Language::Unknown; 454 if (i == 0) 455 dashX = ik; 456 } 457 458 opts.inputs.emplace_back(std::move(inputs[i]), ik); 459 } 460 461 // Set fortranForm based on options -ffree-form and -ffixed-form. 462 if (const auto *arg = 463 args.getLastArg(clang::driver::options::OPT_ffixed_form, 464 clang::driver::options::OPT_ffree_form)) { 465 opts.fortranForm = 466 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 467 ? FortranForm::FixedForm 468 : FortranForm::FreeForm; 469 } 470 471 // Set fixedFormColumns based on -ffixed-line-length=<value> 472 if (const auto *arg = 473 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 474 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 475 std::int64_t columns = -1; 476 if (argValue == "none") { 477 columns = 0; 478 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 479 columns = -1; 480 } 481 if (columns < 0) { 482 diags.Report(clang::diag::err_drv_negative_columns) 483 << arg->getOption().getName() << arg->getValue(); 484 } else if (columns == 0) { 485 opts.fixedFormColumns = 1000000; 486 } else if (columns < 7) { 487 diags.Report(clang::diag::err_drv_small_columns) 488 << arg->getOption().getName() << arg->getValue() << "7"; 489 } else { 490 opts.fixedFormColumns = columns; 491 } 492 } 493 494 // Set conversion based on -fconvert=<value> 495 if (const auto *arg = 496 args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) { 497 const char *argValue = arg->getValue(); 498 if (auto convert = parseConvertArg(argValue)) 499 opts.envDefaults.push_back({"FORT_CONVERT", *convert}); 500 else 501 diags.Report(clang::diag::err_drv_invalid_value) 502 << arg->getAsString(args) << argValue; 503 } 504 505 // -f{no-}implicit-none 506 opts.features.Enable( 507 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 508 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 509 clang::driver::options::OPT_fno_implicit_none, false)); 510 511 // -f{no-}backslash 512 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 513 args.hasFlag(clang::driver::options::OPT_fbackslash, 514 clang::driver::options::OPT_fno_backslash, 515 false)); 516 517 // -f{no-}logical-abbreviations 518 opts.features.Enable( 519 Fortran::common::LanguageFeature::LogicalAbbreviations, 520 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 521 clang::driver::options::OPT_fno_logical_abbreviations, 522 false)); 523 524 // -f{no-}xor-operator 525 opts.features.Enable( 526 Fortran::common::LanguageFeature::XOROperator, 527 args.hasFlag(clang::driver::options::OPT_fxor_operator, 528 clang::driver::options::OPT_fno_xor_operator, false)); 529 530 // -fno-automatic 531 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 532 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 533 } 534 535 if (args.hasArg( 536 clang::driver::options::OPT_falternative_parameter_statement)) { 537 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 538 } 539 if (const llvm::opt::Arg *arg = 540 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 541 llvm::StringRef argValue = arg->getValue(); 542 if (argValue == "utf-8") { 543 opts.encoding = Fortran::parser::Encoding::UTF_8; 544 } else if (argValue == "latin-1") { 545 opts.encoding = Fortran::parser::Encoding::LATIN_1; 546 } else { 547 diags.Report(clang::diag::err_drv_invalid_value) 548 << arg->getAsString(args) << argValue; 549 } 550 } 551 552 setUpFrontendBasedOnAction(opts); 553 opts.dashX = dashX; 554 555 return diags.getNumErrors() == numErrorsBefore; 556 } 557 558 // Generate the path to look for intrinsic modules 559 static std::string getIntrinsicDir() { 560 // TODO: Find a system independent API 561 llvm::SmallString<128> driverPath; 562 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 563 llvm::sys::path::remove_filename(driverPath); 564 driverPath.append("/../include/flang/"); 565 return std::string(driverPath); 566 } 567 568 // Generate the path to look for OpenMP headers 569 static std::string getOpenMPHeadersDir() { 570 llvm::SmallString<128> includePath; 571 includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 572 llvm::sys::path::remove_filename(includePath); 573 includePath.append("/../include/flang/OpenMP/"); 574 return std::string(includePath); 575 } 576 577 /// Parses all preprocessor input arguments and populates the preprocessor 578 /// options accordingly. 579 /// 580 /// \param [in] opts The preprocessor options instance 581 /// \param [out] args The list of input arguments 582 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts, 583 llvm::opt::ArgList &args) { 584 // Add macros from the command line. 585 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D, 586 clang::driver::options::OPT_U)) { 587 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 588 opts.addMacroDef(currentArg->getValue()); 589 } else { 590 opts.addMacroUndef(currentArg->getValue()); 591 } 592 } 593 594 // Add the ordered list of -I's. 595 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 596 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 597 598 // Prepend the ordered list of -intrinsic-modules-path 599 // to the default location to search. 600 for (const auto *currentArg : 601 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 602 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 603 604 // -cpp/-nocpp 605 if (const auto *currentArg = args.getLastArg( 606 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 607 opts.macrosFlag = 608 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 609 ? PPMacrosFlag::Include 610 : PPMacrosFlag::Exclude; 611 612 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 613 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 614 } 615 616 /// Parses all semantic related arguments and populates the variables 617 /// options accordingly. Returns false if new errors are generated. 618 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 619 clang::DiagnosticsEngine &diags) { 620 unsigned numErrorsBefore = diags.getNumErrors(); 621 622 // -J/module-dir option 623 auto moduleDirList = 624 args.getAllArgValues(clang::driver::options::OPT_module_dir); 625 // User can only specify -J/-module-dir once 626 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 627 if (moduleDirList.size() > 1) { 628 const unsigned diagID = 629 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 630 "Only one '-module-dir/-J' option allowed"); 631 diags.Report(diagID); 632 } 633 if (moduleDirList.size() == 1) 634 res.setModuleDir(moduleDirList[0]); 635 636 // -fdebug-module-writer option 637 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 638 res.setDebugModuleDir(true); 639 } 640 641 // -module-suffix 642 if (const auto *moduleSuffix = 643 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 644 res.setModuleFileSuffix(moduleSuffix->getValue()); 645 } 646 647 // -f{no-}analyzed-objects-for-unparse 648 res.setUseAnalyzedObjectsForUnparse(args.hasFlag( 649 clang::driver::options::OPT_fanalyzed_objects_for_unparse, 650 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 651 652 return diags.getNumErrors() == numErrorsBefore; 653 } 654 655 /// Parses all diagnostics related arguments and populates the variables 656 /// options accordingly. Returns false if new errors are generated. 657 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 658 clang::DiagnosticsEngine &diags) { 659 unsigned numErrorsBefore = diags.getNumErrors(); 660 661 // -Werror option 662 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 663 // this has to change when other -W<opt>'s are supported. 664 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 665 const auto &wArgs = 666 args.getAllArgValues(clang::driver::options::OPT_W_Joined); 667 for (const auto &wArg : wArgs) { 668 if (wArg == "error") { 669 res.setWarnAsErr(true); 670 } else { 671 const unsigned diagID = 672 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 673 "Only `-Werror` is supported currently."); 674 diags.Report(diagID); 675 } 676 } 677 } 678 679 // Default to off for `flang-new -fc1`. 680 res.getFrontendOpts().showColors = 681 parseShowColorsArgs(args, /*defaultDiagColor=*/false); 682 683 return diags.getNumErrors() == numErrorsBefore; 684 } 685 686 /// Parses all Dialect related arguments and populates the variables 687 /// options accordingly. Returns false if new errors are generated. 688 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 689 clang::DiagnosticsEngine &diags) { 690 unsigned numErrorsBefore = diags.getNumErrors(); 691 692 // -fdefault* family 693 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 694 res.getDefaultKinds().set_defaultRealKind(8); 695 res.getDefaultKinds().set_doublePrecisionKind(16); 696 } 697 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 698 res.getDefaultKinds().set_defaultIntegerKind(8); 699 res.getDefaultKinds().set_subscriptIntegerKind(8); 700 res.getDefaultKinds().set_sizeIntegerKind(8); 701 } 702 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 703 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 704 // -fdefault-double-8 has to be used with -fdefault-real-8 705 // to be compatible with gfortran 706 const unsigned diagID = diags.getCustomDiagID( 707 clang::DiagnosticsEngine::Error, 708 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 709 diags.Report(diagID); 710 } 711 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 712 res.getDefaultKinds().set_doublePrecisionKind(8); 713 } 714 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 715 res.getDefaultKinds().set_sizeIntegerKind(8); 716 717 // -fopenmp and -fopenacc 718 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 719 res.getFrontendOpts().features.Enable( 720 Fortran::common::LanguageFeature::OpenACC); 721 } 722 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 723 // By default OpenMP is set to 1.1 version 724 res.getLangOpts().OpenMPVersion = 11; 725 res.getFrontendOpts().features.Enable( 726 Fortran::common::LanguageFeature::OpenMP); 727 if (int Version = getLastArgIntValue( 728 args, clang::driver::options::OPT_fopenmp_version_EQ, 729 res.getLangOpts().OpenMPVersion, diags)) { 730 res.getLangOpts().OpenMPVersion = Version; 731 } 732 if (args.hasArg(clang::driver::options::OPT_fopenmp_is_device)) { 733 res.getLangOpts().OpenMPIsDevice = 1; 734 735 // Get OpenMP host file path if any and report if a non existent file is 736 // found 737 if (auto *arg = args.getLastArg( 738 clang::driver::options::OPT_fopenmp_host_ir_file_path)) { 739 res.getLangOpts().OMPHostIRFile = arg->getValue(); 740 if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile)) 741 diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found) 742 << res.getLangOpts().OMPHostIRFile; 743 } 744 745 if (args.hasFlag( 746 clang::driver::options::OPT_fopenmp_assume_teams_oversubscription, 747 clang::driver::options:: 748 OPT_fno_openmp_assume_teams_oversubscription, 749 /*Default=*/false)) 750 res.getLangOpts().OpenMPTeamSubscription = true; 751 752 if (args.hasArg( 753 clang::driver::options::OPT_fopenmp_assume_no_thread_state)) 754 res.getLangOpts().OpenMPNoThreadState = 1; 755 756 if (args.hasArg( 757 clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism)) 758 res.getLangOpts().OpenMPNoNestedParallelism = 1; 759 760 if (args.hasFlag(clang::driver::options:: 761 OPT_fopenmp_assume_threads_oversubscription, 762 clang::driver::options:: 763 OPT_fno_openmp_assume_threads_oversubscription, 764 /*Default=*/false)) 765 res.getLangOpts().OpenMPThreadSubscription = true; 766 767 if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) || 768 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) { 769 res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue( 770 args, clang::driver::options::OPT_fopenmp_target_debug_EQ, 771 res.getLangOpts().OpenMPTargetDebug, diags); 772 773 if (!res.getLangOpts().OpenMPTargetDebug && 774 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug)) 775 res.getLangOpts().OpenMPTargetDebug = 1; 776 } 777 } 778 } 779 780 // -pedantic 781 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 782 res.setEnableConformanceChecks(); 783 res.setEnableUsageChecks(); 784 } 785 // -std=f2018 786 // TODO: Set proper options when more fortran standards 787 // are supported. 788 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 789 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 790 // We only allow f2018 as the given standard 791 if (standard.equals("f2018")) { 792 res.setEnableConformanceChecks(); 793 } else { 794 const unsigned diagID = 795 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 796 "Only -std=f2018 is allowed currently."); 797 diags.Report(diagID); 798 } 799 } 800 return diags.getNumErrors() == numErrorsBefore; 801 } 802 803 /// Parses all floating point related arguments and populates the 804 /// CompilerInvocation accordingly. 805 /// Returns false if new errors are generated. 806 /// 807 /// \param [out] invoc Stores the processed arguments 808 /// \param [in] args The compiler invocation arguments to parse 809 /// \param [out] diags DiagnosticsEngine to report erros with 810 static bool parseFloatingPointArgs(CompilerInvocation &invoc, 811 llvm::opt::ArgList &args, 812 clang::DiagnosticsEngine &diags) { 813 LangOptions &opts = invoc.getLangOpts(); 814 815 if (const llvm::opt::Arg *a = 816 args.getLastArg(clang::driver::options::OPT_ffp_contract)) { 817 const llvm::StringRef val = a->getValue(); 818 enum LangOptions::FPModeKind fpContractMode; 819 820 if (val == "off") 821 fpContractMode = LangOptions::FPM_Off; 822 else if (val == "fast") 823 fpContractMode = LangOptions::FPM_Fast; 824 else { 825 diags.Report(clang::diag::err_drv_unsupported_option_argument) 826 << a->getSpelling() << val; 827 return false; 828 } 829 830 opts.setFPContractMode(fpContractMode); 831 } 832 833 if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) { 834 opts.NoHonorInfs = true; 835 } 836 837 if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) { 838 opts.NoHonorNaNs = true; 839 } 840 841 if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) { 842 opts.ApproxFunc = true; 843 } 844 845 if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) { 846 opts.NoSignedZeros = true; 847 } 848 849 if (args.getLastArg(clang::driver::options::OPT_mreassociate)) { 850 opts.AssociativeMath = true; 851 } 852 853 if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) { 854 opts.ReciprocalMath = true; 855 } 856 857 if (args.getLastArg(clang::driver::options::OPT_ffast_math)) { 858 opts.NoHonorInfs = true; 859 opts.NoHonorNaNs = true; 860 opts.AssociativeMath = true; 861 opts.ReciprocalMath = true; 862 opts.ApproxFunc = true; 863 opts.NoSignedZeros = true; 864 opts.setFPContractMode(LangOptions::FPM_Fast); 865 } 866 867 return true; 868 } 869 870 bool CompilerInvocation::createFromArgs( 871 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 872 clang::DiagnosticsEngine &diags) { 873 874 bool success = true; 875 876 // Set the default triple for this CompilerInvocation. This might be 877 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 878 // below). 879 // NOTE: Like in Clang, it would be nice to use option marshalling 880 // for this so that the entire logic for setting-up the triple is in one 881 // place. 882 res.getTargetOpts().triple = 883 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 884 885 // Parse the arguments 886 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 887 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 888 unsigned missingArgIndex, missingArgCount; 889 llvm::opt::InputArgList args = opts.ParseArgs( 890 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 891 892 // Check for missing argument error. 893 if (missingArgCount) { 894 diags.Report(clang::diag::err_drv_missing_argument) 895 << args.getArgString(missingArgIndex) << missingArgCount; 896 success = false; 897 } 898 899 // Issue errors on unknown arguments 900 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 901 auto argString = a->getAsString(args); 902 std::string nearest; 903 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 904 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 905 else 906 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 907 << argString << nearest; 908 success = false; 909 } 910 911 // -flang-experimental-hlfir 912 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) { 913 res.loweringOpts.setLowerToHighLevelFIR(true); 914 } 915 916 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 917 parseTargetArgs(res.getTargetOpts(), args); 918 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 919 parseCodeGenArgs(res.getCodeGenOpts(), args, diags); 920 success &= parseDebugArgs(res.getCodeGenOpts(), args, diags); 921 success &= parseSemaArgs(res, args, diags); 922 success &= parseDialectArgs(res, args, diags); 923 success &= parseDiagArgs(res, args, diags); 924 res.frontendOpts.llvmArgs = 925 args.getAllArgValues(clang::driver::options::OPT_mllvm); 926 927 res.frontendOpts.mlirArgs = 928 args.getAllArgValues(clang::driver::options::OPT_mmlir); 929 930 success &= parseFloatingPointArgs(res, args, diags); 931 932 return success; 933 } 934 935 void CompilerInvocation::collectMacroDefinitions() { 936 auto &ppOpts = this->getPreprocessorOpts(); 937 938 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 939 llvm::StringRef macro = ppOpts.macros[i].first; 940 bool isUndef = ppOpts.macros[i].second; 941 942 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 943 llvm::StringRef macroName = macroPair.first; 944 llvm::StringRef macroBody = macroPair.second; 945 946 // For an #undef'd macro, we only care about the name. 947 if (isUndef) { 948 parserOpts.predefinitions.emplace_back(macroName.str(), 949 std::optional<std::string>{}); 950 continue; 951 } 952 953 // For a #define'd macro, figure out the actual definition. 954 if (macroName.size() == macro.size()) 955 macroBody = "1"; 956 else { 957 // Note: GCC drops anything following an end-of-line character. 958 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 959 macroBody = macroBody.substr(0, end); 960 } 961 parserOpts.predefinitions.emplace_back( 962 macroName, std::optional<std::string>(macroBody.str())); 963 } 964 } 965 966 void CompilerInvocation::setDefaultFortranOpts() { 967 auto &fortranOptions = getFortranOpts(); 968 969 std::vector<std::string> searchDirectories{"."s}; 970 fortranOptions.searchDirectories = searchDirectories; 971 972 // Add the location of omp_lib.h to the search directories. Currently this is 973 // identical to the modules' directory. 974 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 975 976 fortranOptions.isFixedForm = false; 977 } 978 979 // TODO: When expanding this method, consider creating a dedicated API for 980 // this. Also at some point we will need to differentiate between different 981 // targets and add dedicated predefines for each. 982 void CompilerInvocation::setDefaultPredefinitions() { 983 auto &fortranOptions = getFortranOpts(); 984 const auto &frontendOptions = getFrontendOpts(); 985 986 // Populate the macro list with version numbers and other predefinitions. 987 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 988 fortranOptions.predefinitions.emplace_back("__flang_major__", 989 FLANG_VERSION_MAJOR_STRING); 990 fortranOptions.predefinitions.emplace_back("__flang_minor__", 991 FLANG_VERSION_MINOR_STRING); 992 fortranOptions.predefinitions.emplace_back("__flang_patchlevel__", 993 FLANG_VERSION_PATCHLEVEL_STRING); 994 995 // Add predefinitions based on extensions enabled 996 if (frontendOptions.features.IsEnabled( 997 Fortran::common::LanguageFeature::OpenACC)) { 998 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 999 } 1000 if (frontendOptions.features.IsEnabled( 1001 Fortran::common::LanguageFeature::OpenMP)) { 1002 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 1003 } 1004 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1005 if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) { 1006 fortranOptions.predefinitions.emplace_back("__x86_64__", "1"); 1007 fortranOptions.predefinitions.emplace_back("__x86_64", "1"); 1008 } 1009 } 1010 1011 void CompilerInvocation::setFortranOpts() { 1012 auto &fortranOptions = getFortranOpts(); 1013 const auto &frontendOptions = getFrontendOpts(); 1014 const auto &preprocessorOptions = getPreprocessorOpts(); 1015 auto &moduleDirJ = getModuleDir(); 1016 1017 if (frontendOptions.fortranForm != FortranForm::Unknown) { 1018 fortranOptions.isFixedForm = 1019 frontendOptions.fortranForm == FortranForm::FixedForm; 1020 } 1021 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 1022 1023 fortranOptions.features = frontendOptions.features; 1024 fortranOptions.encoding = frontendOptions.encoding; 1025 1026 // Adding search directories specified by -I 1027 fortranOptions.searchDirectories.insert( 1028 fortranOptions.searchDirectories.end(), 1029 preprocessorOptions.searchDirectoriesFromDashI.begin(), 1030 preprocessorOptions.searchDirectoriesFromDashI.end()); 1031 1032 // Add the ordered list of -intrinsic-modules-path 1033 fortranOptions.searchDirectories.insert( 1034 fortranOptions.searchDirectories.end(), 1035 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 1036 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 1037 1038 // Add the default intrinsic module directory 1039 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 1040 1041 // Add the directory supplied through -J/-module-dir to the list of search 1042 // directories 1043 if (moduleDirJ != ".") 1044 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 1045 1046 if (frontendOptions.instrumentedParse) 1047 fortranOptions.instrumentedParse = true; 1048 1049 if (frontendOptions.showColors) 1050 fortranOptions.showColors = true; 1051 1052 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 1053 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 1054 1055 if (getEnableConformanceChecks()) 1056 fortranOptions.features.WarnOnAllNonstandard(); 1057 1058 if (getEnableUsageChecks()) 1059 fortranOptions.features.WarnOnAllUsage(); 1060 } 1061 1062 void CompilerInvocation::setSemanticsOpts( 1063 Fortran::parser::AllCookedSources &allCookedSources) { 1064 auto &fortranOptions = getFortranOpts(); 1065 1066 semanticsContext = std::make_unique<semantics::SemanticsContext>( 1067 getDefaultKinds(), fortranOptions.features, allCookedSources); 1068 1069 semanticsContext->set_moduleDirectory(getModuleDir()) 1070 .set_searchDirectories(fortranOptions.searchDirectories) 1071 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 1072 .set_warningsAreErrors(getWarnAsErr()) 1073 .set_moduleFileSuffix(getModuleFileSuffix()); 1074 1075 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1076 // FIXME: Handle real(3) ? 1077 if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) { 1078 semanticsContext->targetCharacteristics().DisableType( 1079 Fortran::common::TypeCategory::Real, /*kind=*/10); 1080 } 1081 } 1082 1083 /// Set \p loweringOptions controlling lowering behavior based 1084 /// on the \p optimizationLevel. 1085 void CompilerInvocation::setLoweringOptions() { 1086 const CodeGenOptions &codegenOpts = getCodeGenOpts(); 1087 1088 // Lower TRANSPOSE as a runtime call under -O0. 1089 loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0); 1090 1091 const LangOptions &langOptions = getLangOpts(); 1092 Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions(); 1093 // TODO: when LangOptions are finalized, we can represent 1094 // the math related options using Fortran::commmon::MathOptionsBase, 1095 // so that we can just copy it into LoweringOptions. 1096 mathOpts 1097 .setFPContractEnabled(langOptions.getFPContractMode() == 1098 LangOptions::FPM_Fast) 1099 .setNoHonorInfs(langOptions.NoHonorInfs) 1100 .setNoHonorNaNs(langOptions.NoHonorNaNs) 1101 .setApproxFunc(langOptions.ApproxFunc) 1102 .setNoSignedZeros(langOptions.NoSignedZeros) 1103 .setAssociativeMath(langOptions.AssociativeMath) 1104 .setReciprocalMath(langOptions.ReciprocalMath); 1105 } 1106