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/Common/OpenMP-features.h" 16 #include "flang/Common/Version.h" 17 #include "flang/Frontend/CodeGenOptions.h" 18 #include "flang/Frontend/PreprocessorOptions.h" 19 #include "flang/Frontend/TargetOptions.h" 20 #include "flang/Semantics/semantics.h" 21 #include "flang/Version.inc" 22 #include "clang/Basic/AllDiagnostics.h" 23 #include "clang/Basic/DiagnosticDriver.h" 24 #include "clang/Basic/DiagnosticOptions.h" 25 #include "clang/Driver/DriverDiagnostic.h" 26 #include "clang/Driver/OptionUtils.h" 27 #include "clang/Driver/Options.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/Frontend/Debug/Options.h" 31 #include "llvm/Option/Arg.h" 32 #include "llvm/Option/ArgList.h" 33 #include "llvm/Option/OptTable.h" 34 #include "llvm/Support/FileSystem.h" 35 #include "llvm/Support/FileUtilities.h" 36 #include "llvm/Support/Path.h" 37 #include "llvm/Support/Process.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/TargetParser/Host.h" 40 #include "llvm/TargetParser/Triple.h" 41 #include <cstdlib> 42 #include <memory> 43 #include <optional> 44 45 using namespace Fortran::frontend; 46 47 //===----------------------------------------------------------------------===// 48 // Initialization. 49 //===----------------------------------------------------------------------===// 50 CompilerInvocationBase::CompilerInvocationBase() 51 : diagnosticOpts(new clang::DiagnosticOptions()), 52 preprocessorOpts(new PreprocessorOptions()) {} 53 54 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 55 : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())), 56 preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {} 57 58 CompilerInvocationBase::~CompilerInvocationBase() = default; 59 60 //===----------------------------------------------------------------------===// 61 // Deserialization (from args) 62 //===----------------------------------------------------------------------===// 63 static bool parseShowColorsArgs(const llvm::opt::ArgList &args, 64 bool defaultColor = true) { 65 // Color diagnostics default to auto ("on" if terminal supports) in the 66 // compiler driver `flang-new` but default to off in the frontend driver 67 // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color. 68 // Support both clang's -f[no-]color-diagnostics and gcc's 69 // -f[no-]diagnostics-colors[=never|always|auto]. 70 enum { 71 Colors_On, 72 Colors_Off, 73 Colors_Auto 74 } showColors = defaultColor ? Colors_Auto : Colors_Off; 75 76 for (auto *a : args) { 77 const llvm::opt::Option &opt = a->getOption(); 78 if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) { 79 showColors = Colors_On; 80 } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) { 81 showColors = Colors_Off; 82 } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 83 llvm::StringRef value(a->getValue()); 84 if (value == "always") 85 showColors = Colors_On; 86 else if (value == "never") 87 showColors = Colors_Off; 88 else if (value == "auto") 89 showColors = Colors_Auto; 90 } 91 } 92 93 return showColors == Colors_On || 94 (showColors == Colors_Auto && 95 llvm::sys::Process::StandardErrHasColors()); 96 } 97 98 /// Extracts the optimisation level from \a args. 99 static unsigned getOptimizationLevel(llvm::opt::ArgList &args, 100 clang::DiagnosticsEngine &diags) { 101 unsigned defaultOpt = 0; 102 103 if (llvm::opt::Arg *a = 104 args.getLastArg(clang::driver::options::OPT_O_Group)) { 105 if (a->getOption().matches(clang::driver::options::OPT_O0)) 106 return 0; 107 108 assert(a->getOption().matches(clang::driver::options::OPT_O)); 109 110 return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt, 111 diags); 112 } 113 114 return defaultOpt; 115 } 116 117 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts, 118 llvm::opt::ArgList &args) { 119 opts.ShowColors = parseShowColorsArgs(args); 120 121 return true; 122 } 123 124 static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts, 125 llvm::opt::ArgList &args, 126 clang::DiagnosticsEngine &diags) { 127 using DebugInfoKind = llvm::codegenoptions::DebugInfoKind; 128 if (llvm::opt::Arg *arg = 129 args.getLastArg(clang::driver::options::OPT_debug_info_kind_EQ)) { 130 std::optional<DebugInfoKind> val = 131 llvm::StringSwitch<std::optional<DebugInfoKind>>(arg->getValue()) 132 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly) 133 .Case("line-directives-only", 134 llvm::codegenoptions::DebugDirectivesOnly) 135 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor) 136 .Case("limited", llvm::codegenoptions::LimitedDebugInfo) 137 .Case("standalone", llvm::codegenoptions::FullDebugInfo) 138 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo) 139 .Default(std::nullopt); 140 if (!val.has_value()) { 141 diags.Report(clang::diag::err_drv_invalid_value) 142 << arg->getAsString(args) << arg->getValue(); 143 return false; 144 } 145 opts.setDebugInfo(val.value()); 146 if (val != llvm::codegenoptions::DebugLineTablesOnly && 147 val != llvm::codegenoptions::NoDebugInfo) { 148 const auto debugWarning = diags.getCustomDiagID( 149 clang::DiagnosticsEngine::Warning, "Unsupported debug option: %0"); 150 diags.Report(debugWarning) << arg->getValue(); 151 } 152 } 153 return true; 154 } 155 156 static bool parseVectorLibArg(Fortran::frontend::CodeGenOptions &opts, 157 llvm::opt::ArgList &args, 158 clang::DiagnosticsEngine &diags) { 159 llvm::opt::Arg *arg = args.getLastArg(clang::driver::options::OPT_fveclib); 160 if (!arg) 161 return true; 162 163 using VectorLibrary = llvm::driver::VectorLibrary; 164 std::optional<VectorLibrary> val = 165 llvm::StringSwitch<std::optional<VectorLibrary>>(arg->getValue()) 166 .Case("Accelerate", VectorLibrary::Accelerate) 167 .Case("LIBMVEC", VectorLibrary::LIBMVEC) 168 .Case("MASSV", VectorLibrary::MASSV) 169 .Case("SVML", VectorLibrary::SVML) 170 .Case("SLEEF", VectorLibrary::SLEEF) 171 .Case("Darwin_libsystem_m", VectorLibrary::Darwin_libsystem_m) 172 .Case("ArmPL", VectorLibrary::ArmPL) 173 .Case("NoLibrary", VectorLibrary::NoLibrary) 174 .Default(std::nullopt); 175 if (!val.has_value()) { 176 diags.Report(clang::diag::err_drv_invalid_value) 177 << arg->getAsString(args) << arg->getValue(); 178 return false; 179 } 180 opts.setVecLib(val.value()); 181 return true; 182 } 183 184 // Generate an OptRemark object containing info on if the -Rgroup 185 // specified is enabled or not. 186 static CodeGenOptions::OptRemark 187 parseOptimizationRemark(clang::DiagnosticsEngine &diags, 188 llvm::opt::ArgList &args, llvm::opt::OptSpecifier optEq, 189 llvm::StringRef remarkOptName) { 190 assert((remarkOptName == "pass" || remarkOptName == "pass-missed" || 191 remarkOptName == "pass-analysis") && 192 "Unsupported remark option name provided."); 193 CodeGenOptions::OptRemark result; 194 195 for (llvm::opt::Arg *a : args) { 196 if (a->getOption().matches(clang::driver::options::OPT_R_Joined)) { 197 llvm::StringRef value = a->getValue(); 198 199 if (value == remarkOptName) { 200 result.Kind = CodeGenOptions::RemarkKind::RK_Enabled; 201 // Enable everything 202 result.Pattern = ".*"; 203 result.Regex = std::make_shared<llvm::Regex>(result.Pattern); 204 205 } else if (value.split('-') == 206 std::make_pair(llvm::StringRef("no"), remarkOptName)) { 207 result.Kind = CodeGenOptions::RemarkKind::RK_Disabled; 208 // Disable everything 209 result.Pattern = ""; 210 result.Regex = nullptr; 211 } 212 } else if (a->getOption().matches(optEq)) { 213 result.Kind = CodeGenOptions::RemarkKind::RK_WithPattern; 214 result.Pattern = a->getValue(); 215 result.Regex = std::make_shared<llvm::Regex>(result.Pattern); 216 std::string regexError; 217 218 if (!result.Regex->isValid(regexError)) { 219 diags.Report(clang::diag::err_drv_optimization_remark_pattern) 220 << regexError << a->getAsString(args); 221 return CodeGenOptions::OptRemark(); 222 } 223 } 224 } 225 return result; 226 } 227 228 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts, 229 llvm::opt::ArgList &args, 230 clang::DiagnosticsEngine &diags) { 231 opts.OptimizationLevel = getOptimizationLevel(args, diags); 232 233 if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager, 234 clang::driver::options::OPT_fno_debug_pass_manager, false)) 235 opts.DebugPassManager = 1; 236 237 if (args.hasFlag(clang::driver::options::OPT_fstack_arrays, 238 clang::driver::options::OPT_fno_stack_arrays, false)) 239 opts.StackArrays = 1; 240 241 if (args.hasFlag(clang::driver::options::OPT_floop_versioning, 242 clang::driver::options::OPT_fno_loop_versioning, false)) 243 opts.LoopVersioning = 1; 244 245 opts.AliasAnalysis = 246 args.hasFlag(clang::driver::options::OPT_falias_analysis, 247 clang::driver::options::OPT_fno_alias_analysis, 248 /*default=*/false); 249 250 for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ)) 251 opts.LLVMPassPlugins.push_back(a->getValue()); 252 253 // -fembed-offload-object option 254 for (auto *a : 255 args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ)) 256 opts.OffloadObjects.push_back(a->getValue()); 257 258 // -flto=full/thin option. 259 if (const llvm::opt::Arg *a = 260 args.getLastArg(clang::driver::options::OPT_flto_EQ)) { 261 llvm::StringRef s = a->getValue(); 262 assert((s == "full" || s == "thin") && "Unknown LTO mode."); 263 if (s == "full") 264 opts.PrepareForFullLTO = true; 265 else 266 opts.PrepareForThinLTO = true; 267 } 268 269 // -f[no-]save-optimization-record[=<format>] 270 if (const llvm::opt::Arg *a = 271 args.getLastArg(clang::driver::options::OPT_opt_record_file)) 272 opts.OptRecordFile = a->getValue(); 273 274 // Optimization file format. Defaults to yaml 275 if (const llvm::opt::Arg *a = 276 args.getLastArg(clang::driver::options::OPT_opt_record_format)) 277 opts.OptRecordFormat = a->getValue(); 278 279 // Specifies, using a regex, which successful optimization passes(middle and 280 // backend), to include in the final optimization record file generated. If 281 // not provided -fsave-optimization-record will include all passes. 282 if (const llvm::opt::Arg *a = 283 args.getLastArg(clang::driver::options::OPT_opt_record_passes)) 284 opts.OptRecordPasses = a->getValue(); 285 286 // Create OptRemark that allows printing of all successful optimization 287 // passes applied. 288 opts.OptimizationRemark = 289 parseOptimizationRemark(diags, args, clang::driver::options::OPT_Rpass_EQ, 290 /*remarkOptName=*/"pass"); 291 292 // Create OptRemark that allows all missed optimization passes to be printed. 293 opts.OptimizationRemarkMissed = parseOptimizationRemark( 294 diags, args, clang::driver::options::OPT_Rpass_missed_EQ, 295 /*remarkOptName=*/"pass-missed"); 296 297 // Create OptRemark that allows all optimization decisions made by LLVM 298 // to be printed. 299 opts.OptimizationRemarkAnalysis = parseOptimizationRemark( 300 diags, args, clang::driver::options::OPT_Rpass_analysis_EQ, 301 /*remarkOptName=*/"pass-analysis"); 302 303 if (opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) { 304 // If the user requested a flag that requires source locations available in 305 // the backend, make sure that the backend tracks source location 306 // information. 307 bool needLocTracking = !opts.OptRecordFile.empty() || 308 !opts.OptRecordPasses.empty() || 309 !opts.OptRecordFormat.empty() || 310 opts.OptimizationRemark.hasValidPattern() || 311 opts.OptimizationRemarkMissed.hasValidPattern() || 312 opts.OptimizationRemarkAnalysis.hasValidPattern(); 313 314 if (needLocTracking) 315 opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly); 316 } 317 318 if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ)) 319 opts.SaveTempsDir = a->getValue(); 320 321 // -mrelocation-model option. 322 if (const llvm::opt::Arg *a = 323 args.getLastArg(clang::driver::options::OPT_mrelocation_model)) { 324 llvm::StringRef modelName = a->getValue(); 325 auto relocModel = 326 llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(modelName) 327 .Case("static", llvm::Reloc::Static) 328 .Case("pic", llvm::Reloc::PIC_) 329 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC) 330 .Case("ropi", llvm::Reloc::ROPI) 331 .Case("rwpi", llvm::Reloc::RWPI) 332 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 333 .Default(std::nullopt); 334 if (relocModel.has_value()) 335 opts.setRelocationModel(*relocModel); 336 else 337 diags.Report(clang::diag::err_drv_invalid_value) 338 << a->getAsString(args) << modelName; 339 } 340 341 // -pic-level and -pic-is-pie option. 342 if (int picLevel = getLastArgIntValue( 343 args, clang::driver::options::OPT_pic_level, 0, diags)) { 344 if (picLevel > 2) 345 diags.Report(clang::diag::err_drv_invalid_value) 346 << args.getLastArg(clang::driver::options::OPT_pic_level) 347 ->getAsString(args) 348 << picLevel; 349 350 opts.PICLevel = picLevel; 351 if (args.hasArg(clang::driver::options::OPT_pic_is_pie)) 352 opts.IsPIE = 1; 353 } 354 355 // This option is compatible with -f[no-]underscoring in gfortran. 356 if (args.hasFlag(clang::driver::options::OPT_fno_underscoring, 357 clang::driver::options::OPT_funderscoring, false)) { 358 opts.Underscoring = 0; 359 } 360 } 361 362 /// Parses all target input arguments and populates the target 363 /// options accordingly. 364 /// 365 /// \param [in] opts The target options instance to update 366 /// \param [in] args The list of input arguments (from the compiler invocation) 367 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { 368 if (const llvm::opt::Arg *a = 369 args.getLastArg(clang::driver::options::OPT_triple)) 370 opts.triple = a->getValue(); 371 372 if (const llvm::opt::Arg *a = 373 args.getLastArg(clang::driver::options::OPT_target_cpu)) 374 opts.cpu = a->getValue(); 375 376 for (const llvm::opt::Arg *currentArg : 377 args.filtered(clang::driver::options::OPT_target_feature)) 378 opts.featuresAsWritten.emplace_back(currentArg->getValue()); 379 } 380 381 // Tweak the frontend configuration based on the frontend action 382 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 383 if (opts.programAction == DebugDumpParsingLog) 384 opts.instrumentedParse = true; 385 386 if (opts.programAction == DebugDumpProvenance || 387 opts.programAction == Fortran::frontend::GetDefinition) 388 opts.needProvenanceRangeToCharBlockMappings = true; 389 } 390 391 /// Parse the argument specified for the -fconvert=<value> option 392 static std::optional<const char *> parseConvertArg(const char *s) { 393 return llvm::StringSwitch<std::optional<const char *>>(s) 394 .Case("unknown", "UNKNOWN") 395 .Case("native", "NATIVE") 396 .Case("little-endian", "LITTLE_ENDIAN") 397 .Case("big-endian", "BIG_ENDIAN") 398 .Case("swap", "SWAP") 399 .Default(std::nullopt); 400 } 401 402 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 403 clang::DiagnosticsEngine &diags) { 404 unsigned numErrorsBefore = diags.getNumErrors(); 405 406 // By default the frontend driver creates a ParseSyntaxOnly action. 407 opts.programAction = ParseSyntaxOnly; 408 409 // Treat multiple action options as an invocation error. Note that `clang 410 // -cc1` does accept multiple action options, but will only consider the 411 // rightmost one. 412 if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) { 413 const unsigned diagID = diags.getCustomDiagID( 414 clang::DiagnosticsEngine::Error, "Only one action option is allowed"); 415 diags.Report(diagID); 416 return false; 417 } 418 419 // Identify the action (i.e. opts.ProgramAction) 420 if (const llvm::opt::Arg *a = 421 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 422 switch (a->getOption().getID()) { 423 default: { 424 llvm_unreachable("Invalid option in group!"); 425 } 426 case clang::driver::options::OPT_test_io: 427 opts.programAction = InputOutputTest; 428 break; 429 case clang::driver::options::OPT_E: 430 opts.programAction = PrintPreprocessedInput; 431 break; 432 case clang::driver::options::OPT_fsyntax_only: 433 opts.programAction = ParseSyntaxOnly; 434 break; 435 case clang::driver::options::OPT_emit_fir: 436 opts.programAction = EmitFIR; 437 break; 438 case clang::driver::options::OPT_emit_hlfir: 439 opts.programAction = EmitHLFIR; 440 break; 441 case clang::driver::options::OPT_emit_llvm: 442 opts.programAction = EmitLLVM; 443 break; 444 case clang::driver::options::OPT_emit_llvm_bc: 445 opts.programAction = EmitLLVMBitcode; 446 break; 447 case clang::driver::options::OPT_emit_obj: 448 opts.programAction = EmitObj; 449 break; 450 case clang::driver::options::OPT_S: 451 opts.programAction = EmitAssembly; 452 break; 453 case clang::driver::options::OPT_fdebug_unparse: 454 opts.programAction = DebugUnparse; 455 break; 456 case clang::driver::options::OPT_fdebug_unparse_no_sema: 457 opts.programAction = DebugUnparseNoSema; 458 break; 459 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 460 opts.programAction = DebugUnparseWithSymbols; 461 break; 462 case clang::driver::options::OPT_fdebug_dump_symbols: 463 opts.programAction = DebugDumpSymbols; 464 break; 465 case clang::driver::options::OPT_fdebug_dump_parse_tree: 466 opts.programAction = DebugDumpParseTree; 467 break; 468 case clang::driver::options::OPT_fdebug_dump_pft: 469 opts.programAction = DebugDumpPFT; 470 break; 471 case clang::driver::options::OPT_fdebug_dump_all: 472 opts.programAction = DebugDumpAll; 473 break; 474 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 475 opts.programAction = DebugDumpParseTreeNoSema; 476 break; 477 case clang::driver::options::OPT_fdebug_dump_provenance: 478 opts.programAction = DebugDumpProvenance; 479 break; 480 case clang::driver::options::OPT_fdebug_dump_parsing_log: 481 opts.programAction = DebugDumpParsingLog; 482 break; 483 case clang::driver::options::OPT_fdebug_measure_parse_tree: 484 opts.programAction = DebugMeasureParseTree; 485 break; 486 case clang::driver::options::OPT_fdebug_pre_fir_tree: 487 opts.programAction = DebugPreFIRTree; 488 break; 489 case clang::driver::options::OPT_fget_symbols_sources: 490 opts.programAction = GetSymbolsSources; 491 break; 492 case clang::driver::options::OPT_fget_definition: 493 opts.programAction = GetDefinition; 494 break; 495 case clang::driver::options::OPT_init_only: 496 opts.programAction = InitOnly; 497 break; 498 499 // TODO: 500 // case clang::driver::options::OPT_emit_llvm: 501 // case clang::driver::options::OPT_emit_llvm_only: 502 // case clang::driver::options::OPT_emit_codegen_only: 503 // case clang::driver::options::OPT_emit_module: 504 // (...) 505 } 506 507 // Parse the values provided with `-fget-definition` (there should be 3 508 // integers) 509 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 510 clang::driver::options::OPT_fget_definition) { 511 unsigned optVals[3] = {0, 0, 0}; 512 513 for (unsigned i = 0; i < 3; i++) { 514 llvm::StringRef val = a->getValue(i); 515 516 if (val.getAsInteger(10, optVals[i])) { 517 // A non-integer was encountered - that's an error. 518 diags.Report(clang::diag::err_drv_invalid_value) 519 << a->getOption().getName() << val; 520 break; 521 } 522 } 523 opts.getDefVals.line = optVals[0]; 524 opts.getDefVals.startColumn = optVals[1]; 525 opts.getDefVals.endColumn = optVals[2]; 526 } 527 } 528 529 // Parsing -load <dsopath> option and storing shared object path 530 if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) { 531 opts.plugins.push_back(a->getValue()); 532 } 533 534 // Parsing -plugin <name> option and storing plugin name and setting action 535 if (const llvm::opt::Arg *a = 536 args.getLastArg(clang::driver::options::OPT_plugin)) { 537 opts.programAction = PluginAction; 538 opts.actionName = a->getValue(); 539 } 540 541 opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); 542 opts.showHelp = args.hasArg(clang::driver::options::OPT_help); 543 opts.showVersion = args.hasArg(clang::driver::options::OPT_version); 544 545 // Get the input kind (from the value passed via `-x`) 546 InputKind dashX(Language::Unknown); 547 if (const llvm::opt::Arg *a = 548 args.getLastArg(clang::driver::options::OPT_x)) { 549 llvm::StringRef xValue = a->getValue(); 550 // Principal languages. 551 dashX = llvm::StringSwitch<InputKind>(xValue) 552 // Flang does not differentiate between pre-processed and not 553 // pre-processed inputs. 554 .Case("f95", Language::Fortran) 555 .Case("f95-cpp-input", Language::Fortran) 556 .Default(Language::Unknown); 557 558 // Flang's intermediate representations. 559 if (dashX.isUnknown()) 560 dashX = llvm::StringSwitch<InputKind>(xValue) 561 .Case("ir", Language::LLVM_IR) 562 .Case("fir", Language::MLIR) 563 .Case("mlir", Language::MLIR) 564 .Default(Language::Unknown); 565 566 if (dashX.isUnknown()) 567 diags.Report(clang::diag::err_drv_invalid_value) 568 << a->getAsString(args) << a->getValue(); 569 } 570 571 // Collect the input files and save them in our instance of FrontendOptions. 572 std::vector<std::string> inputs = 573 args.getAllArgValues(clang::driver::options::OPT_INPUT); 574 opts.inputs.clear(); 575 if (inputs.empty()) 576 // '-' is the default input if none is given. 577 inputs.push_back("-"); 578 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 579 InputKind ik = dashX; 580 if (ik.isUnknown()) { 581 ik = FrontendOptions::getInputKindForExtension( 582 llvm::StringRef(inputs[i]).rsplit('.').second); 583 if (ik.isUnknown()) 584 ik = Language::Unknown; 585 if (i == 0) 586 dashX = ik; 587 } 588 589 opts.inputs.emplace_back(std::move(inputs[i]), ik); 590 } 591 592 // Set fortranForm based on options -ffree-form and -ffixed-form. 593 if (const auto *arg = 594 args.getLastArg(clang::driver::options::OPT_ffixed_form, 595 clang::driver::options::OPT_ffree_form)) { 596 opts.fortranForm = 597 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 598 ? FortranForm::FixedForm 599 : FortranForm::FreeForm; 600 } 601 602 // Set fixedFormColumns based on -ffixed-line-length=<value> 603 if (const auto *arg = 604 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 605 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 606 std::int64_t columns = -1; 607 if (argValue == "none") { 608 columns = 0; 609 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 610 columns = -1; 611 } 612 if (columns < 0) { 613 diags.Report(clang::diag::err_drv_negative_columns) 614 << arg->getOption().getName() << arg->getValue(); 615 } else if (columns == 0) { 616 opts.fixedFormColumns = 1000000; 617 } else if (columns < 7) { 618 diags.Report(clang::diag::err_drv_small_columns) 619 << arg->getOption().getName() << arg->getValue() << "7"; 620 } else { 621 opts.fixedFormColumns = columns; 622 } 623 } 624 625 // Set conversion based on -fconvert=<value> 626 if (const auto *arg = 627 args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) { 628 const char *argValue = arg->getValue(); 629 if (auto convert = parseConvertArg(argValue)) 630 opts.envDefaults.push_back({"FORT_CONVERT", *convert}); 631 else 632 diags.Report(clang::diag::err_drv_invalid_value) 633 << arg->getAsString(args) << argValue; 634 } 635 636 // -f{no-}implicit-none 637 opts.features.Enable( 638 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 639 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 640 clang::driver::options::OPT_fno_implicit_none, false)); 641 642 // -f{no-}backslash 643 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 644 args.hasFlag(clang::driver::options::OPT_fbackslash, 645 clang::driver::options::OPT_fno_backslash, 646 false)); 647 648 // -f{no-}logical-abbreviations 649 opts.features.Enable( 650 Fortran::common::LanguageFeature::LogicalAbbreviations, 651 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 652 clang::driver::options::OPT_fno_logical_abbreviations, 653 false)); 654 655 // -f{no-}xor-operator 656 opts.features.Enable( 657 Fortran::common::LanguageFeature::XOROperator, 658 args.hasFlag(clang::driver::options::OPT_fxor_operator, 659 clang::driver::options::OPT_fno_xor_operator, false)); 660 661 // -fno-automatic 662 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 663 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 664 } 665 666 if (args.hasArg( 667 clang::driver::options::OPT_falternative_parameter_statement)) { 668 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 669 } 670 if (const llvm::opt::Arg *arg = 671 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 672 llvm::StringRef argValue = arg->getValue(); 673 if (argValue == "utf-8") { 674 opts.encoding = Fortran::parser::Encoding::UTF_8; 675 } else if (argValue == "latin-1") { 676 opts.encoding = Fortran::parser::Encoding::LATIN_1; 677 } else { 678 diags.Report(clang::diag::err_drv_invalid_value) 679 << arg->getAsString(args) << argValue; 680 } 681 } 682 683 setUpFrontendBasedOnAction(opts); 684 opts.dashX = dashX; 685 686 return diags.getNumErrors() == numErrorsBefore; 687 } 688 689 // Generate the path to look for intrinsic modules 690 static std::string getIntrinsicDir() { 691 // TODO: Find a system independent API 692 llvm::SmallString<128> driverPath; 693 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 694 llvm::sys::path::remove_filename(driverPath); 695 driverPath.append("/../include/flang/"); 696 return std::string(driverPath); 697 } 698 699 // Generate the path to look for OpenMP headers 700 static std::string getOpenMPHeadersDir() { 701 llvm::SmallString<128> includePath; 702 includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 703 llvm::sys::path::remove_filename(includePath); 704 includePath.append("/../include/flang/OpenMP/"); 705 return std::string(includePath); 706 } 707 708 /// Parses all preprocessor input arguments and populates the preprocessor 709 /// options accordingly. 710 /// 711 /// \param [in] opts The preprocessor options instance 712 /// \param [out] args The list of input arguments 713 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts, 714 llvm::opt::ArgList &args) { 715 // Add macros from the command line. 716 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D, 717 clang::driver::options::OPT_U)) { 718 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 719 opts.addMacroDef(currentArg->getValue()); 720 } else { 721 opts.addMacroUndef(currentArg->getValue()); 722 } 723 } 724 725 // Add the ordered list of -I's. 726 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 727 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 728 729 // Prepend the ordered list of -intrinsic-modules-path 730 // to the default location to search. 731 for (const auto *currentArg : 732 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 733 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 734 735 // -cpp/-nocpp 736 if (const auto *currentArg = args.getLastArg( 737 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 738 opts.macrosFlag = 739 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 740 ? PPMacrosFlag::Include 741 : PPMacrosFlag::Exclude; 742 743 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 744 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 745 } 746 747 /// Parses all semantic related arguments and populates the variables 748 /// options accordingly. Returns false if new errors are generated. 749 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 750 clang::DiagnosticsEngine &diags) { 751 unsigned numErrorsBefore = diags.getNumErrors(); 752 753 // -J/module-dir option 754 auto moduleDirList = 755 args.getAllArgValues(clang::driver::options::OPT_module_dir); 756 // User can only specify -J/-module-dir once 757 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 758 if (moduleDirList.size() > 1) { 759 const unsigned diagID = 760 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 761 "Only one '-module-dir/-J' option allowed"); 762 diags.Report(diagID); 763 } 764 if (moduleDirList.size() == 1) 765 res.setModuleDir(moduleDirList[0]); 766 767 // -fdebug-module-writer option 768 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 769 res.setDebugModuleDir(true); 770 } 771 772 // -module-suffix 773 if (const auto *moduleSuffix = 774 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 775 res.setModuleFileSuffix(moduleSuffix->getValue()); 776 } 777 778 // -f{no-}analyzed-objects-for-unparse 779 res.setUseAnalyzedObjectsForUnparse(args.hasFlag( 780 clang::driver::options::OPT_fanalyzed_objects_for_unparse, 781 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 782 783 return diags.getNumErrors() == numErrorsBefore; 784 } 785 786 /// Parses all diagnostics related arguments and populates the variables 787 /// options accordingly. Returns false if new errors are generated. 788 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 789 clang::DiagnosticsEngine &diags) { 790 unsigned numErrorsBefore = diags.getNumErrors(); 791 792 // -Werror option 793 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 794 // this has to change when other -W<opt>'s are supported. 795 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 796 const auto &wArgs = 797 args.getAllArgValues(clang::driver::options::OPT_W_Joined); 798 for (const auto &wArg : wArgs) { 799 if (wArg == "error") { 800 res.setWarnAsErr(true); 801 } else { 802 const unsigned diagID = 803 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 804 "Only `-Werror` is supported currently."); 805 diags.Report(diagID); 806 } 807 } 808 } 809 810 // Default to off for `flang-new -fc1`. 811 res.getFrontendOpts().showColors = 812 parseShowColorsArgs(args, /*defaultDiagColor=*/false); 813 814 // Honor color diagnostics. 815 res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors; 816 817 return diags.getNumErrors() == numErrorsBefore; 818 } 819 820 /// Parses all Dialect related arguments and populates the variables 821 /// options accordingly. Returns false if new errors are generated. 822 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 823 clang::DiagnosticsEngine &diags) { 824 unsigned numErrorsBefore = diags.getNumErrors(); 825 826 // -fdefault* family 827 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 828 res.getDefaultKinds().set_defaultRealKind(8); 829 res.getDefaultKinds().set_doublePrecisionKind(16); 830 } 831 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 832 res.getDefaultKinds().set_defaultIntegerKind(8); 833 res.getDefaultKinds().set_subscriptIntegerKind(8); 834 res.getDefaultKinds().set_sizeIntegerKind(8); 835 res.getDefaultKinds().set_defaultLogicalKind(8); 836 } 837 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 838 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 839 // -fdefault-double-8 has to be used with -fdefault-real-8 840 // to be compatible with gfortran 841 const unsigned diagID = diags.getCustomDiagID( 842 clang::DiagnosticsEngine::Error, 843 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 844 diags.Report(diagID); 845 } 846 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 847 res.getDefaultKinds().set_doublePrecisionKind(8); 848 } 849 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 850 res.getDefaultKinds().set_sizeIntegerKind(8); 851 852 // -fopenmp and -fopenacc 853 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 854 res.getFrontendOpts().features.Enable( 855 Fortran::common::LanguageFeature::OpenACC); 856 } 857 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 858 // By default OpenMP is set to 1.1 version 859 res.getLangOpts().OpenMPVersion = 11; 860 res.getFrontendOpts().features.Enable( 861 Fortran::common::LanguageFeature::OpenMP); 862 if (int Version = getLastArgIntValue( 863 args, clang::driver::options::OPT_fopenmp_version_EQ, 864 res.getLangOpts().OpenMPVersion, diags)) { 865 res.getLangOpts().OpenMPVersion = Version; 866 } 867 if (args.hasArg(clang::driver::options::OPT_fopenmp_is_target_device)) { 868 res.getLangOpts().OpenMPIsTargetDevice = 1; 869 870 // Get OpenMP host file path if any and report if a non existent file is 871 // found 872 if (auto *arg = args.getLastArg( 873 clang::driver::options::OPT_fopenmp_host_ir_file_path)) { 874 res.getLangOpts().OMPHostIRFile = arg->getValue(); 875 if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile)) 876 diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found) 877 << res.getLangOpts().OMPHostIRFile; 878 } 879 880 if (args.hasFlag( 881 clang::driver::options::OPT_fopenmp_assume_teams_oversubscription, 882 clang::driver::options:: 883 OPT_fno_openmp_assume_teams_oversubscription, 884 /*Default=*/false)) 885 res.getLangOpts().OpenMPTeamSubscription = true; 886 887 if (args.hasArg( 888 clang::driver::options::OPT_fopenmp_assume_no_thread_state)) 889 res.getLangOpts().OpenMPNoThreadState = 1; 890 891 if (args.hasArg( 892 clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism)) 893 res.getLangOpts().OpenMPNoNestedParallelism = 1; 894 895 if (args.hasFlag(clang::driver::options:: 896 OPT_fopenmp_assume_threads_oversubscription, 897 clang::driver::options:: 898 OPT_fno_openmp_assume_threads_oversubscription, 899 /*Default=*/false)) 900 res.getLangOpts().OpenMPThreadSubscription = true; 901 902 if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) || 903 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) { 904 res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue( 905 args, clang::driver::options::OPT_fopenmp_target_debug_EQ, 906 res.getLangOpts().OpenMPTargetDebug, diags); 907 908 if (!res.getLangOpts().OpenMPTargetDebug && 909 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug)) 910 res.getLangOpts().OpenMPTargetDebug = 1; 911 } 912 } 913 914 switch (llvm::Triple(res.getTargetOpts().triple).getArch()) { 915 case llvm::Triple::nvptx: 916 case llvm::Triple::nvptx64: 917 case llvm::Triple::amdgcn: 918 if (!res.getLangOpts().OpenMPIsTargetDevice) { 919 const unsigned diagID = diags.getCustomDiagID( 920 clang::DiagnosticsEngine::Error, 921 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 922 diags.Report(diagID); 923 } 924 res.getLangOpts().OpenMPIsGPU = 1; 925 break; 926 default: 927 res.getLangOpts().OpenMPIsGPU = 0; 928 break; 929 } 930 } 931 932 // -pedantic 933 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 934 res.setEnableConformanceChecks(); 935 res.setEnableUsageChecks(); 936 } 937 // -std=f2018 938 // TODO: Set proper options when more fortran standards 939 // are supported. 940 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 941 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 942 // We only allow f2018 as the given standard 943 if (standard.equals("f2018")) { 944 res.setEnableConformanceChecks(); 945 } else { 946 const unsigned diagID = 947 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 948 "Only -std=f2018 is allowed currently."); 949 diags.Report(diagID); 950 } 951 } 952 return diags.getNumErrors() == numErrorsBefore; 953 } 954 955 /// Parses all floating point related arguments and populates the 956 /// CompilerInvocation accordingly. 957 /// Returns false if new errors are generated. 958 /// 959 /// \param [out] invoc Stores the processed arguments 960 /// \param [in] args The compiler invocation arguments to parse 961 /// \param [out] diags DiagnosticsEngine to report erros with 962 static bool parseFloatingPointArgs(CompilerInvocation &invoc, 963 llvm::opt::ArgList &args, 964 clang::DiagnosticsEngine &diags) { 965 LangOptions &opts = invoc.getLangOpts(); 966 967 if (const llvm::opt::Arg *a = 968 args.getLastArg(clang::driver::options::OPT_ffp_contract)) { 969 const llvm::StringRef val = a->getValue(); 970 enum LangOptions::FPModeKind fpContractMode; 971 972 if (val == "off") 973 fpContractMode = LangOptions::FPM_Off; 974 else if (val == "fast") 975 fpContractMode = LangOptions::FPM_Fast; 976 else { 977 diags.Report(clang::diag::err_drv_unsupported_option_argument) 978 << a->getSpelling() << val; 979 return false; 980 } 981 982 opts.setFPContractMode(fpContractMode); 983 } 984 985 if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) { 986 opts.NoHonorInfs = true; 987 } 988 989 if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) { 990 opts.NoHonorNaNs = true; 991 } 992 993 if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) { 994 opts.ApproxFunc = true; 995 } 996 997 if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) { 998 opts.NoSignedZeros = true; 999 } 1000 1001 if (args.getLastArg(clang::driver::options::OPT_mreassociate)) { 1002 opts.AssociativeMath = true; 1003 } 1004 1005 if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) { 1006 opts.ReciprocalMath = true; 1007 } 1008 1009 if (args.getLastArg(clang::driver::options::OPT_ffast_math)) { 1010 opts.NoHonorInfs = true; 1011 opts.NoHonorNaNs = true; 1012 opts.AssociativeMath = true; 1013 opts.ReciprocalMath = true; 1014 opts.ApproxFunc = true; 1015 opts.NoSignedZeros = true; 1016 opts.setFPContractMode(LangOptions::FPM_Fast); 1017 } 1018 1019 return true; 1020 } 1021 1022 /// Parses vscale range options and populates the CompilerInvocation 1023 /// accordingly. 1024 /// Returns false if new errors are generated. 1025 /// 1026 /// \param [out] invoc Stores the processed arguments 1027 /// \param [in] args The compiler invocation arguments to parse 1028 /// \param [out] diags DiagnosticsEngine to report erros with 1029 static bool parseVScaleArgs(CompilerInvocation &invoc, llvm::opt::ArgList &args, 1030 clang::DiagnosticsEngine &diags) { 1031 LangOptions &opts = invoc.getLangOpts(); 1032 if (const auto arg = 1033 args.getLastArg(clang::driver::options::OPT_mvscale_min_EQ)) { 1034 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 1035 unsigned VScaleMin; 1036 if (argValue.getAsInteger(/*Radix=*/10, VScaleMin)) { 1037 diags.Report(clang::diag::err_drv_unsupported_option_argument) 1038 << arg->getSpelling() << argValue; 1039 return false; 1040 } 1041 opts.VScaleMin = VScaleMin; 1042 } 1043 if (const auto arg = 1044 args.getLastArg(clang::driver::options::OPT_mvscale_max_EQ)) { 1045 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 1046 unsigned VScaleMax; 1047 if (argValue.getAsInteger(/*Radix=w*/ 10, VScaleMax)) { 1048 diags.Report(clang::diag::err_drv_unsupported_option_argument) 1049 << arg->getSpelling() << argValue; 1050 return false; 1051 } 1052 opts.VScaleMax = VScaleMax; 1053 } 1054 return true; 1055 } 1056 1057 static bool parseLinkerOptionsArgs(CompilerInvocation &invoc, 1058 llvm::opt::ArgList &args, 1059 clang::DiagnosticsEngine &diags) { 1060 llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple); 1061 1062 // TODO: support --dependent-lib on other platforms when MLIR supports 1063 // !llvm.dependent.lib 1064 if (args.hasArg(clang::driver::options::OPT_dependent_lib) && 1065 !triple.isOSWindows()) { 1066 const unsigned diagID = 1067 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 1068 "--dependent-lib is only supported on Windows"); 1069 diags.Report(diagID); 1070 return false; 1071 } 1072 1073 invoc.getCodeGenOpts().DependentLibs = 1074 args.getAllArgValues(clang::driver::options::OPT_dependent_lib); 1075 return true; 1076 } 1077 1078 bool CompilerInvocation::createFromArgs( 1079 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 1080 clang::DiagnosticsEngine &diags, const char *argv0) { 1081 1082 bool success = true; 1083 1084 // Set the default triple for this CompilerInvocation. This might be 1085 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 1086 // below). 1087 // NOTE: Like in Clang, it would be nice to use option marshalling 1088 // for this so that the entire logic for setting-up the triple is in one 1089 // place. 1090 res.getTargetOpts().triple = 1091 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 1092 1093 // Parse the arguments 1094 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 1095 llvm::opt::Visibility visibilityMask(clang::driver::options::FC1Option); 1096 unsigned missingArgIndex, missingArgCount; 1097 llvm::opt::InputArgList args = opts.ParseArgs( 1098 commandLineArgs, missingArgIndex, missingArgCount, visibilityMask); 1099 1100 // Check for missing argument error. 1101 if (missingArgCount) { 1102 diags.Report(clang::diag::err_drv_missing_argument) 1103 << args.getArgString(missingArgIndex) << missingArgCount; 1104 success = false; 1105 } 1106 1107 // Issue errors on unknown arguments 1108 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 1109 auto argString = a->getAsString(args); 1110 std::string nearest; 1111 if (opts.findNearest(argString, nearest, visibilityMask) > 1) 1112 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 1113 else 1114 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 1115 << argString << nearest; 1116 success = false; 1117 } 1118 1119 // -flang-experimental-hlfir 1120 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) || 1121 args.hasArg(clang::driver::options::OPT_emit_hlfir)) { 1122 res.loweringOpts.setLowerToHighLevelFIR(true); 1123 } 1124 1125 // -flang-deprecated-no-hlfir 1126 if (args.hasArg(clang::driver::options::OPT_flang_deprecated_no_hlfir) && 1127 !args.hasArg(clang::driver::options::OPT_emit_hlfir)) { 1128 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) { 1129 const unsigned diagID = diags.getCustomDiagID( 1130 clang::DiagnosticsEngine::Error, 1131 "Options '-flang-experimental-hlfir' and " 1132 "'-flang-deprecated-no-hlfir' cannot be both specified"); 1133 diags.Report(diagID); 1134 } 1135 res.loweringOpts.setLowerToHighLevelFIR(false); 1136 } 1137 1138 if (args.hasArg(clang::driver::options::OPT_flang_experimental_polymorphism)) { 1139 res.loweringOpts.setPolymorphicTypeImpl(true); 1140 } 1141 1142 // -fno-ppc-native-vector-element-order 1143 if (args.hasArg(clang::driver::options::OPT_fno_ppc_native_vec_elem_order)) { 1144 res.loweringOpts.setNoPPCNativeVecElemOrder(true); 1145 } 1146 1147 // Preserve all the remark options requested, i.e. -Rpass, -Rpass-missed or 1148 // -Rpass-analysis. This will be used later when processing and outputting the 1149 // remarks generated by LLVM in ExecuteCompilerInvocation.cpp. 1150 for (auto *a : args.filtered(clang::driver::options::OPT_R_Group)) { 1151 if (a->getOption().matches(clang::driver::options::OPT_R_value_Group)) 1152 // This is -Rfoo=, where foo is the name of the diagnostic 1153 // group. Add only the remark option name to the diagnostics. e.g. for 1154 // -Rpass= we will add the string "pass". 1155 res.getDiagnosticOpts().Remarks.push_back( 1156 std::string(a->getOption().getName().drop_front(1).rtrim("=-"))); 1157 else 1158 // If no regex was provided, add the provided value, e.g. for -Rpass add 1159 // the string "pass". 1160 res.getDiagnosticOpts().Remarks.push_back(a->getValue()); 1161 } 1162 1163 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 1164 parseTargetArgs(res.getTargetOpts(), args); 1165 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 1166 parseCodeGenArgs(res.getCodeGenOpts(), args, diags); 1167 success &= parseDebugArgs(res.getCodeGenOpts(), args, diags); 1168 success &= parseVectorLibArg(res.getCodeGenOpts(), args, diags); 1169 success &= parseSemaArgs(res, args, diags); 1170 success &= parseDialectArgs(res, args, diags); 1171 success &= parseDiagArgs(res, args, diags); 1172 1173 // Collect LLVM (-mllvm) and MLIR (-mmlir) options. 1174 // NOTE: Try to avoid adding any options directly to `llvmArgs` or 1175 // `mlirArgs`. Instead, you can use 1176 // * `-mllvm <your-llvm-option>`, or 1177 // * `-mmlir <your-mlir-option>`. 1178 res.frontendOpts.llvmArgs = 1179 args.getAllArgValues(clang::driver::options::OPT_mllvm); 1180 res.frontendOpts.mlirArgs = 1181 args.getAllArgValues(clang::driver::options::OPT_mmlir); 1182 1183 success &= parseFloatingPointArgs(res, args, diags); 1184 1185 success &= parseVScaleArgs(res, args, diags); 1186 1187 success &= parseLinkerOptionsArgs(res, args, diags); 1188 1189 // Set the string to be used as the return value of the COMPILER_OPTIONS 1190 // intrinsic of iso_fortran_env. This is either passed in from the parent 1191 // compiler driver invocation with an environment variable, or failing that 1192 // set to the command line arguments of the frontend driver invocation. 1193 res.allCompilerInvocOpts = std::string(); 1194 llvm::raw_string_ostream os(res.allCompilerInvocOpts); 1195 char *compilerOptsEnv = std::getenv("FLANG_COMPILER_OPTIONS_STRING"); 1196 if (compilerOptsEnv != nullptr) { 1197 os << compilerOptsEnv; 1198 } else { 1199 os << argv0 << ' '; 1200 for (auto it = commandLineArgs.begin(), e = commandLineArgs.end(); it != e; 1201 ++it) { 1202 os << ' ' << *it; 1203 } 1204 } 1205 1206 return success; 1207 } 1208 1209 void CompilerInvocation::collectMacroDefinitions() { 1210 auto &ppOpts = this->getPreprocessorOpts(); 1211 1212 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 1213 llvm::StringRef macro = ppOpts.macros[i].first; 1214 bool isUndef = ppOpts.macros[i].second; 1215 1216 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 1217 llvm::StringRef macroName = macroPair.first; 1218 llvm::StringRef macroBody = macroPair.second; 1219 1220 // For an #undef'd macro, we only care about the name. 1221 if (isUndef) { 1222 parserOpts.predefinitions.emplace_back(macroName.str(), 1223 std::optional<std::string>{}); 1224 continue; 1225 } 1226 1227 // For a #define'd macro, figure out the actual definition. 1228 if (macroName.size() == macro.size()) 1229 macroBody = "1"; 1230 else { 1231 // Note: GCC drops anything following an end-of-line character. 1232 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 1233 macroBody = macroBody.substr(0, end); 1234 } 1235 parserOpts.predefinitions.emplace_back( 1236 macroName, std::optional<std::string>(macroBody.str())); 1237 } 1238 } 1239 1240 void CompilerInvocation::setDefaultFortranOpts() { 1241 auto &fortranOptions = getFortranOpts(); 1242 1243 std::vector<std::string> searchDirectories{"."s}; 1244 fortranOptions.searchDirectories = searchDirectories; 1245 1246 // Add the location of omp_lib.h to the search directories. Currently this is 1247 // identical to the modules' directory. 1248 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 1249 1250 fortranOptions.isFixedForm = false; 1251 } 1252 1253 // TODO: When expanding this method, consider creating a dedicated API for 1254 // this. Also at some point we will need to differentiate between different 1255 // targets and add dedicated predefines for each. 1256 void CompilerInvocation::setDefaultPredefinitions() { 1257 auto &fortranOptions = getFortranOpts(); 1258 const auto &frontendOptions = getFrontendOpts(); 1259 // Populate the macro list with version numbers and other predefinitions. 1260 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 1261 fortranOptions.predefinitions.emplace_back("__flang_major__", 1262 FLANG_VERSION_MAJOR_STRING); 1263 fortranOptions.predefinitions.emplace_back("__flang_minor__", 1264 FLANG_VERSION_MINOR_STRING); 1265 fortranOptions.predefinitions.emplace_back("__flang_patchlevel__", 1266 FLANG_VERSION_PATCHLEVEL_STRING); 1267 1268 // Add predefinitions based on extensions enabled 1269 if (frontendOptions.features.IsEnabled( 1270 Fortran::common::LanguageFeature::OpenACC)) { 1271 fortranOptions.predefinitions.emplace_back("_OPENACC", "202211"); 1272 } 1273 if (frontendOptions.features.IsEnabled( 1274 Fortran::common::LanguageFeature::OpenMP)) { 1275 Fortran::common::setOpenMPMacro(getLangOpts().OpenMPVersion, 1276 fortranOptions.predefinitions); 1277 } 1278 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1279 if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) { 1280 fortranOptions.predefinitions.emplace_back("__x86_64__", "1"); 1281 fortranOptions.predefinitions.emplace_back("__x86_64", "1"); 1282 } 1283 } 1284 1285 void CompilerInvocation::setFortranOpts() { 1286 auto &fortranOptions = getFortranOpts(); 1287 const auto &frontendOptions = getFrontendOpts(); 1288 const auto &preprocessorOptions = getPreprocessorOpts(); 1289 auto &moduleDirJ = getModuleDir(); 1290 1291 if (frontendOptions.fortranForm != FortranForm::Unknown) { 1292 fortranOptions.isFixedForm = 1293 frontendOptions.fortranForm == FortranForm::FixedForm; 1294 } 1295 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 1296 1297 fortranOptions.features = frontendOptions.features; 1298 fortranOptions.encoding = frontendOptions.encoding; 1299 1300 // Adding search directories specified by -I 1301 fortranOptions.searchDirectories.insert( 1302 fortranOptions.searchDirectories.end(), 1303 preprocessorOptions.searchDirectoriesFromDashI.begin(), 1304 preprocessorOptions.searchDirectoriesFromDashI.end()); 1305 1306 // Add the ordered list of -intrinsic-modules-path 1307 fortranOptions.searchDirectories.insert( 1308 fortranOptions.searchDirectories.end(), 1309 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 1310 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 1311 1312 // Add the default intrinsic module directory 1313 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 1314 1315 // Add the directory supplied through -J/-module-dir to the list of search 1316 // directories 1317 if (moduleDirJ != ".") 1318 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 1319 1320 if (frontendOptions.instrumentedParse) 1321 fortranOptions.instrumentedParse = true; 1322 1323 if (frontendOptions.showColors) 1324 fortranOptions.showColors = true; 1325 1326 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 1327 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 1328 1329 if (getEnableConformanceChecks()) 1330 fortranOptions.features.WarnOnAllNonstandard(); 1331 1332 if (getEnableUsageChecks()) 1333 fortranOptions.features.WarnOnAllUsage(); 1334 } 1335 1336 void CompilerInvocation::setSemanticsOpts( 1337 Fortran::parser::AllCookedSources &allCookedSources) { 1338 auto &fortranOptions = getFortranOpts(); 1339 1340 semanticsContext = std::make_unique<semantics::SemanticsContext>( 1341 getDefaultKinds(), fortranOptions.features, allCookedSources); 1342 1343 semanticsContext->set_moduleDirectory(getModuleDir()) 1344 .set_searchDirectories(fortranOptions.searchDirectories) 1345 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 1346 .set_warningsAreErrors(getWarnAsErr()) 1347 .set_moduleFileSuffix(getModuleFileSuffix()) 1348 .set_underscoring(getCodeGenOpts().Underscoring); 1349 1350 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1351 // FIXME: Handle real(3) ? 1352 if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) { 1353 semanticsContext->targetCharacteristics().DisableType( 1354 Fortran::common::TypeCategory::Real, /*kind=*/10); 1355 } 1356 1357 std::string version = Fortran::common::getFlangFullVersion(); 1358 semanticsContext->targetCharacteristics() 1359 .set_compilerOptionsString(allCompilerInvocOpts) 1360 .set_compilerVersionString(version); 1361 1362 if (targetTriple.isPPC()) 1363 semanticsContext->targetCharacteristics().set_isPPC(true); 1364 } 1365 1366 /// Set \p loweringOptions controlling lowering behavior based 1367 /// on the \p optimizationLevel. 1368 void CompilerInvocation::setLoweringOptions() { 1369 const CodeGenOptions &codegenOpts = getCodeGenOpts(); 1370 1371 // Lower TRANSPOSE as a runtime call under -O0. 1372 loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0); 1373 loweringOpts.setUnderscoring(codegenOpts.Underscoring); 1374 1375 const LangOptions &langOptions = getLangOpts(); 1376 Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions(); 1377 // TODO: when LangOptions are finalized, we can represent 1378 // the math related options using Fortran::commmon::MathOptionsBase, 1379 // so that we can just copy it into LoweringOptions. 1380 mathOpts 1381 .setFPContractEnabled(langOptions.getFPContractMode() == 1382 LangOptions::FPM_Fast) 1383 .setNoHonorInfs(langOptions.NoHonorInfs) 1384 .setNoHonorNaNs(langOptions.NoHonorNaNs) 1385 .setApproxFunc(langOptions.ApproxFunc) 1386 .setNoSignedZeros(langOptions.NoSignedZeros) 1387 .setAssociativeMath(langOptions.AssociativeMath) 1388 .setReciprocalMath(langOptions.ReciprocalMath); 1389 } 1390