llvm-project/clang/lib/Driver/Compilation.cpp

213 lines
6.9 KiB
C++
Raw Normal View History

//===--- Compilation.cpp - Compilation Task Implementation ----------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "clang/Driver/Compilation.h"
#include "clang/Driver/Action.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang::driver;
using namespace clang;
using namespace llvm::opt;
Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain,
InputArgList *_Args, DerivedArgList *_TranslatedArgs)
: TheDriver(D), DefaultToolChain(_DefaultToolChain),
CudaHostToolChain(&DefaultToolChain), CudaDeviceToolChain(nullptr),
Args(_Args), TranslatedArgs(_TranslatedArgs), Redirects(nullptr),
ForDiagnostics(false) {}
Compilation::~Compilation() {
delete TranslatedArgs;
delete Args;
// Free any derived arg lists.
for (llvm::DenseMap<std::pair<const ToolChain*, const char*>,
DerivedArgList*>::iterator it = TCArgs.begin(),
ie = TCArgs.end(); it != ie; ++it)
if (it->second != TranslatedArgs)
delete it->second;
// Free redirections of stdout/stderr.
if (Redirects) {
delete Redirects[1];
delete Redirects[2];
delete [] Redirects;
}
}
const DerivedArgList &Compilation::getArgsForToolChain(const ToolChain *TC,
const char *BoundArch) {
if (!TC)
TC = &DefaultToolChain;
DerivedArgList *&Entry = TCArgs[std::make_pair(TC, BoundArch)];
if (!Entry) {
Entry = TC->TranslateArgs(*TranslatedArgs, BoundArch);
if (!Entry)
Entry = TranslatedArgs;
}
return *Entry;
}
bool Compilation::CleanupFile(const char *File, bool IssueErrors) const {
// FIXME: Why are we trying to remove files that we have not created? For
// example we should only try to remove a temporary assembly file if
// "clang -cc1" succeed in writing it. Was this a workaround for when
// clang was writing directly to a .s file and sometimes leaving it behind
// during a failure?
// FIXME: If this is necessary, we can still try to split
// llvm::sys::fs::remove into a removeFile and a removeDir and avoid the
// duplicated stat from is_regular_file.
// Don't try to remove files which we don't have write access to (but may be
// able to remove), or non-regular files. Underlying tools may have
// intentionally not overwritten them.
if (!llvm::sys::fs::can_write(File) || !llvm::sys::fs::is_regular_file(File))
return true;
if (std::error_code EC = llvm::sys::fs::remove(File)) {
// Failure is only failure if the file exists and is "regular". We checked
// for it being regular before, and llvm::sys::fs::remove ignores ENOENT,
// so we don't need to check again.
Teach Clang how to use response files when calling other tools Patch by Rafael Auler! This patch addresses PR15171 and teaches Clang how to call other tools with response files, when the command line exceeds system limits. This is a problem for Windows systems, whose maximum command-line length is 32kb. I introduce the concept of "response file support" for each Tool object. A given Tool may have full support for response files (e.g. MSVC's link.exe) or only support file names inside response files, but no flags (e.g. Apple's ld64, as commented in PR15171), or no support at all (the default case). Therefore, if you implement a toolchain in the clang driver and you want clang to be able to use response files in your tools, you must override a method (getReponseFileSupport()) to tell so. I designed it to support different kinds of tools and internationalisation needs: - VS response files ( UTF-16 ) - GNU tools ( uses system's current code page, windows' legacy intl. support, with escaped backslashes. On unix, fallback to UTF-8 ) - Clang itself ( UTF-16 on windows, UTF-8 on unix ) - ld64 response files ( only a limited file list, UTF-8 on unix ) With this design, I was able to test input file names with spaces and international characters for Windows. When the linker input is large enough, it creates a response file with the correct encoding. On a Mac, to test ld64, I temporarily changed Clang's behavior to always use response files regardless of the command size limit (avoiding using huge command line inputs). I tested clang with the LLVM test suite (compiling benchmarks) and it did fine. Test Plan: A LIT test that tests proper response files support. This is tricky, since, for Unix systems, we need a 2MB response file, otherwise Clang will simply use regular arguments instead of a response file. To do this, my LIT test generate the file on the fly by cloning many -DTEST parameters until we have a 2MB file. I found out that processing 2MB of arguments is pretty slow, it takes 1 minute using my notebook in a debug build, or 10s in a Release build. Therefore, I also added "REQUIRES: long_tests", so it will only run when the user wants to run long tests. In the full discussion in http://lists.cs.uiuc.edu/pipermail/llvm-commits/Week-of-Mon-20130408/171463.html, Rafael Espindola discusses a proper way to test llvm::sys::argumentsFitWithinSystemLimits(), and, there, Chandler suggests to use 10 times the current system limit (20MB resp file), so we guarantee that the system will always use response file, even if a new linux comes up that can handle a few more bytes of arguments. However, by testing with a 20MB resp file, the test takes long 8 minutes just to perform a silly check to see if the driver will use a response file. I found it to be unreasonable. Thus, I discarded this approach and uses a 2MB response file, which should be enough. Reviewers: asl, rafael, silvas Reviewed By: silvas Subscribers: silvas, rnk, thakis, cfe-commits Differential Revision: http://reviews.llvm.org/D4897 llvm-svn: 217792
2014-09-16 01:45:39 +08:00
if (IssueErrors)
getDriver().Diag(clang::diag::err_drv_unable_to_remove_file)
<< EC.message();
return false;
}
return true;
}
bool Compilation::CleanupFileList(const ArgStringList &Files,
bool IssueErrors) const {
bool Success = true;
for (ArgStringList::const_iterator
it = Files.begin(), ie = Files.end(); it != ie; ++it)
Success &= CleanupFile(*it, IssueErrors);
return Success;
}
2009-11-24 23:23:21 +08:00
bool Compilation::CleanupFileMap(const ArgStringMap &Files,
const JobAction *JA,
bool IssueErrors) const {
bool Success = true;
for (ArgStringMap::const_iterator
it = Files.begin(), ie = Files.end(); it != ie; ++it) {
// If specified, only delete the files associated with the JobAction.
// Otherwise, delete all files in the map.
if (JA && it->first != JA)
continue;
Success &= CleanupFile(it->second, IssueErrors);
}
return Success;
}
int Compilation::ExecuteCommand(const Command &C,
const Command *&FailingCommand) const {
if ((getDriver().CCPrintOptions ||
getArgs().hasArg(options::OPT_v)) && !getDriver().CCGenDiagnostics) {
raw_ostream *OS = &llvm::errs();
// Follow gcc implementation of CC_PRINT_OPTIONS; we could also cache the
// output stream.
if (getDriver().CCPrintOptions && getDriver().CCPrintOptionsFilename) {
std::error_code EC;
OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, EC,
llvm::sys::fs::F_Append |
llvm::sys::fs::F_Text);
if (EC) {
getDriver().Diag(clang::diag::err_drv_cc_print_options_failure)
<< EC.message();
FailingCommand = &C;
delete OS;
return 1;
}
}
if (getDriver().CCPrintOptions)
*OS << "[Logging clang options]";
C.Print(*OS, "\n", /*Quote=*/getDriver().CCPrintOptions);
if (OS != &llvm::errs())
delete OS;
}
std::string Error;
bool ExecutionFailed;
int Res = C.Execute(Redirects, &Error, &ExecutionFailed);
if (!Error.empty()) {
assert(Res && "Error string set with 0 result code!");
getDriver().Diag(clang::diag::err_drv_command_failure) << Error;
}
if (Res)
FailingCommand = &C;
return ExecutionFailed ? 1 : Res;
}
void Compilation::ExecuteJobs(
const JobList &Jobs,
SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) const {
for (const auto &Job : Jobs) {
const Command *FailingCommand = nullptr;
if (int Res = ExecuteCommand(Job, FailingCommand)) {
FailingCommands.push_back(std::make_pair(Res, FailingCommand));
// Bail as soon as one command fails, so we don't output duplicate error
// messages if we die on e.g. the same file.
return;
}
}
}
void Compilation::initCompilationForDiagnostics() {
ForDiagnostics = true;
// Free actions and jobs.
Actions.clear();
AllActions.clear();
Jobs.clear();
// Clear temporary/results file lists.
TempFiles.clear();
ResultFiles.clear();
FailureResultFiles.clear();
// Remove any user specified output. Claim any unclaimed arguments, so as
// to avoid emitting warnings about unused args.
OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD,
options::OPT_MMD };
for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) {
if (TranslatedArgs->hasArg(OutputOpts[i]))
TranslatedArgs->eraseArg(OutputOpts[i]);
}
TranslatedArgs->ClaimAllArgs();
// Redirect stdout/stderr to /dev/null.
Redirects = new const StringRef*[3]();
Redirects[0] = nullptr;
Redirects[1] = new StringRef();
Redirects[2] = new StringRef();
}
2012-04-16 12:16:43 +08:00
StringRef Compilation::getSysRoot() const {
2012-04-16 12:16:43 +08:00
return getDriver().SysRoot;
}