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