brintos

brintos / llvm-project-archived public Read only

0
0
Text · 7.5 KiB · 0840255 Raw
203 lines · cpp
1//===-- driver.cpp - Flang Driver -----------------------------------------===//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-exception6//7//===----------------------------------------------------------------------===//8//9// This is the entry point to the flang driver; it is a thin wrapper10// for functionality in the Driver flang library.11//12//===----------------------------------------------------------------------===//13//14// Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/15//16//===----------------------------------------------------------------------===//17 18#include "clang/Driver/Driver.h"19#include "flang/Config/config.h"20#include "flang/Frontend/CompilerInvocation.h"21#include "flang/Frontend/TextDiagnosticPrinter.h"22#include "clang/Basic/Diagnostic.h"23#include "clang/Basic/DiagnosticIDs.h"24#include "clang/Basic/DiagnosticOptions.h"25#include "clang/Driver/Compilation.h"26#include "llvm/ADT/ArrayRef.h"27#include "llvm/ADT/IntrusiveRefCntPtr.h"28#include "llvm/Option/ArgList.h"29#include "llvm/Support/CommandLine.h"30#include "llvm/Support/InitLLVM.h"31#include "llvm/Support/VirtualFileSystem.h"32#include "llvm/Support/raw_ostream.h"33#include "llvm/TargetParser/Host.h"34#include <stdlib.h>35 36// main frontend method. Lives inside fc1_main.cpp37extern int fc1_main(llvm::ArrayRef<const char *> argv, const char *argv0);38 39std::string getExecutablePath(const char *argv0) {40  // This just needs to be some symbol in the binary41  void *p = (void *)(intptr_t)getExecutablePath;42  return llvm::sys::fs::getMainExecutable(argv0, p);43}44 45// This lets us create the DiagnosticsEngine with a properly-filled-out46// DiagnosticOptions instance47static std::unique_ptr<clang::DiagnosticOptions>48createAndPopulateDiagOpts(llvm::ArrayRef<const char *> argv) {49  auto diagOpts = std::make_unique<clang::DiagnosticOptions>();50 51  // Ignore missingArgCount and the return value of ParseDiagnosticArgs.52  // Any errors that would be diagnosed here will also be diagnosed later,53  // when the DiagnosticsEngine actually exists.54  unsigned missingArgIndex, missingArgCount;55  llvm::opt::InputArgList args = clang::getDriverOptTable().ParseArgs(56      argv.slice(1), missingArgIndex, missingArgCount,57      llvm::opt::Visibility(clang::options::FlangOption));58 59  (void)Fortran::frontend::parseDiagnosticArgs(*diagOpts, args);60 61  return diagOpts;62}63 64static int executeFC1Tool(llvm::SmallVectorImpl<const char *> &argV) {65  llvm::StringRef tool = argV[1];66  if (tool == "-fc1")67    return fc1_main(llvm::ArrayRef(argV).slice(2), argV[0]);68 69  // Reject unknown tools.70  // ATM it only supports fc1. Any fc1[*] is rejected.71  llvm::errs() << "error: unknown integrated tool '" << tool << "'. "72               << "Valid tools include '-fc1'.\n";73  return 1;74}75 76static void ExpandResponseFiles(llvm::StringSaver &saver,77                                llvm::SmallVectorImpl<const char *> &args) {78  // We're defaulting to the GNU syntax, since we don't have a CL mode.79  llvm::cl::TokenizerCallback tokenizer = &llvm::cl::TokenizeGNUCommandLine;80  llvm::cl::ExpansionContext ExpCtx(saver.getAllocator(), tokenizer);81  if (llvm::Error Err = ExpCtx.expandResponseFiles(args)) {82    llvm::errs() << toString(std::move(Err)) << '\n';83  }84}85 86int main(int argc, const char **argv) {87 88  // Initialize variables to call the driver89  llvm::InitLLVM x(argc, argv);90  llvm::SmallVector<const char *, 256> args(argv, argv + argc);91 92  clang::driver::ParsedClangName targetandMode =93      clang::driver::ToolChain::getTargetAndModeFromProgramName(argv[0]);94  std::string driverPath = getExecutablePath(args[0]);95 96  llvm::BumpPtrAllocator a;97  llvm::StringSaver saver(a);98  ExpandResponseFiles(saver, args);99 100  // Check if flang is in the frontend mode101  auto firstArg = std::find_if(args.begin() + 1, args.end(),102                               [](const char *a) { return a != nullptr; });103  if (firstArg != args.end()) {104    if (llvm::StringRef(args[1]).starts_with("-cc1")) {105      llvm::errs() << "error: unknown integrated tool '" << args[1] << "'. "106                   << "Valid tools include '-fc1'.\n";107      return 1;108    }109    // Call flang frontend110    if (llvm::StringRef(args[1]).starts_with("-fc1")) {111      return executeFC1Tool(args);112    }113  }114 115  llvm::StringSet<> savedStrings;116  // Handle FCC_OVERRIDE_OPTIONS, used for editing a command line behind the117  // scenes.118  if (const char *overrideStr = ::getenv("FCC_OVERRIDE_OPTIONS"))119    clang::driver::applyOverrideOptions(args, overrideStr, savedStrings,120                                        "FCC_OVERRIDE_OPTIONS", &llvm::errs());121 122  // Not in the frontend mode - continue in the compiler driver mode.123 124  // Create DiagnosticsEngine for the compiler driver125  std::unique_ptr<clang::DiagnosticOptions> diagOpts =126      createAndPopulateDiagOpts(args);127  Fortran::frontend::TextDiagnosticPrinter *diagClient =128      new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), *diagOpts);129 130  diagClient->setPrefix(131      std::string(llvm::sys::path::stem(getExecutablePath(args[0]))));132 133  clang::DiagnosticsEngine diags(clang::DiagnosticIDs::create(), *diagOpts,134                                 diagClient);135 136  // Prepare the driver137  clang::driver::Driver theDriver(driverPath,138                                  llvm::sys::getDefaultTargetTriple(), diags,139                                  "flang LLVM compiler");140  theDriver.setTargetAndMode(targetandMode);141  theDriver.setPreferredLinker(FLANG_DEFAULT_LINKER);142#ifdef FLANG_RUNTIME_F128_MATH_LIB143  theDriver.setFlangF128MathLibrary(FLANG_RUNTIME_F128_MATH_LIB);144#endif145  std::unique_ptr<clang::driver::Compilation> c(146      theDriver.BuildCompilation(args));147  llvm::SmallVector<std::pair<int, const clang::driver::Command *>, 4>148      failingCommands;149 150  // Set the environment variable, FLANG_COMPILER_OPTIONS_STRING, to contain all151  // the compiler options. This is intended for the frontend driver,152  // flang -fc1, to enable the implementation of the COMPILER_OPTIONS153  // intrinsic. To this end, the frontend driver requires the list of the154  // original compiler options, which is not available through other means.155  // TODO: This way of passing information between the compiler and frontend156  // drivers is discouraged. We should find a better way not involving env157  // variables.158  std::string compilerOptsGathered;159  llvm::raw_string_ostream os(compilerOptsGathered);160  for (int i = 0; i < argc; ++i) {161    os << argv[i];162    if (i < argc - 1) {163      os << ' ';164    }165  }166#ifdef _WIN32167  _putenv_s("FLANG_COMPILER_OPTIONS_STRING", compilerOptsGathered.c_str());168#else169  setenv("FLANG_COMPILER_OPTIONS_STRING", compilerOptsGathered.c_str(), 1);170#endif171 172  // Run the driver173  int res = 1;174  bool isCrash = false;175  res = theDriver.ExecuteCompilation(*c, failingCommands);176 177  for (const auto &p : failingCommands) {178    int commandRes = p.first;179    const clang::driver::Command *failingCommand = p.second;180    if (!res)181      res = commandRes;182 183    // If result status is < 0 (e.g. when sys::ExecuteAndWait returns -1),184    // then the driver command signalled an error. On Windows, abort will185    // return an exit code of 3. In these cases, generate additional diagnostic186    // information if possible.187    isCrash = commandRes < 0;188#ifdef _WIN32189    isCrash |= commandRes == 3;190#endif191    if (isCrash) {192      theDriver.generateCompilationDiagnostics(*c, *failingCommand);193      break;194    }195  }196 197  diags.getClient()->finish();198 199  // If we have multiple failing commands, we return the result of the first200  // failing command.201  return res;202}203