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