diff options
author | Zancanaro; Carlo <czan8762@plang3.cs.usyd.edu.au> | 2012-09-24 09:58:17 +1000 |
---|---|---|
committer | Zancanaro; Carlo <czan8762@plang3.cs.usyd.edu.au> | 2012-09-24 09:58:17 +1000 |
commit | 222e2a7620e6520ffaf4fc4e69d79c18da31542e (patch) | |
tree | 7bfbc05bfa3b41c8f9d2e56d53a0bc3e310df239 /clang/lib/Driver | |
parent | 3d206f03985b50beacae843d880bccdc91a9f424 (diff) |
Add the clang library to the repo (with some of my changes, too).
Diffstat (limited to 'clang/lib/Driver')
-rw-r--r-- | clang/lib/Driver/Action.cpp | 122 | ||||
-rw-r--r-- | clang/lib/Driver/Arg.cpp | 121 | ||||
-rw-r--r-- | clang/lib/Driver/ArgList.cpp | 333 | ||||
-rw-r--r-- | clang/lib/Driver/CC1AsOptions.cpp | 39 | ||||
-rw-r--r-- | clang/lib/Driver/CC1Options.cpp | 38 | ||||
-rw-r--r-- | clang/lib/Driver/CMakeLists.txt | 33 | ||||
-rw-r--r-- | clang/lib/Driver/Compilation.cpp | 236 | ||||
-rw-r--r-- | clang/lib/Driver/Driver.cpp | 1789 | ||||
-rw-r--r-- | clang/lib/Driver/DriverOptions.cpp | 37 | ||||
-rw-r--r-- | clang/lib/Driver/InputInfo.h | 88 | ||||
-rw-r--r-- | clang/lib/Driver/Job.cpp | 42 | ||||
-rw-r--r-- | clang/lib/Driver/Makefile | 13 | ||||
-rw-r--r-- | clang/lib/Driver/OptTable.cpp | 384 | ||||
-rw-r--r-- | clang/lib/Driver/Option.cpp | 280 | ||||
-rw-r--r-- | clang/lib/Driver/Phases.cpp | 27 | ||||
-rw-r--r-- | clang/lib/Driver/Tool.cpp | 21 | ||||
-rw-r--r-- | clang/lib/Driver/ToolChain.cpp | 288 | ||||
-rw-r--r-- | clang/lib/Driver/ToolChains.cpp | 2334 | ||||
-rw-r--r-- | clang/lib/Driver/ToolChains.h | 596 | ||||
-rw-r--r-- | clang/lib/Driver/Tools.cpp | 5589 | ||||
-rw-r--r-- | clang/lib/Driver/Tools.h | 605 | ||||
-rw-r--r-- | clang/lib/Driver/Types.cpp | 254 | ||||
-rw-r--r-- | clang/lib/Driver/WindowsToolChain.cpp | 368 |
23 files changed, 13637 insertions, 0 deletions
diff --git a/clang/lib/Driver/Action.cpp b/clang/lib/Driver/Action.cpp new file mode 100644 index 0000000..d7b4bc7 --- /dev/null +++ b/clang/lib/Driver/Action.cpp @@ -0,0 +1,122 @@ +//===--- Action.cpp - Abstract compilation steps --------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Action.h" +#include "llvm/Support/ErrorHandling.h" + +#include <cassert> +using namespace clang::driver; + +Action::~Action() { + if (OwnsInputs) { + for (iterator it = begin(), ie = end(); it != ie; ++it) + delete *it; + } +} + +const char *Action::getClassName(ActionClass AC) { + switch (AC) { + case InputClass: return "input"; + case BindArchClass: return "bind-arch"; + case PreprocessJobClass: return "preprocessor"; + case PrecompileJobClass: return "precompiler"; + case AnalyzeJobClass: return "analyzer"; + case MigrateJobClass: return "migrator"; + case CompileJobClass: return "compiler"; + case AssembleJobClass: return "assembler"; + case LinkJobClass: return "linker"; + case LipoJobClass: return "lipo"; + case DsymutilJobClass: return "dsymutil"; + case VerifyJobClass: return "verify"; + } + + llvm_unreachable("invalid class"); +} + +void InputAction::anchor() {} + +InputAction::InputAction(const Arg &_Input, types::ID _Type) + : Action(InputClass, _Type), Input(_Input) { +} + +void BindArchAction::anchor() {} + +BindArchAction::BindArchAction(Action *Input, const char *_ArchName) + : Action(BindArchClass, Input, Input->getType()), ArchName(_ArchName) { +} + +void JobAction::anchor() {} + +JobAction::JobAction(ActionClass Kind, Action *Input, types::ID Type) + : Action(Kind, Input, Type) { +} + +JobAction::JobAction(ActionClass Kind, const ActionList &Inputs, types::ID Type) + : Action(Kind, Inputs, Type) { +} + +void PreprocessJobAction::anchor() {} + +PreprocessJobAction::PreprocessJobAction(Action *Input, types::ID OutputType) + : JobAction(PreprocessJobClass, Input, OutputType) { +} + +void PrecompileJobAction::anchor() {} + +PrecompileJobAction::PrecompileJobAction(Action *Input, types::ID OutputType) + : JobAction(PrecompileJobClass, Input, OutputType) { +} + +void AnalyzeJobAction::anchor() {} + +AnalyzeJobAction::AnalyzeJobAction(Action *Input, types::ID OutputType) + : JobAction(AnalyzeJobClass, Input, OutputType) { +} + +void MigrateJobAction::anchor() {} + +MigrateJobAction::MigrateJobAction(Action *Input, types::ID OutputType) + : JobAction(MigrateJobClass, Input, OutputType) { +} + +void CompileJobAction::anchor() {} + +CompileJobAction::CompileJobAction(Action *Input, types::ID OutputType) + : JobAction(CompileJobClass, Input, OutputType) { +} + +void AssembleJobAction::anchor() {} + +AssembleJobAction::AssembleJobAction(Action *Input, types::ID OutputType) + : JobAction(AssembleJobClass, Input, OutputType) { +} + +void LinkJobAction::anchor() {} + +LinkJobAction::LinkJobAction(ActionList &Inputs, types::ID Type) + : JobAction(LinkJobClass, Inputs, Type) { +} + +void LipoJobAction::anchor() {} + +LipoJobAction::LipoJobAction(ActionList &Inputs, types::ID Type) + : JobAction(LipoJobClass, Inputs, Type) { +} + +void DsymutilJobAction::anchor() {} + +DsymutilJobAction::DsymutilJobAction(ActionList &Inputs, types::ID Type) + : JobAction(DsymutilJobClass, Inputs, Type) { +} + +void VerifyJobAction::anchor() {} + +VerifyJobAction::VerifyJobAction(ActionList &Inputs, types::ID Type) + : JobAction(VerifyJobClass, Inputs, Type) { +} diff --git a/clang/lib/Driver/Arg.cpp b/clang/lib/Driver/Arg.cpp new file mode 100644 index 0000000..c0a2a50 --- /dev/null +++ b/clang/lib/Driver/Arg.cpp @@ -0,0 +1,121 @@ +//===--- Arg.cpp - Argument Implementations -------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Option.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Support/raw_ostream.h" + +using namespace clang::driver; + +Arg::Arg(const Option *_Opt, unsigned _Index, const Arg *_BaseArg) + : Opt(_Opt), BaseArg(_BaseArg), Index(_Index), + Claimed(false), OwnsValues(false) { +} + +Arg::Arg(const Option *_Opt, unsigned _Index, + const char *Value0, const Arg *_BaseArg) + : Opt(_Opt), BaseArg(_BaseArg), Index(_Index), + Claimed(false), OwnsValues(false) { + Values.push_back(Value0); +} + +Arg::Arg(const Option *_Opt, unsigned _Index, + const char *Value0, const char *Value1, const Arg *_BaseArg) + : Opt(_Opt), BaseArg(_BaseArg), Index(_Index), + Claimed(false), OwnsValues(false) { + Values.push_back(Value0); + Values.push_back(Value1); +} + +Arg::~Arg() { + if (OwnsValues) { + for (unsigned i = 0, e = Values.size(); i != e; ++i) + delete[] Values[i]; + } +} + +void Arg::dump() const { + llvm::errs() << "<"; + + llvm::errs() << " Opt:"; + Opt->dump(); + + llvm::errs() << " Index:" << Index; + + llvm::errs() << " Values: ["; + for (unsigned i = 0, e = Values.size(); i != e; ++i) { + if (i) llvm::errs() << ", "; + llvm::errs() << "'" << Values[i] << "'"; + } + + llvm::errs() << "]>\n"; +} + +std::string Arg::getAsString(const ArgList &Args) const { + SmallString<256> Res; + llvm::raw_svector_ostream OS(Res); + + ArgStringList ASL; + render(Args, ASL); + for (ArgStringList::iterator + it = ASL.begin(), ie = ASL.end(); it != ie; ++it) { + if (it != ASL.begin()) + OS << ' '; + OS << *it; + } + + return OS.str(); +} + +void Arg::renderAsInput(const ArgList &Args, ArgStringList &Output) const { + if (!getOption().hasNoOptAsInput()) { + render(Args, Output); + return; + } + + for (unsigned i = 0, e = getNumValues(); i != e; ++i) + Output.push_back(getValue(Args, i)); +} + +void Arg::render(const ArgList &Args, ArgStringList &Output) const { + switch (getOption().getRenderStyle()) { + case Option::RenderValuesStyle: + for (unsigned i = 0, e = getNumValues(); i != e; ++i) + Output.push_back(getValue(Args, i)); + break; + + case Option::RenderCommaJoinedStyle: { + SmallString<256> Res; + llvm::raw_svector_ostream OS(Res); + OS << getOption().getName(); + for (unsigned i = 0, e = getNumValues(); i != e; ++i) { + if (i) OS << ','; + OS << getValue(Args, i); + } + Output.push_back(Args.MakeArgString(OS.str())); + break; + } + + case Option::RenderJoinedStyle: + Output.push_back(Args.GetOrMakeJoinedArgString( + getIndex(), getOption().getName(), getValue(Args, 0))); + for (unsigned i = 1, e = getNumValues(); i != e; ++i) + Output.push_back(getValue(Args, i)); + break; + + case Option::RenderSeparateStyle: + Output.push_back(getOption().getName().data()); + for (unsigned i = 0, e = getNumValues(); i != e; ++i) + Output.push_back(getValue(Args, i)); + break; + } +} diff --git a/clang/lib/Driver/ArgList.cpp b/clang/lib/Driver/ArgList.cpp new file mode 100644 index 0000000..55a0ddf --- /dev/null +++ b/clang/lib/Driver/ArgList.cpp @@ -0,0 +1,333 @@ +//===--- ArgList.cpp - Argument List Management ---------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Arg.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Driver/Option.h" + +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Support/raw_ostream.h" + +using namespace clang; +using namespace clang::driver; + +void arg_iterator::SkipToNextArg() { + for (; Current != Args.end(); ++Current) { + // Done if there are no filters. + if (!Id0.isValid()) + break; + + // Otherwise require a match. + const Option &O = (*Current)->getOption(); + if (O.matches(Id0) || + (Id1.isValid() && O.matches(Id1)) || + (Id2.isValid() && O.matches(Id2))) + break; + } +} + +// + +ArgList::ArgList() { +} + +ArgList::~ArgList() { +} + +void ArgList::append(Arg *A) { + Args.push_back(A); +} + +void ArgList::eraseArg(OptSpecifier Id) { + for (iterator it = begin(), ie = end(); it != ie; ) { + if ((*it)->getOption().matches(Id)) { + it = Args.erase(it); + ie = end(); + } else { + ++it; + } + } +} + +Arg *ArgList::getLastArgNoClaim(OptSpecifier Id) const { + // FIXME: Make search efficient? + for (const_reverse_iterator it = rbegin(), ie = rend(); it != ie; ++it) + if ((*it)->getOption().matches(Id)) + return *it; + return 0; +} + +Arg *ArgList::getLastArg(OptSpecifier Id) const { + Arg *Res = 0; + for (const_iterator it = begin(), ie = end(); it != ie; ++it) { + if ((*it)->getOption().matches(Id)) { + Res = *it; + Res->claim(); + } + } + + return Res; +} + +Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1) const { + Arg *Res = 0; + for (const_iterator it = begin(), ie = end(); it != ie; ++it) { + if ((*it)->getOption().matches(Id0) || + (*it)->getOption().matches(Id1)) { + Res = *it; + Res->claim(); + + } + } + + return Res; +} + +Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1, + OptSpecifier Id2) const { + Arg *Res = 0; + for (const_iterator it = begin(), ie = end(); it != ie; ++it) { + if ((*it)->getOption().matches(Id0) || + (*it)->getOption().matches(Id1) || + (*it)->getOption().matches(Id2)) { + Res = *it; + Res->claim(); + } + } + + return Res; +} + +Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1, + OptSpecifier Id2, OptSpecifier Id3) const { + Arg *Res = 0; + for (const_iterator it = begin(), ie = end(); it != ie; ++it) { + if ((*it)->getOption().matches(Id0) || + (*it)->getOption().matches(Id1) || + (*it)->getOption().matches(Id2) || + (*it)->getOption().matches(Id3)) { + Res = *it; + Res->claim(); + } + } + + return Res; +} + +Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1, + OptSpecifier Id2, OptSpecifier Id3, + OptSpecifier Id4) const { + Arg *Res = 0; + for (const_iterator it = begin(), ie = end(); it != ie; ++it) { + if ((*it)->getOption().matches(Id0) || + (*it)->getOption().matches(Id1) || + (*it)->getOption().matches(Id2) || + (*it)->getOption().matches(Id3) || + (*it)->getOption().matches(Id4)) { + Res = *it; + Res->claim(); + } + } + + return Res; +} + +bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const { + if (Arg *A = getLastArg(Pos, Neg)) + return A->getOption().matches(Pos); + return Default; +} + +StringRef ArgList::getLastArgValue(OptSpecifier Id, + StringRef Default) const { + if (Arg *A = getLastArg(Id)) + return A->getValue(*this); + return Default; +} + +int ArgList::getLastArgIntValue(OptSpecifier Id, int Default, + clang::DiagnosticsEngine *Diags) const { + int Res = Default; + + if (Arg *A = getLastArg(Id)) { + if (StringRef(A->getValue(*this)).getAsInteger(10, Res)) { + if (Diags) + Diags->Report(diag::err_drv_invalid_int_value) + << A->getAsString(*this) << A->getValue(*this); + } + } + + return Res; +} + +std::vector<std::string> ArgList::getAllArgValues(OptSpecifier Id) const { + SmallVector<const char *, 16> Values; + AddAllArgValues(Values, Id); + return std::vector<std::string>(Values.begin(), Values.end()); +} + +void ArgList::AddLastArg(ArgStringList &Output, OptSpecifier Id) const { + if (Arg *A = getLastArg(Id)) { + A->claim(); + A->render(*this, Output); + } +} + +void ArgList::AddAllArgs(ArgStringList &Output, OptSpecifier Id0, + OptSpecifier Id1, OptSpecifier Id2) const { + for (arg_iterator it = filtered_begin(Id0, Id1, Id2), + ie = filtered_end(); it != ie; ++it) { + (*it)->claim(); + (*it)->render(*this, Output); + } +} + +void ArgList::AddAllArgValues(ArgStringList &Output, OptSpecifier Id0, + OptSpecifier Id1, OptSpecifier Id2) const { + for (arg_iterator it = filtered_begin(Id0, Id1, Id2), + ie = filtered_end(); it != ie; ++it) { + (*it)->claim(); + for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i) + Output.push_back((*it)->getValue(*this, i)); + } +} + +void ArgList::AddAllArgsTranslated(ArgStringList &Output, OptSpecifier Id0, + const char *Translation, + bool Joined) const { + for (arg_iterator it = filtered_begin(Id0), + ie = filtered_end(); it != ie; ++it) { + (*it)->claim(); + + if (Joined) { + Output.push_back(MakeArgString(StringRef(Translation) + + (*it)->getValue(*this, 0))); + } else { + Output.push_back(Translation); + Output.push_back((*it)->getValue(*this, 0)); + } + } +} + +void ArgList::ClaimAllArgs(OptSpecifier Id0) const { + for (arg_iterator it = filtered_begin(Id0), + ie = filtered_end(); it != ie; ++it) + (*it)->claim(); +} + +void ArgList::ClaimAllArgs() const { + for (const_iterator it = begin(), ie = end(); it != ie; ++it) + if (!(*it)->isClaimed()) + (*it)->claim(); +} + +const char *ArgList::MakeArgString(const Twine &T) const { + SmallString<256> Str; + T.toVector(Str); + return MakeArgString(Str.str()); +} + +const char *ArgList::GetOrMakeJoinedArgString(unsigned Index, + StringRef LHS, + StringRef RHS) const { + StringRef Cur = getArgString(Index); + if (Cur.size() == LHS.size() + RHS.size() && + Cur.startswith(LHS) && Cur.endswith(RHS)) + return Cur.data(); + + return MakeArgString(LHS + RHS); +} + +// + +InputArgList::InputArgList(const char* const *ArgBegin, + const char* const *ArgEnd) + : NumInputArgStrings(ArgEnd - ArgBegin) { + ArgStrings.append(ArgBegin, ArgEnd); +} + +InputArgList::~InputArgList() { + // An InputArgList always owns its arguments. + for (iterator it = begin(), ie = end(); it != ie; ++it) + delete *it; +} + +unsigned InputArgList::MakeIndex(StringRef String0) const { + unsigned Index = ArgStrings.size(); + + // Tuck away so we have a reliable const char *. + SynthesizedStrings.push_back(String0); + ArgStrings.push_back(SynthesizedStrings.back().c_str()); + + return Index; +} + +unsigned InputArgList::MakeIndex(StringRef String0, + StringRef String1) const { + unsigned Index0 = MakeIndex(String0); + unsigned Index1 = MakeIndex(String1); + assert(Index0 + 1 == Index1 && "Unexpected non-consecutive indices!"); + (void) Index1; + return Index0; +} + +const char *InputArgList::MakeArgString(StringRef Str) const { + return getArgString(MakeIndex(Str)); +} + +// + +DerivedArgList::DerivedArgList(const InputArgList &_BaseArgs) + : BaseArgs(_BaseArgs) { +} + +DerivedArgList::~DerivedArgList() { + // We only own the arguments we explicitly synthesized. + for (iterator it = SynthesizedArgs.begin(), ie = SynthesizedArgs.end(); + it != ie; ++it) + delete *it; +} + +const char *DerivedArgList::MakeArgString(StringRef Str) const { + return BaseArgs.MakeArgString(Str); +} + +Arg *DerivedArgList::MakeFlagArg(const Arg *BaseArg, const Option *Opt) const { + Arg *A = new Arg(Opt, BaseArgs.MakeIndex(Opt->getName()), BaseArg); + SynthesizedArgs.push_back(A); + return A; +} + +Arg *DerivedArgList::MakePositionalArg(const Arg *BaseArg, const Option *Opt, + StringRef Value) const { + unsigned Index = BaseArgs.MakeIndex(Value); + Arg *A = new Arg(Opt, Index, BaseArgs.getArgString(Index), BaseArg); + SynthesizedArgs.push_back(A); + return A; +} + +Arg *DerivedArgList::MakeSeparateArg(const Arg *BaseArg, const Option *Opt, + StringRef Value) const { + unsigned Index = BaseArgs.MakeIndex(Opt->getName(), Value); + Arg *A = new Arg(Opt, Index, BaseArgs.getArgString(Index + 1), BaseArg); + SynthesizedArgs.push_back(A); + return A; +} + +Arg *DerivedArgList::MakeJoinedArg(const Arg *BaseArg, const Option *Opt, + StringRef Value) const { + unsigned Index = BaseArgs.MakeIndex(Opt->getName().str() + Value.str()); + Arg *A = new Arg(Opt, Index, + BaseArgs.getArgString(Index) + Opt->getName().size(), + BaseArg); + SynthesizedArgs.push_back(A); + return A; +} diff --git a/clang/lib/Driver/CC1AsOptions.cpp b/clang/lib/Driver/CC1AsOptions.cpp new file mode 100644 index 0000000..ea80f5a --- /dev/null +++ b/clang/lib/Driver/CC1AsOptions.cpp @@ -0,0 +1,39 @@ +//===--- CC1AsOptions.cpp - Clang Assembler Options Table -----------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/CC1AsOptions.h" +#include "clang/Driver/Option.h" +#include "clang/Driver/OptTable.h" +using namespace clang; +using namespace clang::driver; +using namespace clang::driver::options; +using namespace clang::driver::cc1asoptions; + +static const OptTable::Info CC1AsInfoTable[] = { +#define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ + HELPTEXT, METAVAR) \ + { NAME, HELPTEXT, METAVAR, Option::KIND##Class, PARAM, FLAGS, \ + OPT_##GROUP, OPT_##ALIAS }, +#include "clang/Driver/CC1AsOptions.inc" +}; + +namespace { + +class CC1AsOptTable : public OptTable { +public: + CC1AsOptTable() + : OptTable(CC1AsInfoTable, + sizeof(CC1AsInfoTable) / sizeof(CC1AsInfoTable[0])) {} +}; + +} + +OptTable *clang::driver::createCC1AsOptTable() { + return new CC1AsOptTable(); +} diff --git a/clang/lib/Driver/CC1Options.cpp b/clang/lib/Driver/CC1Options.cpp new file mode 100644 index 0000000..884b363 --- /dev/null +++ b/clang/lib/Driver/CC1Options.cpp @@ -0,0 +1,38 @@ +//===--- CC1Options.cpp - Clang CC1 Options Table -------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/CC1Options.h" +#include "clang/Driver/Option.h" +#include "clang/Driver/OptTable.h" +using namespace clang; +using namespace clang::driver; +using namespace clang::driver::options; +using namespace clang::driver::cc1options; + +static const OptTable::Info CC1InfoTable[] = { +#define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ + HELPTEXT, METAVAR) \ + { NAME, HELPTEXT, METAVAR, Option::KIND##Class, PARAM, FLAGS, \ + OPT_##GROUP, OPT_##ALIAS }, +#include "clang/Driver/CC1Options.inc" +}; + +namespace { + +class CC1OptTable : public OptTable { +public: + CC1OptTable() + : OptTable(CC1InfoTable, sizeof(CC1InfoTable) / sizeof(CC1InfoTable[0])) {} +}; + +} + +OptTable *clang::driver::createCC1OptTable() { + return new CC1OptTable(); +} diff --git a/clang/lib/Driver/CMakeLists.txt b/clang/lib/Driver/CMakeLists.txt new file mode 100644 index 0000000..a798e20 --- /dev/null +++ b/clang/lib/Driver/CMakeLists.txt @@ -0,0 +1,33 @@ +set(LLVM_USED_LIBS clangBasic clangAST clangParse) + +add_clang_library(clangDriver + Action.cpp + Arg.cpp + ArgList.cpp + CC1Options.cpp + CC1AsOptions.cpp + Compilation.cpp + Driver.cpp + DriverOptions.cpp + Job.cpp + Option.cpp + OptTable.cpp + Phases.cpp + Tool.cpp + ToolChain.cpp + ToolChains.cpp + WindowsToolChain.cpp + Tools.cpp + Types.cpp + ) + +IF(MSVC) + get_target_property(NON_ANSI_COMPILE_FLAGS clangDriver COMPILE_FLAGS) + string(REPLACE /Za + "" NON_ANSI_COMPILE_FLAGS + ${NON_ANSI_COMPILE_FLAGS}) + set_target_properties(clangDriver PROPERTIES COMPILE_FLAGS ${NON_ANSI_COMPILE_FLAGS}) +ENDIF(MSVC) + +add_dependencies(clangDriver ClangAttrList ClangDiagnosticDriver + ClangDriverOptions ClangCC1Options ClangCC1AsOptions) diff --git a/clang/lib/Driver/Compilation.cpp b/clang/lib/Driver/Compilation.cpp new file mode 100644 index 0000000..5553fc9 --- /dev/null +++ b/clang/lib/Driver/Compilation.cpp @@ -0,0 +1,236 @@ +//===--- 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/ArgList.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/Support/raw_ostream.h" +#include "llvm/Support/Program.h" +#include <sys/stat.h> +#include <errno.h> + +using namespace clang::driver; +using namespace clang; + +Compilation::Compilation(const Driver &D, const ToolChain &_DefaultToolChain, + InputArgList *_Args, DerivedArgList *_TranslatedArgs) + : TheDriver(D), DefaultToolChain(_DefaultToolChain), Args(_Args), + TranslatedArgs(_TranslatedArgs), Redirects(0) { +} + +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 the actions, if built. + for (ActionList::iterator it = Actions.begin(), ie = Actions.end(); + it != ie; ++it) + delete *it; + + // 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; +} + +void Compilation::PrintJob(raw_ostream &OS, const Job &J, + const char *Terminator, bool Quote) const { + if (const Command *C = dyn_cast<Command>(&J)) { + OS << " \"" << C->getExecutable() << '"'; + for (ArgStringList::const_iterator it = C->getArguments().begin(), + ie = C->getArguments().end(); it != ie; ++it) { + OS << ' '; + if (!Quote && !std::strpbrk(*it, " \"\\$")) { + OS << *it; + continue; + } + + // Quote the argument and escape shell special characters; this isn't + // really complete but is good enough. + OS << '"'; + for (const char *s = *it; *s; ++s) { + if (*s == '"' || *s == '\\' || *s == '$') + OS << '\\'; + OS << *s; + } + OS << '"'; + } + OS << Terminator; + } else { + const JobList *Jobs = cast<JobList>(&J); + for (JobList::const_iterator + it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) + PrintJob(OS, **it, Terminator, Quote); + } +} + +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) { + + llvm::sys::Path P(*it); + std::string Error; + + // Don't try to remove files which we don't have write access to (but may be + // able to remove). Underlying tools may have intentionally not overwritten + // them. + if (!P.canWrite()) + continue; + + if (P.eraseFromDisk(false, &Error)) { + // Failure is only failure if the file exists and is "regular". There is + // a race condition here due to the limited interface of + // llvm::sys::Path, we want to know if the removal gave ENOENT. + + // FIXME: Grumble, P.exists() is broken. PR3837. + struct stat buf; + if (::stat(P.c_str(), &buf) == 0 ? (buf.st_mode & S_IFMT) == S_IFREG : + (errno != ENOENT)) { + if (IssueErrors) + getDriver().Diag(clang::diag::err_drv_unable_to_remove_file) + << Error; + Success = false; + } + } + } + + return Success; +} + +int Compilation::ExecuteCommand(const Command &C, + const Command *&FailingCommand) const { + llvm::sys::Path Prog(C.getExecutable()); + const char **Argv = new const char*[C.getArguments().size() + 2]; + Argv[0] = C.getExecutable(); + std::copy(C.getArguments().begin(), C.getArguments().end(), Argv+1); + Argv[C.getArguments().size() + 1] = 0; + + if ((getDriver().CCCEcho || 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::string Error; + OS = new llvm::raw_fd_ostream(getDriver().CCPrintOptionsFilename, + Error, + llvm::raw_fd_ostream::F_Append); + if (!Error.empty()) { + getDriver().Diag(clang::diag::err_drv_cc_print_options_failure) + << Error; + FailingCommand = &C; + delete OS; + return 1; + } + } + + if (getDriver().CCPrintOptions) + *OS << "[Logging clang options]"; + + PrintJob(*OS, C, "\n", /*Quote=*/getDriver().CCPrintOptions); + + if (OS != &llvm::errs()) + delete OS; + } + + std::string Error; + int Res = + llvm::sys::Program::ExecuteAndWait(Prog, Argv, + /*env*/0, Redirects, + /*secondsToWait*/0, /*memoryLimit*/0, + &Error); + 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; + + delete[] Argv; + return Res; +} + +int Compilation::ExecuteJob(const Job &J, + const Command *&FailingCommand) const { + if (const Command *C = dyn_cast<Command>(&J)) { + return ExecuteCommand(*C, FailingCommand); + } else { + const JobList *Jobs = cast<JobList>(&J); + for (JobList::const_iterator + it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) + if (int Res = ExecuteJob(**it, FailingCommand)) + return Res; + return 0; + } +} + +void Compilation::initCompilationForDiagnostics(void) { + // Free actions and jobs. + DeleteContainerPointers(Actions); + Jobs.clear(); + + // Clear temporary/results file lists. + TempFiles.clear(); + ResultFiles.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; i != sizeof(OutputOpts)/sizeof(OutputOpts[0]); ++i) { + if (TranslatedArgs->hasArg(OutputOpts[i])) + TranslatedArgs->eraseArg(OutputOpts[i]); + } + TranslatedArgs->ClaimAllArgs(); + + // Redirect stdout/stderr to /dev/null. + Redirects = new const llvm::sys::Path*[3](); + Redirects[1] = new const llvm::sys::Path(); + Redirects[2] = new const llvm::sys::Path(); +} + +StringRef Compilation::getSysRoot(void) const { + return getDriver().SysRoot; +} diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp new file mode 100644 index 0000000..3ddac69 --- /dev/null +++ b/clang/lib/Driver/Driver.cpp @@ -0,0 +1,1789 @@ +//===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Driver.h" + +#include "clang/Driver/Action.h" +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Compilation.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Driver/Job.h" +#include "clang/Driver/OptTable.h" +#include "clang/Driver/Option.h" +#include "clang/Driver/Options.h" +#include "clang/Driver/Tool.h" +#include "clang/Driver/ToolChain.h" + +#include "clang/Basic/Version.h" + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringSet.h" +#include "llvm/ADT/OwningPtr.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/PrettyStackTrace.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/Program.h" + +#include "InputInfo.h" +#include "ToolChains.h" + +#include <map> + +#include "clang/Config/config.h" + +using namespace clang::driver; +using namespace clang; + +Driver::Driver(StringRef ClangExecutable, + StringRef DefaultTargetTriple, + StringRef DefaultImageName, + bool IsProduction, + DiagnosticsEngine &Diags) + : Opts(createDriverOptTable()), Diags(Diags), + ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), + UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple), + DefaultImageName(DefaultImageName), + DriverTitle("clang \"gcc-compatible\" driver"), + CCPrintOptionsFilename(0), CCPrintHeadersFilename(0), + CCLogDiagnosticsFilename(0), CCCIsCXX(false), + CCCIsCPP(false),CCCEcho(false), CCCPrintBindings(false), + CCPrintOptions(false), CCPrintHeaders(false), CCLogDiagnostics(false), + CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true), + CCCUseClang(true), CCCUseClangCXX(true), CCCUseClangCPP(true), + CCCUsePCH(true), SuppressMissingInputWarning(false) { + if (IsProduction) { + // In a "production" build, only use clang on architectures we expect to + // work. + // + // During development its more convenient to always have the driver use + // clang, but we don't want users to be confused when things don't work, or + // to file bugs for things we don't support. + CCCClangArchs.insert(llvm::Triple::x86); + CCCClangArchs.insert(llvm::Triple::x86_64); + CCCClangArchs.insert(llvm::Triple::arm); + } + + Name = llvm::sys::path::stem(ClangExecutable); + Dir = llvm::sys::path::parent_path(ClangExecutable); + + // Compute the path to the resource directory. + StringRef ClangResourceDir(CLANG_RESOURCE_DIR); + SmallString<128> P(Dir); + if (ClangResourceDir != "") + llvm::sys::path::append(P, ClangResourceDir); + else + llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING); + ResourceDir = P.str(); +} + +Driver::~Driver() { + delete Opts; + + for (llvm::StringMap<ToolChain *>::iterator I = ToolChains.begin(), + E = ToolChains.end(); + I != E; ++I) + delete I->second; +} + +InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgList) { + llvm::PrettyStackTraceString CrashInfo("Command line argument parsing"); + unsigned MissingArgIndex, MissingArgCount; + InputArgList *Args = getOpts().ParseArgs(ArgList.begin(), ArgList.end(), + MissingArgIndex, MissingArgCount); + + // Check for missing argument error. + if (MissingArgCount) + Diag(clang::diag::err_drv_missing_argument) + << Args->getArgString(MissingArgIndex) << MissingArgCount; + + // Check for unsupported options. + for (ArgList::const_iterator it = Args->begin(), ie = Args->end(); + it != ie; ++it) { + Arg *A = *it; + if (A->getOption().isUnsupported()) { + Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args); + continue; + } + + // Warn about -mcpu= without an argument. + if (A->getOption().matches(options::OPT_mcpu_EQ) && + A->containsValue("")) { + Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(*Args); + } + } + + return Args; +} + +// Determine which compilation mode we are in. We look for options which +// affect the phase, starting with the earliest phases, and record which +// option we used to determine the final phase. +phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg) +const { + Arg *PhaseArg = 0; + phases::ID FinalPhase; + + // -{E,M,MM} only run the preprocessor. + if (CCCIsCPP || + (PhaseArg = DAL.getLastArg(options::OPT_E)) || + (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM))) { + FinalPhase = phases::Preprocess; + + // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler. + } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) || + (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) || + (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) || + (PhaseArg = DAL.getLastArg(options::OPT__migrate)) || + (PhaseArg = DAL.getLastArg(options::OPT__analyze, + options::OPT__analyze_auto)) || + (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) || + (PhaseArg = DAL.getLastArg(options::OPT_S))) { + FinalPhase = phases::Compile; + + // -c only runs up to the assembler. + } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) { + FinalPhase = phases::Assemble; + + // Otherwise do everything. + } else + FinalPhase = phases::Link; + + if (FinalPhaseArg) + *FinalPhaseArg = PhaseArg; + + return FinalPhase; +} + +DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const { + DerivedArgList *DAL = new DerivedArgList(Args); + + bool HasNostdlib = Args.hasArg(options::OPT_nostdlib); + for (ArgList::const_iterator it = Args.begin(), + ie = Args.end(); it != ie; ++it) { + const Arg *A = *it; + + // Unfortunately, we have to parse some forwarding options (-Xassembler, + // -Xlinker, -Xpreprocessor) because we either integrate their functionality + // (assembler and preprocessor), or bypass a previous driver ('collect2'). + + // Rewrite linker options, to replace --no-demangle with a custom internal + // option. + if ((A->getOption().matches(options::OPT_Wl_COMMA) || + A->getOption().matches(options::OPT_Xlinker)) && + A->containsValue("--no-demangle")) { + // Add the rewritten no-demangle argument. + DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle)); + + // Add the remaining values as Xlinker arguments. + for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) + if (StringRef(A->getValue(Args, i)) != "--no-demangle") + DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), + A->getValue(Args, i)); + + continue; + } + + // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by + // some build systems. We don't try to be complete here because we don't + // care to encourage this usage model. + if (A->getOption().matches(options::OPT_Wp_COMMA) && + A->getNumValues() == 2 && + (A->getValue(Args, 0) == StringRef("-MD") || + A->getValue(Args, 0) == StringRef("-MMD"))) { + // Rewrite to -MD/-MMD along with -MF. + if (A->getValue(Args, 0) == StringRef("-MD")) + DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); + else + DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); + DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), + A->getValue(Args, 1)); + continue; + } + + // Rewrite reserved library names. + if (A->getOption().matches(options::OPT_l)) { + StringRef Value = A->getValue(Args); + + // Rewrite unless -nostdlib is present. + if (!HasNostdlib && Value == "stdc++") { + DAL->AddFlagArg(A, Opts->getOption( + options::OPT_Z_reserved_lib_stdcxx)); + continue; + } + + // Rewrite unconditionally. + if (Value == "cc_kext") { + DAL->AddFlagArg(A, Opts->getOption( + options::OPT_Z_reserved_lib_cckext)); + continue; + } + } + + DAL->append(*it); + } + + // Add a default value of -mlinker-version=, if one was given and the user + // didn't specify one. +#if defined(HOST_LINK_VERSION) + if (!Args.hasArg(options::OPT_mlinker_version_EQ)) { + DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ), + HOST_LINK_VERSION); + DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim(); + } +#endif + + return DAL; +} + +Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) { + llvm::PrettyStackTraceString CrashInfo("Compilation construction"); + + // FIXME: Handle environment options which affect driver behavior, somewhere + // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS. + + if (char *env = ::getenv("COMPILER_PATH")) { + StringRef CompilerPath = env; + while (!CompilerPath.empty()) { + std::pair<StringRef, StringRef> Split = CompilerPath.split(':'); + PrefixDirs.push_back(Split.first); + CompilerPath = Split.second; + } + } + + // FIXME: What are we going to do with -V and -b? + + // FIXME: This stuff needs to go into the Compilation, not the driver. + bool CCCPrintOptions = false, CCCPrintActions = false; + + InputArgList *Args = ParseArgStrings(ArgList.slice(1)); + + // -no-canonical-prefixes is used very early in main. + Args->ClaimAllArgs(options::OPT_no_canonical_prefixes); + + // Ignore -pipe. + Args->ClaimAllArgs(options::OPT_pipe); + + // Extract -ccc args. + // + // FIXME: We need to figure out where this behavior should live. Most of it + // should be outside in the client; the parts that aren't should have proper + // options, either by introducing new ones or by overloading gcc ones like -V + // or -b. + CCCPrintOptions = Args->hasArg(options::OPT_ccc_print_options); + CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases); + CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings); + CCCIsCXX = Args->hasArg(options::OPT_ccc_cxx) || CCCIsCXX; + CCCEcho = Args->hasArg(options::OPT_ccc_echo); + if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name)) + CCCGenericGCCName = A->getValue(*Args); + CCCUseClangCXX = Args->hasFlag(options::OPT_ccc_clang_cxx, + options::OPT_ccc_no_clang_cxx, + CCCUseClangCXX); + CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch, + options::OPT_ccc_pch_is_pth); + CCCUseClang = !Args->hasArg(options::OPT_ccc_no_clang); + CCCUseClangCPP = !Args->hasArg(options::OPT_ccc_no_clang_cpp); + if (const Arg *A = Args->getLastArg(options::OPT_ccc_clang_archs)) { + StringRef Cur = A->getValue(*Args); + + CCCClangArchs.clear(); + while (!Cur.empty()) { + std::pair<StringRef, StringRef> Split = Cur.split(','); + + if (!Split.first.empty()) { + llvm::Triple::ArchType Arch = + llvm::Triple(Split.first, "", "").getArch(); + + if (Arch == llvm::Triple::UnknownArch) + Diag(clang::diag::err_drv_invalid_arch_name) << Split.first; + + CCCClangArchs.insert(Arch); + } + + Cur = Split.second; + } + } + // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld + // and getToolChain is const. + if (const Arg *A = Args->getLastArg(options::OPT_target)) + DefaultTargetTriple = A->getValue(*Args); + if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir)) + Dir = InstalledDir = A->getValue(*Args); + for (arg_iterator it = Args->filtered_begin(options::OPT_B), + ie = Args->filtered_end(); it != ie; ++it) { + const Arg *A = *it; + A->claim(); + PrefixDirs.push_back(A->getValue(*Args, 0)); + } + if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ)) + SysRoot = A->getValue(*Args); + if (Args->hasArg(options::OPT_nostdlib)) + UseStdLib = false; + + // Perform the default argument translations. + DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args); + + // Owned by the host. + const ToolChain &TC = getToolChain(*Args); + + // The compilation takes ownership of Args. + Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs); + + // FIXME: This behavior shouldn't be here. + if (CCCPrintOptions) { + PrintOptions(C->getInputArgs()); + return C; + } + + if (!HandleImmediateArgs(*C)) + return C; + + // Construct the list of inputs. + InputList Inputs; + BuildInputs(C->getDefaultToolChain(), C->getArgs(), Inputs); + + // Construct the list of abstract actions to perform for this compilation. On + // Darwin target OSes this uses the driver-driver and universal actions. + if (TC.getTriple().isOSDarwin()) + BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(), + Inputs, C->getActions()); + else + BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs, + C->getActions()); + + if (CCCPrintActions) { + PrintActions(*C); + return C; + } + + BuildJobs(*C); + + return C; +} + +// When clang crashes, produce diagnostic information including the fully +// preprocessed source file(s). Request that the developer attach the +// diagnostic information to a bug report. +void Driver::generateCompilationDiagnostics(Compilation &C, + const Command *FailingCommand) { + if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics)) + return; + + // Don't try to generate diagnostics for link jobs. + if (FailingCommand->getCreator().isLinkJob()) + return; + + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Please submit a bug report to " BUG_REPORT_URL " and include command" + " line arguments and all diagnostic information."; + + // Suppress driver output and emit preprocessor output to temp file. + CCCIsCPP = true; + CCGenDiagnostics = true; + + // Save the original job command(s). + std::string Cmd; + llvm::raw_string_ostream OS(Cmd); + C.PrintJob(OS, C.getJobs(), "\n", false); + OS.flush(); + + // Clear stale state and suppress tool output. + C.initCompilationForDiagnostics(); + Diags.Reset(); + + // Construct the list of inputs. + InputList Inputs; + BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs); + + for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) { + bool IgnoreInput = false; + + // Ignore input from stdin or any inputs that cannot be preprocessed. + if (!strcmp(it->second->getValue(C.getArgs()), "-")) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating preprocessed source(s) - ignoring input from stdin" + "."; + IgnoreInput = true; + } else if (types::getPreprocessedType(it->first) == types::TY_INVALID) { + IgnoreInput = true; + } + + if (IgnoreInput) { + it = Inputs.erase(it); + ie = Inputs.end(); + } else { + ++it; + } + } + + // Don't attempt to generate preprocessed files if multiple -arch options are + // used, unless they're all duplicates. + llvm::StringSet<> ArchNames; + for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); + it != ie; ++it) { + Arg *A = *it; + if (A->getOption().matches(options::OPT_arch)) { + StringRef ArchName = A->getValue(C.getArgs()); + ArchNames.insert(ArchName); + } + } + if (ArchNames.size() > 1) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating preprocessed source(s) - cannot generate " + "preprocessed source with multiple -arch options."; + return; + } + + if (Inputs.empty()) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating preprocessed source(s) - no preprocessable inputs."; + return; + } + + // Construct the list of abstract actions to perform for this compilation. On + // Darwin OSes this uses the driver-driver and builds universal actions. + const ToolChain &TC = C.getDefaultToolChain(); + if (TC.getTriple().isOSDarwin()) + BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions()); + else + BuildActions(TC, C.getArgs(), Inputs, C.getActions()); + + BuildJobs(C); + + // If there were errors building the compilation, quit now. + if (Diags.hasErrorOccurred()) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating preprocessed source(s)."; + return; + } + + // Generate preprocessed output. + FailingCommand = 0; + int Res = C.ExecuteJob(C.getJobs(), FailingCommand); + + // If the command succeeded, we are done. + if (Res == 0) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Preprocessed source(s) and associated run script(s) are located at:"; + ArgStringList Files = C.getTempFiles(); + for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end(); + it != ie; ++it) { + Diag(clang::diag::note_drv_command_failed_diag_msg) << *it; + + std::string Err; + std::string Script = StringRef(*it).rsplit('.').first; + Script += ".sh"; + llvm::raw_fd_ostream ScriptOS(Script.c_str(), Err, + llvm::raw_fd_ostream::F_Excl | + llvm::raw_fd_ostream::F_Binary); + if (!Err.empty()) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating run script: " + Script + " " + Err; + } else { + ScriptOS << Cmd; + Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; + } + } + } else { + // Failure, remove preprocessed files. + if (!C.getArgs().hasArg(options::OPT_save_temps)) + C.CleanupFileList(C.getTempFiles(), true); + + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating preprocessed source(s)."; + } +} + +int Driver::ExecuteCompilation(const Compilation &C, + const Command *&FailingCommand) const { + // Just print if -### was present. + if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { + C.PrintJob(llvm::errs(), C.getJobs(), "\n", true); + return 0; + } + + // If there were errors building the compilation, quit now. + if (Diags.hasErrorOccurred()) + return 1; + + int Res = C.ExecuteJob(C.getJobs(), FailingCommand); + + // Remove temp files. + C.CleanupFileList(C.getTempFiles()); + + // If the command succeeded, we are done. + if (Res == 0) + return Res; + + // Otherwise, remove result files as well. + if (!C.getArgs().hasArg(options::OPT_save_temps)) { + C.CleanupFileList(C.getResultFiles(), true); + + // Failure result files are valid unless we crashed. + if (Res < 0) { + C.CleanupFileList(C.getFailureResultFiles(), true); +#ifdef _WIN32 + // Exit status should not be negative on Win32, + // unless abnormal termination. + Res = 1; +#endif + } + } + + // Print extra information about abnormal failures, if possible. + // + // This is ad-hoc, but we don't want to be excessively noisy. If the result + // status was 1, assume the command failed normally. In particular, if it was + // the compiler then assume it gave a reasonable error code. Failures in other + // tools are less common, and they generally have worse diagnostics, so always + // print the diagnostic there. + const Tool &FailingTool = FailingCommand->getCreator(); + + if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) { + // FIXME: See FIXME above regarding result code interpretation. + if (Res < 0) + Diag(clang::diag::err_drv_command_signalled) + << FailingTool.getShortName(); + else + Diag(clang::diag::err_drv_command_failed) + << FailingTool.getShortName() << Res; + } + + return Res; +} + +void Driver::PrintOptions(const ArgList &Args) const { + unsigned i = 0; + for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); + it != ie; ++it, ++i) { + Arg *A = *it; + llvm::errs() << "Option " << i << " - " + << "Name: \"" << A->getOption().getName() << "\", " + << "Values: {"; + for (unsigned j = 0; j < A->getNumValues(); ++j) { + if (j) + llvm::errs() << ", "; + llvm::errs() << '"' << A->getValue(Args, j) << '"'; + } + llvm::errs() << "}\n"; + } +} + +void Driver::PrintHelp(bool ShowHidden) const { + getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), + ShowHidden); +} + +void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const { + // FIXME: The following handlers should use a callback mechanism, we don't + // know what the client would like to do. + OS << getClangFullVersion() << '\n'; + const ToolChain &TC = C.getDefaultToolChain(); + OS << "Target: " << TC.getTripleString() << '\n'; + + // Print the threading model. + // + // FIXME: Implement correctly. + OS << "Thread model: " << "posix" << '\n'; +} + +/// PrintDiagnosticCategories - Implement the --print-diagnostic-categories +/// option. +static void PrintDiagnosticCategories(raw_ostream &OS) { + // Skip the empty category. + for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); + i != max; ++i) + OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n'; +} + +bool Driver::HandleImmediateArgs(const Compilation &C) { + // The order these options are handled in gcc is all over the place, but we + // don't expect inconsistencies w.r.t. that to matter in practice. + + if (C.getArgs().hasArg(options::OPT_dumpmachine)) { + llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n'; + return false; + } + + if (C.getArgs().hasArg(options::OPT_dumpversion)) { + // Since -dumpversion is only implemented for pedantic GCC compatibility, we + // return an answer which matches our definition of __VERSION__. + // + // If we want to return a more correct answer some day, then we should + // introduce a non-pedantically GCC compatible mode to Clang in which we + // provide sensible definitions for -dumpversion, __VERSION__, etc. + llvm::outs() << "4.2.1\n"; + return false; + } + + if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) { + PrintDiagnosticCategories(llvm::outs()); + return false; + } + + if (C.getArgs().hasArg(options::OPT__help) || + C.getArgs().hasArg(options::OPT__help_hidden)) { + PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden)); + return false; + } + + if (C.getArgs().hasArg(options::OPT__version)) { + // Follow gcc behavior and use stdout for --version and stderr for -v. + PrintVersion(C, llvm::outs()); + return false; + } + + if (C.getArgs().hasArg(options::OPT_v) || + C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) { + PrintVersion(C, llvm::errs()); + SuppressMissingInputWarning = true; + } + + const ToolChain &TC = C.getDefaultToolChain(); + if (C.getArgs().hasArg(options::OPT_print_search_dirs)) { + llvm::outs() << "programs: ="; + for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(), + ie = TC.getProgramPaths().end(); it != ie; ++it) { + if (it != TC.getProgramPaths().begin()) + llvm::outs() << ':'; + llvm::outs() << *it; + } + llvm::outs() << "\n"; + llvm::outs() << "libraries: =" << ResourceDir; + + StringRef sysroot = C.getSysRoot(); + + for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(), + ie = TC.getFilePaths().end(); it != ie; ++it) { + llvm::outs() << ':'; + const char *path = it->c_str(); + if (path[0] == '=') + llvm::outs() << sysroot << path + 1; + else + llvm::outs() << path; + } + llvm::outs() << "\n"; + return false; + } + + // FIXME: The following handlers should use a callback mechanism, we don't + // know what the client would like to do. + if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) { + llvm::outs() << GetFilePath(A->getValue(C.getArgs()), TC) << "\n"; + return false; + } + + if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { + llvm::outs() << GetProgramPath(A->getValue(C.getArgs()), TC) << "\n"; + return false; + } + + if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) { + llvm::outs() << GetFilePath("libgcc.a", TC) << "\n"; + return false; + } + + if (C.getArgs().hasArg(options::OPT_print_multi_lib)) { + // FIXME: We need tool chain support for this. + llvm::outs() << ".;\n"; + + switch (C.getDefaultToolChain().getTriple().getArch()) { + default: + break; + + case llvm::Triple::x86_64: + llvm::outs() << "x86_64;@m64" << "\n"; + break; + + case llvm::Triple::ppc64: + llvm::outs() << "ppc64;@m64" << "\n"; + break; + } + return false; + } + + // FIXME: What is the difference between print-multi-directory and + // print-multi-os-directory? + if (C.getArgs().hasArg(options::OPT_print_multi_directory) || + C.getArgs().hasArg(options::OPT_print_multi_os_directory)) { + switch (C.getDefaultToolChain().getTriple().getArch()) { + default: + case llvm::Triple::x86: + case llvm::Triple::ppc: + llvm::outs() << "." << "\n"; + break; + + case llvm::Triple::x86_64: + llvm::outs() << "x86_64" << "\n"; + break; + + case llvm::Triple::ppc64: + llvm::outs() << "ppc64" << "\n"; + break; + } + return false; + } + + return true; +} + +static unsigned PrintActions1(const Compilation &C, Action *A, + std::map<Action*, unsigned> &Ids) { + if (Ids.count(A)) + return Ids[A]; + + std::string str; + llvm::raw_string_ostream os(str); + + os << Action::getClassName(A->getKind()) << ", "; + if (InputAction *IA = dyn_cast<InputAction>(A)) { + os << "\"" << IA->getInputArg().getValue(C.getArgs()) << "\""; + } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { + os << '"' << (BIA->getArchName() ? BIA->getArchName() : + C.getDefaultToolChain().getArchName()) << '"' + << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}"; + } else { + os << "{"; + for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) { + os << PrintActions1(C, *it, Ids); + ++it; + if (it != ie) + os << ", "; + } + os << "}"; + } + + unsigned Id = Ids.size(); + Ids[A] = Id; + llvm::errs() << Id << ": " << os.str() << ", " + << types::getTypeName(A->getType()) << "\n"; + + return Id; +} + +void Driver::PrintActions(const Compilation &C) const { + std::map<Action*, unsigned> Ids; + for (ActionList::const_iterator it = C.getActions().begin(), + ie = C.getActions().end(); it != ie; ++it) + PrintActions1(C, *it, Ids); +} + +/// \brief Check whether the given input tree contains any compilation or +/// assembly actions. +static bool ContainsCompileOrAssembleAction(const Action *A) { + if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A)) + return true; + + for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it) + if (ContainsCompileOrAssembleAction(*it)) + return true; + + return false; +} + +void Driver::BuildUniversalActions(const ToolChain &TC, + const DerivedArgList &Args, + const InputList &BAInputs, + ActionList &Actions) const { + llvm::PrettyStackTraceString CrashInfo("Building universal build actions"); + // Collect the list of architectures. Duplicates are allowed, but should only + // be handled once (in the order seen). + llvm::StringSet<> ArchNames; + SmallVector<const char *, 4> Archs; + for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); + it != ie; ++it) { + Arg *A = *it; + + if (A->getOption().matches(options::OPT_arch)) { + // Validate the option here; we don't save the type here because its + // particular spelling may participate in other driver choices. + llvm::Triple::ArchType Arch = + llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args)); + if (Arch == llvm::Triple::UnknownArch) { + Diag(clang::diag::err_drv_invalid_arch_name) + << A->getAsString(Args); + continue; + } + + A->claim(); + if (ArchNames.insert(A->getValue(Args))) + Archs.push_back(A->getValue(Args)); + } + } + + // When there is no explicit arch for this platform, make sure we still bind + // the architecture (to the default) so that -Xarch_ is handled correctly. + if (!Archs.size()) + Archs.push_back(0); + + // FIXME: We killed off some others but these aren't yet detected in a + // functional manner. If we added information to jobs about which "auxiliary" + // files they wrote then we could detect the conflict these cause downstream. + if (Archs.size() > 1) { + // No recovery needed, the point of this is just to prevent + // overwriting the same files. + if (const Arg *A = Args.getLastArg(options::OPT_save_temps)) + Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs) + << A->getAsString(Args); + } + + ActionList SingleActions; + BuildActions(TC, Args, BAInputs, SingleActions); + + // Add in arch bindings for every top level action, as well as lipo and + // dsymutil steps if needed. + for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) { + Action *Act = SingleActions[i]; + + // Make sure we can lipo this kind of output. If not (and it is an actual + // output) then we disallow, since we can't create an output file with the + // right name without overwriting it. We could remove this oddity by just + // changing the output names to include the arch, which would also fix + // -save-temps. Compatibility wins for now. + + if (Archs.size() > 1 && !types::canLipoType(Act->getType())) + Diag(clang::diag::err_drv_invalid_output_with_multiple_archs) + << types::getTypeName(Act->getType()); + + ActionList Inputs; + for (unsigned i = 0, e = Archs.size(); i != e; ++i) { + Inputs.push_back(new BindArchAction(Act, Archs[i])); + if (i != 0) + Inputs.back()->setOwnsInputs(false); + } + + // Lipo if necessary, we do it this way because we need to set the arch flag + // so that -Xarch_ gets overwritten. + if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing) + Actions.append(Inputs.begin(), Inputs.end()); + else + Actions.push_back(new LipoJobAction(Inputs, Act->getType())); + + // Handle debug info queries. + Arg *A = Args.getLastArg(options::OPT_g_Group); + if (A && !A->getOption().matches(options::OPT_g0) && + !A->getOption().matches(options::OPT_gstabs) && + ContainsCompileOrAssembleAction(Actions.back())) { + + // Add a 'dsymutil' step if necessary, when debug info is enabled and we + // have a compile input. We need to run 'dsymutil' ourselves in such cases + // because the debug info will refer to a temporary object file which is + // will be removed at the end of the compilation process. + if (Act->getType() == types::TY_Image) { + ActionList Inputs; + Inputs.push_back(Actions.back()); + Actions.pop_back(); + Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM)); + } + + // Verify the output (debug information only) if we passed '-verify'. + if (Args.hasArg(options::OPT_verify)) { + ActionList VerifyInputs; + VerifyInputs.push_back(Actions.back()); + Actions.pop_back(); + Actions.push_back(new VerifyJobAction(VerifyInputs, + types::TY_Nothing)); + } + } + } +} + +// Construct a the list of inputs and their types. +void Driver::BuildInputs(const ToolChain &TC, const DerivedArgList &Args, + InputList &Inputs) const { + // Track the current user specified (-x) input. We also explicitly track the + // argument used to set the type; we only want to claim the type when we + // actually use it, so we warn about unused -x arguments. + types::ID InputType = types::TY_Nothing; + Arg *InputTypeArg = 0; + + for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); + it != ie; ++it) { + Arg *A = *it; + + if (isa<InputOption>(A->getOption())) { + const char *Value = A->getValue(Args); + types::ID Ty = types::TY_INVALID; + + // Infer the input type if necessary. + if (InputType == types::TY_Nothing) { + // If there was an explicit arg for this, claim it. + if (InputTypeArg) + InputTypeArg->claim(); + + // stdin must be handled specially. + if (memcmp(Value, "-", 2) == 0) { + // If running with -E, treat as a C input (this changes the builtin + // macros, for example). This may be overridden by -ObjC below. + // + // Otherwise emit an error but still use a valid type to avoid + // spurious errors (e.g., no inputs). + if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP) + Diag(clang::diag::err_drv_unknown_stdin_type); + Ty = types::TY_C; + } else { + // Otherwise lookup by extension. + // Fallback is C if invoked as C preprocessor or Object otherwise. + // We use a host hook here because Darwin at least has its own + // idea of what .s is. + if (const char *Ext = strrchr(Value, '.')) + Ty = TC.LookupTypeForExtension(Ext + 1); + + if (Ty == types::TY_INVALID) { + if (CCCIsCPP) + Ty = types::TY_C; + else + Ty = types::TY_Object; + } + + // If the driver is invoked as C++ compiler (like clang++ or c++) it + // should autodetect some input files as C++ for g++ compatibility. + if (CCCIsCXX) { + types::ID OldTy = Ty; + Ty = types::lookupCXXTypeForCType(Ty); + + if (Ty != OldTy) + Diag(clang::diag::warn_drv_treating_input_as_cxx) + << getTypeName(OldTy) << getTypeName(Ty); + } + } + + // -ObjC and -ObjC++ override the default language, but only for "source + // files". We just treat everything that isn't a linker input as a + // source file. + // + // FIXME: Clean this up if we move the phase sequence into the type. + if (Ty != types::TY_Object) { + if (Args.hasArg(options::OPT_ObjC)) + Ty = types::TY_ObjC; + else if (Args.hasArg(options::OPT_ObjCXX)) + Ty = types::TY_ObjCXX; + } + } else { + assert(InputTypeArg && "InputType set w/o InputTypeArg"); + InputTypeArg->claim(); + Ty = InputType; + } + + // Check that the file exists, if enabled. + if (CheckInputsExist && memcmp(Value, "-", 2) != 0) { + SmallString<64> Path(Value); + if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) { + SmallString<64> Directory(WorkDir->getValue(Args)); + if (llvm::sys::path::is_absolute(Directory.str())) { + llvm::sys::path::append(Directory, Value); + Path.assign(Directory); + } + } + + bool exists = false; + if (llvm::sys::fs::exists(Path.c_str(), exists) || !exists) + Diag(clang::diag::err_drv_no_such_file) << Path.str(); + else + Inputs.push_back(std::make_pair(Ty, A)); + } else + Inputs.push_back(std::make_pair(Ty, A)); + + } else if (A->getOption().isLinkerInput()) { + // Just treat as object type, we could make a special type for this if + // necessary. + Inputs.push_back(std::make_pair(types::TY_Object, A)); + + } else if (A->getOption().matches(options::OPT_x)) { + InputTypeArg = A; + InputType = types::lookupTypeForTypeSpecifier(A->getValue(Args)); + A->claim(); + + // Follow gcc behavior and treat as linker input for invalid -x + // options. Its not clear why we shouldn't just revert to unknown; but + // this isn't very important, we might as well be bug compatible. + if (!InputType) { + Diag(clang::diag::err_drv_unknown_language) << A->getValue(Args); + InputType = types::TY_Object; + } + } + } + if (CCCIsCPP && Inputs.empty()) { + // If called as standalone preprocessor, stdin is processed + // if no other input is present. + unsigned Index = Args.getBaseArgs().MakeIndex("-"); + Arg *A = Opts->ParseOneArg(Args, Index); + A->claim(); + Inputs.push_back(std::make_pair(types::TY_C, A)); + } +} + +void Driver::BuildActions(const ToolChain &TC, const DerivedArgList &Args, + const InputList &Inputs, ActionList &Actions) const { + llvm::PrettyStackTraceString CrashInfo("Building compilation actions"); + + if (!SuppressMissingInputWarning && Inputs.empty()) { + Diag(clang::diag::err_drv_no_input_files); + return; + } + + Arg *FinalPhaseArg; + phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg); + + // Reject -Z* at the top level, these options should never have been exposed + // by gcc. + if (Arg *A = Args.getLastArg(options::OPT_Z_Joined)) + Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args); + + // Construct the actions to perform. + ActionList LinkerInputs; + unsigned NumSteps = 0; + for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { + types::ID InputType = Inputs[i].first; + const Arg *InputArg = Inputs[i].second; + + NumSteps = types::getNumCompilationPhases(InputType); + assert(NumSteps && "Invalid number of steps!"); + + // If the first step comes after the final phase we are doing as part of + // this compilation, warn the user about it. + phases::ID InitialPhase = types::getCompilationPhase(InputType, 0); + if (InitialPhase > FinalPhase) { + // Claim here to avoid the more general unused warning. + InputArg->claim(); + + // Suppress all unused style warnings with -Qunused-arguments + if (Args.hasArg(options::OPT_Qunused_arguments)) + continue; + + // Special case '-E' warning on a previously preprocessed file to make + // more sense. + if (InitialPhase == phases::Compile && FinalPhase == phases::Preprocess && + getPreprocessedType(InputType) == types::TY_INVALID) + Diag(clang::diag::warn_drv_preprocessed_input_file_unused) + << InputArg->getAsString(Args) + << FinalPhaseArg->getOption().getName(); + else + Diag(clang::diag::warn_drv_input_file_unused) + << InputArg->getAsString(Args) + << getPhaseName(InitialPhase) + << FinalPhaseArg->getOption().getName(); + continue; + } + + // Build the pipeline for this file. + OwningPtr<Action> Current(new InputAction(*InputArg, InputType)); + for (unsigned i = 0; i != NumSteps; ++i) { + phases::ID Phase = types::getCompilationPhase(InputType, i); + + // We are done if this step is past what the user requested. + if (Phase > FinalPhase) + break; + + // Queue linker inputs. + if (Phase == phases::Link) { + assert(i + 1 == NumSteps && "linking must be final compilation step."); + LinkerInputs.push_back(Current.take()); + break; + } + + // Some types skip the assembler phase (e.g., llvm-bc), but we can't + // encode this in the steps because the intermediate type depends on + // arguments. Just special case here. + if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm) + continue; + + // Otherwise construct the appropriate action. + Current.reset(ConstructPhaseAction(Args, Phase, Current.take())); + if (Current->getType() == types::TY_Nothing) + break; + } + + // If we ended with something, add to the output list. + if (Current) + Actions.push_back(Current.take()); + } + + // Add a link action if necessary. + if (!LinkerInputs.empty()) + Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image)); + + // If we are linking, claim any options which are obviously only used for + // compilation. + if (FinalPhase == phases::Link && (NumSteps == 1)) + Args.ClaimAllArgs(options::OPT_CompileOnly_Group); +} + +Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase, + Action *Input) const { + llvm::PrettyStackTraceString CrashInfo("Constructing phase actions"); + // Build the appropriate action. + switch (Phase) { + case phases::Link: llvm_unreachable("link action invalid here."); + case phases::Preprocess: { + types::ID OutputTy; + // -{M, MM} alter the output type. + if (Args.hasArg(options::OPT_M, options::OPT_MM)) { + OutputTy = types::TY_Dependencies; + } else { + OutputTy = types::getPreprocessedType(Input->getType()); + assert(OutputTy != types::TY_INVALID && + "Cannot preprocess this input type!"); + } + return new PreprocessJobAction(Input, OutputTy); + } + case phases::Precompile: + return new PrecompileJobAction(Input, types::TY_PCH); + case phases::Compile: { + if (Args.hasArg(options::OPT_fsyntax_only)) { + return new CompileJobAction(Input, types::TY_Nothing); + } else if (Args.hasArg(options::OPT_rewrite_objc)) { + return new CompileJobAction(Input, types::TY_RewrittenObjC); + } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) { + return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC); + } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) { + return new AnalyzeJobAction(Input, types::TY_Plist); + } else if (Args.hasArg(options::OPT__migrate)) { + return new MigrateJobAction(Input, types::TY_Remap); + } else if (Args.hasArg(options::OPT_emit_ast)) { + return new CompileJobAction(Input, types::TY_AST); + } else if (IsUsingLTO(Args)) { + types::ID Output = + Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC; + return new CompileJobAction(Input, Output); + } else { + return new CompileJobAction(Input, types::TY_PP_Asm); + } + } + case phases::Assemble: + return new AssembleJobAction(Input, types::TY_Object); + } + + llvm_unreachable("invalid phase in ConstructPhaseAction"); +} + +bool Driver::IsUsingLTO(const ArgList &Args) const { + // Check for -emit-llvm or -flto. + if (Args.hasArg(options::OPT_emit_llvm) || + Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false)) + return true; + + // Check for -O4. + if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) + return A->getOption().matches(options::OPT_O4); + + return false; +} + +void Driver::BuildJobs(Compilation &C) const { + llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); + + Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o); + + // It is an error to provide a -o option if we are making multiple output + // files. + if (FinalOutput) { + unsigned NumOutputs = 0; + for (ActionList::const_iterator it = C.getActions().begin(), + ie = C.getActions().end(); it != ie; ++it) + if ((*it)->getType() != types::TY_Nothing) + ++NumOutputs; + + if (NumOutputs > 1) { + Diag(clang::diag::err_drv_output_argument_with_multiple_files); + FinalOutput = 0; + } + } + + for (ActionList::const_iterator it = C.getActions().begin(), + ie = C.getActions().end(); it != ie; ++it) { + Action *A = *it; + + // If we are linking an image for multiple archs then the linker wants + // -arch_multiple and -final_output <final image name>. Unfortunately, this + // doesn't fit in cleanly because we have to pass this information down. + // + // FIXME: This is a hack; find a cleaner way to integrate this into the + // process. + const char *LinkingOutput = 0; + if (isa<LipoJobAction>(A)) { + if (FinalOutput) + LinkingOutput = FinalOutput->getValue(C.getArgs()); + else + LinkingOutput = DefaultImageName.c_str(); + } + + InputInfo II; + BuildJobsForAction(C, A, &C.getDefaultToolChain(), + /*BoundArch*/0, + /*AtTopLevel*/ true, + /*LinkingOutput*/ LinkingOutput, + II); + } + + // If the user passed -Qunused-arguments or there were errors, don't warn + // about any unused arguments. + if (Diags.hasErrorOccurred() || + C.getArgs().hasArg(options::OPT_Qunused_arguments)) + return; + + // Claim -### here. + (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH); + + for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end(); + it != ie; ++it) { + Arg *A = *it; + + // FIXME: It would be nice to be able to send the argument to the + // DiagnosticsEngine, so that extra values, position, and so on could be + // printed. + if (!A->isClaimed()) { + if (A->getOption().hasNoArgumentUnused()) + continue; + + // Suppress the warning automatically if this is just a flag, and it is an + // instance of an argument we already claimed. + const Option &Opt = A->getOption(); + if (isa<FlagOption>(Opt)) { + bool DuplicateClaimed = false; + + for (arg_iterator it = C.getArgs().filtered_begin(&Opt), + ie = C.getArgs().filtered_end(); it != ie; ++it) { + if ((*it)->isClaimed()) { + DuplicateClaimed = true; + break; + } + } + + if (DuplicateClaimed) + continue; + } + + Diag(clang::diag::warn_drv_unused_argument) + << A->getAsString(C.getArgs()); + } + } +} + +static const Tool &SelectToolForJob(Compilation &C, const ToolChain *TC, + const JobAction *JA, + const ActionList *&Inputs) { + const Tool *ToolForJob = 0; + + // See if we should look for a compiler with an integrated assembler. We match + // bottom up, so what we are actually looking for is an assembler job with a + // compiler input. + + if (C.getArgs().hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + TC->IsIntegratedAssemblerDefault()) && + !C.getArgs().hasArg(options::OPT_save_temps) && + isa<AssembleJobAction>(JA) && + Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) { + const Tool &Compiler = TC->SelectTool( + C, cast<JobAction>(**Inputs->begin()), (*Inputs)[0]->getInputs()); + if (Compiler.hasIntegratedAssembler()) { + Inputs = &(*Inputs)[0]->getInputs(); + ToolForJob = &Compiler; + } + } + + // Otherwise use the tool for the current job. + if (!ToolForJob) + ToolForJob = &TC->SelectTool(C, *JA, *Inputs); + + // See if we should use an integrated preprocessor. We do so when we have + // exactly one input, since this is the only use case we care about + // (irrelevant since we don't support combine yet). + if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) && + !C.getArgs().hasArg(options::OPT_no_integrated_cpp) && + !C.getArgs().hasArg(options::OPT_traditional_cpp) && + !C.getArgs().hasArg(options::OPT_save_temps) && + ToolForJob->hasIntegratedCPP()) + Inputs = &(*Inputs)[0]->getInputs(); + + return *ToolForJob; +} + +void Driver::BuildJobsForAction(Compilation &C, + const Action *A, + const ToolChain *TC, + const char *BoundArch, + bool AtTopLevel, + const char *LinkingOutput, + InputInfo &Result) const { + llvm::PrettyStackTraceString CrashInfo("Building compilation jobs"); + + if (const InputAction *IA = dyn_cast<InputAction>(A)) { + // FIXME: It would be nice to not claim this here; maybe the old scheme of + // just using Args was better? + const Arg &Input = IA->getInputArg(); + Input.claim(); + if (Input.getOption().matches(options::OPT_INPUT)) { + const char *Name = Input.getValue(C.getArgs()); + Result = InputInfo(Name, A->getType(), Name); + } else + Result = InputInfo(&Input, A->getType(), ""); + return; + } + + if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { + const ToolChain *TC = &C.getDefaultToolChain(); + + if (BAA->getArchName()) + TC = &getToolChain(C.getArgs(), BAA->getArchName()); + + BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(), + AtTopLevel, LinkingOutput, Result); + return; + } + + const ActionList *Inputs = &A->getInputs(); + + const JobAction *JA = cast<JobAction>(A); + const Tool &T = SelectToolForJob(C, TC, JA, Inputs); + + // Only use pipes when there is exactly one input. + InputInfoList InputInfos; + for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end(); + it != ie; ++it) { + // Treat dsymutil sub-jobs as being at the top-level too, they shouldn't get + // temporary output names. + // + // FIXME: Clean this up. + bool SubJobAtTopLevel = false; + if (AtTopLevel && isa<DsymutilJobAction>(A)) + SubJobAtTopLevel = true; + + // Also treat verify sub-jobs as being at the top-level. They don't + // produce any output and so don't need temporary output names. + if (AtTopLevel && isa<VerifyJobAction>(A)) + SubJobAtTopLevel = true; + + InputInfo II; + BuildJobsForAction(C, *it, TC, BoundArch, + SubJobAtTopLevel, LinkingOutput, II); + InputInfos.push_back(II); + } + + // Always use the first input as the base input. + const char *BaseInput = InputInfos[0].getBaseInput(); + + // ... except dsymutil actions, which use their actual input as the base + // input. + if (JA->getType() == types::TY_dSYM) + BaseInput = InputInfos[0].getFilename(); + + // Determine the place to write output to, if any. + if (JA->getType() == types::TY_Nothing) { + Result = InputInfo(A->getType(), BaseInput); + } else { + Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel), + A->getType(), BaseInput); + } + + if (CCCPrintBindings && !CCGenDiagnostics) { + llvm::errs() << "# \"" << T.getToolChain().getTripleString() << '"' + << " - \"" << T.getName() << "\", inputs: ["; + for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) { + llvm::errs() << InputInfos[i].getAsString(); + if (i + 1 != e) + llvm::errs() << ", "; + } + llvm::errs() << "], output: " << Result.getAsString() << "\n"; + } else { + T.ConstructJob(C, *JA, Result, InputInfos, + C.getArgsForToolChain(TC, BoundArch), LinkingOutput); + } +} + +const char *Driver::GetNamedOutputPath(Compilation &C, + const JobAction &JA, + const char *BaseInput, + bool AtTopLevel) const { + llvm::PrettyStackTraceString CrashInfo("Computing output path"); + // Output to a user requested destination? + if (AtTopLevel && !isa<DsymutilJobAction>(JA) && + !isa<VerifyJobAction>(JA)) { + if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o)) + return C.addResultFile(FinalOutput->getValue(C.getArgs())); + } + + // Default to writing to stdout? + if (AtTopLevel && isa<PreprocessJobAction>(JA) && !CCGenDiagnostics) + return "-"; + + // Output to a temporary file? + if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps)) || + CCGenDiagnostics) { + StringRef Name = llvm::sys::path::filename(BaseInput); + std::pair<StringRef, StringRef> Split = Name.split('.'); + std::string TmpName = + GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); + return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); + } + + SmallString<128> BasePath(BaseInput); + StringRef BaseName; + + // Dsymutil actions should use the full path. + if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA)) + BaseName = BasePath; + else + BaseName = llvm::sys::path::filename(BasePath); + + // Determine what the derived output name should be. + const char *NamedOutput; + if (JA.getType() == types::TY_Image) { + NamedOutput = DefaultImageName.c_str(); + } else { + const char *Suffix = types::getTypeTempSuffix(JA.getType()); + assert(Suffix && "All types used for output should have a suffix."); + + std::string::size_type End = std::string::npos; + if (!types::appendSuffixForType(JA.getType())) + End = BaseName.rfind('.'); + std::string Suffixed(BaseName.substr(0, End)); + Suffixed += '.'; + Suffixed += Suffix; + NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str()); + } + + // If we're saving temps and the temp filename conflicts with the input + // filename, then avoid overwriting input file. + if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) && + NamedOutput == BaseName) { + StringRef Name = llvm::sys::path::filename(BaseInput); + std::pair<StringRef, StringRef> Split = Name.split('.'); + std::string TmpName = + GetTemporaryPath(Split.first, types::getTypeTempSuffix(JA.getType())); + return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())); + } + + // As an annoying special case, PCH generation doesn't strip the pathname. + if (JA.getType() == types::TY_PCH) { + llvm::sys::path::remove_filename(BasePath); + if (BasePath.empty()) + BasePath = NamedOutput; + else + llvm::sys::path::append(BasePath, NamedOutput); + return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str())); + } else { + return C.addResultFile(NamedOutput); + } +} + +std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const { + // Respect a limited subset of the '-Bprefix' functionality in GCC by + // attempting to use this prefix when lokup up program paths. + for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), + ie = PrefixDirs.end(); it != ie; ++it) { + std::string Dir(*it); + if (Dir.empty()) + continue; + if (Dir[0] == '=') + Dir = SysRoot + Dir.substr(1); + llvm::sys::Path P(Dir); + P.appendComponent(Name); + bool Exists; + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + return P.str(); + } + + llvm::sys::Path P(ResourceDir); + P.appendComponent(Name); + bool Exists; + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + return P.str(); + + const ToolChain::path_list &List = TC.getFilePaths(); + for (ToolChain::path_list::const_iterator + it = List.begin(), ie = List.end(); it != ie; ++it) { + std::string Dir(*it); + if (Dir.empty()) + continue; + if (Dir[0] == '=') + Dir = SysRoot + Dir.substr(1); + llvm::sys::Path P(Dir); + P.appendComponent(Name); + bool Exists; + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + return P.str(); + } + + return Name; +} + +static bool isPathExecutable(llvm::sys::Path &P, bool WantFile) { + bool Exists; + return (WantFile ? !llvm::sys::fs::exists(P.str(), Exists) && Exists + : P.canExecute()); +} + +std::string Driver::GetProgramPath(const char *Name, const ToolChain &TC, + bool WantFile) const { + // FIXME: Needs a better variable than DefaultTargetTriple + std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name); + // Respect a limited subset of the '-Bprefix' functionality in GCC by + // attempting to use this prefix when lokup up program paths. + for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), + ie = PrefixDirs.end(); it != ie; ++it) { + llvm::sys::Path P(*it); + P.appendComponent(TargetSpecificExecutable); + if (isPathExecutable(P, WantFile)) return P.str(); + P.eraseComponent(); + P.appendComponent(Name); + if (isPathExecutable(P, WantFile)) return P.str(); + } + + const ToolChain::path_list &List = TC.getProgramPaths(); + for (ToolChain::path_list::const_iterator + it = List.begin(), ie = List.end(); it != ie; ++it) { + llvm::sys::Path P(*it); + P.appendComponent(TargetSpecificExecutable); + if (isPathExecutable(P, WantFile)) return P.str(); + P.eraseComponent(); + P.appendComponent(Name); + if (isPathExecutable(P, WantFile)) return P.str(); + } + + // If all else failed, search the path. + llvm::sys::Path + P(llvm::sys::Program::FindProgramByName(TargetSpecificExecutable)); + if (!P.empty()) + return P.str(); + + P = llvm::sys::Path(llvm::sys::Program::FindProgramByName(Name)); + if (!P.empty()) + return P.str(); + + return Name; +} + +std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix) + const { + // FIXME: This is lame; sys::Path should provide this function (in particular, + // it should know how to find the temporary files dir). + std::string Error; + const char *TmpDir = ::getenv("TMPDIR"); + if (!TmpDir) + TmpDir = ::getenv("TEMP"); + if (!TmpDir) + TmpDir = ::getenv("TMP"); + if (!TmpDir) + TmpDir = "/tmp"; + llvm::sys::Path P(TmpDir); + P.appendComponent(Prefix); + if (P.makeUnique(false, &Error)) { + Diag(clang::diag::err_drv_unable_to_make_temp) << Error; + return ""; + } + + // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. + P.eraseFromDisk(false, 0); + + P.appendSuffix(Suffix); + return P.str(); +} + +/// \brief Compute target triple from args. +/// +/// This routine provides the logic to compute a target triple from various +/// args passed to the driver and the default triple string. +static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple, + const ArgList &Args, + StringRef DarwinArchName) { + // FIXME: Already done in Compilation *Driver::BuildCompilation + if (const Arg *A = Args.getLastArg(options::OPT_target)) + DefaultTargetTriple = A->getValue(Args); + + llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple)); + + // Handle Darwin-specific options available here. + if (Target.isOSDarwin()) { + // If an explict Darwin arch name is given, that trumps all. + if (!DarwinArchName.empty()) { + Target.setArch( + llvm::Triple::getArchTypeForDarwinArchName(DarwinArchName)); + return Target; + } + + // Handle the Darwin '-arch' flag. + if (Arg *A = Args.getLastArg(options::OPT_arch)) { + llvm::Triple::ArchType DarwinArch + = llvm::Triple::getArchTypeForDarwinArchName(A->getValue(Args)); + if (DarwinArch != llvm::Triple::UnknownArch) + Target.setArch(DarwinArch); + } + } + + // Skip further flag support on OSes which don't support '-m32' or '-m64'. + if (Target.getArchName() == "tce" || + Target.getOS() == llvm::Triple::AuroraUX || + Target.getOS() == llvm::Triple::Minix) + return Target; + + // Handle pseudo-target flags '-m32' and '-m64'. + // FIXME: Should this information be in llvm::Triple? + if (Arg *A = Args.getLastArg(options::OPT_m32, options::OPT_m64)) { + if (A->getOption().matches(options::OPT_m32)) { + if (Target.getArch() == llvm::Triple::x86_64) + Target.setArch(llvm::Triple::x86); + if (Target.getArch() == llvm::Triple::ppc64) + Target.setArch(llvm::Triple::ppc); + } else { + if (Target.getArch() == llvm::Triple::x86) + Target.setArch(llvm::Triple::x86_64); + if (Target.getArch() == llvm::Triple::ppc) + Target.setArch(llvm::Triple::ppc64); + } + } + + return Target; +} + +const ToolChain &Driver::getToolChain(const ArgList &Args, + StringRef DarwinArchName) const { + llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args, + DarwinArchName); + + ToolChain *&TC = ToolChains[Target.str()]; + if (!TC) { + switch (Target.getOS()) { + case llvm::Triple::AuroraUX: + TC = new toolchains::AuroraUX(*this, Target, Args); + break; + case llvm::Triple::Darwin: + case llvm::Triple::MacOSX: + case llvm::Triple::IOS: + if (Target.getArch() == llvm::Triple::x86 || + Target.getArch() == llvm::Triple::x86_64 || + Target.getArch() == llvm::Triple::arm || + Target.getArch() == llvm::Triple::thumb) + TC = new toolchains::DarwinClang(*this, Target); + else + TC = new toolchains::Darwin_Generic_GCC(*this, Target, Args); + break; + case llvm::Triple::DragonFly: + TC = new toolchains::DragonFly(*this, Target, Args); + break; + case llvm::Triple::OpenBSD: + TC = new toolchains::OpenBSD(*this, Target, Args); + break; + case llvm::Triple::NetBSD: + TC = new toolchains::NetBSD(*this, Target, Args); + break; + case llvm::Triple::FreeBSD: + TC = new toolchains::FreeBSD(*this, Target, Args); + break; + case llvm::Triple::Minix: + TC = new toolchains::Minix(*this, Target, Args); + break; + case llvm::Triple::Linux: + if (Target.getArch() == llvm::Triple::hexagon) + TC = new toolchains::Hexagon_TC(*this, Target); + else + TC = new toolchains::Linux(*this, Target, Args); + break; + case llvm::Triple::Solaris: + TC = new toolchains::Solaris(*this, Target, Args); + break; + case llvm::Triple::Win32: + TC = new toolchains::Windows(*this, Target); + break; + case llvm::Triple::MinGW32: + // FIXME: We need a MinGW toolchain. Fallthrough for now. + default: + // TCE is an OSless target + if (Target.getArchName() == "tce") { + TC = new toolchains::TCEToolChain(*this, Target); + break; + } + + TC = new toolchains::Generic_GCC(*this, Target, Args); + break; + } + } + return *TC; +} + +bool Driver::ShouldUseClangCompiler(const Compilation &C, const JobAction &JA, + const llvm::Triple &Triple) const { + // Check if user requested no clang, or clang doesn't understand this type (we + // only handle single inputs for now). + if (!CCCUseClang || JA.size() != 1 || + !types::isAcceptedByClang((*JA.begin())->getType())) + return false; + + // Otherwise make sure this is an action clang understands. + if (isa<PreprocessJobAction>(JA)) { + if (!CCCUseClangCPP) { + Diag(clang::diag::warn_drv_not_using_clang_cpp); + return false; + } + } else if (!isa<PrecompileJobAction>(JA) && !isa<CompileJobAction>(JA)) + return false; + + // Use clang for C++? + if (!CCCUseClangCXX && types::isCXX((*JA.begin())->getType())) { + Diag(clang::diag::warn_drv_not_using_clang_cxx); + return false; + } + + // Always use clang for precompiling, AST generation, and rewriting, + // regardless of archs. + if (isa<PrecompileJobAction>(JA) || + types::isOnlyAcceptedByClang(JA.getType())) + return true; + + // Finally, don't use clang if this isn't one of the user specified archs to + // build. + if (!CCCClangArchs.empty() && !CCCClangArchs.count(Triple.getArch())) { + Diag(clang::diag::warn_drv_not_using_clang_arch) << Triple.getArchName(); + return false; + } + + return true; +} + +/// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the +/// grouped values as integers. Numbers which are not provided are set to 0. +/// +/// \return True if the entire string was parsed (9.2), or all groups were +/// parsed (10.3.5extrastuff). +bool Driver::GetReleaseVersion(const char *Str, unsigned &Major, + unsigned &Minor, unsigned &Micro, + bool &HadExtra) { + HadExtra = false; + + Major = Minor = Micro = 0; + if (*Str == '\0') + return true; + + char *End; + Major = (unsigned) strtol(Str, &End, 10); + if (*Str != '\0' && *End == '\0') + return true; + if (*End != '.') + return false; + + Str = End+1; + Minor = (unsigned) strtol(Str, &End, 10); + if (*Str != '\0' && *End == '\0') + return true; + if (*End != '.') + return false; + + Str = End+1; + Micro = (unsigned) strtol(Str, &End, 10); + if (*Str != '\0' && *End == '\0') + return true; + if (Str == End) + return false; + HadExtra = true; + return true; +} diff --git a/clang/lib/Driver/DriverOptions.cpp b/clang/lib/Driver/DriverOptions.cpp new file mode 100644 index 0000000..715819d --- /dev/null +++ b/clang/lib/Driver/DriverOptions.cpp @@ -0,0 +1,37 @@ +//===--- DriverOptions.cpp - Driver Options Table -------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Options.h" +#include "clang/Driver/OptTable.h" +#include "clang/Driver/Option.h" + +using namespace clang::driver; +using namespace clang::driver::options; + +static const OptTable::Info InfoTable[] = { +#define OPTION(NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ + HELPTEXT, METAVAR) \ + { NAME, HELPTEXT, METAVAR, Option::KIND##Class, PARAM, FLAGS, \ + OPT_##GROUP, OPT_##ALIAS }, +#include "clang/Driver/Options.inc" +}; + +namespace { + +class DriverOptTable : public OptTable { +public: + DriverOptTable() + : OptTable(InfoTable, sizeof(InfoTable) / sizeof(InfoTable[0])) {} +}; + +} + +OptTable *clang::driver::createDriverOptTable() { + return new DriverOptTable(); +} diff --git a/clang/lib/Driver/InputInfo.h b/clang/lib/Driver/InputInfo.h new file mode 100644 index 0000000..2a2f4b9 --- /dev/null +++ b/clang/lib/Driver/InputInfo.h @@ -0,0 +1,88 @@ +//===--- InputInfo.h - Input Source & Type Information ----------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef CLANG_LIB_DRIVER_INPUTINFO_H_ +#define CLANG_LIB_DRIVER_INPUTINFO_H_ + +#include "clang/Driver/Types.h" + +#include <cassert> +#include <string> + +namespace clang { +namespace driver { + +/// InputInfo - Wrapper for information about an input source. +class InputInfo { + // FIXME: The distinction between filenames and inputarg here is + // gross; we should probably drop the idea of a "linker + // input". Doing so means tweaking pipelining to still create link + // steps when it sees linker inputs (but not treat them as + // arguments), and making sure that arguments get rendered + // correctly. + enum Class { + Nothing, + Filename, + InputArg, + Pipe + }; + + union { + const char *Filename; + const Arg *InputArg; + } Data; + Class Kind; + types::ID Type; + const char *BaseInput; + +public: + InputInfo() {} + InputInfo(types::ID _Type, const char *_BaseInput) + : Kind(Nothing), Type(_Type), BaseInput(_BaseInput) { + } + InputInfo(const char *_Filename, types::ID _Type, const char *_BaseInput) + : Kind(Filename), Type(_Type), BaseInput(_BaseInput) { + Data.Filename = _Filename; + } + InputInfo(const Arg *_InputArg, types::ID _Type, const char *_BaseInput) + : Kind(InputArg), Type(_Type), BaseInput(_BaseInput) { + Data.InputArg = _InputArg; + } + + bool isNothing() const { return Kind == Nothing; } + bool isFilename() const { return Kind == Filename; } + bool isInputArg() const { return Kind == InputArg; } + types::ID getType() const { return Type; } + const char *getBaseInput() const { return BaseInput; } + + const char *getFilename() const { + assert(isFilename() && "Invalid accessor."); + return Data.Filename; + } + const Arg &getInputArg() const { + assert(isInputArg() && "Invalid accessor."); + return *Data.InputArg; + } + + /// getAsString - Return a string name for this input, for + /// debugging. + std::string getAsString() const { + if (isFilename()) + return std::string("\"") + getFilename() + '"'; + else if (isInputArg()) + return "(input arg)"; + else + return "(nothing)"; + } +}; + +} // end namespace driver +} // end namespace clang + +#endif diff --git a/clang/lib/Driver/Job.cpp b/clang/lib/Driver/Job.cpp new file mode 100644 index 0000000..825c86a --- /dev/null +++ b/clang/lib/Driver/Job.cpp @@ -0,0 +1,42 @@ +//===--- Job.cpp - Command to Execute -------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Job.h" + +#include "llvm/ADT/STLExtras.h" + +#include <cassert> +using namespace clang::driver; + +Job::~Job() {} + +void Command::anchor() {} + +Command::Command(const Action &_Source, const Tool &_Creator, + const char *_Executable, const ArgStringList &_Arguments) + : Job(CommandClass), Source(_Source), Creator(_Creator), + Executable(_Executable), Arguments(_Arguments) +{ +} + +JobList::JobList() : Job(JobListClass) {} + +JobList::~JobList() { + for (iterator it = begin(), ie = end(); it != ie; ++it) + delete *it; +} + +void JobList::clear() { + DeleteContainerPointers(Jobs); +} + +void Job::addCommand(Command *C) { + cast<JobList>(this)->addJob(C); +} + diff --git a/clang/lib/Driver/Makefile b/clang/lib/Driver/Makefile new file mode 100644 index 0000000..454ab86 --- /dev/null +++ b/clang/lib/Driver/Makefile @@ -0,0 +1,13 @@ +##===- clang/lib/Driver/Makefile ---------------------------*- Makefile -*-===## +# +# The LLVM Compiler Infrastructure +# +# This file is distributed under the University of Illinois Open Source +# License. See LICENSE.TXT for details. +# +##===----------------------------------------------------------------------===## + +CLANG_LEVEL := ../.. +LIBRARYNAME := clangDriver + +include $(CLANG_LEVEL)/Makefile diff --git a/clang/lib/Driver/OptTable.cpp b/clang/lib/Driver/OptTable.cpp new file mode 100644 index 0000000..4f5390b --- /dev/null +++ b/clang/lib/Driver/OptTable.cpp @@ -0,0 +1,384 @@ +//===--- OptTable.cpp - Option Table 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/OptTable.h" +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Option.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/ErrorHandling.h" +#include <algorithm> +#include <map> +using namespace clang::driver; +using namespace clang::driver::options; +using namespace clang; + +// Ordering on Info. The ordering is *almost* lexicographic, with two +// exceptions. First, '\0' comes at the end of the alphabet instead of +// the beginning (thus options precede any other options which prefix +// them). Second, for options with the same name, the less permissive +// version should come first; a Flag option should precede a Joined +// option, for example. + +static int StrCmpOptionName(const char *A, const char *B) { + char a = *A, b = *B; + while (a == b) { + if (a == '\0') + return 0; + + a = *++A; + b = *++B; + } + + if (a == '\0') // A is a prefix of B. + return 1; + if (b == '\0') // B is a prefix of A. + return -1; + + // Otherwise lexicographic. + return (a < b) ? -1 : 1; +} + +namespace clang { +namespace driver { +static inline bool operator<(const OptTable::Info &A, const OptTable::Info &B) { + if (&A == &B) + return false; + + if (int N = StrCmpOptionName(A.Name, B.Name)) + return N == -1; + + // Names are the same, check that classes are in order; exactly one + // should be joined, and it should succeed the other. + assert(((A.Kind == Option::JoinedClass) ^ (B.Kind == Option::JoinedClass)) && + "Unexpected classes for options with same name."); + return B.Kind == Option::JoinedClass; +} + +// Support lower_bound between info and an option name. +static inline bool operator<(const OptTable::Info &I, const char *Name) { + return StrCmpOptionName(I.Name, Name) == -1; +} +static inline bool operator<(const char *Name, const OptTable::Info &I) { + return StrCmpOptionName(Name, I.Name) == -1; +} +} +} + +// + +OptSpecifier::OptSpecifier(const Option *Opt) : ID(Opt->getID()) {} + +// + +OptTable::OptTable(const Info *_OptionInfos, unsigned _NumOptionInfos) + : OptionInfos(_OptionInfos), NumOptionInfos(_NumOptionInfos), + Options(new Option*[NumOptionInfos]), + TheInputOption(0), TheUnknownOption(0), FirstSearchableIndex(0) +{ + // Explicitly zero initialize the error to work around a bug in array + // value-initialization on MinGW with gcc 4.3.5. + memset(Options, 0, sizeof(*Options) * NumOptionInfos); + + // Find start of normal options. + for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { + unsigned Kind = getInfo(i + 1).Kind; + if (Kind == Option::InputClass) { + assert(!TheInputOption && "Cannot have multiple input options!"); + TheInputOption = getOption(i + 1); + } else if (Kind == Option::UnknownClass) { + assert(!TheUnknownOption && "Cannot have multiple input options!"); + TheUnknownOption = getOption(i + 1); + } else if (Kind != Option::GroupClass) { + FirstSearchableIndex = i; + break; + } + } + assert(FirstSearchableIndex != 0 && "No searchable options?"); + +#ifndef NDEBUG + // Check that everything after the first searchable option is a + // regular option class. + for (unsigned i = FirstSearchableIndex, e = getNumOptions(); i != e; ++i) { + Option::OptionClass Kind = (Option::OptionClass) getInfo(i + 1).Kind; + assert((Kind != Option::InputClass && Kind != Option::UnknownClass && + Kind != Option::GroupClass) && + "Special options should be defined first!"); + } + + // Check that options are in order. + for (unsigned i = FirstSearchableIndex+1, e = getNumOptions(); i != e; ++i) { + if (!(getInfo(i) < getInfo(i + 1))) { + getOption(i)->dump(); + getOption(i + 1)->dump(); + llvm_unreachable("Options are not in order!"); + } + } +#endif +} + +OptTable::~OptTable() { + for (unsigned i = 0, e = getNumOptions(); i != e; ++i) + delete Options[i]; + delete[] Options; +} + +Option *OptTable::CreateOption(unsigned id) const { + const Info &info = getInfo(id); + const OptionGroup *Group = + cast_or_null<OptionGroup>(getOption(info.GroupID)); + const Option *Alias = getOption(info.AliasID); + + Option *Opt = 0; + switch (info.Kind) { + case Option::InputClass: + Opt = new InputOption(id); break; + case Option::UnknownClass: + Opt = new UnknownOption(id); break; + case Option::GroupClass: + Opt = new OptionGroup(id, info.Name, Group); break; + case Option::FlagClass: + Opt = new FlagOption(id, info.Name, Group, Alias); break; + case Option::JoinedClass: + Opt = new JoinedOption(id, info.Name, Group, Alias); break; + case Option::SeparateClass: + Opt = new SeparateOption(id, info.Name, Group, Alias); break; + case Option::CommaJoinedClass: + Opt = new CommaJoinedOption(id, info.Name, Group, Alias); break; + case Option::MultiArgClass: + Opt = new MultiArgOption(id, info.Name, Group, Alias, info.Param); break; + case Option::JoinedOrSeparateClass: + Opt = new JoinedOrSeparateOption(id, info.Name, Group, Alias); break; + case Option::JoinedAndSeparateClass: + Opt = new JoinedAndSeparateOption(id, info.Name, Group, Alias); break; + } + + if (info.Flags & DriverOption) + Opt->setDriverOption(true); + if (info.Flags & LinkerInput) + Opt->setLinkerInput(true); + if (info.Flags & NoArgumentUnused) + Opt->setNoArgumentUnused(true); + if (info.Flags & NoForward) + Opt->setNoForward(true); + if (info.Flags & RenderAsInput) + Opt->setNoOptAsInput(true); + if (info.Flags & RenderJoined) { + assert((info.Kind == Option::JoinedOrSeparateClass || + info.Kind == Option::SeparateClass) && "Invalid option."); + Opt->setRenderStyle(Option::RenderJoinedStyle); + } + if (info.Flags & RenderSeparate) { + assert((info.Kind == Option::JoinedOrSeparateClass || + info.Kind == Option::JoinedClass) && "Invalid option."); + Opt->setRenderStyle(Option::RenderSeparateStyle); + } + if (info.Flags & Unsupported) + Opt->setUnsupported(true); + + return Opt; +} + +Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index) const { + unsigned Prev = Index; + const char *Str = Args.getArgString(Index); + + // Anything that doesn't start with '-' is an input, as is '-' itself. + if (Str[0] != '-' || Str[1] == '\0') + return new Arg(TheInputOption, Index++, Str); + + const Info *Start = OptionInfos + FirstSearchableIndex; + const Info *End = OptionInfos + getNumOptions(); + + // Search for the first next option which could be a prefix. + Start = std::lower_bound(Start, End, Str); + + // Options are stored in sorted order, with '\0' at the end of the + // alphabet. Since the only options which can accept a string must + // prefix it, we iteratively search for the next option which could + // be a prefix. + // + // FIXME: This is searching much more than necessary, but I am + // blanking on the simplest way to make it fast. We can solve this + // problem when we move to TableGen. + for (; Start != End; ++Start) { + // Scan for first option which is a proper prefix. + for (; Start != End; ++Start) + if (memcmp(Str, Start->Name, strlen(Start->Name)) == 0) + break; + if (Start == End) + break; + + // See if this option matches. + if (Arg *A = getOption(Start - OptionInfos + 1)->accept(Args, Index)) + return A; + + // Otherwise, see if this argument was missing values. + if (Prev != Index) + return 0; + } + + return new Arg(TheUnknownOption, Index++, Str); +} + +InputArgList *OptTable::ParseArgs(const char* const *ArgBegin, + const char* const *ArgEnd, + unsigned &MissingArgIndex, + unsigned &MissingArgCount) const { + InputArgList *Args = new InputArgList(ArgBegin, ArgEnd); + + // FIXME: Handle '@' args (or at least error on them). + + MissingArgIndex = MissingArgCount = 0; + unsigned Index = 0, End = ArgEnd - ArgBegin; + while (Index < End) { + // Ignore empty arguments (other things may still take them as arguments). + if (Args->getArgString(Index)[0] == '\0') { + ++Index; + continue; + } + + unsigned Prev = Index; + Arg *A = ParseOneArg(*Args, Index); + assert(Index > Prev && "Parser failed to consume argument."); + + // Check for missing argument error. + if (!A) { + assert(Index >= End && "Unexpected parser error."); + assert(Index - Prev - 1 && "No missing arguments!"); + MissingArgIndex = Prev; + MissingArgCount = Index - Prev - 1; + break; + } + + Args->append(A); + } + + return Args; +} + +static std::string getOptionHelpName(const OptTable &Opts, OptSpecifier Id) { + std::string Name = Opts.getOptionName(Id); + + // Add metavar, if used. + switch (Opts.getOptionKind(Id)) { + case Option::GroupClass: case Option::InputClass: case Option::UnknownClass: + llvm_unreachable("Invalid option with help text."); + + case Option::MultiArgClass: + llvm_unreachable("Cannot print metavar for this kind of option."); + + case Option::FlagClass: + break; + + case Option::SeparateClass: case Option::JoinedOrSeparateClass: + Name += ' '; + // FALLTHROUGH + case Option::JoinedClass: case Option::CommaJoinedClass: + case Option::JoinedAndSeparateClass: + if (const char *MetaVarName = Opts.getOptionMetaVar(Id)) + Name += MetaVarName; + else + Name += "<value>"; + break; + } + + return Name; +} + +static void PrintHelpOptionList(raw_ostream &OS, StringRef Title, + std::vector<std::pair<std::string, + const char*> > &OptionHelp) { + OS << Title << ":\n"; + + // Find the maximum option length. + unsigned OptionFieldWidth = 0; + for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { + // Skip titles. + if (!OptionHelp[i].second) + continue; + + // Limit the amount of padding we are willing to give up for alignment. + unsigned Length = OptionHelp[i].first.size(); + if (Length <= 23) + OptionFieldWidth = std::max(OptionFieldWidth, Length); + } + + const unsigned InitialPad = 2; + for (unsigned i = 0, e = OptionHelp.size(); i != e; ++i) { + const std::string &Option = OptionHelp[i].first; + int Pad = OptionFieldWidth - int(Option.size()); + OS.indent(InitialPad) << Option; + + // Break on long option names. + if (Pad < 0) { + OS << "\n"; + Pad = OptionFieldWidth + InitialPad; + } + OS.indent(Pad + 1) << OptionHelp[i].second << '\n'; + } +} + +static const char *getOptionHelpGroup(const OptTable &Opts, OptSpecifier Id) { + unsigned GroupID = Opts.getOptionGroupID(Id); + + // If not in a group, return the default help group. + if (!GroupID) + return "OPTIONS"; + + // Abuse the help text of the option groups to store the "help group" + // name. + // + // FIXME: Split out option groups. + if (const char *GroupHelp = Opts.getOptionHelpText(GroupID)) + return GroupHelp; + + // Otherwise keep looking. + return getOptionHelpGroup(Opts, GroupID); +} + +void OptTable::PrintHelp(raw_ostream &OS, const char *Name, + const char *Title, bool ShowHidden) const { + OS << "OVERVIEW: " << Title << "\n"; + OS << '\n'; + OS << "USAGE: " << Name << " [options] <inputs>\n"; + OS << '\n'; + + // Render help text into a map of group-name to a list of (option, help) + // pairs. + typedef std::map<std::string, + std::vector<std::pair<std::string, const char*> > > helpmap_ty; + helpmap_ty GroupedOptionHelp; + + for (unsigned i = 0, e = getNumOptions(); i != e; ++i) { + unsigned Id = i + 1; + + // FIXME: Split out option groups. + if (getOptionKind(Id) == Option::GroupClass) + continue; + + if (!ShowHidden && isOptionHelpHidden(Id)) + continue; + + if (const char *Text = getOptionHelpText(Id)) { + const char *HelpGroup = getOptionHelpGroup(*this, Id); + const std::string &OptName = getOptionHelpName(*this, Id); + GroupedOptionHelp[HelpGroup].push_back(std::make_pair(OptName, Text)); + } + } + + for (helpmap_ty::iterator it = GroupedOptionHelp .begin(), + ie = GroupedOptionHelp.end(); it != ie; ++it) { + if (it != GroupedOptionHelp .begin()) + OS << "\n"; + PrintHelpOptionList(OS, it->first, it->second); + } + + OS.flush(); +} diff --git a/clang/lib/Driver/Option.cpp b/clang/lib/Driver/Option.cpp new file mode 100644 index 0000000..03360ea --- /dev/null +++ b/clang/lib/Driver/Option.cpp @@ -0,0 +1,280 @@ +//===--- Option.cpp - Abstract Driver Options -----------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Option.h" + +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/ErrorHandling.h" +#include <cassert> +#include <algorithm> +using namespace clang::driver; + +Option::Option(OptionClass _Kind, OptSpecifier _ID, const char *_Name, + const OptionGroup *_Group, const Option *_Alias) + : Kind(_Kind), ID(_ID.getID()), Name(_Name), Group(_Group), Alias(_Alias), + Unsupported(false), LinkerInput(false), NoOptAsInput(false), + DriverOption(false), NoArgumentUnused(false), NoForward(false) { + + // Multi-level aliases are not supported, and alias options cannot + // have groups. This just simplifies option tracking, it is not an + // inherent limitation. + assert((!Alias || (!Alias->Alias && !Group)) && + "Multi-level aliases and aliases with groups are unsupported."); + + // Initialize rendering options based on the class. + switch (Kind) { + case GroupClass: + case InputClass: + case UnknownClass: + RenderStyle = RenderValuesStyle; + break; + + case JoinedClass: + case JoinedAndSeparateClass: + RenderStyle = RenderJoinedStyle; + break; + + case CommaJoinedClass: + RenderStyle = RenderCommaJoinedStyle; + break; + + case FlagClass: + case SeparateClass: + case MultiArgClass: + case JoinedOrSeparateClass: + RenderStyle = RenderSeparateStyle; + break; + } +} + +Option::~Option() { +} + +void Option::dump() const { + llvm::errs() << "<"; + switch (Kind) { +#define P(N) case N: llvm::errs() << #N; break + P(GroupClass); + P(InputClass); + P(UnknownClass); + P(FlagClass); + P(JoinedClass); + P(SeparateClass); + P(CommaJoinedClass); + P(MultiArgClass); + P(JoinedOrSeparateClass); + P(JoinedAndSeparateClass); +#undef P + } + + llvm::errs() << " Name:\"" << Name << '"'; + + if (Group) { + llvm::errs() << " Group:"; + Group->dump(); + } + + if (Alias) { + llvm::errs() << " Alias:"; + Alias->dump(); + } + + if (const MultiArgOption *MOA = dyn_cast<MultiArgOption>(this)) + llvm::errs() << " NumArgs:" << MOA->getNumArgs(); + + llvm::errs() << ">\n"; +} + +bool Option::matches(OptSpecifier Opt) const { + // Aliases are never considered in matching, look through them. + if (Alias) + return Alias->matches(Opt); + + // Check exact match. + if (ID == Opt) + return true; + + if (Group) + return Group->matches(Opt); + return false; +} + +OptionGroup::OptionGroup(OptSpecifier ID, const char *Name, + const OptionGroup *Group) + : Option(Option::GroupClass, ID, Name, Group, 0) { +} + +Arg *OptionGroup::accept(const ArgList &Args, unsigned &Index) const { + llvm_unreachable("accept() should never be called on an OptionGroup"); +} + +InputOption::InputOption(OptSpecifier ID) + : Option(Option::InputClass, ID, "<input>", 0, 0) { +} + +Arg *InputOption::accept(const ArgList &Args, unsigned &Index) const { + llvm_unreachable("accept() should never be called on an InputOption"); +} + +UnknownOption::UnknownOption(OptSpecifier ID) + : Option(Option::UnknownClass, ID, "<unknown>", 0, 0) { +} + +Arg *UnknownOption::accept(const ArgList &Args, unsigned &Index) const { + llvm_unreachable("accept() should never be called on an UnknownOption"); +} + +FlagOption::FlagOption(OptSpecifier ID, const char *Name, + const OptionGroup *Group, const Option *Alias) + : Option(Option::FlagClass, ID, Name, Group, Alias) { +} + +Arg *FlagOption::accept(const ArgList &Args, unsigned &Index) const { + // Matches iff this is an exact match. + // FIXME: Avoid strlen. + if (getName().size() != strlen(Args.getArgString(Index))) + return 0; + + return new Arg(getUnaliasedOption(), Index++); +} + +JoinedOption::JoinedOption(OptSpecifier ID, const char *Name, + const OptionGroup *Group, const Option *Alias) + : Option(Option::JoinedClass, ID, Name, Group, Alias) { +} + +Arg *JoinedOption::accept(const ArgList &Args, unsigned &Index) const { + // Always matches. + const char *Value = Args.getArgString(Index) + getName().size(); + return new Arg(getUnaliasedOption(), Index++, Value); +} + +CommaJoinedOption::CommaJoinedOption(OptSpecifier ID, const char *Name, + const OptionGroup *Group, + const Option *Alias) + : Option(Option::CommaJoinedClass, ID, Name, Group, Alias) { +} + +Arg *CommaJoinedOption::accept(const ArgList &Args, + unsigned &Index) const { + // Always matches. + const char *Str = Args.getArgString(Index) + getName().size(); + Arg *A = new Arg(getUnaliasedOption(), Index++); + + // Parse out the comma separated values. + const char *Prev = Str; + for (;; ++Str) { + char c = *Str; + + if (!c || c == ',') { + if (Prev != Str) { + char *Value = new char[Str - Prev + 1]; + memcpy(Value, Prev, Str - Prev); + Value[Str - Prev] = '\0'; + A->getValues().push_back(Value); + } + + if (!c) + break; + + Prev = Str + 1; + } + } + A->setOwnsValues(true); + + return A; +} + +SeparateOption::SeparateOption(OptSpecifier ID, const char *Name, + const OptionGroup *Group, const Option *Alias) + : Option(Option::SeparateClass, ID, Name, Group, Alias) { +} + +Arg *SeparateOption::accept(const ArgList &Args, unsigned &Index) const { + // Matches iff this is an exact match. + // FIXME: Avoid strlen. + if (getName().size() != strlen(Args.getArgString(Index))) + return 0; + + Index += 2; + if (Index > Args.getNumInputArgStrings()) + return 0; + + return new Arg(getUnaliasedOption(), Index - 2, Args.getArgString(Index - 1)); +} + +MultiArgOption::MultiArgOption(OptSpecifier ID, const char *Name, + const OptionGroup *Group, const Option *Alias, + unsigned _NumArgs) + : Option(Option::MultiArgClass, ID, Name, Group, Alias), NumArgs(_NumArgs) { + assert(NumArgs > 1 && "Invalid MultiArgOption!"); +} + +Arg *MultiArgOption::accept(const ArgList &Args, unsigned &Index) const { + // Matches iff this is an exact match. + // FIXME: Avoid strlen. + if (getName().size() != strlen(Args.getArgString(Index))) + return 0; + + Index += 1 + NumArgs; + if (Index > Args.getNumInputArgStrings()) + return 0; + + Arg *A = new Arg(getUnaliasedOption(), Index - 1 - NumArgs, + Args.getArgString(Index - NumArgs)); + for (unsigned i = 1; i != NumArgs; ++i) + A->getValues().push_back(Args.getArgString(Index - NumArgs + i)); + return A; +} + +JoinedOrSeparateOption::JoinedOrSeparateOption(OptSpecifier ID, + const char *Name, + const OptionGroup *Group, + const Option *Alias) + : Option(Option::JoinedOrSeparateClass, ID, Name, Group, Alias) { +} + +Arg *JoinedOrSeparateOption::accept(const ArgList &Args, + unsigned &Index) const { + // If this is not an exact match, it is a joined arg. + // FIXME: Avoid strlen. + if (getName().size() != strlen(Args.getArgString(Index))) { + const char *Value = Args.getArgString(Index) + getName().size(); + return new Arg(this, Index++, Value); + } + + // Otherwise it must be separate. + Index += 2; + if (Index > Args.getNumInputArgStrings()) + return 0; + + return new Arg(getUnaliasedOption(), Index - 2, Args.getArgString(Index - 1)); +} + +JoinedAndSeparateOption::JoinedAndSeparateOption(OptSpecifier ID, + const char *Name, + const OptionGroup *Group, + const Option *Alias) + : Option(Option::JoinedAndSeparateClass, ID, Name, Group, Alias) { +} + +Arg *JoinedAndSeparateOption::accept(const ArgList &Args, + unsigned &Index) const { + // Always matches. + + Index += 2; + if (Index > Args.getNumInputArgStrings()) + return 0; + + return new Arg(getUnaliasedOption(), Index - 2, + Args.getArgString(Index-2)+getName().size(), + Args.getArgString(Index-1)); +} diff --git a/clang/lib/Driver/Phases.cpp b/clang/lib/Driver/Phases.cpp new file mode 100644 index 0000000..b885eee --- /dev/null +++ b/clang/lib/Driver/Phases.cpp @@ -0,0 +1,27 @@ +//===--- Phases.cpp - Transformations on Driver Types ---------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Phases.h" +#include "llvm/Support/ErrorHandling.h" + +#include <cassert> + +using namespace clang::driver; + +const char *phases::getPhaseName(ID Id) { + switch (Id) { + case Preprocess: return "preprocessor"; + case Precompile: return "precompiler"; + case Compile: return "compiler"; + case Assemble: return "assembler"; + case Link: return "linker"; + } + + llvm_unreachable("Invalid phase id."); +} diff --git a/clang/lib/Driver/Tool.cpp b/clang/lib/Driver/Tool.cpp new file mode 100644 index 0000000..b93864f --- /dev/null +++ b/clang/lib/Driver/Tool.cpp @@ -0,0 +1,21 @@ +//===--- Tool.cpp - Compilation Tools -------------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Tool.h" + +using namespace clang::driver; + +Tool::Tool(const char *_Name, const char *_ShortName, + const ToolChain &TC) : Name(_Name), ShortName(_ShortName), + TheToolChain(TC) +{ +} + +Tool::~Tool() { +} diff --git a/clang/lib/Driver/ToolChain.cpp b/clang/lib/Driver/ToolChain.cpp new file mode 100644 index 0000000..db4d2a8 --- /dev/null +++ b/clang/lib/Driver/ToolChain.cpp @@ -0,0 +1,288 @@ +//===--- ToolChain.cpp - Collections of tools for one platform ------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/ToolChain.h" + +#include "clang/Driver/Action.h" +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Driver.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Driver/ObjCRuntime.h" +#include "clang/Driver/Options.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/Support/ErrorHandling.h" +using namespace clang::driver; +using namespace clang; + +ToolChain::ToolChain(const Driver &D, const llvm::Triple &T) + : D(D), Triple(T) { +} + +ToolChain::~ToolChain() { +} + +const Driver &ToolChain::getDriver() const { + return D; +} + +std::string ToolChain::GetFilePath(const char *Name) const { + return D.GetFilePath(Name, *this); + +} + +std::string ToolChain::GetProgramPath(const char *Name, bool WantFile) const { + return D.GetProgramPath(Name, *this, WantFile); +} + +types::ID ToolChain::LookupTypeForExtension(const char *Ext) const { + return types::lookupTypeForExtension(Ext); +} + +bool ToolChain::HasNativeLLVMSupport() const { + return false; +} + +void ToolChain::configureObjCRuntime(ObjCRuntime &runtime) const { + switch (runtime.getKind()) { + case ObjCRuntime::NeXT: + // Assume a minimal NeXT runtime. + runtime.HasARC = false; + runtime.HasWeak = false; + runtime.HasSubscripting = false; + runtime.HasTerminate = false; + return; + + case ObjCRuntime::GNU: + // Assume a maximal GNU runtime. + runtime.HasARC = true; + runtime.HasWeak = true; + runtime.HasSubscripting = false; // to be added + runtime.HasTerminate = false; // to be added + return; + } + llvm_unreachable("invalid runtime kind!"); +} + +/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting. +// +// FIXME: tblgen this. +static const char *getARMTargetCPU(const ArgList &Args, + const llvm::Triple &Triple) { + // For Darwin targets, the -arch option (which is translated to a + // corresponding -march option) should determine the architecture + // (and the Mach-O slice) regardless of any -mcpu options. + if (!Triple.isOSDarwin()) { + // FIXME: Warn on inconsistent use of -mcpu and -march. + // If we have -mcpu=, use that. + if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) + return A->getValue(Args); + } + + StringRef MArch; + if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { + // Otherwise, if we have -march= choose the base CPU for that arch. + MArch = A->getValue(Args); + } else { + // Otherwise, use the Arch from the triple. + MArch = Triple.getArchName(); + } + + return llvm::StringSwitch<const char *>(MArch) + .Cases("armv2", "armv2a","arm2") + .Case("armv3", "arm6") + .Case("armv3m", "arm7m") + .Cases("armv4", "armv4t", "arm7tdmi") + .Cases("armv5", "armv5t", "arm10tdmi") + .Cases("armv5e", "armv5te", "arm1026ejs") + .Case("armv5tej", "arm926ej-s") + .Cases("armv6", "armv6k", "arm1136jf-s") + .Case("armv6j", "arm1136j-s") + .Cases("armv6z", "armv6zk", "arm1176jzf-s") + .Case("armv6t2", "arm1156t2-s") + .Cases("armv7", "armv7a", "armv7-a", "cortex-a8") + .Cases("armv7r", "armv7-r", "cortex-r4") + .Cases("armv7m", "armv7-m", "cortex-m3") + .Case("ep9312", "ep9312") + .Case("iwmmxt", "iwmmxt") + .Case("xscale", "xscale") + .Cases("armv6m", "armv6-m", "cortex-m0") + // If all else failed, return the most base CPU LLVM supports. + .Default("arm7tdmi"); +} + +/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular +/// CPU. +// +// FIXME: This is redundant with -mcpu, why does LLVM use this. +// FIXME: tblgen this, or kill it! +static const char *getLLVMArchSuffixForARM(StringRef CPU) { + return llvm::StringSwitch<const char *>(CPU) + .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t") + .Cases("arm720t", "arm9", "arm9tdmi", "v4t") + .Cases("arm920", "arm920t", "arm922t", "v4t") + .Cases("arm940t", "ep9312","v4t") + .Cases("arm10tdmi", "arm1020t", "v5") + .Cases("arm9e", "arm926ej-s", "arm946e-s", "v5e") + .Cases("arm966e-s", "arm968e-s", "arm10e", "v5e") + .Cases("arm1020e", "arm1022e", "xscale", "iwmmxt", "v5e") + .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "v6") + .Cases("arm1176jzf-s", "mpcorenovfp", "mpcore", "v6") + .Cases("arm1156t2-s", "arm1156t2f-s", "v6t2") + .Cases("cortex-a8", "cortex-a9", "v7") + .Case("cortex-m3", "v7m") + .Case("cortex-m4", "v7m") + .Case("cortex-m0", "v6m") + .Default(""); +} + +std::string ToolChain::ComputeLLVMTriple(const ArgList &Args, + types::ID InputType) const { + switch (getTriple().getArch()) { + default: + return getTripleString(); + + case llvm::Triple::arm: + case llvm::Triple::thumb: { + // FIXME: Factor into subclasses. + llvm::Triple Triple = getTriple(); + + // Thumb2 is the default for V7 on Darwin. + // + // FIXME: Thumb should just be another -target-feaure, not in the triple. + StringRef Suffix = + getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple)); + bool ThumbDefault = (Suffix == "v7" && getTriple().isOSDarwin()); + std::string ArchName = "arm"; + + // Assembly files should start in ARM mode. + if (InputType != types::TY_PP_Asm && + Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault)) + ArchName = "thumb"; + Triple.setArchName(ArchName + Suffix.str()); + + return Triple.getTriple(); + } + } +} + +std::string ToolChain::ComputeEffectiveClangTriple(const ArgList &Args, + types::ID InputType) const { + // Diagnose use of Darwin OS deployment target arguments on non-Darwin. + if (Arg *A = Args.getLastArg(options::OPT_mmacosx_version_min_EQ, + options::OPT_miphoneos_version_min_EQ, + options::OPT_mios_simulator_version_min_EQ)) + getDriver().Diag(diag::err_drv_clang_unsupported) + << A->getAsString(Args); + + return ComputeLLVMTriple(Args, InputType); +} + +void ToolChain::AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + // Each toolchain should provide the appropriate include flags. +} + +ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( + const ArgList &Args) const +{ + if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) { + StringRef Value = A->getValue(Args); + if (Value == "compiler-rt") + return ToolChain::RLT_CompilerRT; + if (Value == "libgcc") + return ToolChain::RLT_Libgcc; + getDriver().Diag(diag::err_drv_invalid_rtlib_name) + << A->getAsString(Args); + } + + return GetDefaultRuntimeLibType(); +} + +ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{ + if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) { + StringRef Value = A->getValue(Args); + if (Value == "libc++") + return ToolChain::CST_Libcxx; + if (Value == "libstdc++") + return ToolChain::CST_Libstdcxx; + getDriver().Diag(diag::err_drv_invalid_stdlib_name) + << A->getAsString(Args); + } + + return ToolChain::CST_Libstdcxx; +} + +/// \brief Utility function to add a system include directory to CC1 arguments. +/*static*/ void ToolChain::addSystemInclude(const ArgList &DriverArgs, + ArgStringList &CC1Args, + const Twine &Path) { + CC1Args.push_back("-internal-isystem"); + CC1Args.push_back(DriverArgs.MakeArgString(Path)); +} + +/// \brief Utility function to add a system include directory with extern "C" +/// semantics to CC1 arguments. +/// +/// Note that this should be used rarely, and only for directories that +/// historically and for legacy reasons are treated as having implicit extern +/// "C" semantics. These semantics are *ignored* by and large today, but its +/// important to preserve the preprocessor changes resulting from the +/// classification. +/*static*/ void ToolChain::addExternCSystemInclude(const ArgList &DriverArgs, + ArgStringList &CC1Args, + const Twine &Path) { + CC1Args.push_back("-internal-externc-isystem"); + CC1Args.push_back(DriverArgs.MakeArgString(Path)); +} + +/// \brief Utility function to add a list of system include directories to CC1. +/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs, + ArgStringList &CC1Args, + ArrayRef<StringRef> Paths) { + for (ArrayRef<StringRef>::iterator I = Paths.begin(), E = Paths.end(); + I != E; ++I) { + CC1Args.push_back("-internal-isystem"); + CC1Args.push_back(DriverArgs.MakeArgString(*I)); + } +} + +void ToolChain::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + // Header search paths should be handled by each of the subclasses. + // Historically, they have not been, and instead have been handled inside of + // the CC1-layer frontend. As the logic is hoisted out, this generic function + // will slowly stop being called. + // + // While it is being called, replicate a bit of a hack to propagate the + // '-stdlib=' flag down to CC1 so that it can in turn customize the C++ + // header search paths with it. Once all systems are overriding this + // function, the CC1 flag and this line can be removed. + DriverArgs.AddAllArgs(CC1Args, options::OPT_stdlib_EQ); +} + +void ToolChain::AddCXXStdlibLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + CXXStdlibType Type = GetCXXStdlibType(Args); + + switch (Type) { + case ToolChain::CST_Libcxx: + CmdArgs.push_back("-lc++"); + break; + + case ToolChain::CST_Libstdcxx: + CmdArgs.push_back("-lstdc++"); + break; + } +} + +void ToolChain::AddCCKextLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + CmdArgs.push_back("-lcc_kext"); +} diff --git a/clang/lib/Driver/ToolChains.cpp b/clang/lib/Driver/ToolChains.cpp new file mode 100644 index 0000000..7f9ed9a --- /dev/null +++ b/clang/lib/Driver/ToolChains.cpp @@ -0,0 +1,2334 @@ +//===--- ToolChains.cpp - ToolChain Implementations -----------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "ToolChains.h" + +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Compilation.h" +#include "clang/Driver/Driver.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Driver/ObjCRuntime.h" +#include "clang/Driver/OptTable.h" +#include "clang/Driver/Option.h" +#include "clang/Driver/Options.h" +#include "clang/Basic/Version.h" + +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/system_error.h" + +#include <cstdlib> // ::getenv + +#include "clang/Config/config.h" // for GCC_INSTALL_PREFIX + +using namespace clang::driver; +using namespace clang::driver::toolchains; +using namespace clang; + +/// Darwin - Darwin tool chain for i386 and x86_64. + +Darwin::Darwin(const Driver &D, const llvm::Triple& Triple) + : ToolChain(D, Triple), TargetInitialized(false), + ARCRuntimeForSimulator(ARCSimulator_None), + LibCXXForSimulator(LibCXXSimulator_None) +{ + // Compute the initial Darwin version from the triple + unsigned Major, Minor, Micro; + if (!Triple.getMacOSXVersion(Major, Minor, Micro)) + getDriver().Diag(diag::err_drv_invalid_darwin_version) << + Triple.getOSName(); + llvm::raw_string_ostream(MacosxVersionMin) + << Major << '.' << Minor << '.' << Micro; + + // FIXME: DarwinVersion is only used to find GCC's libexec directory. + // It should be removed when we stop supporting that. + DarwinVersion[0] = Minor + 4; + DarwinVersion[1] = Micro; + DarwinVersion[2] = 0; +} + +types::ID Darwin::LookupTypeForExtension(const char *Ext) const { + types::ID Ty = types::lookupTypeForExtension(Ext); + + // Darwin always preprocesses assembly files (unless -x is used explicitly). + if (Ty == types::TY_PP_Asm) + return types::TY_Asm; + + return Ty; +} + +bool Darwin::HasNativeLLVMSupport() const { + return true; +} + +bool Darwin::hasARCRuntime() const { + // FIXME: Remove this once there is a proper way to detect an ARC runtime + // for the simulator. + switch (ARCRuntimeForSimulator) { + case ARCSimulator_None: + break; + case ARCSimulator_HasARCRuntime: + return true; + case ARCSimulator_NoARCRuntime: + return false; + } + + if (isTargetIPhoneOS()) + return !isIPhoneOSVersionLT(5); + else + return !isMacosxVersionLT(10, 7); +} + +bool Darwin::hasSubscriptingRuntime() const { + return !isTargetIPhoneOS() && !isMacosxVersionLT(10, 8); +} + +/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0. +void Darwin::configureObjCRuntime(ObjCRuntime &runtime) const { + if (runtime.getKind() != ObjCRuntime::NeXT) + return ToolChain::configureObjCRuntime(runtime); + + runtime.HasARC = runtime.HasWeak = hasARCRuntime(); + runtime.HasSubscripting = hasSubscriptingRuntime(); + + // So far, objc_terminate is only available in iOS 5. + // FIXME: do the simulator logic properly. + if (!ARCRuntimeForSimulator && isTargetIPhoneOS()) + runtime.HasTerminate = !isIPhoneOSVersionLT(5); + else + runtime.HasTerminate = false; +} + +/// Darwin provides a blocks runtime starting in MacOS X 10.6 and iOS 3.2. +bool Darwin::hasBlocksRuntime() const { + if (isTargetIPhoneOS()) + return !isIPhoneOSVersionLT(3, 2); + else + return !isMacosxVersionLT(10, 6); +} + +static const char *GetArmArchForMArch(StringRef Value) { + return llvm::StringSwitch<const char*>(Value) + .Case("armv6k", "armv6") + .Case("armv5tej", "armv5") + .Case("xscale", "xscale") + .Case("armv4t", "armv4t") + .Case("armv7", "armv7") + .Cases("armv7a", "armv7-a", "armv7") + .Cases("armv7r", "armv7-r", "armv7") + .Cases("armv7m", "armv7-m", "armv7") + .Default(0); +} + +static const char *GetArmArchForMCpu(StringRef Value) { + return llvm::StringSwitch<const char *>(Value) + .Cases("arm9e", "arm946e-s", "arm966e-s", "arm968e-s", "arm926ej-s","armv5") + .Cases("arm10e", "arm10tdmi", "armv5") + .Cases("arm1020t", "arm1020e", "arm1022e", "arm1026ej-s", "armv5") + .Case("xscale", "xscale") + .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", + "arm1176jzf-s", "cortex-m0", "armv6") + .Cases("cortex-a8", "cortex-r4", "cortex-m3", "cortex-a9", "armv7") + .Default(0); +} + +StringRef Darwin::getDarwinArchName(const ArgList &Args) const { + switch (getTriple().getArch()) { + default: + return getArchName(); + + case llvm::Triple::thumb: + case llvm::Triple::arm: { + if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) + if (const char *Arch = GetArmArchForMArch(A->getValue(Args))) + return Arch; + + if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) + if (const char *Arch = GetArmArchForMCpu(A->getValue(Args))) + return Arch; + + return "arm"; + } + } +} + +Darwin::~Darwin() { + // Free tool implementations. + for (llvm::DenseMap<unsigned, Tool*>::iterator + it = Tools.begin(), ie = Tools.end(); it != ie; ++it) + delete it->second; +} + +std::string Darwin::ComputeEffectiveClangTriple(const ArgList &Args, + types::ID InputType) const { + llvm::Triple Triple(ComputeLLVMTriple(Args, InputType)); + + // If the target isn't initialized (e.g., an unknown Darwin platform, return + // the default triple). + if (!isTargetInitialized()) + return Triple.getTriple(); + + SmallString<16> Str; + Str += isTargetIPhoneOS() ? "ios" : "macosx"; + Str += getTargetVersion().getAsString(); + Triple.setOSName(Str); + + return Triple.getTriple(); +} + +void Generic_ELF::anchor() {} + +Tool &Darwin::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) { + // Fallback to llvm-gcc for i386 kext compiles, we don't support that ABI. + if (Inputs.size() == 1 && + types::isCXX(Inputs[0]->getType()) && + getTriple().isOSDarwin() && + getTriple().getArch() == llvm::Triple::x86 && + (C.getArgs().getLastArg(options::OPT_fapple_kext) || + C.getArgs().getLastArg(options::OPT_mkernel))) + Key = JA.getKind(); + else + Key = Action::AnalyzeJobClass; + } else + Key = JA.getKind(); + + bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIntegratedAssemblerDefault()); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::InputClass: + case Action::BindArchClass: + llvm_unreachable("Invalid tool kind."); + case Action::PreprocessJobClass: + T = new tools::darwin::Preprocess(*this); break; + case Action::AnalyzeJobClass: + case Action::MigrateJobClass: + T = new tools::Clang(*this); break; + case Action::PrecompileJobClass: + case Action::CompileJobClass: + T = new tools::darwin::Compile(*this); break; + case Action::AssembleJobClass: { + if (UseIntegratedAs) + T = new tools::ClangAs(*this); + else + T = new tools::darwin::Assemble(*this); + break; + } + case Action::LinkJobClass: + T = new tools::darwin::Link(*this); break; + case Action::LipoJobClass: + T = new tools::darwin::Lipo(*this); break; + case Action::DsymutilJobClass: + T = new tools::darwin::Dsymutil(*this); break; + case Action::VerifyJobClass: + T = new tools::darwin::VerifyDebug(*this); break; + } + } + + return *T; +} + + +DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple) + : Darwin(D, Triple) +{ + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir) + getProgramPaths().push_back(getDriver().Dir); + + // We expect 'as', 'ld', etc. to be adjacent to our install dir. + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir) + getProgramPaths().push_back(getDriver().Dir); + + // For fallback, we need to know how to find the GCC cc1 executables, so we + // also add the GCC libexec paths. This is legacy code that can be removed + // once fallback is no longer useful. + AddGCCLibexecPath(DarwinVersion[0]); + AddGCCLibexecPath(DarwinVersion[0] - 2); + AddGCCLibexecPath(DarwinVersion[0] - 1); + AddGCCLibexecPath(DarwinVersion[0] + 1); + AddGCCLibexecPath(DarwinVersion[0] + 2); +} + +void DarwinClang::AddGCCLibexecPath(unsigned darwinVersion) { + std::string ToolChainDir = "i686-apple-darwin"; + ToolChainDir += llvm::utostr(darwinVersion); + ToolChainDir += "/4.2.1"; + + std::string Path = getDriver().Dir; + Path += "/../llvm-gcc-4.2/libexec/gcc/"; + Path += ToolChainDir; + getProgramPaths().push_back(Path); + + Path = "/usr/llvm-gcc-4.2/libexec/gcc/"; + Path += ToolChainDir; + getProgramPaths().push_back(Path); +} + +void DarwinClang::AddLinkSearchPathArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + // The Clang toolchain uses explicit paths for internal libraries. + + // Unfortunately, we still might depend on a few of the libraries that are + // only available in the gcc library directory (in particular + // libstdc++.dylib). For now, hardcode the path to the known install location. + // FIXME: This should get ripped out someday. However, when building on + // 10.6 (darwin10), we're still relying on this to find libstdc++.dylib. + llvm::sys::Path P(getDriver().Dir); + P.eraseComponent(); // .../usr/bin -> ../usr + P.appendComponent("llvm-gcc-4.2"); + P.appendComponent("lib"); + P.appendComponent("gcc"); + switch (getTriple().getArch()) { + default: + llvm_unreachable("Invalid Darwin arch!"); + case llvm::Triple::x86: + case llvm::Triple::x86_64: + P.appendComponent("i686-apple-darwin10"); + break; + case llvm::Triple::arm: + case llvm::Triple::thumb: + P.appendComponent("arm-apple-darwin10"); + break; + case llvm::Triple::ppc: + case llvm::Triple::ppc64: + P.appendComponent("powerpc-apple-darwin10"); + break; + } + P.appendComponent("4.2.1"); + + // Determine the arch specific GCC subdirectory. + const char *ArchSpecificDir = 0; + switch (getTriple().getArch()) { + default: + break; + case llvm::Triple::arm: + case llvm::Triple::thumb: { + std::string Triple = ComputeLLVMTriple(Args); + StringRef TripleStr = Triple; + if (TripleStr.startswith("armv5") || TripleStr.startswith("thumbv5")) + ArchSpecificDir = "v5"; + else if (TripleStr.startswith("armv6") || TripleStr.startswith("thumbv6")) + ArchSpecificDir = "v6"; + else if (TripleStr.startswith("armv7") || TripleStr.startswith("thumbv7")) + ArchSpecificDir = "v7"; + break; + } + case llvm::Triple::ppc64: + ArchSpecificDir = "ppc64"; + break; + case llvm::Triple::x86_64: + ArchSpecificDir = "x86_64"; + break; + } + + if (ArchSpecificDir) { + P.appendComponent(ArchSpecificDir); + bool Exists; + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + CmdArgs.push_back(Args.MakeArgString("-L" + P.str())); + P.eraseComponent(); + } + + bool Exists; + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + CmdArgs.push_back(Args.MakeArgString("-L" + P.str())); +} + +void DarwinClang::AddLinkARCArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + + CmdArgs.push_back("-force_load"); + llvm::sys::Path P(getDriver().ClangExecutable); + P.eraseComponent(); // 'clang' + P.eraseComponent(); // 'bin' + P.appendComponent("lib"); + P.appendComponent("arc"); + P.appendComponent("libarclite_"); + std::string s = P.str(); + // Mash in the platform. + if (isTargetIOSSimulator()) + s += "iphonesimulator"; + else if (isTargetIPhoneOS()) + s += "iphoneos"; + // FIXME: Remove this once we depend fully on -mios-simulator-version-min. + else if (ARCRuntimeForSimulator != ARCSimulator_None) + s += "iphonesimulator"; + else + s += "macosx"; + s += ".a"; + + CmdArgs.push_back(Args.MakeArgString(s)); +} + +void DarwinClang::AddLinkRuntimeLib(const ArgList &Args, + ArgStringList &CmdArgs, + const char *DarwinStaticLib) const { + llvm::sys::Path P(getDriver().ResourceDir); + P.appendComponent("lib"); + P.appendComponent("darwin"); + P.appendComponent(DarwinStaticLib); + + // For now, allow missing resource libraries to support developers who may + // not have compiler-rt checked out or integrated into their build. + bool Exists; + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + CmdArgs.push_back(Args.MakeArgString(P.str())); +} + +void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + // Darwin only supports the compiler-rt based runtime libraries. + switch (GetRuntimeLibType(Args)) { + case ToolChain::RLT_CompilerRT: + break; + default: + getDriver().Diag(diag::err_drv_unsupported_rtlib_for_platform) + << Args.getLastArg(options::OPT_rtlib_EQ)->getValue(Args) << "darwin"; + return; + } + + // Darwin doesn't support real static executables, don't link any runtime + // libraries with -static. + if (Args.hasArg(options::OPT_static)) + return; + + // Reject -static-libgcc for now, we can deal with this when and if someone + // cares. This is useful in situations where someone wants to statically link + // something like libstdc++, and needs its runtime support routines. + if (const Arg *A = Args.getLastArg(options::OPT_static_libgcc)) { + getDriver().Diag(diag::err_drv_unsupported_opt) + << A->getAsString(Args); + return; + } + + // If we are building profile support, link that library in. + if (Args.hasArg(options::OPT_fprofile_arcs) || + Args.hasArg(options::OPT_fprofile_generate) || + Args.hasArg(options::OPT_fcreate_profile) || + Args.hasArg(options::OPT_coverage)) { + // Select the appropriate runtime library for the target. + if (isTargetIPhoneOS()) { + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_ios.a"); + } else { + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.profile_osx.a"); + } + } + + // Add ASAN runtime library, if required. Dynamic libraries and bundles + // should not be linked with the runtime library. + if (Args.hasFlag(options::OPT_faddress_sanitizer, + options::OPT_fno_address_sanitizer, false)) { + if (Args.hasArg(options::OPT_dynamiclib) || + Args.hasArg(options::OPT_bundle)) return; + if (isTargetIPhoneOS()) { + getDriver().Diag(diag::err_drv_clang_unsupported_per_platform) + << "-faddress-sanitizer"; + } else { + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.asan_osx.a"); + + // The ASAN runtime library requires C++ and CoreFoundation. + AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("-framework"); + CmdArgs.push_back("CoreFoundation"); + } + } + + // Otherwise link libSystem, then the dynamic runtime library, and finally any + // target specific static runtime library. + CmdArgs.push_back("-lSystem"); + + // Select the dynamic runtime library and the target specific static library. + if (isTargetIPhoneOS()) { + // If we are compiling as iOS / simulator, don't attempt to link libgcc_s.1, + // it never went into the SDK. + // Linking against libgcc_s.1 isn't needed for iOS 5.0+ + if (isIPhoneOSVersionLT(5, 0) && !isTargetIOSSimulator()) + CmdArgs.push_back("-lgcc_s.1"); + + // We currently always need a static runtime library for iOS. + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ios.a"); + } else { + // The dynamic runtime library was merged with libSystem for 10.6 and + // beyond; only 10.4 and 10.5 need an additional runtime library. + if (isMacosxVersionLT(10, 5)) + CmdArgs.push_back("-lgcc_s.10.4"); + else if (isMacosxVersionLT(10, 6)) + CmdArgs.push_back("-lgcc_s.10.5"); + + // For OS X, we thought we would only need a static runtime library when + // targeting 10.4, to provide versions of the static functions which were + // omitted from 10.4.dylib. + // + // Unfortunately, that turned out to not be true, because Darwin system + // headers can still use eprintf on i386, and it is not exported from + // libSystem. Therefore, we still must provide a runtime library just for + // the tiny tiny handful of projects that *might* use that symbol. + if (isMacosxVersionLT(10, 5)) { + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.10.4.a"); + } else { + if (getTriple().getArch() == llvm::Triple::x86) + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.eprintf.a"); + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.osx.a"); + } + } +} + +static inline StringRef SimulatorVersionDefineName() { + return "__IPHONE_OS_VERSION_MIN_REQUIRED"; +} + +/// \brief Parse the simulator version define: +/// __IPHONE_OS_VERSION_MIN_REQUIRED=([0-9])([0-9][0-9])([0-9][0-9]) +// and return the grouped values as integers, e.g: +// __IPHONE_OS_VERSION_MIN_REQUIRED=40201 +// will return Major=4, Minor=2, Micro=1. +static bool GetVersionFromSimulatorDefine(StringRef define, + unsigned &Major, unsigned &Minor, + unsigned &Micro) { + assert(define.startswith(SimulatorVersionDefineName())); + StringRef name, version; + llvm::tie(name, version) = define.split('='); + if (version.empty()) + return false; + std::string verstr = version.str(); + char *end; + unsigned num = (unsigned) strtol(verstr.c_str(), &end, 10); + if (*end != '\0') + return false; + Major = num / 10000; + num = num % 10000; + Minor = num / 100; + Micro = num % 100; + return true; +} + +void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { + const OptTable &Opts = getDriver().getOpts(); + + Arg *OSXVersion = Args.getLastArg(options::OPT_mmacosx_version_min_EQ); + Arg *iOSVersion = Args.getLastArg(options::OPT_miphoneos_version_min_EQ); + Arg *iOSSimVersion = Args.getLastArg( + options::OPT_mios_simulator_version_min_EQ); + + // FIXME: HACK! When compiling for the simulator we don't get a + // '-miphoneos-version-min' to help us know whether there is an ARC runtime + // or not; try to parse a __IPHONE_OS_VERSION_MIN_REQUIRED + // define passed in command-line. + if (!iOSVersion && !iOSSimVersion) { + for (arg_iterator it = Args.filtered_begin(options::OPT_D), + ie = Args.filtered_end(); it != ie; ++it) { + StringRef define = (*it)->getValue(Args); + if (define.startswith(SimulatorVersionDefineName())) { + unsigned Major = 0, Minor = 0, Micro = 0; + if (GetVersionFromSimulatorDefine(define, Major, Minor, Micro) && + Major < 10 && Minor < 100 && Micro < 100) { + ARCRuntimeForSimulator = Major < 5 ? ARCSimulator_NoARCRuntime + : ARCSimulator_HasARCRuntime; + LibCXXForSimulator = Major < 5 ? LibCXXSimulator_NotAvailable + : LibCXXSimulator_Available; + } + break; + } + } + } + + if (OSXVersion && (iOSVersion || iOSSimVersion)) { + getDriver().Diag(diag::err_drv_argument_not_allowed_with) + << OSXVersion->getAsString(Args) + << (iOSVersion ? iOSVersion : iOSSimVersion)->getAsString(Args); + iOSVersion = iOSSimVersion = 0; + } else if (iOSVersion && iOSSimVersion) { + getDriver().Diag(diag::err_drv_argument_not_allowed_with) + << iOSVersion->getAsString(Args) + << iOSSimVersion->getAsString(Args); + iOSSimVersion = 0; + } else if (!OSXVersion && !iOSVersion && !iOSSimVersion) { + // If no deployment target was specified on the command line, check for + // environment defines. + StringRef OSXTarget; + StringRef iOSTarget; + StringRef iOSSimTarget; + if (char *env = ::getenv("MACOSX_DEPLOYMENT_TARGET")) + OSXTarget = env; + if (char *env = ::getenv("IPHONEOS_DEPLOYMENT_TARGET")) + iOSTarget = env; + if (char *env = ::getenv("IOS_SIMULATOR_DEPLOYMENT_TARGET")) + iOSSimTarget = env; + + // If no '-miphoneos-version-min' specified on the command line and + // IPHONEOS_DEPLOYMENT_TARGET is not defined, see if we can set the default + // based on -isysroot. + if (iOSTarget.empty()) { + if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { + StringRef first, second; + StringRef isysroot = A->getValue(Args); + llvm::tie(first, second) = isysroot.split(StringRef("SDKs/iPhoneOS")); + if (second != "") + iOSTarget = second.substr(0,3); + } + } + + // If no OSX or iOS target has been specified and we're compiling for armv7, + // go ahead as assume we're targeting iOS. + if (OSXTarget.empty() && iOSTarget.empty()) + if (getDarwinArchName(Args) == "armv7") + iOSTarget = "0.0"; + + // Handle conflicting deployment targets + // + // FIXME: Don't hardcode default here. + + // Do not allow conflicts with the iOS simulator target. + if (!iOSSimTarget.empty() && (!OSXTarget.empty() || !iOSTarget.empty())) { + getDriver().Diag(diag::err_drv_conflicting_deployment_targets) + << "IOS_SIMULATOR_DEPLOYMENT_TARGET" + << (!OSXTarget.empty() ? "MACOSX_DEPLOYMENT_TARGET" : + "IPHONEOS_DEPLOYMENT_TARGET"); + } + + // Allow conflicts among OSX and iOS for historical reasons, but choose the + // default platform. + if (!OSXTarget.empty() && !iOSTarget.empty()) { + if (getTriple().getArch() == llvm::Triple::arm || + getTriple().getArch() == llvm::Triple::thumb) + OSXTarget = ""; + else + iOSTarget = ""; + } + + if (!OSXTarget.empty()) { + const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ); + OSXVersion = Args.MakeJoinedArg(0, O, OSXTarget); + Args.append(OSXVersion); + } else if (!iOSTarget.empty()) { + const Option *O = Opts.getOption(options::OPT_miphoneos_version_min_EQ); + iOSVersion = Args.MakeJoinedArg(0, O, iOSTarget); + Args.append(iOSVersion); + } else if (!iOSSimTarget.empty()) { + const Option *O = Opts.getOption( + options::OPT_mios_simulator_version_min_EQ); + iOSSimVersion = Args.MakeJoinedArg(0, O, iOSSimTarget); + Args.append(iOSSimVersion); + } else { + // Otherwise, assume we are targeting OS X. + const Option *O = Opts.getOption(options::OPT_mmacosx_version_min_EQ); + OSXVersion = Args.MakeJoinedArg(0, O, MacosxVersionMin); + Args.append(OSXVersion); + } + } + + // Reject invalid architecture combinations. + if (iOSSimVersion && (getTriple().getArch() != llvm::Triple::x86 && + getTriple().getArch() != llvm::Triple::x86_64)) { + getDriver().Diag(diag::err_drv_invalid_arch_for_deployment_target) + << getTriple().getArchName() << iOSSimVersion->getAsString(Args); + } + + // Set the tool chain target information. + unsigned Major, Minor, Micro; + bool HadExtra; + if (OSXVersion) { + assert((!iOSVersion && !iOSSimVersion) && "Unknown target platform!"); + if (!Driver::GetReleaseVersion(OSXVersion->getValue(Args), Major, Minor, + Micro, HadExtra) || HadExtra || + Major != 10 || Minor >= 100 || Micro >= 100) + getDriver().Diag(diag::err_drv_invalid_version_number) + << OSXVersion->getAsString(Args); + } else { + const Arg *Version = iOSVersion ? iOSVersion : iOSSimVersion; + assert(Version && "Unknown target platform!"); + if (!Driver::GetReleaseVersion(Version->getValue(Args), Major, Minor, + Micro, HadExtra) || HadExtra || + Major >= 10 || Minor >= 100 || Micro >= 100) + getDriver().Diag(diag::err_drv_invalid_version_number) + << Version->getAsString(Args); + } + + bool IsIOSSim = bool(iOSSimVersion); + + // In GCC, the simulator historically was treated as being OS X in some + // contexts, like determining the link logic, despite generally being called + // with an iOS deployment target. For compatibility, we detect the + // simulator as iOS + x86, and treat it differently in a few contexts. + if (iOSVersion && (getTriple().getArch() == llvm::Triple::x86 || + getTriple().getArch() == llvm::Triple::x86_64)) + IsIOSSim = true; + + setTarget(/*IsIPhoneOS=*/ !OSXVersion, Major, Minor, Micro, IsIOSSim); +} + +void DarwinClang::AddCXXStdlibLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + CXXStdlibType Type = GetCXXStdlibType(Args); + + switch (Type) { + case ToolChain::CST_Libcxx: + CmdArgs.push_back("-lc++"); + break; + + case ToolChain::CST_Libstdcxx: { + // Unfortunately, -lstdc++ doesn't always exist in the standard search path; + // it was previously found in the gcc lib dir. However, for all the Darwin + // platforms we care about it was -lstdc++.6, so we search for that + // explicitly if we can't see an obvious -lstdc++ candidate. + + // Check in the sysroot first. + bool Exists; + if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { + llvm::sys::Path P(A->getValue(Args)); + P.appendComponent("usr"); + P.appendComponent("lib"); + P.appendComponent("libstdc++.dylib"); + + if (llvm::sys::fs::exists(P.str(), Exists) || !Exists) { + P.eraseComponent(); + P.appendComponent("libstdc++.6.dylib"); + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) { + CmdArgs.push_back(Args.MakeArgString(P.str())); + return; + } + } + } + + // Otherwise, look in the root. + // FIXME: This should be removed someday when we don't have to care about + // 10.6 and earlier, where /usr/lib/libstdc++.dylib does not exist. + if ((llvm::sys::fs::exists("/usr/lib/libstdc++.dylib", Exists) || !Exists)&& + (!llvm::sys::fs::exists("/usr/lib/libstdc++.6.dylib", Exists) && Exists)){ + CmdArgs.push_back("/usr/lib/libstdc++.6.dylib"); + return; + } + + // Otherwise, let the linker search. + CmdArgs.push_back("-lstdc++"); + break; + } + } +} + +void DarwinClang::AddCCKextLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + + // For Darwin platforms, use the compiler-rt-based support library + // instead of the gcc-provided one (which is also incidentally + // only present in the gcc lib dir, which makes it hard to find). + + llvm::sys::Path P(getDriver().ResourceDir); + P.appendComponent("lib"); + P.appendComponent("darwin"); + P.appendComponent("libclang_rt.cc_kext.a"); + + // For now, allow missing resource libraries to support developers who may + // not have compiler-rt checked out or integrated into their build. + bool Exists; + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + CmdArgs.push_back(Args.MakeArgString(P.str())); +} + +DerivedArgList *Darwin::TranslateArgs(const DerivedArgList &Args, + const char *BoundArch) const { + DerivedArgList *DAL = new DerivedArgList(Args.getBaseArgs()); + const OptTable &Opts = getDriver().getOpts(); + + // FIXME: We really want to get out of the tool chain level argument + // translation business, as it makes the driver functionality much + // more opaque. For now, we follow gcc closely solely for the + // purpose of easily achieving feature parity & testability. Once we + // have something that works, we should reevaluate each translation + // and try to push it down into tool specific logic. + + for (ArgList::const_iterator it = Args.begin(), + ie = Args.end(); it != ie; ++it) { + Arg *A = *it; + + if (A->getOption().matches(options::OPT_Xarch__)) { + // Skip this argument unless the architecture matches either the toolchain + // triple arch, or the arch being bound. + // + // FIXME: Canonicalize name. + StringRef XarchArch = A->getValue(Args, 0); + if (!(XarchArch == getArchName() || + (BoundArch && XarchArch == BoundArch))) + continue; + + Arg *OriginalArg = A; + unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(Args, 1)); + unsigned Prev = Index; + Arg *XarchArg = Opts.ParseOneArg(Args, Index); + + // If the argument parsing failed or more than one argument was + // consumed, the -Xarch_ argument's parameter tried to consume + // extra arguments. Emit an error and ignore. + // + // We also want to disallow any options which would alter the + // driver behavior; that isn't going to work in our model. We + // use isDriverOption() as an approximation, although things + // like -O4 are going to slip through. + if (!XarchArg || Index > Prev + 1) { + getDriver().Diag(diag::err_drv_invalid_Xarch_argument_with_args) + << A->getAsString(Args); + continue; + } else if (XarchArg->getOption().isDriverOption()) { + getDriver().Diag(diag::err_drv_invalid_Xarch_argument_isdriver) + << A->getAsString(Args); + continue; + } + + XarchArg->setBaseArg(A); + A = XarchArg; + + DAL->AddSynthesizedArg(A); + + // Linker input arguments require custom handling. The problem is that we + // have already constructed the phase actions, so we can not treat them as + // "input arguments". + if (A->getOption().isLinkerInput()) { + // Convert the argument into individual Zlinker_input_args. + for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) { + DAL->AddSeparateArg(OriginalArg, + Opts.getOption(options::OPT_Zlinker_input), + A->getValue(Args, i)); + + } + continue; + } + } + + // Sob. These is strictly gcc compatible for the time being. Apple + // gcc translates options twice, which means that self-expanding + // options add duplicates. + switch ((options::ID) A->getOption().getID()) { + default: + DAL->append(A); + break; + + case options::OPT_mkernel: + case options::OPT_fapple_kext: + DAL->append(A); + DAL->AddFlagArg(A, Opts.getOption(options::OPT_static)); + break; + + case options::OPT_dependency_file: + DAL->AddSeparateArg(A, Opts.getOption(options::OPT_MF), + A->getValue(Args)); + break; + + case options::OPT_gfull: + DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); + DAL->AddFlagArg(A, + Opts.getOption(options::OPT_fno_eliminate_unused_debug_symbols)); + break; + + case options::OPT_gused: + DAL->AddFlagArg(A, Opts.getOption(options::OPT_g_Flag)); + DAL->AddFlagArg(A, + Opts.getOption(options::OPT_feliminate_unused_debug_symbols)); + break; + + case options::OPT_shared: + DAL->AddFlagArg(A, Opts.getOption(options::OPT_dynamiclib)); + break; + + case options::OPT_fconstant_cfstrings: + DAL->AddFlagArg(A, Opts.getOption(options::OPT_mconstant_cfstrings)); + break; + + case options::OPT_fno_constant_cfstrings: + DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_constant_cfstrings)); + break; + + case options::OPT_Wnonportable_cfstrings: + DAL->AddFlagArg(A, + Opts.getOption(options::OPT_mwarn_nonportable_cfstrings)); + break; + + case options::OPT_Wno_nonportable_cfstrings: + DAL->AddFlagArg(A, + Opts.getOption(options::OPT_mno_warn_nonportable_cfstrings)); + break; + + case options::OPT_fpascal_strings: + DAL->AddFlagArg(A, Opts.getOption(options::OPT_mpascal_strings)); + break; + + case options::OPT_fno_pascal_strings: + DAL->AddFlagArg(A, Opts.getOption(options::OPT_mno_pascal_strings)); + break; + } + } + + if (getTriple().getArch() == llvm::Triple::x86 || + getTriple().getArch() == llvm::Triple::x86_64) + if (!Args.hasArgNoClaim(options::OPT_mtune_EQ)) + DAL->AddJoinedArg(0, Opts.getOption(options::OPT_mtune_EQ), "core2"); + + // Add the arch options based on the particular spelling of -arch, to match + // how the driver driver works. + if (BoundArch) { + StringRef Name = BoundArch; + const Option *MCpu = Opts.getOption(options::OPT_mcpu_EQ); + const Option *MArch = Opts.getOption(options::OPT_march_EQ); + + // This code must be kept in sync with LLVM's getArchTypeForDarwinArch, + // which defines the list of which architectures we accept. + if (Name == "ppc") + ; + else if (Name == "ppc601") + DAL->AddJoinedArg(0, MCpu, "601"); + else if (Name == "ppc603") + DAL->AddJoinedArg(0, MCpu, "603"); + else if (Name == "ppc604") + DAL->AddJoinedArg(0, MCpu, "604"); + else if (Name == "ppc604e") + DAL->AddJoinedArg(0, MCpu, "604e"); + else if (Name == "ppc750") + DAL->AddJoinedArg(0, MCpu, "750"); + else if (Name == "ppc7400") + DAL->AddJoinedArg(0, MCpu, "7400"); + else if (Name == "ppc7450") + DAL->AddJoinedArg(0, MCpu, "7450"); + else if (Name == "ppc970") + DAL->AddJoinedArg(0, MCpu, "970"); + + else if (Name == "ppc64") + DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64)); + + else if (Name == "i386") + ; + else if (Name == "i486") + DAL->AddJoinedArg(0, MArch, "i486"); + else if (Name == "i586") + DAL->AddJoinedArg(0, MArch, "i586"); + else if (Name == "i686") + DAL->AddJoinedArg(0, MArch, "i686"); + else if (Name == "pentium") + DAL->AddJoinedArg(0, MArch, "pentium"); + else if (Name == "pentium2") + DAL->AddJoinedArg(0, MArch, "pentium2"); + else if (Name == "pentpro") + DAL->AddJoinedArg(0, MArch, "pentiumpro"); + else if (Name == "pentIIm3") + DAL->AddJoinedArg(0, MArch, "pentium2"); + + else if (Name == "x86_64") + DAL->AddFlagArg(0, Opts.getOption(options::OPT_m64)); + + else if (Name == "arm") + DAL->AddJoinedArg(0, MArch, "armv4t"); + else if (Name == "armv4t") + DAL->AddJoinedArg(0, MArch, "armv4t"); + else if (Name == "armv5") + DAL->AddJoinedArg(0, MArch, "armv5tej"); + else if (Name == "xscale") + DAL->AddJoinedArg(0, MArch, "xscale"); + else if (Name == "armv6") + DAL->AddJoinedArg(0, MArch, "armv6k"); + else if (Name == "armv7") + DAL->AddJoinedArg(0, MArch, "armv7a"); + + else + llvm_unreachable("invalid Darwin arch"); + } + + // Add an explicit version min argument for the deployment target. We do this + // after argument translation because -Xarch_ arguments may add a version min + // argument. + AddDeploymentTarget(*DAL); + + // Validate the C++ standard library choice. + CXXStdlibType Type = GetCXXStdlibType(*DAL); + if (Type == ToolChain::CST_Libcxx) { + switch (LibCXXForSimulator) { + case LibCXXSimulator_None: + // Handle non-simulator cases. + if (isTargetIPhoneOS()) { + if (isIPhoneOSVersionLT(5, 0)) { + getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) + << "iOS 5.0"; + } + } + break; + case LibCXXSimulator_NotAvailable: + getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) + << "iOS 5.0"; + break; + case LibCXXSimulator_Available: + break; + } + } + + return DAL; +} + +bool Darwin::IsUnwindTablesDefault() const { + // FIXME: Gross; we should probably have some separate target + // definition, possibly even reusing the one in clang. + return getArchName() == "x86_64"; +} + +bool Darwin::UseDwarfDebugFlags() const { + if (const char *S = ::getenv("RC_DEBUG_OPTIONS")) + return S[0] != '\0'; + return false; +} + +bool Darwin::UseSjLjExceptions() const { + // Darwin uses SjLj exceptions on ARM. + return (getTriple().getArch() == llvm::Triple::arm || + getTriple().getArch() == llvm::Triple::thumb); +} + +const char *Darwin::GetDefaultRelocationModel() const { + return "pic"; +} + +const char *Darwin::GetForcedPicModel() const { + if (getArchName() == "x86_64") + return "pic"; + return 0; +} + +bool Darwin::SupportsProfiling() const { + // Profiling instrumentation is only supported on x86. + return getArchName() == "i386" || getArchName() == "x86_64"; +} + +bool Darwin::SupportsObjCGC() const { + // Garbage collection is supported everywhere except on iPhone OS. + return !isTargetIPhoneOS(); +} + +bool Darwin::SupportsObjCARC() const { + return isTargetIPhoneOS() || !isMacosxVersionLT(10, 6); +} + +std::string +Darwin_Generic_GCC::ComputeEffectiveClangTriple(const ArgList &Args, + types::ID InputType) const { + return ComputeLLVMTriple(Args, InputType); +} + +/// Generic_GCC - A tool chain using the 'gcc' command to perform +/// all subcommands; this relies on gcc translating the majority of +/// command line options. + +/// \brief Parse a GCCVersion object out of a string of text. +/// +/// This is the primary means of forming GCCVersion objects. +/*static*/ +Generic_GCC::GCCVersion Linux::GCCVersion::Parse(StringRef VersionText) { + const GCCVersion BadVersion = { VersionText.str(), -1, -1, -1, "" }; + std::pair<StringRef, StringRef> First = VersionText.split('.'); + std::pair<StringRef, StringRef> Second = First.second.split('.'); + + GCCVersion GoodVersion = { VersionText.str(), -1, -1, -1, "" }; + if (First.first.getAsInteger(10, GoodVersion.Major) || + GoodVersion.Major < 0) + return BadVersion; + if (Second.first.getAsInteger(10, GoodVersion.Minor) || + GoodVersion.Minor < 0) + return BadVersion; + + // First look for a number prefix and parse that if present. Otherwise just + // stash the entire patch string in the suffix, and leave the number + // unspecified. This covers versions strings such as: + // 4.4 + // 4.4.0 + // 4.4.x + // 4.4.2-rc4 + // 4.4.x-patched + // And retains any patch number it finds. + StringRef PatchText = GoodVersion.PatchSuffix = Second.second.str(); + if (!PatchText.empty()) { + if (unsigned EndNumber = PatchText.find_first_not_of("0123456789")) { + // Try to parse the number and any suffix. + if (PatchText.slice(0, EndNumber).getAsInteger(10, GoodVersion.Patch) || + GoodVersion.Patch < 0) + return BadVersion; + GoodVersion.PatchSuffix = PatchText.substr(EndNumber).str(); + } + } + + return GoodVersion; +} + +/// \brief Less-than for GCCVersion, implementing a Strict Weak Ordering. +bool Generic_GCC::GCCVersion::operator<(const GCCVersion &RHS) const { + if (Major < RHS.Major) return true; if (Major > RHS.Major) return false; + if (Minor < RHS.Minor) return true; if (Minor > RHS.Minor) return false; + + // Note that we rank versions with *no* patch specified is better than ones + // hard-coding a patch version. Thus if the RHS has no patch, it always + // wins, and the LHS only wins if it has no patch and the RHS does have + // a patch. + if (RHS.Patch == -1) return true; if (Patch == -1) return false; + if (Patch < RHS.Patch) return true; if (Patch > RHS.Patch) return false; + if (PatchSuffix == RHS.PatchSuffix) return false; + + // Finally, between completely tied version numbers, the version with the + // suffix loses as we prefer full releases. + if (RHS.PatchSuffix.empty()) return true; + return false; +} + +static StringRef getGCCToolchainDir(const ArgList &Args) { + const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain); + if (A) + return A->getValue(Args); + return GCC_INSTALL_PREFIX; +} + +/// \brief Construct a GCCInstallationDetector from the driver. +/// +/// This performs all of the autodetection and sets up the various paths. +/// Once constructed, a GCCInstallationDetector is essentially immutable. +/// +/// FIXME: We shouldn't need an explicit TargetTriple parameter here, and +/// should instead pull the target out of the driver. This is currently +/// necessary because the driver doesn't store the final version of the target +/// triple. +Generic_GCC::GCCInstallationDetector::GCCInstallationDetector( + const Driver &D, + const llvm::Triple &TargetTriple, + const ArgList &Args) + : IsValid(false) { + llvm::Triple MultiarchTriple + = TargetTriple.isArch32Bit() ? TargetTriple.get64BitArchVariant() + : TargetTriple.get32BitArchVariant(); + llvm::Triple::ArchType TargetArch = TargetTriple.getArch(); + // The library directories which may contain GCC installations. + SmallVector<StringRef, 4> CandidateLibDirs, CandidateMultiarchLibDirs; + // The compatible GCC triples for this particular architecture. + SmallVector<StringRef, 10> CandidateTripleAliases; + SmallVector<StringRef, 10> CandidateMultiarchTripleAliases; + CollectLibDirsAndTriples(TargetTriple, MultiarchTriple, CandidateLibDirs, + CandidateTripleAliases, + CandidateMultiarchLibDirs, + CandidateMultiarchTripleAliases); + + // Compute the set of prefixes for our search. + SmallVector<std::string, 8> Prefixes(D.PrefixDirs.begin(), + D.PrefixDirs.end()); + + StringRef GCCToolchainDir = getGCCToolchainDir(Args); + if (GCCToolchainDir != "") { + if (GCCToolchainDir.back() == '/') + GCCToolchainDir = GCCToolchainDir.drop_back(); // remove the / + + Prefixes.push_back(GCCToolchainDir); + } else { + Prefixes.push_back(D.SysRoot); + Prefixes.push_back(D.SysRoot + "/usr"); + Prefixes.push_back(D.InstalledDir + "/.."); + } + + // Loop over the various components which exist and select the best GCC + // installation available. GCC installs are ranked by version number. + Version = GCCVersion::Parse("0.0.0"); + for (unsigned i = 0, ie = Prefixes.size(); i < ie; ++i) { + if (!llvm::sys::fs::exists(Prefixes[i])) + continue; + for (unsigned j = 0, je = CandidateLibDirs.size(); j < je; ++j) { + const std::string LibDir = Prefixes[i] + CandidateLibDirs[j].str(); + if (!llvm::sys::fs::exists(LibDir)) + continue; + for (unsigned k = 0, ke = CandidateTripleAliases.size(); k < ke; ++k) + ScanLibDirForGCCTriple(TargetArch, LibDir, CandidateTripleAliases[k]); + } + for (unsigned j = 0, je = CandidateMultiarchLibDirs.size(); j < je; ++j) { + const std::string LibDir + = Prefixes[i] + CandidateMultiarchLibDirs[j].str(); + if (!llvm::sys::fs::exists(LibDir)) + continue; + for (unsigned k = 0, ke = CandidateMultiarchTripleAliases.size(); k < ke; + ++k) + ScanLibDirForGCCTriple(TargetArch, LibDir, + CandidateMultiarchTripleAliases[k], + /*NeedsMultiarchSuffix=*/true); + } + } +} + +/*static*/ void Generic_GCC::GCCInstallationDetector::CollectLibDirsAndTriples( + const llvm::Triple &TargetTriple, + const llvm::Triple &MultiarchTriple, + SmallVectorImpl<StringRef> &LibDirs, + SmallVectorImpl<StringRef> &TripleAliases, + SmallVectorImpl<StringRef> &MultiarchLibDirs, + SmallVectorImpl<StringRef> &MultiarchTripleAliases) { + // Declare a bunch of static data sets that we'll select between below. These + // are specifically designed to always refer to string literals to avoid any + // lifetime or initialization issues. + static const char *const ARMLibDirs[] = { "/lib" }; + static const char *const ARMTriples[] = { + "arm-linux-gnueabi", + "arm-linux-androideabi" + }; + + static const char *const X86_64LibDirs[] = { "/lib64", "/lib" }; + static const char *const X86_64Triples[] = { + "x86_64-linux-gnu", + "x86_64-unknown-linux-gnu", + "x86_64-pc-linux-gnu", + "x86_64-redhat-linux6E", + "x86_64-redhat-linux", + "x86_64-suse-linux", + "x86_64-manbo-linux-gnu", + "x86_64-linux-gnu", + "x86_64-slackware-linux" + }; + static const char *const X86LibDirs[] = { "/lib32", "/lib" }; + static const char *const X86Triples[] = { + "i686-linux-gnu", + "i686-pc-linux-gnu", + "i486-linux-gnu", + "i386-linux-gnu", + "i686-redhat-linux", + "i586-redhat-linux", + "i386-redhat-linux", + "i586-suse-linux", + "i486-slackware-linux" + }; + + static const char *const MIPSLibDirs[] = { "/lib" }; + static const char *const MIPSTriples[] = { "mips-linux-gnu" }; + static const char *const MIPSELLibDirs[] = { "/lib" }; + static const char *const MIPSELTriples[] = { "mipsel-linux-gnu" }; + + static const char *const PPCLibDirs[] = { "/lib32", "/lib" }; + static const char *const PPCTriples[] = { + "powerpc-linux-gnu", + "powerpc-unknown-linux-gnu", + "powerpc-suse-linux" + }; + static const char *const PPC64LibDirs[] = { "/lib64", "/lib" }; + static const char *const PPC64Triples[] = { + "powerpc64-linux-gnu", + "powerpc64-unknown-linux-gnu", + "powerpc64-suse-linux", + "ppc64-redhat-linux" + }; + + switch (TargetTriple.getArch()) { + case llvm::Triple::arm: + case llvm::Triple::thumb: + LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs)); + TripleAliases.append( + ARMTriples, ARMTriples + llvm::array_lengthof(ARMTriples)); + break; + case llvm::Triple::x86_64: + LibDirs.append( + X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs)); + TripleAliases.append( + X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples)); + MultiarchLibDirs.append( + X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs)); + MultiarchTripleAliases.append( + X86Triples, X86Triples + llvm::array_lengthof(X86Triples)); + break; + case llvm::Triple::x86: + LibDirs.append(X86LibDirs, X86LibDirs + llvm::array_lengthof(X86LibDirs)); + TripleAliases.append( + X86Triples, X86Triples + llvm::array_lengthof(X86Triples)); + MultiarchLibDirs.append( + X86_64LibDirs, X86_64LibDirs + llvm::array_lengthof(X86_64LibDirs)); + MultiarchTripleAliases.append( + X86_64Triples, X86_64Triples + llvm::array_lengthof(X86_64Triples)); + break; + case llvm::Triple::mips: + LibDirs.append( + MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs)); + TripleAliases.append( + MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples)); + break; + case llvm::Triple::mipsel: + LibDirs.append( + MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs)); + TripleAliases.append( + MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples)); + break; + case llvm::Triple::ppc: + LibDirs.append(PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs)); + TripleAliases.append( + PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples)); + MultiarchLibDirs.append( + PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs)); + MultiarchTripleAliases.append( + PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples)); + break; + case llvm::Triple::ppc64: + LibDirs.append( + PPC64LibDirs, PPC64LibDirs + llvm::array_lengthof(PPC64LibDirs)); + TripleAliases.append( + PPC64Triples, PPC64Triples + llvm::array_lengthof(PPC64Triples)); + MultiarchLibDirs.append( + PPCLibDirs, PPCLibDirs + llvm::array_lengthof(PPCLibDirs)); + MultiarchTripleAliases.append( + PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples)); + break; + + default: + // By default, just rely on the standard lib directories and the original + // triple. + break; + } + + // Always append the drivers target triple to the end, in case it doesn't + // match any of our aliases. + TripleAliases.push_back(TargetTriple.str()); + + // Also include the multiarch variant if it's different. + if (TargetTriple.str() != MultiarchTriple.str()) + MultiarchTripleAliases.push_back(MultiarchTriple.str()); +} + +void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple( + llvm::Triple::ArchType TargetArch, const std::string &LibDir, + StringRef CandidateTriple, bool NeedsMultiarchSuffix) { + // There are various different suffixes involving the triple we + // check for. We also record what is necessary to walk from each back + // up to the lib directory. + const std::string LibSuffixes[] = { + "/gcc/" + CandidateTriple.str(), + "/" + CandidateTriple.str() + "/gcc/" + CandidateTriple.str(), + + // Ubuntu has a strange mis-matched pair of triples that this happens to + // match. + // FIXME: It may be worthwhile to generalize this and look for a second + // triple. + "/i386-linux-gnu/gcc/" + CandidateTriple.str() + }; + const std::string InstallSuffixes[] = { + "/../../..", + "/../../../..", + "/../../../.." + }; + // Only look at the final, weird Ubuntu suffix for i386-linux-gnu. + const unsigned NumLibSuffixes = (llvm::array_lengthof(LibSuffixes) - + (TargetArch != llvm::Triple::x86)); + for (unsigned i = 0; i < NumLibSuffixes; ++i) { + StringRef LibSuffix = LibSuffixes[i]; + llvm::error_code EC; + for (llvm::sys::fs::directory_iterator LI(LibDir + LibSuffix, EC), LE; + !EC && LI != LE; LI = LI.increment(EC)) { + StringRef VersionText = llvm::sys::path::filename(LI->path()); + GCCVersion CandidateVersion = GCCVersion::Parse(VersionText); + static const GCCVersion MinVersion = { "4.1.1", 4, 1, 1, "" }; + if (CandidateVersion < MinVersion) + continue; + if (CandidateVersion <= Version) + continue; + + // Some versions of SUSE and Fedora on ppc64 put 32-bit libs + // in what would normally be GCCInstallPath and put the 64-bit + // libs in a subdirectory named 64. The simple logic we follow is that + // *if* there is a subdirectory of the right name with crtbegin.o in it, + // we use that. If not, and if not a multiarch triple, we look for + // crtbegin.o without the subdirectory. + StringRef MultiarchSuffix + = (TargetArch == llvm::Triple::x86_64 || + TargetArch == llvm::Triple::ppc64) ? "/64" : "/32"; + if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) { + GCCMultiarchSuffix = MultiarchSuffix.str(); + } else { + if (NeedsMultiarchSuffix || + !llvm::sys::fs::exists(LI->path() + "/crtbegin.o")) + continue; + GCCMultiarchSuffix.clear(); + } + + Version = CandidateVersion; + GCCTriple.setTriple(CandidateTriple); + // FIXME: We hack together the directory name here instead of + // using LI to ensure stable path separators across Windows and + // Linux. + GCCInstallPath = LibDir + LibSuffixes[i] + "/" + VersionText.str(); + GCCParentLibPath = GCCInstallPath + InstallSuffixes[i]; + IsValid = true; + } + } +} + +Generic_GCC::Generic_GCC(const Driver &D, const llvm::Triple& Triple, + const ArgList &Args) + : ToolChain(D, Triple), GCCInstallation(getDriver(), Triple, Args) { + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir) + getProgramPaths().push_back(getDriver().Dir); +} + +Generic_GCC::~Generic_GCC() { + // Free tool implementations. + for (llvm::DenseMap<unsigned, Tool*>::iterator + it = Tools.begin(), ie = Tools.end(); it != ie; ++it) + delete it->second; +} + +Tool &Generic_GCC::SelectTool(const Compilation &C, + const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::InputClass: + case Action::BindArchClass: + llvm_unreachable("Invalid tool kind."); + case Action::PreprocessJobClass: + T = new tools::gcc::Preprocess(*this); break; + case Action::PrecompileJobClass: + T = new tools::gcc::Precompile(*this); break; + case Action::AnalyzeJobClass: + case Action::MigrateJobClass: + T = new tools::Clang(*this); break; + case Action::CompileJobClass: + T = new tools::gcc::Compile(*this); break; + case Action::AssembleJobClass: + T = new tools::gcc::Assemble(*this); break; + case Action::LinkJobClass: + T = new tools::gcc::Link(*this); break; + + // This is a bit ungeneric, but the only platform using a driver + // driver is Darwin. + case Action::LipoJobClass: + T = new tools::darwin::Lipo(*this); break; + case Action::DsymutilJobClass: + T = new tools::darwin::Dsymutil(*this); break; + case Action::VerifyJobClass: + T = new tools::darwin::VerifyDebug(*this); break; + } + } + + return *T; +} + +bool Generic_GCC::IsUnwindTablesDefault() const { + // FIXME: Gross; we should probably have some separate target + // definition, possibly even reusing the one in clang. + return getArchName() == "x86_64"; +} + +const char *Generic_GCC::GetDefaultRelocationModel() const { + return "static"; +} + +const char *Generic_GCC::GetForcedPicModel() const { + return 0; +} +/// Hexagon Toolchain + +Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple& Triple) + : ToolChain(D, Triple) { + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir.c_str()) + getProgramPaths().push_back(getDriver().Dir); +} + +Hexagon_TC::~Hexagon_TC() { + // Free tool implementations. + for (llvm::DenseMap<unsigned, Tool*>::iterator + it = Tools.begin(), ie = Tools.end(); it != ie; ++it) + delete it->second; +} + +Tool &Hexagon_TC::SelectTool(const Compilation &C, + const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + // if (JA.getKind () == Action::CompileJobClass) + // Key = JA.getKind (); + // else + + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + // if ((JA.getKind () == Action::CompileJobClass) + // && (JA.getType () != types::TY_LTO_BC)) { + // Key = JA.getKind (); + // } + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::InputClass: + case Action::BindArchClass: + assert(0 && "Invalid tool kind."); + case Action::AnalyzeJobClass: + T = new tools::Clang(*this); break; + case Action::AssembleJobClass: + T = new tools::hexagon::Assemble(*this); break; + case Action::LinkJobClass: + T = new tools::hexagon::Link(*this); break; + default: + assert(false && "Unsupported action for Hexagon target."); + } + } + + return *T; +} + +bool Hexagon_TC::IsUnwindTablesDefault() const { + // FIXME: Gross; we should probably have some separate target + // definition, possibly even reusing the one in clang. + return getArchName() == "x86_64"; +} + +const char *Hexagon_TC::GetDefaultRelocationModel() const { + return "static"; +} + +const char *Hexagon_TC::GetForcedPicModel() const { + return 0; +} // End Hexagon + + +/// TCEToolChain - A tool chain using the llvm bitcode tools to perform +/// all subcommands. See http://tce.cs.tut.fi for our peculiar target. +/// Currently does not support anything else but compilation. + +TCEToolChain::TCEToolChain(const Driver &D, const llvm::Triple& Triple) + : ToolChain(D, Triple) { + // Path mangling to find libexec + std::string Path(getDriver().Dir); + + Path += "/../libexec"; + getProgramPaths().push_back(Path); +} + +TCEToolChain::~TCEToolChain() { + for (llvm::DenseMap<unsigned, Tool*>::iterator + it = Tools.begin(), ie = Tools.end(); it != ie; ++it) + delete it->second; +} + +bool TCEToolChain::IsMathErrnoDefault() const { + return true; +} + +bool TCEToolChain::IsUnwindTablesDefault() const { + return false; +} + +const char *TCEToolChain::GetDefaultRelocationModel() const { + return "static"; +} + +const char *TCEToolChain::GetForcedPicModel() const { + return 0; +} + +Tool &TCEToolChain::SelectTool(const Compilation &C, + const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + Key = Action::AnalyzeJobClass; + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::PreprocessJobClass: + T = new tools::gcc::Preprocess(*this); break; + case Action::AnalyzeJobClass: + T = new tools::Clang(*this); break; + default: + llvm_unreachable("Unsupported action for TCE target."); + } + } + return *T; +} + +/// OpenBSD - OpenBSD tool chain which can call as(1) and ld(1) directly. + +OpenBSD::OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + getFilePaths().push_back(getDriver().Dir + "/../lib"); + getFilePaths().push_back("/usr/lib"); +} + +Tool &OpenBSD::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIntegratedAssemblerDefault()); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: { + if (UseIntegratedAs) + T = new tools::ClangAs(*this); + else + T = new tools::openbsd::Assemble(*this); + break; + } + case Action::LinkJobClass: + T = new tools::openbsd::Link(*this); break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} + +/// FreeBSD - FreeBSD tool chain which can call as(1) and ld(1) directly. + +FreeBSD::FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + + // When targeting 32-bit platforms, look for '/usr/lib32/crt1.o' and fall + // back to '/usr/lib' if it doesn't exist. + if ((Triple.getArch() == llvm::Triple::x86 || + Triple.getArch() == llvm::Triple::ppc) && + llvm::sys::fs::exists(getDriver().SysRoot + "/usr/lib32/crt1.o")) + getFilePaths().push_back(getDriver().SysRoot + "/usr/lib32"); + else + getFilePaths().push_back(getDriver().SysRoot + "/usr/lib"); +} + +Tool &FreeBSD::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIntegratedAssemblerDefault()); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: + if (UseIntegratedAs) + T = new tools::ClangAs(*this); + else + T = new tools::freebsd::Assemble(*this); + break; + case Action::LinkJobClass: + T = new tools::freebsd::Link(*this); break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} + +/// NetBSD - NetBSD tool chain which can call as(1) and ld(1) directly. + +NetBSD::NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + + if (getDriver().UseStdLib) { + // When targeting a 32-bit platform, try the special directory used on + // 64-bit hosts, and only fall back to the main library directory if that + // doesn't work. + // FIXME: It'd be nicer to test if this directory exists, but I'm not sure + // what all logic is needed to emulate the '=' prefix here. + if (Triple.getArch() == llvm::Triple::x86) + getFilePaths().push_back("=/usr/lib/i386"); + + getFilePaths().push_back("=/usr/lib"); + } +} + +Tool &NetBSD::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIntegratedAssemblerDefault()); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: + if (UseIntegratedAs) + T = new tools::ClangAs(*this); + else + T = new tools::netbsd::Assemble(*this); + break; + case Action::LinkJobClass: + T = new tools::netbsd::Link(*this); + break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} + +/// Minix - Minix tool chain which can call as(1) and ld(1) directly. + +Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + getFilePaths().push_back(getDriver().Dir + "/../lib"); + getFilePaths().push_back("/usr/lib"); +} + +Tool &Minix::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: + T = new tools::minix::Assemble(*this); break; + case Action::LinkJobClass: + T = new tools::minix::Link(*this); break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} + +/// AuroraUX - AuroraUX tool chain which can call as(1) and ld(1) directly. + +AuroraUX::AuroraUX(const Driver &D, const llvm::Triple& Triple, + const ArgList &Args) + : Generic_GCC(D, Triple, Args) { + + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir) + getProgramPaths().push_back(getDriver().Dir); + + getFilePaths().push_back(getDriver().Dir + "/../lib"); + getFilePaths().push_back("/usr/lib"); + getFilePaths().push_back("/usr/sfw/lib"); + getFilePaths().push_back("/opt/gcc4/lib"); + getFilePaths().push_back("/opt/gcc4/lib/gcc/i386-pc-solaris2.11/4.2.4"); + +} + +Tool &AuroraUX::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: + T = new tools::auroraux::Assemble(*this); break; + case Action::LinkJobClass: + T = new tools::auroraux::Link(*this); break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} + +/// Solaris - Solaris tool chain which can call as(1) and ld(1) directly. + +Solaris::Solaris(const Driver &D, const llvm::Triple& Triple, + const ArgList &Args) + : Generic_GCC(D, Triple, Args) { + + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir) + getProgramPaths().push_back(getDriver().Dir); + + getFilePaths().push_back(getDriver().Dir + "/../lib"); + getFilePaths().push_back("/usr/lib"); +} + +Tool &Solaris::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: + T = new tools::solaris::Assemble(*this); break; + case Action::LinkJobClass: + T = new tools::solaris::Link(*this); break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} + +/// Linux toolchain (very bare-bones at the moment). + +enum LinuxDistro { + ArchLinux, + DebianLenny, + DebianSqueeze, + DebianWheezy, + Exherbo, + RHEL4, + RHEL5, + RHEL6, + Fedora13, + Fedora14, + Fedora15, + Fedora16, + FedoraRawhide, + OpenSuse11_3, + OpenSuse11_4, + OpenSuse12_1, + OpenSuse12_2, + UbuntuHardy, + UbuntuIntrepid, + UbuntuJaunty, + UbuntuKarmic, + UbuntuLucid, + UbuntuMaverick, + UbuntuNatty, + UbuntuOneiric, + UbuntuPrecise, + UnknownDistro +}; + +static bool IsRedhat(enum LinuxDistro Distro) { + return (Distro >= Fedora13 && Distro <= FedoraRawhide) || + (Distro >= RHEL4 && Distro <= RHEL6); +} + +static bool IsOpenSuse(enum LinuxDistro Distro) { + return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2; +} + +static bool IsDebian(enum LinuxDistro Distro) { + return Distro >= DebianLenny && Distro <= DebianWheezy; +} + +static bool IsUbuntu(enum LinuxDistro Distro) { + return Distro >= UbuntuHardy && Distro <= UbuntuPrecise; +} + +static LinuxDistro DetectLinuxDistro(llvm::Triple::ArchType Arch) { + OwningPtr<llvm::MemoryBuffer> File; + if (!llvm::MemoryBuffer::getFile("/etc/lsb-release", File)) { + StringRef Data = File.get()->getBuffer(); + SmallVector<StringRef, 8> Lines; + Data.split(Lines, "\n"); + LinuxDistro Version = UnknownDistro; + for (unsigned i = 0, s = Lines.size(); i != s; ++i) + if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME=")) + Version = llvm::StringSwitch<LinuxDistro>(Lines[i].substr(17)) + .Case("hardy", UbuntuHardy) + .Case("intrepid", UbuntuIntrepid) + .Case("jaunty", UbuntuJaunty) + .Case("karmic", UbuntuKarmic) + .Case("lucid", UbuntuLucid) + .Case("maverick", UbuntuMaverick) + .Case("natty", UbuntuNatty) + .Case("oneiric", UbuntuOneiric) + .Case("precise", UbuntuPrecise) + .Default(UnknownDistro); + return Version; + } + + if (!llvm::MemoryBuffer::getFile("/etc/redhat-release", File)) { + StringRef Data = File.get()->getBuffer(); + if (Data.startswith("Fedora release 16")) + return Fedora16; + else if (Data.startswith("Fedora release 15")) + return Fedora15; + else if (Data.startswith("Fedora release 14")) + return Fedora14; + else if (Data.startswith("Fedora release 13")) + return Fedora13; + else if (Data.startswith("Fedora release") && + Data.find("Rawhide") != StringRef::npos) + return FedoraRawhide; + else if (Data.startswith("Red Hat Enterprise Linux") && + Data.find("release 6") != StringRef::npos) + return RHEL6; + else if ((Data.startswith("Red Hat Enterprise Linux") || + Data.startswith("CentOS")) && + Data.find("release 5") != StringRef::npos) + return RHEL5; + else if ((Data.startswith("Red Hat Enterprise Linux") || + Data.startswith("CentOS")) && + Data.find("release 4") != StringRef::npos) + return RHEL4; + return UnknownDistro; + } + + if (!llvm::MemoryBuffer::getFile("/etc/debian_version", File)) { + StringRef Data = File.get()->getBuffer(); + if (Data[0] == '5') + return DebianLenny; + else if (Data.startswith("squeeze/sid") || Data[0] == '6') + return DebianSqueeze; + else if (Data.startswith("wheezy/sid") || Data[0] == '7') + return DebianWheezy; + return UnknownDistro; + } + + if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) + return llvm::StringSwitch<LinuxDistro>(File.get()->getBuffer()) + .StartsWith("openSUSE 11.3", OpenSuse11_3) + .StartsWith("openSUSE 11.4", OpenSuse11_4) + .StartsWith("openSUSE 12.1", OpenSuse12_1) + .StartsWith("openSUSE 12.2", OpenSuse12_2) + .Default(UnknownDistro); + + bool Exists; + if (!llvm::sys::fs::exists("/etc/exherbo-release", Exists) && Exists) + return Exherbo; + + if (!llvm::sys::fs::exists("/etc/arch-release", Exists) && Exists) + return ArchLinux; + + return UnknownDistro; +} + +/// \brief Get our best guess at the multiarch triple for a target. +/// +/// Debian-based systems are starting to use a multiarch setup where they use +/// a target-triple directory in the library and header search paths. +/// Unfortunately, this triple does not align with the vanilla target triple, +/// so we provide a rough mapping here. +static std::string getMultiarchTriple(const llvm::Triple TargetTriple, + StringRef SysRoot) { + // For most architectures, just use whatever we have rather than trying to be + // clever. + switch (TargetTriple.getArch()) { + default: + return TargetTriple.str(); + + // We use the existence of '/lib/<triple>' as a directory to detect some + // common linux triples that don't quite match the Clang triple for both + // 32-bit and 64-bit targets. Multiarch fixes its install triples to these + // regardless of what the actual target triple is. + case llvm::Triple::x86: + if (llvm::sys::fs::exists(SysRoot + "/lib/i386-linux-gnu")) + return "i386-linux-gnu"; + return TargetTriple.str(); + case llvm::Triple::x86_64: + if (llvm::sys::fs::exists(SysRoot + "/lib/x86_64-linux-gnu")) + return "x86_64-linux-gnu"; + return TargetTriple.str(); + case llvm::Triple::mips: + if (llvm::sys::fs::exists(SysRoot + "/lib/mips-linux-gnu")) + return "mips-linux-gnu"; + return TargetTriple.str(); + case llvm::Triple::mipsel: + if (llvm::sys::fs::exists(SysRoot + "/lib/mipsel-linux-gnu")) + return "mipsel-linux-gnu"; + return TargetTriple.str(); + case llvm::Triple::ppc: + if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc-linux-gnu")) + return "powerpc-linux-gnu"; + return TargetTriple.str(); + case llvm::Triple::ppc64: + if (llvm::sys::fs::exists(SysRoot + "/lib/powerpc64-linux-gnu")) + return "powerpc64-linux-gnu"; + return TargetTriple.str(); + } +} + +static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) { + if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str()); +} + +Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + llvm::Triple::ArchType Arch = Triple.getArch(); + const std::string &SysRoot = getDriver().SysRoot; + + // OpenSuse stores the linker with the compiler, add that to the search + // path. + ToolChain::path_list &PPaths = getProgramPaths(); + PPaths.push_back(Twine(GCCInstallation.getParentLibPath() + "/../" + + GCCInstallation.getTriple().str() + "/bin").str()); + + Linker = GetProgramPath("ld"); + + LinuxDistro Distro = DetectLinuxDistro(Arch); + + if (IsOpenSuse(Distro) || IsUbuntu(Distro)) { + ExtraOpts.push_back("-z"); + ExtraOpts.push_back("relro"); + } + + if (Arch == llvm::Triple::arm || Arch == llvm::Triple::thumb) + ExtraOpts.push_back("-X"); + + const bool IsMips = Arch == llvm::Triple::mips || + Arch == llvm::Triple::mipsel || + Arch == llvm::Triple::mips64 || + Arch == llvm::Triple::mips64el; + + const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::ANDROIDEABI; + + // Do not use 'gnu' hash style for Mips targets because .gnu.hash + // and the MIPS ABI require .dynsym to be sorted in different ways. + // .gnu.hash needs symbols to be grouped by hash code whereas the MIPS + // ABI requires a mapping between the GOT and the symbol table. + // Android loader does not support .gnu.hash. + if (!IsMips && !IsAndroid) { + if (IsRedhat(Distro) || IsOpenSuse(Distro) || + (IsUbuntu(Distro) && Distro >= UbuntuMaverick)) + ExtraOpts.push_back("--hash-style=gnu"); + + if (IsDebian(Distro) || IsOpenSuse(Distro) || Distro == UbuntuLucid || + Distro == UbuntuJaunty || Distro == UbuntuKarmic) + ExtraOpts.push_back("--hash-style=both"); + } + + if (IsRedhat(Distro)) + ExtraOpts.push_back("--no-add-needed"); + + if (Distro == DebianSqueeze || Distro == DebianWheezy || + IsOpenSuse(Distro) || + (IsRedhat(Distro) && Distro != RHEL4 && Distro != RHEL5) || + (IsUbuntu(Distro) && Distro >= UbuntuKarmic)) + ExtraOpts.push_back("--build-id"); + + if (IsOpenSuse(Distro)) + ExtraOpts.push_back("--enable-new-dtags"); + + // The selection of paths to try here is designed to match the patterns which + // the GCC driver itself uses, as this is part of the GCC-compatible driver. + // This was determined by running GCC in a fake filesystem, creating all + // possible permutations of these directories, and seeing which ones it added + // to the link paths. + path_list &Paths = getFilePaths(); + + const std::string Multilib = Triple.isArch32Bit() ? "lib32" : "lib64"; + const std::string MultiarchTriple = getMultiarchTriple(Triple, SysRoot); + + // Add the multilib suffixed paths where they are available. + if (GCCInstallation.isValid()) { + const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); + const std::string &LibPath = GCCInstallation.getParentLibPath(); + addPathIfExists((GCCInstallation.getInstallPath() + + GCCInstallation.getMultiarchSuffix()), + Paths); + + // If the GCC installation we found is inside of the sysroot, we want to + // prefer libraries installed in the parent prefix of the GCC installation. + // It is important to *not* use these paths when the GCC installation is + // outside of the system root as that can pick up unintended libraries. + // This usually happens when there is an external cross compiler on the + // host system, and a more minimal sysroot available that is the target of + // the cross. + if (StringRef(LibPath).startswith(SysRoot)) { + addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" + Multilib, + Paths); + addPathIfExists(LibPath + "/" + MultiarchTriple, Paths); + addPathIfExists(LibPath + "/../" + Multilib, Paths); + } + } + addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths); + addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths); + addPathIfExists(SysRoot + "/usr/lib/" + MultiarchTriple, Paths); + addPathIfExists(SysRoot + "/usr/lib/../" + Multilib, Paths); + + // Try walking via the GCC triple path in case of multiarch GCC + // installations with strange symlinks. + if (GCCInstallation.isValid()) + addPathIfExists(SysRoot + "/usr/lib/" + GCCInstallation.getTriple().str() + + "/../../" + Multilib, Paths); + + // Add the non-multilib suffixed paths (if potentially different). + if (GCCInstallation.isValid()) { + const std::string &LibPath = GCCInstallation.getParentLibPath(); + const llvm::Triple &GCCTriple = GCCInstallation.getTriple(); + if (!GCCInstallation.getMultiarchSuffix().empty()) + addPathIfExists(GCCInstallation.getInstallPath(), Paths); + + if (StringRef(LibPath).startswith(SysRoot)) { + addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths); + addPathIfExists(LibPath, Paths); + } + } + addPathIfExists(SysRoot + "/lib", Paths); + addPathIfExists(SysRoot + "/usr/lib", Paths); +} + +bool Linux::HasNativeLLVMSupport() const { + return true; +} + +Tool &Linux::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIntegratedAssemblerDefault()); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: + if (UseIntegratedAs) + T = new tools::ClangAs(*this); + else + T = new tools::linuxtools::Assemble(*this); + break; + case Action::LinkJobClass: + T = new tools::linuxtools::Link(*this); break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} + +void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + const Driver &D = getDriver(); + + if (DriverArgs.hasArg(options::OPT_nostdinc)) + return; + + if (!DriverArgs.hasArg(options::OPT_nostdlibinc)) + addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include"); + + if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { + llvm::sys::Path P(D.ResourceDir); + P.appendComponent("include"); + addSystemInclude(DriverArgs, CC1Args, P.str()); + } + + if (DriverArgs.hasArg(options::OPT_nostdlibinc)) + return; + + // Check for configure-time C include directories. + StringRef CIncludeDirs(C_INCLUDE_DIRS); + if (CIncludeDirs != "") { + SmallVector<StringRef, 5> dirs; + CIncludeDirs.split(dirs, ":"); + for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end(); + I != E; ++I) { + StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : ""; + addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I); + } + return; + } + + // Lacking those, try to detect the correct set of system includes for the + // target triple. + + // Implement generic Debian multiarch support. + const StringRef X86_64MultiarchIncludeDirs[] = { + "/usr/include/x86_64-linux-gnu", + + // FIXME: These are older forms of multiarch. It's not clear that they're + // in use in any released version of Debian, so we should consider + // removing them. + "/usr/include/i686-linux-gnu/64", + "/usr/include/i486-linux-gnu/64" + }; + const StringRef X86MultiarchIncludeDirs[] = { + "/usr/include/i386-linux-gnu", + + // FIXME: These are older forms of multiarch. It's not clear that they're + // in use in any released version of Debian, so we should consider + // removing them. + "/usr/include/x86_64-linux-gnu/32", + "/usr/include/i686-linux-gnu", + "/usr/include/i486-linux-gnu" + }; + const StringRef ARMMultiarchIncludeDirs[] = { + "/usr/include/arm-linux-gnueabi" + }; + const StringRef MIPSMultiarchIncludeDirs[] = { + "/usr/include/mips-linux-gnu" + }; + const StringRef MIPSELMultiarchIncludeDirs[] = { + "/usr/include/mipsel-linux-gnu" + }; + const StringRef PPCMultiarchIncludeDirs[] = { + "/usr/include/powerpc-linux-gnu" + }; + const StringRef PPC64MultiarchIncludeDirs[] = { + "/usr/include/powerpc64-linux-gnu" + }; + ArrayRef<StringRef> MultiarchIncludeDirs; + if (getTriple().getArch() == llvm::Triple::x86_64) { + MultiarchIncludeDirs = X86_64MultiarchIncludeDirs; + } else if (getTriple().getArch() == llvm::Triple::x86) { + MultiarchIncludeDirs = X86MultiarchIncludeDirs; + } else if (getTriple().getArch() == llvm::Triple::arm) { + MultiarchIncludeDirs = ARMMultiarchIncludeDirs; + } else if (getTriple().getArch() == llvm::Triple::mips) { + MultiarchIncludeDirs = MIPSMultiarchIncludeDirs; + } else if (getTriple().getArch() == llvm::Triple::mipsel) { + MultiarchIncludeDirs = MIPSELMultiarchIncludeDirs; + } else if (getTriple().getArch() == llvm::Triple::ppc) { + MultiarchIncludeDirs = PPCMultiarchIncludeDirs; + } else if (getTriple().getArch() == llvm::Triple::ppc64) { + MultiarchIncludeDirs = PPC64MultiarchIncludeDirs; + } + for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(), + E = MultiarchIncludeDirs.end(); + I != E; ++I) { + if (llvm::sys::fs::exists(D.SysRoot + *I)) { + addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I); + break; + } + } + + if (getTriple().getOS() == llvm::Triple::RTEMS) + return; + + // Add an include of '/include' directly. This isn't provided by default by + // system GCCs, but is often used with cross-compiling GCCs, and harmless to + // add even when Clang is acting as-if it were a system compiler. + addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include"); + + addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include"); +} + +/// \brief Helper to add the thre variant paths for a libstdc++ installation. +/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir, + const ArgList &DriverArgs, + ArgStringList &CC1Args) { + if (!llvm::sys::fs::exists(Base)) + return false; + addSystemInclude(DriverArgs, CC1Args, Base); + addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir); + addSystemInclude(DriverArgs, CC1Args, Base + "/backward"); + return true; +} + +void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + if (DriverArgs.hasArg(options::OPT_nostdlibinc) || + DriverArgs.hasArg(options::OPT_nostdincxx)) + return; + + // Check if libc++ has been enabled and provide its include paths if so. + if (GetCXXStdlibType(DriverArgs) == ToolChain::CST_Libcxx) { + // libc++ is always installed at a fixed path on Linux currently. + addSystemInclude(DriverArgs, CC1Args, + getDriver().SysRoot + "/usr/include/c++/v1"); + return; + } + + // We need a detected GCC installation on Linux to provide libstdc++'s + // headers. We handled the libc++ case above. + if (!GCCInstallation.isValid()) + return; + + // By default, look for the C++ headers in an include directory adjacent to + // the lib directory of the GCC installation. Note that this is expect to be + // equivalent to '/usr/include/c++/X.Y' in almost all cases. + StringRef LibDir = GCCInstallation.getParentLibPath(); + StringRef InstallDir = GCCInstallation.getInstallPath(); + StringRef Version = GCCInstallation.getVersion(); + if (!addLibStdCXXIncludePaths(LibDir + "/../include/c++/" + Version, + (GCCInstallation.getTriple().str() + + GCCInstallation.getMultiarchSuffix()), + DriverArgs, CC1Args)) { + // Gentoo is weird and places its headers inside the GCC install, so if the + // first attempt to find the headers fails, try this pattern. + addLibStdCXXIncludePaths(InstallDir + "/include/g++-v4", + (GCCInstallation.getTriple().str() + + GCCInstallation.getMultiarchSuffix()), + DriverArgs, CC1Args); + } +} + +/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly. + +DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) + : Generic_ELF(D, Triple, Args) { + + // Path mangling to find libexec + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir) + getProgramPaths().push_back(getDriver().Dir); + + getFilePaths().push_back(getDriver().Dir + "/../lib"); + getFilePaths().push_back("/usr/lib"); + getFilePaths().push_back("/usr/lib/gcc41"); +} + +Tool &DragonFly::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::AssembleJobClass: + T = new tools::dragonfly::Assemble(*this); break; + case Action::LinkJobClass: + T = new tools::dragonfly::Link(*this); break; + default: + T = &Generic_GCC::SelectTool(C, JA, Inputs); + } + } + + return *T; +} diff --git a/clang/lib/Driver/ToolChains.h b/clang/lib/Driver/ToolChains.h new file mode 100644 index 0000000..eaa6be1 --- /dev/null +++ b/clang/lib/Driver/ToolChains.h @@ -0,0 +1,596 @@ +//===--- ToolChains.h - ToolChain Implementations ---------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef CLANG_LIB_DRIVER_TOOLCHAINS_H_ +#define CLANG_LIB_DRIVER_TOOLCHAINS_H_ + +#include "clang/Driver/Action.h" +#include "clang/Driver/ToolChain.h" + +#include "clang/Basic/VersionTuple.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/Support/Compiler.h" + +#include "Tools.h" + +namespace clang { +namespace driver { +namespace toolchains { + +/// Generic_GCC - A tool chain using the 'gcc' command to perform +/// all subcommands; this relies on gcc translating the majority of +/// command line options. +class LLVM_LIBRARY_VISIBILITY Generic_GCC : public ToolChain { +protected: + /// \brief Struct to store and manipulate GCC versions. + /// + /// We rely on assumptions about the form and structure of GCC version + /// numbers: they consist of at most three '.'-separated components, and each + /// component is a non-negative integer except for the last component. For + /// the last component we are very flexible in order to tolerate release + /// candidates or 'x' wildcards. + /// + /// Note that the ordering established among GCCVersions is based on the + /// preferred version string to use. For example we prefer versions without + /// a hard-coded patch number to those with a hard coded patch number. + /// + /// Currently this doesn't provide any logic for textual suffixes to patches + /// in the way that (for example) Debian's version format does. If that ever + /// becomes necessary, it can be added. + struct GCCVersion { + /// \brief The unparsed text of the version. + std::string Text; + + /// \brief The parsed major, minor, and patch numbers. + int Major, Minor, Patch; + + /// \brief Any textual suffix on the patch number. + std::string PatchSuffix; + + static GCCVersion Parse(StringRef VersionText); + bool operator<(const GCCVersion &RHS) const; + bool operator>(const GCCVersion &RHS) const { return RHS < *this; } + bool operator<=(const GCCVersion &RHS) const { return !(*this > RHS); } + bool operator>=(const GCCVersion &RHS) const { return !(*this < RHS); } + }; + + + /// \brief This is a class to find a viable GCC installation for Clang to + /// use. + /// + /// This class tries to find a GCC installation on the system, and report + /// information about it. It starts from the host information provided to the + /// Driver, and has logic for fuzzing that where appropriate. + class GCCInstallationDetector { + + bool IsValid; + llvm::Triple GCCTriple; + + // FIXME: These might be better as path objects. + std::string GCCInstallPath; + std::string GCCMultiarchSuffix; + std::string GCCParentLibPath; + + GCCVersion Version; + + public: + GCCInstallationDetector(const Driver &D, const llvm::Triple &TargetTriple, + const ArgList &Args); + + /// \brief Check whether we detected a valid GCC install. + bool isValid() const { return IsValid; } + + /// \brief Get the GCC triple for the detected install. + const llvm::Triple &getTriple() const { return GCCTriple; } + + /// \brief Get the detected GCC installation path. + StringRef getInstallPath() const { return GCCInstallPath; } + + /// \brief Get the detected GCC installation path suffix for multiarch GCCs. + StringRef getMultiarchSuffix() const { return GCCMultiarchSuffix; } + + /// \brief Get the detected GCC parent lib path. + StringRef getParentLibPath() const { return GCCParentLibPath; } + + /// \brief Get the detected GCC version string. + StringRef getVersion() const { return Version.Text; } + + private: + static void CollectLibDirsAndTriples( + const llvm::Triple &TargetTriple, + const llvm::Triple &MultiarchTriple, + SmallVectorImpl<StringRef> &LibDirs, + SmallVectorImpl<StringRef> &TripleAliases, + SmallVectorImpl<StringRef> &MultiarchLibDirs, + SmallVectorImpl<StringRef> &MultiarchTripleAliases); + + void ScanLibDirForGCCTriple(llvm::Triple::ArchType TargetArch, + const std::string &LibDir, + StringRef CandidateTriple, + bool NeedsMultiarchSuffix = false); + }; + + GCCInstallationDetector GCCInstallation; + + mutable llvm::DenseMap<unsigned, Tool*> Tools; + +public: + Generic_GCC(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + ~Generic_GCC(); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; + + virtual bool IsUnwindTablesDefault() const; + virtual const char *GetDefaultRelocationModel() const; + virtual const char *GetForcedPicModel() const; + +protected: + /// \name ToolChain Implementation Helper Functions + /// @{ + + /// \brief Check whether the target triple's architecture is 64-bits. + bool isTarget64Bit() const { return getTriple().isArch64Bit(); } + + /// \brief Check whether the target triple's architecture is 32-bits. + bool isTarget32Bit() const { return getTriple().isArch32Bit(); } + + /// @} +}; + +class LLVM_LIBRARY_VISIBILITY Hexagon_TC : public ToolChain { +protected: + mutable llvm::DenseMap<unsigned, Tool*> Tools; + +public: + Hexagon_TC(const Driver &D, const llvm::Triple& Triple); + ~Hexagon_TC(); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; + + virtual bool IsUnwindTablesDefault() const; + virtual const char *GetDefaultRelocationModel() const; + virtual const char *GetForcedPicModel() const; +}; + + /// Darwin - The base Darwin tool chain. +class LLVM_LIBRARY_VISIBILITY Darwin : public ToolChain { +public: + /// The host version. + unsigned DarwinVersion[3]; + +private: + mutable llvm::DenseMap<unsigned, Tool*> Tools; + + /// Whether the information on the target has been initialized. + // + // FIXME: This should be eliminated. What we want to do is make this part of + // the "default target for arguments" selection process, once we get out of + // the argument translation business. + mutable bool TargetInitialized; + + // FIXME: Remove this once there is a proper way to detect an ARC runtime + // for the simulator. + public: + mutable enum { + ARCSimulator_None, + ARCSimulator_HasARCRuntime, + ARCSimulator_NoARCRuntime + } ARCRuntimeForSimulator; + + mutable enum { + LibCXXSimulator_None, + LibCXXSimulator_NotAvailable, + LibCXXSimulator_Available + } LibCXXForSimulator; + +private: + /// Whether we are targeting iPhoneOS target. + mutable bool TargetIsIPhoneOS; + + /// Whether we are targeting the iPhoneOS simulator target. + mutable bool TargetIsIPhoneOSSimulator; + + /// The OS version we are targeting. + mutable VersionTuple TargetVersion; + + /// The default macosx-version-min of this tool chain; empty until + /// initialized. + std::string MacosxVersionMin; + + bool hasARCRuntime() const; + bool hasSubscriptingRuntime() const; + +private: + void AddDeploymentTarget(DerivedArgList &Args) const; + +public: + Darwin(const Driver &D, const llvm::Triple& Triple); + ~Darwin(); + + std::string ComputeEffectiveClangTriple(const ArgList &Args, + types::ID InputType) const; + + /// @name Darwin Specific Toolchain API + /// { + + // FIXME: Eliminate these ...Target functions and derive separate tool chains + // for these targets and put version in constructor. + void setTarget(bool IsIPhoneOS, unsigned Major, unsigned Minor, + unsigned Micro, bool IsIOSSim) const { + assert((!IsIOSSim || IsIPhoneOS) && "Unexpected deployment target!"); + + // FIXME: For now, allow reinitialization as long as values don't + // change. This will go away when we move away from argument translation. + if (TargetInitialized && TargetIsIPhoneOS == IsIPhoneOS && + TargetIsIPhoneOSSimulator == IsIOSSim && + TargetVersion == VersionTuple(Major, Minor, Micro)) + return; + + assert(!TargetInitialized && "Target already initialized!"); + TargetInitialized = true; + TargetIsIPhoneOS = IsIPhoneOS; + TargetIsIPhoneOSSimulator = IsIOSSim; + TargetVersion = VersionTuple(Major, Minor, Micro); + } + + bool isTargetIPhoneOS() const { + assert(TargetInitialized && "Target not initialized!"); + return TargetIsIPhoneOS; + } + + bool isTargetIOSSimulator() const { + assert(TargetInitialized && "Target not initialized!"); + return TargetIsIPhoneOSSimulator; + } + + bool isTargetMacOS() const { + return !isTargetIOSSimulator() && + !isTargetIPhoneOS() && + ARCRuntimeForSimulator == ARCSimulator_None; + } + + bool isTargetInitialized() const { return TargetInitialized; } + + VersionTuple getTargetVersion() const { + assert(TargetInitialized && "Target not initialized!"); + return TargetVersion; + } + + /// getDarwinArchName - Get the "Darwin" arch name for a particular compiler + /// invocation. For example, Darwin treats different ARM variations as + /// distinct architectures. + StringRef getDarwinArchName(const ArgList &Args) const; + + bool isIPhoneOSVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const { + assert(isTargetIPhoneOS() && "Unexpected call for OS X target!"); + return TargetVersion < VersionTuple(V0, V1, V2); + } + + bool isMacosxVersionLT(unsigned V0, unsigned V1=0, unsigned V2=0) const { + assert(!isTargetIPhoneOS() && "Unexpected call for iPhoneOS target!"); + return TargetVersion < VersionTuple(V0, V1, V2); + } + + /// AddLinkSearchPathArgs - Add the linker search paths to \arg CmdArgs. + /// + /// \param Args - The input argument list. + /// \param CmdArgs [out] - The command argument list to append the paths + /// (prefixed by -L) to. + virtual void AddLinkSearchPathArgs(const ArgList &Args, + ArgStringList &CmdArgs) const = 0; + + /// AddLinkARCArgs - Add the linker arguments to link the ARC runtime library. + virtual void AddLinkARCArgs(const ArgList &Args, + ArgStringList &CmdArgs) const = 0; + + /// AddLinkRuntimeLibArgs - Add the linker arguments to link the compiler + /// runtime library. + virtual void AddLinkRuntimeLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const = 0; + + /// } + /// @name ToolChain Implementation + /// { + + virtual types::ID LookupTypeForExtension(const char *Ext) const; + + virtual bool HasNativeLLVMSupport() const; + + virtual void configureObjCRuntime(ObjCRuntime &runtime) const; + virtual bool hasBlocksRuntime() const; + + virtual DerivedArgList *TranslateArgs(const DerivedArgList &Args, + const char *BoundArch) const; + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; + + virtual bool IsBlocksDefault() const { + // Always allow blocks on Darwin; users interested in versioning are + // expected to use /usr/include/Blocks.h. + return true; + } + virtual bool IsIntegratedAssemblerDefault() const { +#ifdef DISABLE_DEFAULT_INTEGRATED_ASSEMBLER + return false; +#else + // Default integrated assembler to on for Darwin. + return true; +#endif + } + virtual bool IsStrictAliasingDefault() const { +#ifdef DISABLE_DEFAULT_STRICT_ALIASING + return false; +#else + return ToolChain::IsStrictAliasingDefault(); +#endif + } + + virtual bool IsObjCDefaultSynthPropertiesDefault() const { + return true; + } + + virtual bool IsObjCNonFragileABIDefault() const { + // Non-fragile ABI is default for everything but i386. + return getTriple().getArch() != llvm::Triple::x86; + } + virtual bool IsObjCLegacyDispatchDefault() const { + // This is only used with the non-fragile ABI. + + // Legacy dispatch is used everywhere except on x86_64. + return getTriple().getArch() != llvm::Triple::x86_64; + } + virtual bool UseObjCMixedDispatch() const { + // This is only used with the non-fragile ABI and non-legacy dispatch. + + // Mixed dispatch is used everywhere except OS X before 10.6. + return !(!isTargetIPhoneOS() && isMacosxVersionLT(10, 6)); + } + virtual bool IsUnwindTablesDefault() const; + virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const { + // Stack protectors default to on for user code on 10.5, + // and for everything in 10.6 and beyond + return isTargetIPhoneOS() || + (!isMacosxVersionLT(10, 6) || + (!isMacosxVersionLT(10, 5) && !KernelOrKext)); + } + virtual RuntimeLibType GetDefaultRuntimeLibType() const { + return ToolChain::RLT_CompilerRT; + } + virtual const char *GetDefaultRelocationModel() const; + virtual const char *GetForcedPicModel() const; + + virtual bool SupportsProfiling() const; + + virtual bool SupportsObjCGC() const; + + virtual bool SupportsObjCARC() const; + + virtual bool UseDwarfDebugFlags() const; + + virtual bool UseSjLjExceptions() const; + + /// } +}; + +/// DarwinClang - The Darwin toolchain used by Clang. +class LLVM_LIBRARY_VISIBILITY DarwinClang : public Darwin { +private: + void AddGCCLibexecPath(unsigned darwinVersion); + +public: + DarwinClang(const Driver &D, const llvm::Triple& Triple); + + /// @name Darwin ToolChain Implementation + /// { + + virtual void AddLinkSearchPathArgs(const ArgList &Args, + ArgStringList &CmdArgs) const; + + virtual void AddLinkRuntimeLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const; + void AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs, + const char *DarwinStaticLib) const; + + virtual void AddCXXStdlibLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const; + + virtual void AddCCKextLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const; + + virtual void AddLinkARCArgs(const ArgList &Args, + ArgStringList &CmdArgs) const; + /// } +}; + +/// Darwin_Generic_GCC - Generic Darwin tool chain using gcc. +class LLVM_LIBRARY_VISIBILITY Darwin_Generic_GCC : public Generic_GCC { +public: + Darwin_Generic_GCC(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) + : Generic_GCC(D, Triple, Args) {} + + std::string ComputeEffectiveClangTriple(const ArgList &Args, + types::ID InputType) const; + + virtual const char *GetDefaultRelocationModel() const { return "pic"; } +}; + +class LLVM_LIBRARY_VISIBILITY Generic_ELF : public Generic_GCC { + virtual void anchor(); +public: + Generic_ELF(const Driver &D, const llvm::Triple& Triple, const ArgList &Args) + : Generic_GCC(D, Triple, Args) {} + + virtual bool IsIntegratedAssemblerDefault() const { + // Default integrated assembler to on for x86. + return (getTriple().getArch() == llvm::Triple::x86 || + getTriple().getArch() == llvm::Triple::x86_64); + } +}; + +class LLVM_LIBRARY_VISIBILITY AuroraUX : public Generic_GCC { +public: + AuroraUX(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; +}; + +class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_GCC { +public: + Solaris(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; + + virtual bool IsIntegratedAssemblerDefault() const { return true; } +}; + + +class LLVM_LIBRARY_VISIBILITY OpenBSD : public Generic_ELF { +public: + OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsObjCNonFragileABIDefault() const { return true; } + virtual bool IsObjCLegacyDispatchDefault() const { + llvm::Triple::ArchType Arch = getTriple().getArch(); + if (Arch == llvm::Triple::arm || + Arch == llvm::Triple::x86 || + Arch == llvm::Triple::x86_64) + return false; + return true; + } + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; +}; + +class LLVM_LIBRARY_VISIBILITY FreeBSD : public Generic_ELF { +public: + FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsObjCNonFragileABIDefault() const { return true; } + virtual bool IsObjCLegacyDispatchDefault() const { + llvm::Triple::ArchType Arch = getTriple().getArch(); + if (Arch == llvm::Triple::arm || + Arch == llvm::Triple::x86 || + Arch == llvm::Triple::x86_64) + return false; + return true; + } + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; +}; + +class LLVM_LIBRARY_VISIBILITY NetBSD : public Generic_ELF { +public: + NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsObjCNonFragileABIDefault() const { return true; } + virtual bool IsObjCLegacyDispatchDefault() const { + llvm::Triple::ArchType Arch = getTriple().getArch(); + if (Arch == llvm::Triple::arm || + Arch == llvm::Triple::x86 || + Arch == llvm::Triple::x86_64) + return false; + return true; + } + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; +}; + +class LLVM_LIBRARY_VISIBILITY Minix : public Generic_ELF { +public: + Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; +}; + +class LLVM_LIBRARY_VISIBILITY DragonFly : public Generic_ELF { +public: + DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; +}; + +class LLVM_LIBRARY_VISIBILITY Linux : public Generic_ELF { +public: + Linux(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool HasNativeLLVMSupport() const; + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; + + virtual void AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + + std::string Linker; + std::vector<std::string> ExtraOpts; + +private: + static bool addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir, + const ArgList &DriverArgs, + ArgStringList &CC1Args); +}; + + +/// TCEToolChain - A tool chain using the llvm bitcode tools to perform +/// all subcommands. See http://tce.cs.tut.fi for our peculiar target. +class LLVM_LIBRARY_VISIBILITY TCEToolChain : public ToolChain { +public: + TCEToolChain(const Driver &D, const llvm::Triple& Triple); + ~TCEToolChain(); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; + bool IsMathErrnoDefault() const; + bool IsUnwindTablesDefault() const; + const char* GetDefaultRelocationModel() const; + const char* GetForcedPicModel() const; + +private: + mutable llvm::DenseMap<unsigned, Tool*> Tools; + +}; + +class LLVM_LIBRARY_VISIBILITY Windows : public ToolChain { + mutable llvm::DenseMap<unsigned, Tool*> Tools; + +public: + Windows(const Driver &D, const llvm::Triple& Triple); + + virtual Tool &SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const; + + virtual bool IsIntegratedAssemblerDefault() const; + virtual bool IsUnwindTablesDefault() const; + virtual const char *GetDefaultRelocationModel() const; + virtual const char *GetForcedPicModel() const; + + virtual void AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + +}; + +} // end namespace toolchains +} // end namespace driver +} // end namespace clang + +#endif diff --git a/clang/lib/Driver/Tools.cpp b/clang/lib/Driver/Tools.cpp new file mode 100644 index 0000000..47b5294 --- /dev/null +++ b/clang/lib/Driver/Tools.cpp @@ -0,0 +1,5589 @@ +//===--- Tools.cpp - Tools Implementations --------------------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "Tools.h" + +#include "clang/Driver/Action.h" +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Driver.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Driver/Compilation.h" +#include "clang/Driver/Job.h" +#include "clang/Driver/ObjCRuntime.h" +#include "clang/Driver/Option.h" +#include "clang/Driver/Options.h" +#include "clang/Driver/ToolChain.h" +#include "clang/Driver/Util.h" + +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Format.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/Host.h" +#include "llvm/Support/Process.h" +#include "llvm/Support/ErrorHandling.h" + +#include "InputInfo.h" +#include "ToolChains.h" + +using namespace clang::driver; +using namespace clang::driver::tools; +using namespace clang; + +/// CheckPreprocessingOptions - Perform some validation of preprocessing +/// arguments that is shared with gcc. +static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) { + if (Arg *A = Args.getLastArg(options::OPT_C, options::OPT_CC)) + if (!Args.hasArg(options::OPT_E) && !D.CCCIsCPP) + D.Diag(diag::err_drv_argument_only_allowed_with) + << A->getAsString(Args) << "-E"; +} + +/// CheckCodeGenerationOptions - Perform some validation of code generation +/// arguments that is shared with gcc. +static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) { + // In gcc, only ARM checks this, but it seems reasonable to check universally. + if (Args.hasArg(options::OPT_static)) + if (const Arg *A = Args.getLastArg(options::OPT_dynamic, + options::OPT_mdynamic_no_pic)) + D.Diag(diag::err_drv_argument_not_allowed_with) + << A->getAsString(Args) << "-static"; +} + +// Quote target names for inclusion in GNU Make dependency files. +// Only the characters '$', '#', ' ', '\t' are quoted. +static void QuoteTarget(StringRef Target, + SmallVectorImpl<char> &Res) { + for (unsigned i = 0, e = Target.size(); i != e; ++i) { + switch (Target[i]) { + case ' ': + case '\t': + // Escape the preceding backslashes + for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j) + Res.push_back('\\'); + + // Escape the space/tab + Res.push_back('\\'); + break; + case '$': + Res.push_back('$'); + break; + case '#': + Res.push_back('\\'); + break; + default: + break; + } + + Res.push_back(Target[i]); + } +} + +static void addDirectoryList(const ArgList &Args, + ArgStringList &CmdArgs, + const char *ArgName, + const char *EnvVar) { + const char *DirList = ::getenv(EnvVar); + if (!DirList) + return; // Nothing to do. + + StringRef Dirs(DirList); + if (Dirs.empty()) // Empty string should not add '.'. + return; + + StringRef::size_type Delim; + while ((Delim = Dirs.find(llvm::sys::PathSeparator)) != StringRef::npos) { + if (Delim == 0) { // Leading colon. + CmdArgs.push_back(ArgName); + CmdArgs.push_back("."); + } else { + CmdArgs.push_back(ArgName); + CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); + } + Dirs = Dirs.substr(Delim + 1); + } + + if (Dirs.empty()) { // Trailing colon. + CmdArgs.push_back(ArgName); + CmdArgs.push_back("."); + } else { // Add the last path. + CmdArgs.push_back(ArgName); + CmdArgs.push_back(Args.MakeArgString(Dirs)); + } +} + +static void AddLinkerInputs(const ToolChain &TC, + const InputInfoList &Inputs, const ArgList &Args, + ArgStringList &CmdArgs) { + const Driver &D = TC.getDriver(); + + // Add extra linker input arguments which are not treated as inputs + // (constructed via -Xarch_). + Args.AddAllArgValues(CmdArgs, options::OPT_Zlinker_input); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + + if (!TC.HasNativeLLVMSupport()) { + // Don't try to pass LLVM inputs unless we have native support. + if (II.getType() == types::TY_LLVM_IR || + II.getType() == types::TY_LTO_IR || + II.getType() == types::TY_LLVM_BC || + II.getType() == types::TY_LTO_BC) + D.Diag(diag::err_drv_no_linker_llvm_support) + << TC.getTripleString(); + } + + // Add filenames immediately. + if (II.isFilename()) { + CmdArgs.push_back(II.getFilename()); + continue; + } + + // Otherwise, this is a linker input argument. + const Arg &A = II.getInputArg(); + + // Handle reserved library options. + if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) { + TC.AddCXXStdlibLibArgs(Args, CmdArgs); + } else if (A.getOption().matches(options::OPT_Z_reserved_lib_cckext)) { + TC.AddCCKextLibArgs(Args, CmdArgs); + } else + A.renderAsInput(Args, CmdArgs); + } + + // LIBRARY_PATH - included following the user specified library paths. + addDirectoryList(Args, CmdArgs, "-L", "LIBRARY_PATH"); +} + +/// \brief Determine whether Objective-C automated reference counting is +/// enabled. +static bool isObjCAutoRefCount(const ArgList &Args) { + return Args.hasFlag(options::OPT_fobjc_arc, options::OPT_fno_objc_arc, false); +} + +/// \brief Determine whether we are linking the ObjC runtime. +static bool isObjCRuntimeLinked(const ArgList &Args) { + if (isObjCAutoRefCount(Args)) + return true; + return Args.hasArg(options::OPT_fobjc_link_runtime); +} + +static void addProfileRT(const ToolChain &TC, const ArgList &Args, + ArgStringList &CmdArgs, + llvm::Triple Triple) { + if (!(Args.hasArg(options::OPT_fprofile_arcs) || + Args.hasArg(options::OPT_fprofile_generate) || + Args.hasArg(options::OPT_fcreate_profile) || + Args.hasArg(options::OPT_coverage))) + return; + + // GCC links libgcov.a by adding -L<inst>/gcc/lib/gcc/<triple>/<ver> -lgcov to + // the link line. We cannot do the same thing because unlike gcov there is a + // libprofile_rt.so. We used to use the -l:libprofile_rt.a syntax, but that is + // not supported by old linkers. + std::string ProfileRT = + std::string(TC.getDriver().Dir) + "/../lib/libprofile_rt.a"; + + CmdArgs.push_back(Args.MakeArgString(ProfileRT)); +} + +void Clang::AddPreprocessingOptions(Compilation &C, + const Driver &D, + const ArgList &Args, + ArgStringList &CmdArgs, + const InputInfo &Output, + const InputInfoList &Inputs) const { + Arg *A; + + CheckPreprocessingOptions(D, Args); + + Args.AddLastArg(CmdArgs, options::OPT_C); + Args.AddLastArg(CmdArgs, options::OPT_CC); + + // Handle dependency file generation. + if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) || + (A = Args.getLastArg(options::OPT_MD)) || + (A = Args.getLastArg(options::OPT_MMD))) { + // Determine the output location. + const char *DepFile; + if (Output.getType() == types::TY_Dependencies) { + DepFile = Output.getFilename(); + } else if (Arg *MF = Args.getLastArg(options::OPT_MF)) { + DepFile = MF->getValue(Args); + C.addFailureResultFile(DepFile); + } else if (A->getOption().matches(options::OPT_M) || + A->getOption().matches(options::OPT_MM)) { + DepFile = "-"; + } else { + DepFile = darwin::CC1::getDependencyFileName(Args, Inputs); + C.addFailureResultFile(DepFile); + } + CmdArgs.push_back("-dependency-file"); + CmdArgs.push_back(DepFile); + + // Add a default target if one wasn't specified. + if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) { + const char *DepTarget; + + // If user provided -o, that is the dependency target, except + // when we are only generating a dependency file. + Arg *OutputOpt = Args.getLastArg(options::OPT_o); + if (OutputOpt && Output.getType() != types::TY_Dependencies) { + DepTarget = OutputOpt->getValue(Args); + } else { + // Otherwise derive from the base input. + // + // FIXME: This should use the computed output file location. + SmallString<128> P(Inputs[0].getBaseInput()); + llvm::sys::path::replace_extension(P, "o"); + DepTarget = Args.MakeArgString(llvm::sys::path::filename(P)); + } + + CmdArgs.push_back("-MT"); + SmallString<128> Quoted; + QuoteTarget(DepTarget, Quoted); + CmdArgs.push_back(Args.MakeArgString(Quoted)); + } + + if (A->getOption().matches(options::OPT_M) || + A->getOption().matches(options::OPT_MD)) + CmdArgs.push_back("-sys-header-deps"); + } + + if (Args.hasArg(options::OPT_MG)) { + if (!A || A->getOption().matches(options::OPT_MD) || + A->getOption().matches(options::OPT_MMD)) + D.Diag(diag::err_drv_mg_requires_m_or_mm); + CmdArgs.push_back("-MG"); + } + + Args.AddLastArg(CmdArgs, options::OPT_MP); + + // Convert all -MQ <target> args to -MT <quoted target> + for (arg_iterator it = Args.filtered_begin(options::OPT_MT, + options::OPT_MQ), + ie = Args.filtered_end(); it != ie; ++it) { + const Arg *A = *it; + A->claim(); + + if (A->getOption().matches(options::OPT_MQ)) { + CmdArgs.push_back("-MT"); + SmallString<128> Quoted; + QuoteTarget(A->getValue(Args), Quoted); + CmdArgs.push_back(Args.MakeArgString(Quoted)); + + // -MT flag - no change + } else { + A->render(Args, CmdArgs); + } + } + + // Add -i* options, and automatically translate to + // -include-pch/-include-pth for transparent PCH support. It's + // wonky, but we include looking for .gch so we can support seamless + // replacement into a build system already set up to be generating + // .gch files. + bool RenderedImplicitInclude = false; + for (arg_iterator it = Args.filtered_begin(options::OPT_clang_i_Group), + ie = Args.filtered_end(); it != ie; ++it) { + const Arg *A = it; + + if (A->getOption().matches(options::OPT_include)) { + bool IsFirstImplicitInclude = !RenderedImplicitInclude; + RenderedImplicitInclude = true; + + // Use PCH if the user requested it. + bool UsePCH = D.CCCUsePCH; + + bool FoundPTH = false; + bool FoundPCH = false; + llvm::sys::Path P(A->getValue(Args)); + bool Exists; + if (UsePCH) { + P.appendSuffix("pch"); + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + FoundPCH = true; + else + P.eraseSuffix(); + } + + if (!FoundPCH) { + P.appendSuffix("pth"); + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) + FoundPTH = true; + else + P.eraseSuffix(); + } + + if (!FoundPCH && !FoundPTH) { + P.appendSuffix("gch"); + if (!llvm::sys::fs::exists(P.str(), Exists) && Exists) { + FoundPCH = UsePCH; + FoundPTH = !UsePCH; + } + else + P.eraseSuffix(); + } + + if (FoundPCH || FoundPTH) { + if (IsFirstImplicitInclude) { + A->claim(); + if (UsePCH) + CmdArgs.push_back("-include-pch"); + else + CmdArgs.push_back("-include-pth"); + CmdArgs.push_back(Args.MakeArgString(P.str())); + continue; + } else { + // Ignore the PCH if not first on command line and emit warning. + D.Diag(diag::warn_drv_pch_not_first_include) + << P.str() << A->getAsString(Args); + } + } + } + + // Not translated, render as usual. + A->claim(); + A->render(Args, CmdArgs); + } + + Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U); + Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F, + options::OPT_index_header_map); + + // Add -Wp, and -Xassembler if using the preprocessor. + + // FIXME: There is a very unfortunate problem here, some troubled + // souls abuse -Wp, to pass preprocessor options in gcc syntax. To + // really support that we would have to parse and then translate + // those options. :( + Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA, + options::OPT_Xpreprocessor); + + // -I- is a deprecated GCC feature, reject it. + if (Arg *A = Args.getLastArg(options::OPT_I_)) + D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args); + + // If we have a --sysroot, and don't have an explicit -isysroot flag, add an + // -isysroot to the CC1 invocation. + StringRef sysroot = C.getSysRoot(); + if (sysroot != "") { + if (!Args.hasArg(options::OPT_isysroot)) { + CmdArgs.push_back("-isysroot"); + CmdArgs.push_back(C.getArgs().MakeArgString(sysroot)); + } + } + + // If a module path was provided, pass it along. Otherwise, use a temporary + // directory. + if (Arg *A = Args.getLastArg(options::OPT_fmodule_cache_path)) { + A->claim(); + A->render(Args, CmdArgs); + } else { + SmallString<128> DefaultModuleCache; + llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, + DefaultModuleCache); + llvm::sys::path::append(DefaultModuleCache, "clang-module-cache"); + CmdArgs.push_back("-fmodule-cache-path"); + CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache)); + } + + // Parse additional include paths from environment variables. + // FIXME: We should probably sink the logic for handling these from the + // frontend into the driver. It will allow deleting 4 otherwise unused flags. + // CPATH - included following the user specified includes (but prior to + // builtin and standard includes). + addDirectoryList(Args, CmdArgs, "-I", "CPATH"); + // C_INCLUDE_PATH - system includes enabled when compiling C. + addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH"); + // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++. + addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH"); + // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC. + addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH"); + // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++. + addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH"); + + // Add C++ include arguments, if needed. + if (types::isCXX(Inputs[0].getType())) + getToolChain().AddClangCXXStdlibIncludeArgs(Args, CmdArgs); + + // Add system include arguments. + getToolChain().AddClangSystemIncludeArgs(Args, CmdArgs); +} + +/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting. +// +// FIXME: tblgen this. +static const char *getARMTargetCPU(const ArgList &Args, + const llvm::Triple &Triple) { + // FIXME: Warn on inconsistent use of -mcpu and -march. + + // If we have -mcpu=, use that. + if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) + return A->getValue(Args); + + StringRef MArch; + if (Arg *A = Args.getLastArg(options::OPT_march_EQ)) { + // Otherwise, if we have -march= choose the base CPU for that arch. + MArch = A->getValue(Args); + } else { + // Otherwise, use the Arch from the triple. + MArch = Triple.getArchName(); + } + + return llvm::StringSwitch<const char *>(MArch) + .Cases("armv2", "armv2a","arm2") + .Case("armv3", "arm6") + .Case("armv3m", "arm7m") + .Cases("armv4", "armv4t", "arm7tdmi") + .Cases("armv5", "armv5t", "arm10tdmi") + .Cases("armv5e", "armv5te", "arm1026ejs") + .Case("armv5tej", "arm926ej-s") + .Cases("armv6", "armv6k", "arm1136jf-s") + .Case("armv6j", "arm1136j-s") + .Cases("armv6z", "armv6zk", "arm1176jzf-s") + .Case("armv6t2", "arm1156t2-s") + .Cases("armv7", "armv7a", "armv7-a", "cortex-a8") + .Cases("armv7r", "armv7-r", "cortex-r4") + .Cases("armv7m", "armv7-m", "cortex-m3") + .Case("ep9312", "ep9312") + .Case("iwmmxt", "iwmmxt") + .Case("xscale", "xscale") + .Cases("armv6m", "armv6-m", "cortex-m0") + // If all else failed, return the most base CPU LLVM supports. + .Default("arm7tdmi"); +} + +/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular +/// CPU. +// +// FIXME: This is redundant with -mcpu, why does LLVM use this. +// FIXME: tblgen this, or kill it! +static const char *getLLVMArchSuffixForARM(StringRef CPU) { + return llvm::StringSwitch<const char *>(CPU) + .Cases("arm7tdmi", "arm7tdmi-s", "arm710t", "v4t") + .Cases("arm720t", "arm9", "arm9tdmi", "v4t") + .Cases("arm920", "arm920t", "arm922t", "v4t") + .Cases("arm940t", "ep9312","v4t") + .Cases("arm10tdmi", "arm1020t", "v5") + .Cases("arm9e", "arm926ej-s", "arm946e-s", "v5e") + .Cases("arm966e-s", "arm968e-s", "arm10e", "v5e") + .Cases("arm1020e", "arm1022e", "xscale", "iwmmxt", "v5e") + .Cases("arm1136j-s", "arm1136jf-s", "arm1176jz-s", "v6") + .Cases("arm1176jzf-s", "mpcorenovfp", "mpcore", "v6") + .Cases("arm1156t2-s", "arm1156t2f-s", "v6t2") + .Cases("cortex-a8", "cortex-a9", "v7") + .Case("cortex-m3", "v7m") + .Case("cortex-m4", "v7m") + .Case("cortex-m0", "v6m") + .Default(""); +} + +// FIXME: Move to target hook. +static bool isSignedCharDefault(const llvm::Triple &Triple) { + switch (Triple.getArch()) { + default: + return true; + + case llvm::Triple::arm: + case llvm::Triple::ppc: + case llvm::Triple::ppc64: + if (Triple.isOSDarwin()) + return true; + return false; + } +} + +// Handle -mfpu=. +// +// FIXME: Centralize feature selection, defaulting shouldn't be also in the +// frontend target. +static void addFPUArgs(const Driver &D, const Arg *A, const ArgList &Args, + ArgStringList &CmdArgs) { + StringRef FPU = A->getValue(Args); + + // Set the target features based on the FPU. + if (FPU == "fpa" || FPU == "fpe2" || FPU == "fpe3" || FPU == "maverick") { + // Disable any default FPU support. + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-vfp2"); + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-vfp3"); + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-neon"); + } else if (FPU == "vfp3-d16" || FPU == "vfpv3-d16") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+vfp3"); + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+d16"); + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-neon"); + } else if (FPU == "vfp") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+vfp2"); + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-neon"); + } else if (FPU == "vfp3" || FPU == "vfpv3") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+vfp3"); + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-neon"); + } else if (FPU == "neon") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+neon"); + } else + D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); +} + +// Handle -mfpmath=. +static void addFPMathArgs(const Driver &D, const Arg *A, const ArgList &Args, + ArgStringList &CmdArgs, StringRef CPU) { + StringRef FPMath = A->getValue(Args); + + // Set the target features based on the FPMath. + if (FPMath == "neon") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+neonfp"); + + if (CPU != "cortex-a8" && CPU != "cortex-a9" && CPU != "cortex-a9-mp") + D.Diag(diag::err_drv_invalid_feature) << "-mfpmath=neon" << CPU; + + } else if (FPMath == "vfp" || FPMath == "vfp2" || FPMath == "vfp3" || + FPMath == "vfp4") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-neonfp"); + + // FIXME: Add warnings when disabling a feature not present for a given CPU. + } else + D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); +} + +// Select the float ABI as determined by -msoft-float, -mhard-float, and +// -mfloat-abi=. +static StringRef getARMFloatABI(const Driver &D, + const ArgList &Args, + const llvm::Triple &Triple) { + StringRef FloatABI; + if (Arg *A = Args.getLastArg(options::OPT_msoft_float, + options::OPT_mhard_float, + options::OPT_mfloat_abi_EQ)) { + if (A->getOption().matches(options::OPT_msoft_float)) + FloatABI = "soft"; + else if (A->getOption().matches(options::OPT_mhard_float)) + FloatABI = "hard"; + else { + FloatABI = A->getValue(Args); + if (FloatABI != "soft" && FloatABI != "softfp" && FloatABI != "hard") { + D.Diag(diag::err_drv_invalid_mfloat_abi) + << A->getAsString(Args); + FloatABI = "soft"; + } + } + } + + // If unspecified, choose the default based on the platform. + if (FloatABI.empty()) { + switch (Triple.getOS()) { + case llvm::Triple::Darwin: + case llvm::Triple::MacOSX: + case llvm::Triple::IOS: { + // Darwin defaults to "softfp" for v6 and v7. + // + // FIXME: Factor out an ARM class so we can cache the arch somewhere. + StringRef ArchName = + getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple)); + if (ArchName.startswith("v6") || ArchName.startswith("v7")) + FloatABI = "softfp"; + else + FloatABI = "soft"; + break; + } + + case llvm::Triple::Linux: { + if (Triple.getEnvironment() == llvm::Triple::GNUEABI) { + FloatABI = "softfp"; + break; + } + } + // fall through + + default: + switch(Triple.getEnvironment()) { + case llvm::Triple::GNUEABI: + FloatABI = "softfp"; + break; + case llvm::Triple::EABI: + // EABI is always AAPCS, and if it was not marked 'hard', it's softfp + FloatABI = "softfp"; + break; + case llvm::Triple::ANDROIDEABI: { + StringRef ArchName = + getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple)); + if (ArchName.startswith("v7")) + FloatABI = "softfp"; + else + FloatABI = "soft"; + break; + } + default: + // Assume "soft", but warn the user we are guessing. + FloatABI = "soft"; + D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft"; + break; + } + } + } + + return FloatABI; +} + + +void Clang::AddARMTargetArgs(const ArgList &Args, + ArgStringList &CmdArgs, + bool KernelOrKext) const { + const Driver &D = getToolChain().getDriver(); + llvm::Triple Triple = getToolChain().getTriple(); + + // Select the ABI to use. + // + // FIXME: Support -meabi. + const char *ABIName = 0; + if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) { + ABIName = A->getValue(Args); + } else { + // Select the default based on the platform. + switch(Triple.getEnvironment()) { + case llvm::Triple::ANDROIDEABI: + case llvm::Triple::GNUEABI: + ABIName = "aapcs-linux"; + break; + case llvm::Triple::EABI: + ABIName = "aapcs"; + break; + default: + ABIName = "apcs-gnu"; + } + } + CmdArgs.push_back("-target-abi"); + CmdArgs.push_back(ABIName); + + // Set the CPU based on -march= and -mcpu=. + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(getARMTargetCPU(Args, Triple)); + + // Determine floating point ABI from the options & target defaults. + StringRef FloatABI = getARMFloatABI(D, Args, Triple); + if (FloatABI == "soft") { + // Floating point operations and argument passing are soft. + // + // FIXME: This changes CPP defines, we need -target-soft-float. + CmdArgs.push_back("-msoft-float"); + CmdArgs.push_back("-mfloat-abi"); + CmdArgs.push_back("soft"); + } else if (FloatABI == "softfp") { + // Floating point operations are hard, but argument passing is soft. + CmdArgs.push_back("-mfloat-abi"); + CmdArgs.push_back("soft"); + } else { + // Floating point operations and argument passing are hard. + assert(FloatABI == "hard" && "Invalid float abi!"); + CmdArgs.push_back("-mfloat-abi"); + CmdArgs.push_back("hard"); + } + + // Set appropriate target features for floating point mode. + // + // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these + // yet (it uses the -mfloat-abi and -msoft-float options above), and it is + // stripped out by the ARM target. + + // Use software floating point operations? + if (FloatABI == "soft") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+soft-float"); + } + + // Use software floating point argument passing? + if (FloatABI != "hard") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+soft-float-abi"); + } + + // Honor -mfpu=. + if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ)) + addFPUArgs(D, A, Args, CmdArgs); + + // Honor -mfpmath=. + if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) + addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple)); + + // Setting -msoft-float effectively disables NEON because of the GCC + // implementation, although the same isn't true of VFP or VFP3. + if (FloatABI == "soft") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-neon"); + } + + // Kernel code has more strict alignment requirements. + if (KernelOrKext) { + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-arm-long-calls"); + + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-arm-strict-align"); + + // The kext linker doesn't know how to deal with movw/movt. + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-arm-darwin-use-movt=0"); + } + + // Setting -mno-global-merge disables the codegen global merge pass. Setting + // -mglobal-merge has no effect as the pass is enabled by default. + if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge, + options::OPT_mno_global_merge)) { + if (A->getOption().matches(options::OPT_mno_global_merge)) + CmdArgs.push_back("-mno-global-merge"); + } +} + +// Get default architecture. +static const char* getMipsArchFromCPU(StringRef CPUName) { + if (CPUName == "mips32" || CPUName == "mips32r2") + return "mips"; + + assert((CPUName == "mips64" || CPUName == "mips64r2") && + "Unexpected cpu name."); + + return "mips64"; +} + +// Check that ArchName is a known Mips architecture name. +static bool checkMipsArchName(StringRef ArchName) { + return ArchName == "mips" || + ArchName == "mipsel" || + ArchName == "mips64" || + ArchName == "mips64el"; +} + +// Get default target cpu. +static const char* getMipsCPUFromArch(StringRef ArchName) { + if (ArchName == "mips" || ArchName == "mipsel") + return "mips32"; + + assert((ArchName == "mips64" || ArchName == "mips64el") && + "Unexpected arch name."); + + return "mips64"; +} + +// Get default ABI. +static const char* getMipsABIFromArch(StringRef ArchName) { + if (ArchName == "mips" || ArchName == "mipsel") + return "o32"; + + assert((ArchName == "mips64" || ArchName == "mips64el") && + "Unexpected arch name."); + return "n64"; +} + +// Get CPU and ABI names. They are not independent +// so we have to calculate them together. +static void getMipsCPUAndABI(const ArgList &Args, + const ToolChain &TC, + StringRef &CPUName, + StringRef &ABIName) { + StringRef ArchName; + + // Select target cpu and architecture. + if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { + CPUName = A->getValue(Args); + ArchName = getMipsArchFromCPU(CPUName); + } + else { + ArchName = Args.MakeArgString(TC.getArchName()); + if (!checkMipsArchName(ArchName)) + TC.getDriver().Diag(diag::err_drv_invalid_arch_name) << ArchName; + else + CPUName = getMipsCPUFromArch(ArchName); + } + + // Select the ABI to use. + if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) + ABIName = A->getValue(Args); + else + ABIName = getMipsABIFromArch(ArchName); +} + +void Clang::AddMIPSTargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + const Driver &D = getToolChain().getDriver(); + StringRef CPUName; + StringRef ABIName; + getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName); + + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(CPUName.data()); + + CmdArgs.push_back("-target-abi"); + CmdArgs.push_back(ABIName.data()); + + // Select the float ABI as determined by -msoft-float, -mhard-float, + // and -mfloat-abi=. + StringRef FloatABI; + if (Arg *A = Args.getLastArg(options::OPT_msoft_float, + options::OPT_mhard_float, + options::OPT_mfloat_abi_EQ)) { + if (A->getOption().matches(options::OPT_msoft_float)) + FloatABI = "soft"; + else if (A->getOption().matches(options::OPT_mhard_float)) + FloatABI = "hard"; + else { + FloatABI = A->getValue(Args); + if (FloatABI != "soft" && FloatABI != "single" && FloatABI != "hard") { + D.Diag(diag::err_drv_invalid_mfloat_abi) + << A->getAsString(Args); + FloatABI = "hard"; + } + } + } + + // If unspecified, choose the default based on the platform. + if (FloatABI.empty()) { + // Assume "hard", because it's a default value used by gcc. + // When we start to recognize specific target MIPS processors, + // we will be able to select the default more correctly. + FloatABI = "hard"; + } + + if (FloatABI == "soft") { + // Floating point operations and argument passing are soft. + CmdArgs.push_back("-msoft-float"); + CmdArgs.push_back("-mfloat-abi"); + CmdArgs.push_back("soft"); + + // FIXME: Note, this is a hack. We need to pass the selected float + // mode to the MipsTargetInfoBase to define appropriate macros there. + // Now it is the only method. + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+soft-float"); + } + else if (FloatABI == "single") { + // Restrict the use of hardware floating-point + // instructions to 32-bit operations. + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+single-float"); + } + else { + // Floating point operations and argument passing are hard. + assert(FloatABI == "hard" && "Invalid float abi!"); + CmdArgs.push_back("-mfloat-abi"); + CmdArgs.push_back("hard"); + } +} + +void Clang::AddSparcTargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + const Driver &D = getToolChain().getDriver(); + + if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) { + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(A->getValue(Args)); + } + + // Select the float ABI as determined by -msoft-float, -mhard-float, and + StringRef FloatABI; + if (Arg *A = Args.getLastArg(options::OPT_msoft_float, + options::OPT_mhard_float)) { + if (A->getOption().matches(options::OPT_msoft_float)) + FloatABI = "soft"; + else if (A->getOption().matches(options::OPT_mhard_float)) + FloatABI = "hard"; + } + + // If unspecified, choose the default based on the platform. + if (FloatABI.empty()) { + switch (getToolChain().getTriple().getOS()) { + default: + // Assume "soft", but warn the user we are guessing. + FloatABI = "soft"; + D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft"; + break; + } + } + + if (FloatABI == "soft") { + // Floating point operations and argument passing are soft. + // + // FIXME: This changes CPP defines, we need -target-soft-float. + CmdArgs.push_back("-msoft-float"); + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+soft-float"); + } else { + assert(FloatABI == "hard" && "Invalid float abi!"); + CmdArgs.push_back("-mhard-float"); + } +} + +void Clang::AddX86TargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + if (!Args.hasFlag(options::OPT_mred_zone, + options::OPT_mno_red_zone, + true) || + Args.hasArg(options::OPT_mkernel) || + Args.hasArg(options::OPT_fapple_kext)) + CmdArgs.push_back("-disable-red-zone"); + + if (Args.hasFlag(options::OPT_msoft_float, + options::OPT_mno_soft_float, + false)) + CmdArgs.push_back("-no-implicit-float"); + + const char *CPUName = 0; + if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) { + if (StringRef(A->getValue(Args)) == "native") { + // FIXME: Reject attempts to use -march=native unless the target matches + // the host. + // + // FIXME: We should also incorporate the detected target features for use + // with -native. + std::string CPU = llvm::sys::getHostCPUName(); + if (!CPU.empty()) + CPUName = Args.MakeArgString(CPU); + } else + CPUName = A->getValue(Args); + } + + // Select the default CPU if none was given (or detection failed). + if (!CPUName) { + // FIXME: Need target hooks. + if (getToolChain().getTriple().isOSDarwin()) { + if (getToolChain().getArch() == llvm::Triple::x86_64) + CPUName = "core2"; + else if (getToolChain().getArch() == llvm::Triple::x86) + CPUName = "yonah"; + } else if (getToolChain().getOS().startswith("haiku")) { + if (getToolChain().getArch() == llvm::Triple::x86_64) + CPUName = "x86-64"; + else if (getToolChain().getArch() == llvm::Triple::x86) + CPUName = "i586"; + } else if (getToolChain().getOS().startswith("openbsd")) { + if (getToolChain().getArch() == llvm::Triple::x86_64) + CPUName = "x86-64"; + else if (getToolChain().getArch() == llvm::Triple::x86) + CPUName = "i486"; + } else if (getToolChain().getOS().startswith("freebsd")) { + if (getToolChain().getArch() == llvm::Triple::x86_64) + CPUName = "x86-64"; + else if (getToolChain().getArch() == llvm::Triple::x86) + CPUName = "i486"; + } else if (getToolChain().getOS().startswith("netbsd")) { + if (getToolChain().getArch() == llvm::Triple::x86_64) + CPUName = "x86-64"; + else if (getToolChain().getArch() == llvm::Triple::x86) + CPUName = "i486"; + } else { + if (getToolChain().getArch() == llvm::Triple::x86_64) + CPUName = "x86-64"; + else if (getToolChain().getArch() == llvm::Triple::x86) + CPUName = "pentium4"; + } + } + + if (CPUName) { + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(CPUName); + } + + // The required algorithm here is slightly strange: the options are applied + // in order (so -mno-sse -msse2 disables SSE3), but any option that gets + // directly overridden later is ignored (so "-mno-sse -msse2 -mno-sse2 -msse" + // is equivalent to "-mno-sse2 -msse"). The -cc1 handling deals with the + // former correctly, but not the latter; handle directly-overridden + // attributes here. + llvm::StringMap<unsigned> PrevFeature; + std::vector<const char*> Features; + for (arg_iterator it = Args.filtered_begin(options::OPT_m_x86_Features_Group), + ie = Args.filtered_end(); it != ie; ++it) { + StringRef Name = (*it)->getOption().getName(); + (*it)->claim(); + + // Skip over "-m". + assert(Name.startswith("-m") && "Invalid feature name."); + Name = Name.substr(2); + + bool IsNegative = Name.startswith("no-"); + if (IsNegative) + Name = Name.substr(3); + + unsigned& Prev = PrevFeature[Name]; + if (Prev) + Features[Prev - 1] = 0; + Prev = Features.size() + 1; + Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name)); + } + for (unsigned i = 0; i < Features.size(); i++) { + if (Features[i]) { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back(Features[i]); + } + } +} + +static Arg* getLastHexagonArchArg (const ArgList &Args) +{ + Arg * A = NULL; + + for (ArgList::const_iterator it = Args.begin(), ie = Args.end(); + it != ie; ++it) { + if ((*it)->getOption().matches(options::OPT_march_EQ) || + (*it)->getOption().matches(options::OPT_mcpu_EQ)) { + A = *it; + A->claim(); + } + else if ((*it)->getOption().matches(options::OPT_m_Joined)){ + StringRef Value = (*it)->getValue(Args,0); + if (Value.startswith("v")) { + A = *it; + A->claim(); + } + } + } + return A; +} + +static StringRef getHexagonTargetCPU(const ArgList &Args) +{ + Arg *A; + llvm::StringRef WhichHexagon; + + // Select the default CPU (v4) if none was given or detection failed. + if ((A = getLastHexagonArchArg (Args))) { + WhichHexagon = A->getValue(Args); + if (WhichHexagon == "") + return "v4"; + else + return WhichHexagon; + } + else + return "v4"; +} + +void Clang::AddHexagonTargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + llvm::Triple Triple = getToolChain().getTriple(); + + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(Args.MakeArgString("hexagon" + getHexagonTargetCPU(Args))); + CmdArgs.push_back("-fno-signed-char"); + CmdArgs.push_back("-nobuiltininc"); + + if (Args.hasArg(options::OPT_mqdsp6_compat)) + CmdArgs.push_back("-mqdsp6-compat"); + + if (Arg *A = Args.getLastArg(options::OPT_G, + options::OPT_msmall_data_threshold_EQ)) { + std::string SmallDataThreshold="-small-data-threshold="; + SmallDataThreshold += A->getValue(Args); + CmdArgs.push_back ("-mllvm"); + CmdArgs.push_back(Args.MakeArgString(SmallDataThreshold)); + A->claim(); + } + + CmdArgs.push_back ("-mllvm"); + CmdArgs.push_back ("-machine-sink-split=0"); +} + +static bool +shouldUseExceptionTablesForObjCExceptions(unsigned objcABIVersion, + const llvm::Triple &Triple) { + // We use the zero-cost exception tables for Objective-C if the non-fragile + // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and + // later. + + if (objcABIVersion >= 2) + return true; + + if (!Triple.isOSDarwin()) + return false; + + return (!Triple.isMacOSXVersionLT(10,5) && + (Triple.getArch() == llvm::Triple::x86_64 || + Triple.getArch() == llvm::Triple::arm)); +} + +/// addExceptionArgs - Adds exception related arguments to the driver command +/// arguments. There's a master flag, -fexceptions and also language specific +/// flags to enable/disable C++ and Objective-C exceptions. +/// This makes it possible to for example disable C++ exceptions but enable +/// Objective-C exceptions. +static void addExceptionArgs(const ArgList &Args, types::ID InputType, + const llvm::Triple &Triple, + bool KernelOrKext, + unsigned objcABIVersion, + ArgStringList &CmdArgs) { + if (KernelOrKext) { + // -mkernel and -fapple-kext imply no exceptions, so claim exception related + // arguments now to avoid warnings about unused arguments. + Args.ClaimAllArgs(options::OPT_fexceptions); + Args.ClaimAllArgs(options::OPT_fno_exceptions); + Args.ClaimAllArgs(options::OPT_fobjc_exceptions); + Args.ClaimAllArgs(options::OPT_fno_objc_exceptions); + Args.ClaimAllArgs(options::OPT_fcxx_exceptions); + Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions); + return; + } + + // Exceptions are enabled by default. + bool ExceptionsEnabled = true; + + // This keeps track of whether exceptions were explicitly turned on or off. + bool DidHaveExplicitExceptionFlag = false; + + if (Arg *A = Args.getLastArg(options::OPT_fexceptions, + options::OPT_fno_exceptions)) { + if (A->getOption().matches(options::OPT_fexceptions)) + ExceptionsEnabled = true; + else + ExceptionsEnabled = false; + + DidHaveExplicitExceptionFlag = true; + } + + bool ShouldUseExceptionTables = false; + + // Exception tables and cleanups can be enabled with -fexceptions even if the + // language itself doesn't support exceptions. + if (ExceptionsEnabled && DidHaveExplicitExceptionFlag) + ShouldUseExceptionTables = true; + + // Obj-C exceptions are enabled by default, regardless of -fexceptions. This + // is not necessarily sensible, but follows GCC. + if (types::isObjC(InputType) && + Args.hasFlag(options::OPT_fobjc_exceptions, + options::OPT_fno_objc_exceptions, + true)) { + CmdArgs.push_back("-fobjc-exceptions"); + + ShouldUseExceptionTables |= + shouldUseExceptionTablesForObjCExceptions(objcABIVersion, Triple); + } + + if (types::isCXX(InputType)) { + bool CXXExceptionsEnabled = ExceptionsEnabled; + + if (Arg *A = Args.getLastArg(options::OPT_fcxx_exceptions, + options::OPT_fno_cxx_exceptions, + options::OPT_fexceptions, + options::OPT_fno_exceptions)) { + if (A->getOption().matches(options::OPT_fcxx_exceptions)) + CXXExceptionsEnabled = true; + else if (A->getOption().matches(options::OPT_fno_cxx_exceptions)) + CXXExceptionsEnabled = false; + } + + if (CXXExceptionsEnabled) { + CmdArgs.push_back("-fcxx-exceptions"); + + ShouldUseExceptionTables = true; + } + } + + if (ShouldUseExceptionTables) + CmdArgs.push_back("-fexceptions"); +} + +static bool ShouldDisableCFI(const ArgList &Args, + const ToolChain &TC) { + bool Default = true; + if (TC.getTriple().isOSDarwin()) { + // The native darwin assembler doesn't support cfi directives, so + // we disable them if we think the .s file will be passed to it. + Default = Args.hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + TC.IsIntegratedAssemblerDefault()); + } + return !Args.hasFlag(options::OPT_fdwarf2_cfi_asm, + options::OPT_fno_dwarf2_cfi_asm, + Default); +} + +static bool ShouldDisableDwarfDirectory(const ArgList &Args, + const ToolChain &TC) { + bool IsIADefault = TC.IsIntegratedAssemblerDefault(); + bool UseIntegratedAs = Args.hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIADefault); + bool UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm, + options::OPT_fno_dwarf_directory_asm, + UseIntegratedAs); + return !UseDwarfDirectory; +} + +/// \brief Check whether the given input tree contains any compilation actions. +static bool ContainsCompileAction(const Action *A) { + if (isa<CompileJobAction>(A)) + return true; + + for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it) + if (ContainsCompileAction(*it)) + return true; + + return false; +} + +/// \brief Check if -relax-all should be passed to the internal assembler. +/// This is done by default when compiling non-assembler source with -O0. +static bool UseRelaxAll(Compilation &C, const ArgList &Args) { + bool RelaxDefault = true; + + if (Arg *A = Args.getLastArg(options::OPT_O_Group)) + RelaxDefault = A->getOption().matches(options::OPT_O0); + + if (RelaxDefault) { + RelaxDefault = false; + for (ActionList::const_iterator it = C.getActions().begin(), + ie = C.getActions().end(); it != ie; ++it) { + if (ContainsCompileAction(*it)) { + RelaxDefault = true; + break; + } + } + } + + return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all, + RelaxDefault); +} + +/// If AddressSanitizer is enabled, add appropriate linker flags (Linux). +/// This needs to be called before we add the C run-time (malloc, etc). +static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args, + ArgStringList &CmdArgs) { + // Add asan linker flags when linking an executable, but not a shared object. + if (Args.hasArg(options::OPT_shared) || + !Args.hasFlag(options::OPT_faddress_sanitizer, + options::OPT_fno_address_sanitizer, false)) + return; + + // LibAsan is "libclang_rt.asan-<ArchName>.a" in the Linux library resource + // directory. + SmallString<128> LibAsan(TC.getDriver().ResourceDir); + llvm::sys::path::append(LibAsan, "lib", "linux", + (Twine("libclang_rt.asan-") + + TC.getArchName() + ".a")); + CmdArgs.push_back(Args.MakeArgString(LibAsan)); + CmdArgs.push_back("-lpthread"); + CmdArgs.push_back("-ldl"); + CmdArgs.push_back("-export-dynamic"); +} + +static bool shouldUseFramePointer(const ArgList &Args, + const llvm::Triple &Triple) { + if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer, + options::OPT_fomit_frame_pointer)) + return A->getOption().matches(options::OPT_fno_omit_frame_pointer); + + // Don't use a frame pointer on linux x86 and x86_64 if optimizing. + if ((Triple.getArch() == llvm::Triple::x86_64 || + Triple.getArch() == llvm::Triple::x86) && + Triple.getOS() == llvm::Triple::Linux) { + if (Arg *A = Args.getLastArg(options::OPT_O_Group)) + if (!A->getOption().matches(options::OPT_O0)) + return false; + } + + return true; +} + +void Clang::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + bool KernelOrKext = Args.hasArg(options::OPT_mkernel, + options::OPT_fapple_kext); + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + assert(Inputs.size() == 1 && "Unable to handle multiple inputs."); + + // Invoke ourselves in -cc1 mode. + // + // FIXME: Implement custom jobs for internal actions. + CmdArgs.push_back("-cc1"); + + // Add the "effective" target triple. + CmdArgs.push_back("-triple"); + std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args); + CmdArgs.push_back(Args.MakeArgString(TripleStr)); + + // Select the appropriate action. + bool IsRewriter = false; + bool IsModernRewriter = false; + + if (isa<AnalyzeJobAction>(JA)) { + assert(JA.getType() == types::TY_Plist && "Invalid output type."); + CmdArgs.push_back("-analyze"); + } else if (isa<MigrateJobAction>(JA)) { + CmdArgs.push_back("-migrate"); + } else if (isa<PreprocessJobAction>(JA)) { + if (Output.getType() == types::TY_Dependencies) + CmdArgs.push_back("-Eonly"); + else + CmdArgs.push_back("-E"); + } else if (isa<AssembleJobAction>(JA)) { + CmdArgs.push_back("-emit-obj"); + + if (UseRelaxAll(C, Args)) + CmdArgs.push_back("-mrelax-all"); + + // When using an integrated assembler, translate -Wa, and -Xassembler + // options. + for (arg_iterator it = Args.filtered_begin(options::OPT_Wa_COMMA, + options::OPT_Xassembler), + ie = Args.filtered_end(); it != ie; ++it) { + const Arg *A = *it; + A->claim(); + + for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) { + StringRef Value = A->getValue(Args, i); + + if (Value == "-force_cpusubtype_ALL") { + // Do nothing, this is the default and we don't support anything else. + } else if (Value == "-L") { + CmdArgs.push_back("-msave-temp-labels"); + } else if (Value == "--fatal-warnings") { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-fatal-assembler-warnings"); + } else if (Value == "--noexecstack") { + CmdArgs.push_back("-mnoexecstack"); + } else { + D.Diag(diag::err_drv_unsupported_option_argument) + << A->getOption().getName() << Value; + } + } + } + + // Also ignore explicit -force_cpusubtype_ALL option. + (void) Args.hasArg(options::OPT_force__cpusubtype__ALL); + } else if (isa<PrecompileJobAction>(JA)) { + // Use PCH if the user requested it. + bool UsePCH = D.CCCUsePCH; + + if (UsePCH) + CmdArgs.push_back("-emit-pch"); + else + CmdArgs.push_back("-emit-pth"); + } else { + assert(isa<CompileJobAction>(JA) && "Invalid action for clang tool."); + + if (JA.getType() == types::TY_Nothing) { + CmdArgs.push_back("-fsyntax-only"); + } else if (JA.getType() == types::TY_LLVM_IR || + JA.getType() == types::TY_LTO_IR) { + CmdArgs.push_back("-emit-llvm"); + } else if (JA.getType() == types::TY_LLVM_BC || + JA.getType() == types::TY_LTO_BC) { + CmdArgs.push_back("-emit-llvm-bc"); + } else if (JA.getType() == types::TY_PP_Asm) { + CmdArgs.push_back("-S"); + } else if (JA.getType() == types::TY_AST) { + CmdArgs.push_back("-emit-pch"); + } else if (JA.getType() == types::TY_RewrittenObjC) { + CmdArgs.push_back("-rewrite-objc"); + IsModernRewriter = true; + } else if (JA.getType() == types::TY_RewrittenLegacyObjC) { + CmdArgs.push_back("-rewrite-objc"); + IsRewriter = true; + } else { + assert(JA.getType() == types::TY_PP_Asm && + "Unexpected output type!"); + } + } + + // The make clang go fast button. + CmdArgs.push_back("-disable-free"); + + // Disable the verification pass in -asserts builds. +#ifdef NDEBUG + CmdArgs.push_back("-disable-llvm-verifier"); +#endif + + // Set the main file name, so that debug info works even with + // -save-temps. + CmdArgs.push_back("-main-file-name"); + CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs)); + + // Some flags which affect the language (via preprocessor + // defines). See darwin::CC1::AddCPPArgs. + if (Args.hasArg(options::OPT_static)) + CmdArgs.push_back("-static-define"); + + if (isa<AnalyzeJobAction>(JA)) { + // Enable region store model by default. + CmdArgs.push_back("-analyzer-store=region"); + + // Treat blocks as analysis entry points. + CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks"); + + CmdArgs.push_back("-analyzer-eagerly-assume"); + + CmdArgs.push_back("-analyzer-ipa=inlining"); + + // Add default argument set. + if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) { + CmdArgs.push_back("-analyzer-checker=core"); + + if (getToolChain().getTriple().getOS() != llvm::Triple::Win32) + CmdArgs.push_back("-analyzer-checker=unix"); + + if (getToolChain().getTriple().getVendor() == llvm::Triple::Apple) + CmdArgs.push_back("-analyzer-checker=osx"); + + CmdArgs.push_back("-analyzer-checker=deadcode"); + + // Enable the following experimental checkers for testing. + CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn"); + CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw"); + CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets"); + CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp"); + CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp"); + CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork"); + } + + // Set the output format. The default is plist, for (lame) historical + // reasons. + CmdArgs.push_back("-analyzer-output"); + if (Arg *A = Args.getLastArg(options::OPT__analyzer_output)) + CmdArgs.push_back(A->getValue(Args)); + else + CmdArgs.push_back("plist"); + + // Disable the presentation of standard compiler warnings when + // using --analyze. We only want to show static analyzer diagnostics + // or frontend errors. + CmdArgs.push_back("-w"); + + // Add -Xanalyzer arguments when running as analyzer. + Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer); + } + + CheckCodeGenerationOptions(D, Args); + + // Perform argument translation for LLVM backend. This + // takes some care in reconciling with llvm-gcc. The + // issue is that llvm-gcc translates these options based on + // the values in cc1, whereas we are processing based on + // the driver arguments. + + // This comes from the default translation the driver + cc1 + // would do to enable flag_pic. + // + // FIXME: Centralize this code. + Arg *LastPICArg = 0; + for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I) { + if ((*I)->getOption().matches(options::OPT_fPIC) || + (*I)->getOption().matches(options::OPT_fno_PIC) || + (*I)->getOption().matches(options::OPT_fpic) || + (*I)->getOption().matches(options::OPT_fno_pic) || + (*I)->getOption().matches(options::OPT_fPIE) || + (*I)->getOption().matches(options::OPT_fno_PIE) || + (*I)->getOption().matches(options::OPT_fpie) || + (*I)->getOption().matches(options::OPT_fno_pie)) { + LastPICArg = *I; + (*I)->claim(); + } + } + bool PICDisabled = false; + bool PICEnabled = false; + bool PICForPIE = false; + if (LastPICArg) { + PICForPIE = (LastPICArg->getOption().matches(options::OPT_fPIE) || + LastPICArg->getOption().matches(options::OPT_fpie)); + PICEnabled = (PICForPIE || + LastPICArg->getOption().matches(options::OPT_fPIC) || + LastPICArg->getOption().matches(options::OPT_fpic)); + PICDisabled = !PICEnabled; + } + // Note that these flags are trump-cards. Regardless of the order w.r.t. the + // PIC or PIE options above, if these show up, PIC is disabled. + if (Args.hasArg(options::OPT_mkernel)) + PICDisabled = true; + if (Args.hasArg(options::OPT_static)) + PICDisabled = true; + bool DynamicNoPIC = Args.hasArg(options::OPT_mdynamic_no_pic); + + // Select the relocation model. + const char *Model = getToolChain().GetForcedPicModel(); + if (!Model) { + if (DynamicNoPIC) + Model = "dynamic-no-pic"; + else if (PICDisabled) + Model = "static"; + else if (PICEnabled) + Model = "pic"; + else + Model = getToolChain().GetDefaultRelocationModel(); + } + StringRef ModelStr = Model ? Model : ""; + if (Model && ModelStr != "pic") { + CmdArgs.push_back("-mrelocation-model"); + CmdArgs.push_back(Model); + } + + // Infer the __PIC__ and __PIE__ values. + if (ModelStr == "pic" && PICForPIE) { + CmdArgs.push_back("-pie-level"); + CmdArgs.push_back((LastPICArg && + LastPICArg->getOption().matches(options::OPT_fPIE)) ? + "2" : "1"); + } else if (ModelStr == "pic" || ModelStr == "dynamic-no-pic") { + CmdArgs.push_back("-pic-level"); + CmdArgs.push_back(((ModelStr != "dynamic-no-pic" && LastPICArg && + LastPICArg->getOption().matches(options::OPT_fPIC)) || + getToolChain().getTriple().isOSDarwin()) ? "2" : "1"); + } + + if (!Args.hasFlag(options::OPT_fmerge_all_constants, + options::OPT_fno_merge_all_constants)) + CmdArgs.push_back("-fno-merge-all-constants"); + + // LLVM Code Generator Options. + + if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) { + CmdArgs.push_back("-mregparm"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false)) + CmdArgs.push_back("-mrtd"); + + if (shouldUseFramePointer(Args, getToolChain().getTriple())) + CmdArgs.push_back("-mdisable-fp-elim"); + if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss, + options::OPT_fno_zero_initialized_in_bss)) + CmdArgs.push_back("-mno-zero-initialized-in-bss"); + if (!Args.hasFlag(options::OPT_fstrict_aliasing, + options::OPT_fno_strict_aliasing, + getToolChain().IsStrictAliasingDefault())) + CmdArgs.push_back("-relaxed-aliasing"); + if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums, + false)) + CmdArgs.push_back("-fstrict-enums"); + if (!Args.hasFlag(options::OPT_foptimize_sibling_calls, + options::OPT_fno_optimize_sibling_calls)) + CmdArgs.push_back("-mdisable-tail-calls"); + + // Handle various floating point optimization flags, mapping them to the + // appropriate LLVM code generation flags. The pattern for all of these is to + // default off the codegen optimizations, and if any flag enables them and no + // flag disables them after the flag enabling them, enable the codegen + // optimization. This is complicated by several "umbrella" flags. + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_ffinite_math_only, + options::OPT_fno_finite_math_only, + options::OPT_fhonor_infinities, + options::OPT_fno_honor_infinities)) + if (A->getOption().getID() != options::OPT_fno_finite_math_only && + A->getOption().getID() != options::OPT_fhonor_infinities) + CmdArgs.push_back("-menable-no-infs"); + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_ffinite_math_only, + options::OPT_fno_finite_math_only, + options::OPT_fhonor_nans, + options::OPT_fno_honor_nans)) + if (A->getOption().getID() != options::OPT_fno_finite_math_only && + A->getOption().getID() != options::OPT_fhonor_nans) + CmdArgs.push_back("-menable-no-nans"); + + // -fno-math-errno is default. + bool MathErrno = false; + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_fmath_errno, + options::OPT_fno_math_errno)) { + if (A->getOption().getID() == options::OPT_fmath_errno) { + CmdArgs.push_back("-fmath-errno"); + MathErrno = true; + } + } + + // There are several flags which require disabling very specific + // optimizations. Any of these being disabled forces us to turn off the + // entire set of LLVM optimizations, so collect them through all the flag + // madness. + bool AssociativeMath = false; + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_funsafe_math_optimizations, + options::OPT_fno_unsafe_math_optimizations, + options::OPT_fassociative_math, + options::OPT_fno_associative_math)) + if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations && + A->getOption().getID() != options::OPT_fno_associative_math) + AssociativeMath = true; + bool ReciprocalMath = false; + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_funsafe_math_optimizations, + options::OPT_fno_unsafe_math_optimizations, + options::OPT_freciprocal_math, + options::OPT_fno_reciprocal_math)) + if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations && + A->getOption().getID() != options::OPT_fno_reciprocal_math) + ReciprocalMath = true; + bool SignedZeros = true; + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_funsafe_math_optimizations, + options::OPT_fno_unsafe_math_optimizations, + options::OPT_fsigned_zeros, + options::OPT_fno_signed_zeros)) + if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations && + A->getOption().getID() != options::OPT_fsigned_zeros) + SignedZeros = false; + bool TrappingMath = true; + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_funsafe_math_optimizations, + options::OPT_fno_unsafe_math_optimizations, + options::OPT_ftrapping_math, + options::OPT_fno_trapping_math)) + if (A->getOption().getID() != options::OPT_fno_unsafe_math_optimizations && + A->getOption().getID() != options::OPT_ftrapping_math) + TrappingMath = false; + if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros && + !TrappingMath) + CmdArgs.push_back("-menable-unsafe-fp-math"); + + // We separately look for the '-ffast-math' flag, and if we find it, tell the + // frontend to provide the appropriate preprocessor macros. This is distinct + // from enabling any optimizations as it induces a language change which must + // survive serialization and deserialization, etc. + if (Args.hasArg(options::OPT_ffast_math)) + CmdArgs.push_back("-ffast-math"); + + // Decide whether to use verbose asm. Verbose assembly is the default on + // toolchains which have the integrated assembler on by default. + bool IsVerboseAsmDefault = getToolChain().IsIntegratedAssemblerDefault(); + if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm, + IsVerboseAsmDefault) || + Args.hasArg(options::OPT_dA)) + CmdArgs.push_back("-masm-verbose"); + + if (Args.hasArg(options::OPT_fdebug_pass_structure)) { + CmdArgs.push_back("-mdebug-pass"); + CmdArgs.push_back("Structure"); + } + if (Args.hasArg(options::OPT_fdebug_pass_arguments)) { + CmdArgs.push_back("-mdebug-pass"); + CmdArgs.push_back("Arguments"); + } + + // Enable -mconstructor-aliases except on darwin, where we have to + // work around a linker bug; see <rdar://problem/7651567>. + if (!getToolChain().getTriple().isOSDarwin()) + CmdArgs.push_back("-mconstructor-aliases"); + + // Darwin's kernel doesn't support guard variables; just die if we + // try to use them. + if (KernelOrKext && getToolChain().getTriple().isOSDarwin()) + CmdArgs.push_back("-fforbid-guard-variables"); + + if (Args.hasArg(options::OPT_mms_bitfields)) { + CmdArgs.push_back("-mms-bitfields"); + } + + // This is a coarse approximation of what llvm-gcc actually does, both + // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more + // complicated ways. + bool AsynchronousUnwindTables = + Args.hasFlag(options::OPT_fasynchronous_unwind_tables, + options::OPT_fno_asynchronous_unwind_tables, + getToolChain().IsUnwindTablesDefault() && + !KernelOrKext); + if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables, + AsynchronousUnwindTables)) + CmdArgs.push_back("-munwind-tables"); + + if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) { + CmdArgs.push_back("-mlimit-float-precision"); + CmdArgs.push_back(A->getValue(Args)); + } + + // FIXME: Handle -mtune=. + (void) Args.hasArg(options::OPT_mtune_EQ); + + if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) { + CmdArgs.push_back("-mcode-model"); + CmdArgs.push_back(A->getValue(Args)); + } + + // Add target specific cpu and features flags. + switch(getToolChain().getTriple().getArch()) { + default: + break; + + case llvm::Triple::arm: + case llvm::Triple::thumb: + AddARMTargetArgs(Args, CmdArgs, KernelOrKext); + break; + + case llvm::Triple::mips: + case llvm::Triple::mipsel: + case llvm::Triple::mips64: + case llvm::Triple::mips64el: + AddMIPSTargetArgs(Args, CmdArgs); + break; + + case llvm::Triple::sparc: + AddSparcTargetArgs(Args, CmdArgs); + break; + + case llvm::Triple::x86: + case llvm::Triple::x86_64: + AddX86TargetArgs(Args, CmdArgs); + break; + + case llvm::Triple::hexagon: + AddHexagonTargetArgs(Args, CmdArgs); + break; + } + + + + // Pass the linker version in use. + if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) { + CmdArgs.push_back("-target-linker-version"); + CmdArgs.push_back(A->getValue(Args)); + } + + // -mno-omit-leaf-frame-pointer is the default on Darwin. + if (Args.hasFlag(options::OPT_momit_leaf_frame_pointer, + options::OPT_mno_omit_leaf_frame_pointer, + !getToolChain().getTriple().isOSDarwin())) + CmdArgs.push_back("-momit-leaf-frame-pointer"); + + // Explicitly error on some things we know we don't support and can't just + // ignore. + types::ID InputType = Inputs[0].getType(); + if (!Args.hasArg(options::OPT_fallow_unsupported)) { + Arg *Unsupported; + if (types::isCXX(InputType) && + getToolChain().getTriple().isOSDarwin() && + getToolChain().getTriple().getArch() == llvm::Triple::x86) { + if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) || + (Unsupported = Args.getLastArg(options::OPT_mkernel))) + D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386) + << Unsupported->getOption().getName(); + } + } + + Args.AddAllArgs(CmdArgs, options::OPT_v); + Args.AddLastArg(CmdArgs, options::OPT_H); + if (D.CCPrintHeaders && !D.CCGenDiagnostics) { + CmdArgs.push_back("-header-include-file"); + CmdArgs.push_back(D.CCPrintHeadersFilename ? + D.CCPrintHeadersFilename : "-"); + } + Args.AddLastArg(CmdArgs, options::OPT_P); + Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout); + + if (D.CCLogDiagnostics && !D.CCGenDiagnostics) { + CmdArgs.push_back("-diagnostic-log-file"); + CmdArgs.push_back(D.CCLogDiagnosticsFilename ? + D.CCLogDiagnosticsFilename : "-"); + } + + // Special case debug options to only pass -g to clang. This is + // wrong. + Args.ClaimAllArgs(options::OPT_g_Group); + if (Arg *A = Args.getLastArg(options::OPT_g_Group)) + if (!A->getOption().matches(options::OPT_g0)) { + CmdArgs.push_back("-g"); + } + + Args.AddAllArgs(CmdArgs, options::OPT_ffunction_sections); + Args.AddAllArgs(CmdArgs, options::OPT_fdata_sections); + + Args.AddAllArgs(CmdArgs, options::OPT_finstrument_functions); + + if (Args.hasArg(options::OPT_ftest_coverage) || + Args.hasArg(options::OPT_coverage)) + CmdArgs.push_back("-femit-coverage-notes"); + if (Args.hasArg(options::OPT_fprofile_arcs) || + Args.hasArg(options::OPT_coverage)) + CmdArgs.push_back("-femit-coverage-data"); + + if (C.getArgs().hasArg(options::OPT_c) || + C.getArgs().hasArg(options::OPT_S)) { + if (Output.isFilename()) { + CmdArgs.push_back("-coverage-file"); + CmdArgs.push_back(Args.MakeArgString(Output.getFilename())); + } + } + + // Pass options for controlling the default header search paths. + if (Args.hasArg(options::OPT_nostdinc)) { + CmdArgs.push_back("-nostdsysteminc"); + CmdArgs.push_back("-nobuiltininc"); + } else { + if (Args.hasArg(options::OPT_nostdlibinc)) + CmdArgs.push_back("-nostdsysteminc"); + Args.AddLastArg(CmdArgs, options::OPT_nostdincxx); + Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc); + } + + // Pass the path to compiler resource files. + CmdArgs.push_back("-resource-dir"); + CmdArgs.push_back(D.ResourceDir.c_str()); + + Args.AddLastArg(CmdArgs, options::OPT_working_directory); + + bool ARCMTEnabled = false; + if (!Args.hasArg(options::OPT_fno_objc_arc)) { + if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check, + options::OPT_ccc_arcmt_modify, + options::OPT_ccc_arcmt_migrate)) { + ARCMTEnabled = true; + switch (A->getOption().getID()) { + default: + llvm_unreachable("missed a case"); + case options::OPT_ccc_arcmt_check: + CmdArgs.push_back("-arcmt-check"); + break; + case options::OPT_ccc_arcmt_modify: + CmdArgs.push_back("-arcmt-modify"); + break; + case options::OPT_ccc_arcmt_migrate: + CmdArgs.push_back("-arcmt-migrate"); + CmdArgs.push_back("-mt-migrate-directory"); + CmdArgs.push_back(A->getValue(Args)); + + Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output); + Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors); + break; + } + } + } + + if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) { + if (ARCMTEnabled) { + D.Diag(diag::err_drv_argument_not_allowed_with) + << A->getAsString(Args) << "-ccc-arcmt-migrate"; + } + CmdArgs.push_back("-mt-migrate-directory"); + CmdArgs.push_back(A->getValue(Args)); + + if (!Args.hasArg(options::OPT_objcmt_migrate_literals, + options::OPT_objcmt_migrate_subscripting)) { + // None specified, means enable them all. + CmdArgs.push_back("-objcmt-migrate-literals"); + CmdArgs.push_back("-objcmt-migrate-subscripting"); + } else { + Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals); + Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting); + } + } + + // Add preprocessing options like -I, -D, etc. if we are using the + // preprocessor. + // + // FIXME: Support -fpreprocessed + if (types::getPreprocessedType(InputType) != types::TY_INVALID) + AddPreprocessingOptions(C, D, Args, CmdArgs, Output, Inputs); + + // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes + // that "The compiler can only warn and ignore the option if not recognized". + // When building with ccache, it will pass -D options to clang even on + // preprocessed inputs and configure concludes that -fPIC is not supported. + Args.ClaimAllArgs(options::OPT_D); + + // Manually translate -O to -O2 and -O4 to -O3; let clang reject + // others. + if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { + if (A->getOption().matches(options::OPT_O4)) + CmdArgs.push_back("-O3"); + else if (A->getOption().matches(options::OPT_O) && + A->getValue(Args)[0] == '\0') + CmdArgs.push_back("-O2"); + else + A->render(Args, CmdArgs); + } + + Args.AddAllArgs(CmdArgs, options::OPT_W_Group); + Args.AddLastArg(CmdArgs, options::OPT_pedantic); + Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors); + Args.AddLastArg(CmdArgs, options::OPT_w); + + // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi} + // (-ansi is equivalent to -std=c89). + // + // If a std is supplied, only add -trigraphs if it follows the + // option. + if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) { + if (Std->getOption().matches(options::OPT_ansi)) + if (types::isCXX(InputType)) + CmdArgs.push_back("-std=c++98"); + else + CmdArgs.push_back("-std=c89"); + else + Std->render(Args, CmdArgs); + + if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi, + options::OPT_trigraphs)) + if (A != Std) + A->render(Args, CmdArgs); + } else { + // Honor -std-default. + // + // FIXME: Clang doesn't correctly handle -std= when the input language + // doesn't match. For the time being just ignore this for C++ inputs; + // eventually we want to do all the standard defaulting here instead of + // splitting it between the driver and clang -cc1. + if (!types::isCXX(InputType)) + Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, + "-std=", /*Joined=*/true); + Args.AddLastArg(CmdArgs, options::OPT_trigraphs); + } + + // Map the bizarre '-Wwrite-strings' flag to a more sensible + // '-fconst-strings'; this better indicates its actual behavior. + if (Args.hasFlag(options::OPT_Wwrite_strings, options::OPT_Wno_write_strings, + false)) { + // For perfect compatibility with GCC, we do this even in the presence of + // '-w'. This flag names something other than a warning for GCC. + CmdArgs.push_back("-fconst-strings"); + } + + // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active + // during C++ compilation, which it is by default. GCC keeps this define even + // in the presence of '-w', match this behavior bug-for-bug. + if (types::isCXX(InputType) && + Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated, + true)) { + CmdArgs.push_back("-fdeprecated-macro"); + } + + // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'. + if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) { + if (Asm->getOption().matches(options::OPT_fasm)) + CmdArgs.push_back("-fgnu-keywords"); + else + CmdArgs.push_back("-fno-gnu-keywords"); + } + + if (ShouldDisableCFI(Args, getToolChain())) + CmdArgs.push_back("-fno-dwarf2-cfi-asm"); + + if (ShouldDisableDwarfDirectory(Args, getToolChain())) + CmdArgs.push_back("-fno-dwarf-directory-asm"); + + if (const char *pwd = ::getenv("PWD")) { + // GCC also verifies that stat(pwd) and stat(".") have the same inode + // number. Not doing those because stats are slow, but we could. + if (llvm::sys::path::is_absolute(pwd)) { + std::string CompDir = pwd; + CmdArgs.push_back("-fdebug-compilation-dir"); + CmdArgs.push_back(Args.MakeArgString(CompDir)); + } + } + + if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_, + options::OPT_ftemplate_depth_EQ)) { + CmdArgs.push_back("-ftemplate-depth"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) { + CmdArgs.push_back("-fconstexpr-depth"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ, + options::OPT_Wlarge_by_value_copy_def)) { + CmdArgs.push_back("-Wlarge-by-value-copy"); + if (A->getNumValues()) + CmdArgs.push_back(A->getValue(Args)); + else + CmdArgs.push_back("64"); // default value for -Wlarge-by-value-copy. + } + + if (Args.hasArg(options::OPT__relocatable_pch)) + CmdArgs.push_back("-relocatable-pch"); + + if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) { + CmdArgs.push_back("-fconstant-string-class"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) { + CmdArgs.push_back("-ftabstop"); + CmdArgs.push_back(A->getValue(Args)); + } + + CmdArgs.push_back("-ferror-limit"); + if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ)) + CmdArgs.push_back(A->getValue(Args)); + else + CmdArgs.push_back("19"); + + if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) { + CmdArgs.push_back("-fmacro-backtrace-limit"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) { + CmdArgs.push_back("-ftemplate-backtrace-limit"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) { + CmdArgs.push_back("-fconstexpr-backtrace-limit"); + CmdArgs.push_back(A->getValue(Args)); + } + + // Pass -fmessage-length=. + CmdArgs.push_back("-fmessage-length"); + if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) { + CmdArgs.push_back(A->getValue(Args)); + } else { + // If -fmessage-length=N was not specified, determine whether this is a + // terminal and, if so, implicitly define -fmessage-length appropriately. + unsigned N = llvm::sys::Process::StandardErrColumns(); + CmdArgs.push_back(Args.MakeArgString(Twine(N))); + } + + if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ)) { + CmdArgs.push_back("-fvisibility"); + CmdArgs.push_back(A->getValue(Args)); + } + + Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden); + + // -fhosted is default. + if (Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) || + KernelOrKext) + CmdArgs.push_back("-ffreestanding"); + + // Forward -f (flag) options which we can pass directly. + Args.AddLastArg(CmdArgs, options::OPT_fcatch_undefined_behavior); + Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls); + Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions); + Args.AddLastArg(CmdArgs, options::OPT_flimit_debug_info); + Args.AddLastArg(CmdArgs, options::OPT_fno_limit_debug_info); + Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names); + Args.AddLastArg(CmdArgs, options::OPT_faltivec); + + // Report and error for -faltivec on anything other then PowerPC. + if (const Arg *A = Args.getLastArg(options::OPT_faltivec)) + if (!(getToolChain().getTriple().getArch() == llvm::Triple::ppc || + getToolChain().getTriple().getArch() == llvm::Triple::ppc64)) + D.Diag(diag::err_drv_argument_only_allowed_with) + << A->getAsString(Args) << "ppc/ppc64"; + + if (getToolChain().SupportsProfiling()) + Args.AddLastArg(CmdArgs, options::OPT_pg); + + if (Args.hasFlag(options::OPT_faddress_sanitizer, + options::OPT_fno_address_sanitizer, false)) + CmdArgs.push_back("-faddress-sanitizer"); + + if (Args.hasFlag(options::OPT_fthread_sanitizer, + options::OPT_fno_thread_sanitizer, false)) + CmdArgs.push_back("-fthread-sanitizer"); + + // -flax-vector-conversions is default. + if (!Args.hasFlag(options::OPT_flax_vector_conversions, + options::OPT_fno_lax_vector_conversions)) + CmdArgs.push_back("-fno-lax-vector-conversions"); + + if (Args.getLastArg(options::OPT_fapple_kext)) + CmdArgs.push_back("-fapple-kext"); + + Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch); + Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info); + Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits); + Args.AddLastArg(CmdArgs, options::OPT_ftime_report); + Args.AddLastArg(CmdArgs, options::OPT_ftrapv); + + if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) { + CmdArgs.push_back("-ftrapv-handler"); + CmdArgs.push_back(A->getValue(Args)); + } + + Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ); + + // -fno-strict-overflow implies -fwrapv if it isn't disabled, but + // -fstrict-overflow won't turn off an explicitly enabled -fwrapv. + if (Arg *A = Args.getLastArg(options::OPT_fwrapv, + options::OPT_fno_wrapv)) { + if (A->getOption().matches(options::OPT_fwrapv)) + CmdArgs.push_back("-fwrapv"); + } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow, + options::OPT_fno_strict_overflow)) { + if (A->getOption().matches(options::OPT_fno_strict_overflow)) + CmdArgs.push_back("-fwrapv"); + } + Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings); + Args.AddLastArg(CmdArgs, options::OPT_funroll_loops); + + Args.AddLastArg(CmdArgs, options::OPT_pthread); + + // -stack-protector=0 is default. + unsigned StackProtectorLevel = 0; + if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector, + options::OPT_fstack_protector_all, + options::OPT_fstack_protector)) { + if (A->getOption().matches(options::OPT_fstack_protector)) + StackProtectorLevel = 1; + else if (A->getOption().matches(options::OPT_fstack_protector_all)) + StackProtectorLevel = 2; + } else { + StackProtectorLevel = + getToolChain().GetDefaultStackProtectorLevel(KernelOrKext); + } + if (StackProtectorLevel) { + CmdArgs.push_back("-stack-protector"); + CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel))); + } + + // Translate -mstackrealign + if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign, + false)) { + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-force-align-stack"); + } + if (!Args.hasFlag(options::OPT_mno_stackrealign, options::OPT_mstackrealign, + false)) { + CmdArgs.push_back(Args.MakeArgString("-mstackrealign")); + } + + if (Args.hasArg(options::OPT_mstack_alignment)) { + StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment); + CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment)); + } + + // Forward -f options with positive and negative forms; we translate + // these by hand. + + if (Args.hasArg(options::OPT_mkernel)) { + if (!Args.hasArg(options::OPT_fapple_kext) && types::isCXX(InputType)) + CmdArgs.push_back("-fapple-kext"); + if (!Args.hasArg(options::OPT_fbuiltin)) + CmdArgs.push_back("-fno-builtin"); + Args.ClaimAllArgs(options::OPT_fno_builtin); + } + // -fbuiltin is default. + else if (!Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin)) + CmdArgs.push_back("-fno-builtin"); + + if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, + options::OPT_fno_assume_sane_operator_new)) + CmdArgs.push_back("-fno-assume-sane-operator-new"); + + // -fblocks=0 is default. + if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks, + getToolChain().IsBlocksDefault()) || + (Args.hasArg(options::OPT_fgnu_runtime) && + Args.hasArg(options::OPT_fobjc_nonfragile_abi) && + !Args.hasArg(options::OPT_fno_blocks))) { + CmdArgs.push_back("-fblocks"); + + if (!Args.hasArg(options::OPT_fgnu_runtime) && + !getToolChain().hasBlocksRuntime()) + CmdArgs.push_back("-fblocks-runtime-optional"); + } + + // -fmodules enables modules (off by default). However, for C++/Objective-C++, + // users must also pass -fcxx-modules. The latter flag will disappear once the + // modules implementation is solid for C++/Objective-C++ programs as well. + if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) { + bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules, + options::OPT_fno_cxx_modules, + false); + if (AllowedInCXX || !types::isCXX(InputType)) + CmdArgs.push_back("-fmodules"); + } + + // -faccess-control is default. + if (Args.hasFlag(options::OPT_fno_access_control, + options::OPT_faccess_control, + false)) + CmdArgs.push_back("-fno-access-control"); + + // -felide-constructors is the default. + if (Args.hasFlag(options::OPT_fno_elide_constructors, + options::OPT_felide_constructors, + false)) + CmdArgs.push_back("-fno-elide-constructors"); + + // -frtti is default. + if (!Args.hasFlag(options::OPT_frtti, options::OPT_fno_rtti) || + KernelOrKext) + CmdArgs.push_back("-fno-rtti"); + + // -fshort-enums=0 is default for all architectures except Hexagon. + if (Args.hasFlag(options::OPT_fshort_enums, + options::OPT_fno_short_enums, + getToolChain().getTriple().getArch() == + llvm::Triple::hexagon)) + CmdArgs.push_back("-fshort-enums"); + + // -fsigned-char is default. + if (!Args.hasFlag(options::OPT_fsigned_char, options::OPT_funsigned_char, + isSignedCharDefault(getToolChain().getTriple()))) + CmdArgs.push_back("-fno-signed-char"); + + // -fthreadsafe-static is default. + if (!Args.hasFlag(options::OPT_fthreadsafe_statics, + options::OPT_fno_threadsafe_statics)) + CmdArgs.push_back("-fno-threadsafe-statics"); + + // -fuse-cxa-atexit is default. + if (!Args.hasFlag(options::OPT_fuse_cxa_atexit, + options::OPT_fno_use_cxa_atexit, + getToolChain().getTriple().getOS() != llvm::Triple::Cygwin && + getToolChain().getTriple().getOS() != llvm::Triple::MinGW32 && + getToolChain().getTriple().getArch() != llvm::Triple::hexagon) || + KernelOrKext) + CmdArgs.push_back("-fno-use-cxa-atexit"); + + // -fms-extensions=0 is default. + if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions, + getToolChain().getTriple().getOS() == llvm::Triple::Win32)) + CmdArgs.push_back("-fms-extensions"); + + // -fms-compatibility=0 is default. + if (Args.hasFlag(options::OPT_fms_compatibility, + options::OPT_fno_ms_compatibility, + (getToolChain().getTriple().getOS() == llvm::Triple::Win32 && + Args.hasFlag(options::OPT_fms_extensions, + options::OPT_fno_ms_extensions, + true)))) + CmdArgs.push_back("-fms-compatibility"); + + // -fmsc-version=1300 is default. + if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions, + getToolChain().getTriple().getOS() == llvm::Triple::Win32) || + Args.hasArg(options::OPT_fmsc_version)) { + StringRef msc_ver = Args.getLastArgValue(options::OPT_fmsc_version); + if (msc_ver.empty()) + CmdArgs.push_back("-fmsc-version=1300"); + else + CmdArgs.push_back(Args.MakeArgString("-fmsc-version=" + msc_ver)); + } + + + // -fborland-extensions=0 is default. + if (Args.hasFlag(options::OPT_fborland_extensions, + options::OPT_fno_borland_extensions, false)) + CmdArgs.push_back("-fborland-extensions"); + + // -fno-delayed-template-parsing is default, except for Windows where MSVC STL + // needs it. + if (Args.hasFlag(options::OPT_fdelayed_template_parsing, + options::OPT_fno_delayed_template_parsing, + getToolChain().getTriple().getOS() == llvm::Triple::Win32)) + CmdArgs.push_back("-fdelayed-template-parsing"); + + // -fgnu-keywords default varies depending on language; only pass if + // specified. + if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords, + options::OPT_fno_gnu_keywords)) + A->render(Args, CmdArgs); + + if (Args.hasFlag(options::OPT_fgnu89_inline, + options::OPT_fno_gnu89_inline, + false)) + CmdArgs.push_back("-fgnu89-inline"); + + if (Args.hasArg(options::OPT_fno_inline)) + CmdArgs.push_back("-fno-inline"); + + if (Args.hasArg(options::OPT_fno_inline_functions)) + CmdArgs.push_back("-fno-inline-functions"); + + // -fobjc-nonfragile-abi=0 is default. + ObjCRuntime objCRuntime; + unsigned objcABIVersion = 0; + bool NeXTRuntimeIsDefault + = (IsRewriter || IsModernRewriter || + getToolChain().getTriple().isOSDarwin()); + if (Args.hasFlag(options::OPT_fnext_runtime, options::OPT_fgnu_runtime, + NeXTRuntimeIsDefault)) { + objCRuntime.setKind(ObjCRuntime::NeXT); + } else { + CmdArgs.push_back("-fgnu-runtime"); + objCRuntime.setKind(ObjCRuntime::GNU); + } + getToolChain().configureObjCRuntime(objCRuntime); + if (objCRuntime.HasARC) + CmdArgs.push_back("-fobjc-runtime-has-arc"); + if (objCRuntime.HasWeak) + CmdArgs.push_back("-fobjc-runtime-has-weak"); + if (objCRuntime.HasTerminate) + CmdArgs.push_back("-fobjc-runtime-has-terminate"); + + // Compute the Objective-C ABI "version" to use. Version numbers are + // slightly confusing for historical reasons: + // 1 - Traditional "fragile" ABI + // 2 - Non-fragile ABI, version 1 + // 3 - Non-fragile ABI, version 2 + objcABIVersion = 1; + // If -fobjc-abi-version= is present, use that to set the version. + if (Arg *A = Args.getLastArg(options::OPT_fobjc_abi_version_EQ)) { + if (StringRef(A->getValue(Args)) == "1") + objcABIVersion = 1; + else if (StringRef(A->getValue(Args)) == "2") + objcABIVersion = 2; + else if (StringRef(A->getValue(Args)) == "3") + objcABIVersion = 3; + else + D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); + } else { + // Otherwise, determine if we are using the non-fragile ABI. + bool NonFragileABIIsDefault = + (IsModernRewriter || + (!IsRewriter && getToolChain().IsObjCNonFragileABIDefault())); + if (Args.hasFlag(options::OPT_fobjc_nonfragile_abi, + options::OPT_fno_objc_nonfragile_abi, + NonFragileABIIsDefault)) { + // Determine the non-fragile ABI version to use. +#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO + unsigned NonFragileABIVersion = 1; +#else + unsigned NonFragileABIVersion = 2; +#endif + + if (Arg *A = Args.getLastArg( + options::OPT_fobjc_nonfragile_abi_version_EQ)) { + if (StringRef(A->getValue(Args)) == "1") + NonFragileABIVersion = 1; + else if (StringRef(A->getValue(Args)) == "2") + NonFragileABIVersion = 2; + else + D.Diag(diag::err_drv_clang_unsupported) + << A->getAsString(Args); + } + + objcABIVersion = 1 + NonFragileABIVersion; + } else { + objcABIVersion = 1; + } + } + + if (objcABIVersion == 1) { + CmdArgs.push_back("-fobjc-fragile-abi"); + } else { + // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and + // legacy is the default. + if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch, + options::OPT_fno_objc_legacy_dispatch, + getToolChain().IsObjCLegacyDispatchDefault())) { + if (getToolChain().UseObjCMixedDispatch()) + CmdArgs.push_back("-fobjc-dispatch-method=mixed"); + else + CmdArgs.push_back("-fobjc-dispatch-method=non-legacy"); + } + } + + // -fobjc-default-synthesize-properties=1 is default. This only has an effect + // if the nonfragile objc abi is used. + if (getToolChain().IsObjCDefaultSynthPropertiesDefault()) { + CmdArgs.push_back("-fobjc-default-synthesize-properties"); + } + + // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc. + // NOTE: This logic is duplicated in ToolChains.cpp. + bool ARC = isObjCAutoRefCount(Args); + if (ARC) { + if (!getToolChain().SupportsObjCARC()) + D.Diag(diag::err_arc_unsupported); + + CmdArgs.push_back("-fobjc-arc"); + + // FIXME: It seems like this entire block, and several around it should be + // wrapped in isObjC, but for now we just use it here as this is where it + // was being used previously. + if (types::isCXX(InputType) && types::isObjC(InputType)) { + if (getToolChain().GetCXXStdlibType(Args) == ToolChain::CST_Libcxx) + CmdArgs.push_back("-fobjc-arc-cxxlib=libc++"); + else + CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++"); + } + + // Allow the user to enable full exceptions code emission. + // We define off for Objective-CC, on for Objective-C++. + if (Args.hasFlag(options::OPT_fobjc_arc_exceptions, + options::OPT_fno_objc_arc_exceptions, + /*default*/ types::isCXX(InputType))) + CmdArgs.push_back("-fobjc-arc-exceptions"); + } + + // -fobjc-infer-related-result-type is the default, except in the Objective-C + // rewriter. + if (IsRewriter || IsModernRewriter) + CmdArgs.push_back("-fno-objc-infer-related-result-type"); + + // Handle -fobjc-gc and -fobjc-gc-only. They are exclusive, and -fobjc-gc-only + // takes precedence. + const Arg *GCArg = Args.getLastArg(options::OPT_fobjc_gc_only); + if (!GCArg) + GCArg = Args.getLastArg(options::OPT_fobjc_gc); + if (GCArg) { + if (ARC) { + D.Diag(diag::err_drv_objc_gc_arr) + << GCArg->getAsString(Args); + } else if (getToolChain().SupportsObjCGC()) { + GCArg->render(Args, CmdArgs); + } else { + // FIXME: We should move this to a hard error. + D.Diag(diag::warn_drv_objc_gc_unsupported) + << GCArg->getAsString(Args); + } + } + + // Add exception args. + addExceptionArgs(Args, InputType, getToolChain().getTriple(), + KernelOrKext, objcABIVersion, CmdArgs); + + if (getToolChain().UseSjLjExceptions()) + CmdArgs.push_back("-fsjlj-exceptions"); + + // C++ "sane" operator new. + if (!Args.hasFlag(options::OPT_fassume_sane_operator_new, + options::OPT_fno_assume_sane_operator_new)) + CmdArgs.push_back("-fno-assume-sane-operator-new"); + + // -fconstant-cfstrings is default, and may be subject to argument translation + // on Darwin. + if (!Args.hasFlag(options::OPT_fconstant_cfstrings, + options::OPT_fno_constant_cfstrings) || + !Args.hasFlag(options::OPT_mconstant_cfstrings, + options::OPT_mno_constant_cfstrings)) + CmdArgs.push_back("-fno-constant-cfstrings"); + + // -fshort-wchar default varies depending on platform; only + // pass if specified. + if (Arg *A = Args.getLastArg(options::OPT_fshort_wchar)) + A->render(Args, CmdArgs); + + // -fno-pascal-strings is default, only pass non-default. If the tool chain + // happened to translate to -mpascal-strings, we want to back translate here. + // + // FIXME: This is gross; that translation should be pulled from the + // tool chain. + if (Args.hasFlag(options::OPT_fpascal_strings, + options::OPT_fno_pascal_strings, + false) || + Args.hasFlag(options::OPT_mpascal_strings, + options::OPT_mno_pascal_strings, + false)) + CmdArgs.push_back("-fpascal-strings"); + + // Honor -fpack-struct= and -fpack-struct, if given. Note that + // -fno-pack-struct doesn't apply to -fpack-struct=. + if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) { + CmdArgs.push_back("-fpack-struct"); + CmdArgs.push_back(A->getValue(Args)); + } else if (Args.hasFlag(options::OPT_fpack_struct, + options::OPT_fno_pack_struct, false)) { + CmdArgs.push_back("-fpack-struct"); + CmdArgs.push_back("1"); + } + + if (Args.hasArg(options::OPT_mkernel) || + Args.hasArg(options::OPT_fapple_kext)) { + if (!Args.hasArg(options::OPT_fcommon)) + CmdArgs.push_back("-fno-common"); + Args.ClaimAllArgs(options::OPT_fno_common); + } + + // -fcommon is default, only pass non-default. + else if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common)) + CmdArgs.push_back("-fno-common"); + + // -fsigned-bitfields is default, and clang doesn't yet support + // -funsigned-bitfields. + if (!Args.hasFlag(options::OPT_fsigned_bitfields, + options::OPT_funsigned_bitfields)) + D.Diag(diag::warn_drv_clang_unsupported) + << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args); + + // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope. + if (!Args.hasFlag(options::OPT_ffor_scope, + options::OPT_fno_for_scope)) + D.Diag(diag::err_drv_clang_unsupported) + << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args); + + // -fcaret-diagnostics is default. + if (!Args.hasFlag(options::OPT_fcaret_diagnostics, + options::OPT_fno_caret_diagnostics, true)) + CmdArgs.push_back("-fno-caret-diagnostics"); + + // -fdiagnostics-fixit-info is default, only pass non-default. + if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info, + options::OPT_fno_diagnostics_fixit_info)) + CmdArgs.push_back("-fno-diagnostics-fixit-info"); + + // Enable -fdiagnostics-show-option by default. + if (Args.hasFlag(options::OPT_fdiagnostics_show_option, + options::OPT_fno_diagnostics_show_option)) + CmdArgs.push_back("-fdiagnostics-show-option"); + + if (const Arg *A = + Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) { + CmdArgs.push_back("-fdiagnostics-show-category"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (const Arg *A = + Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) { + CmdArgs.push_back("-fdiagnostics-format"); + CmdArgs.push_back(A->getValue(Args)); + } + + if (Arg *A = Args.getLastArg( + options::OPT_fdiagnostics_show_note_include_stack, + options::OPT_fno_diagnostics_show_note_include_stack)) { + if (A->getOption().matches( + options::OPT_fdiagnostics_show_note_include_stack)) + CmdArgs.push_back("-fdiagnostics-show-note-include-stack"); + else + CmdArgs.push_back("-fno-diagnostics-show-note-include-stack"); + } + + // Color diagnostics are the default, unless the terminal doesn't support + // them. + if (Args.hasFlag(options::OPT_fcolor_diagnostics, + options::OPT_fno_color_diagnostics, + llvm::sys::Process::StandardErrHasColors())) + CmdArgs.push_back("-fcolor-diagnostics"); + + if (!Args.hasFlag(options::OPT_fshow_source_location, + options::OPT_fno_show_source_location)) + CmdArgs.push_back("-fno-show-source-location"); + + if (!Args.hasFlag(options::OPT_fshow_column, + options::OPT_fno_show_column, + true)) + CmdArgs.push_back("-fno-show-column"); + + if (!Args.hasFlag(options::OPT_fspell_checking, + options::OPT_fno_spell_checking)) + CmdArgs.push_back("-fno-spell-checking"); + + + // Silently ignore -fasm-blocks for now. + (void) Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks, + false); + + if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ)) + A->render(Args, CmdArgs); + + // -fdollars-in-identifiers default varies depending on platform and + // language; only pass if specified. + if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers, + options::OPT_fno_dollars_in_identifiers)) { + if (A->getOption().matches(options::OPT_fdollars_in_identifiers)) + CmdArgs.push_back("-fdollars-in-identifiers"); + else + CmdArgs.push_back("-fno-dollars-in-identifiers"); + } + + // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for + // practical purposes. + if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time, + options::OPT_fno_unit_at_a_time)) { + if (A->getOption().matches(options::OPT_fno_unit_at_a_time)) + D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args); + } + + if (Args.hasFlag(options::OPT_fapple_pragma_pack, + options::OPT_fno_apple_pragma_pack, false)) + CmdArgs.push_back("-fapple-pragma-pack"); + + // Default to -fno-builtin-str{cat,cpy} on Darwin for ARM. + // + // FIXME: This is disabled until clang -cc1 supports -fno-builtin-foo. PR4941. +#if 0 + if (getToolChain().getTriple().isOSDarwin() && + (getToolChain().getTriple().getArch() == llvm::Triple::arm || + getToolChain().getTriple().getArch() == llvm::Triple::thumb)) { + if (!Args.hasArg(options::OPT_fbuiltin_strcat)) + CmdArgs.push_back("-fno-builtin-strcat"); + if (!Args.hasArg(options::OPT_fbuiltin_strcpy)) + CmdArgs.push_back("-fno-builtin-strcpy"); + } +#endif + + // Only allow -traditional or -traditional-cpp outside in preprocessing modes. + if (Arg *A = Args.getLastArg(options::OPT_traditional, + options::OPT_traditional_cpp)) { + if (isa<PreprocessJobAction>(JA)) + CmdArgs.push_back("-traditional-cpp"); + else + D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args); + } + + Args.AddLastArg(CmdArgs, options::OPT_dM); + Args.AddLastArg(CmdArgs, options::OPT_dD); + + // Handle serialized diagnostics. + if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) { + CmdArgs.push_back("-serialize-diagnostic-file"); + CmdArgs.push_back(Args.MakeArgString(A->getValue(Args))); + } + + // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option + // parser. + Args.AddAllArgValues(CmdArgs, options::OPT_Xclang); + for (arg_iterator it = Args.filtered_begin(options::OPT_mllvm), + ie = Args.filtered_end(); it != ie; ++it) { + (*it)->claim(); + + // We translate this by hand to the -cc1 argument, since nightly test uses + // it and developers have been trained to spell it with -mllvm. + if (StringRef((*it)->getValue(Args, 0)) == "-disable-llvm-optzns") + CmdArgs.push_back("-disable-llvm-optzns"); + else + (*it)->render(Args, CmdArgs); + } + + if (Output.getType() == types::TY_Dependencies) { + // Handled with other dependency code. + } else if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back("-x"); + CmdArgs.push_back(types::getTypeName(II.getType())); + if (II.isFilename()) + CmdArgs.push_back(II.getFilename()); + else + II.getInputArg().renderAsInput(Args, CmdArgs); + } + + Args.AddAllArgs(CmdArgs, options::OPT_undef); + + const char *Exec = getToolChain().getDriver().getClangProgramPath(); + + // Optionally embed the -cc1 level arguments into the debug info, for build + // analysis. + if (getToolChain().UseDwarfDebugFlags()) { + ArgStringList OriginalArgs; + for (ArgList::const_iterator it = Args.begin(), + ie = Args.end(); it != ie; ++it) + (*it)->render(Args, OriginalArgs); + + SmallString<256> Flags; + Flags += Exec; + for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) { + Flags += " "; + Flags += OriginalArgs[i]; + } + CmdArgs.push_back("-dwarf-debug-flags"); + CmdArgs.push_back(Args.MakeArgString(Flags.str())); + } + + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); + + if (Arg *A = Args.getLastArg(options::OPT_pg)) + if (Args.hasArg(options::OPT_fomit_frame_pointer)) + D.Diag(diag::err_drv_argument_not_allowed_with) + << "-fomit-frame-pointer" << A->getAsString(Args); + + // Claim some arguments which clang supports automatically. + + // -fpch-preprocess is used with gcc to add a special marker in the output to + // include the PCH file. Clang's PTH solution is completely transparent, so we + // do not need to deal with it at all. + Args.ClaimAllArgs(options::OPT_fpch_preprocess); + + // Claim some arguments which clang doesn't support, but we don't + // care to warn the user about. + Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group); + Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group); + + // Disable warnings for clang -E -use-gold-plugin -emit-llvm foo.c + Args.ClaimAllArgs(options::OPT_use_gold_plugin); + Args.ClaimAllArgs(options::OPT_emit_llvm); +} + +void ClangAs::AddARMTargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + const Driver &D = getToolChain().getDriver(); + llvm::Triple Triple = getToolChain().getTriple(); + + // Set the CPU based on -march= and -mcpu=. + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(getARMTargetCPU(Args, Triple)); + + // Honor -mfpu=. + if (const Arg *A = Args.getLastArg(options::OPT_mfpu_EQ)) + addFPUArgs(D, A, Args, CmdArgs); + + // Honor -mfpmath=. + if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) + addFPMathArgs(D, A, Args, CmdArgs, getARMTargetCPU(Args, Triple)); +} + +void ClangAs::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + assert(Inputs.size() == 1 && "Unexpected number of inputs."); + const InputInfo &Input = Inputs[0]; + + // Don't warn about "clang -w -c foo.s" + Args.ClaimAllArgs(options::OPT_w); + // and "clang -emit-llvm -c foo.s" + Args.ClaimAllArgs(options::OPT_emit_llvm); + // and "clang -use-gold-plugin -c foo.s" + Args.ClaimAllArgs(options::OPT_use_gold_plugin); + + // Invoke ourselves in -cc1as mode. + // + // FIXME: Implement custom jobs for internal actions. + CmdArgs.push_back("-cc1as"); + + // Add the "effective" target triple. + CmdArgs.push_back("-triple"); + std::string TripleStr = + getToolChain().ComputeEffectiveClangTriple(Args, Input.getType()); + CmdArgs.push_back(Args.MakeArgString(TripleStr)); + + // Set the output mode, we currently only expect to be used as a real + // assembler. + CmdArgs.push_back("-filetype"); + CmdArgs.push_back("obj"); + + if (UseRelaxAll(C, Args)) + CmdArgs.push_back("-relax-all"); + + // Add target specific cpu and features flags. + switch(getToolChain().getTriple().getArch()) { + default: + break; + + case llvm::Triple::arm: + case llvm::Triple::thumb: + AddARMTargetArgs(Args, CmdArgs); + break; + } + + // Ignore explicit -force_cpusubtype_ALL option. + (void) Args.hasArg(options::OPT_force__cpusubtype__ALL); + + // Determine the original source input. + const Action *SourceAction = &JA; + while (SourceAction->getKind() != Action::InputClass) { + assert(!SourceAction->getInputs().empty() && "unexpected root action!"); + SourceAction = SourceAction->getInputs()[0]; + } + + // Forward -g, assuming we are dealing with an actual assembly file. + if (SourceAction->getType() == types::TY_Asm || + SourceAction->getType() == types::TY_PP_Asm) { + Args.ClaimAllArgs(options::OPT_g_Group); + if (Arg *A = Args.getLastArg(options::OPT_g_Group)) + if (!A->getOption().matches(options::OPT_g0)) + CmdArgs.push_back("-g"); + } + + // Optionally embed the -cc1as level arguments into the debug info, for build + // analysis. + if (getToolChain().UseDwarfDebugFlags()) { + ArgStringList OriginalArgs; + for (ArgList::const_iterator it = Args.begin(), + ie = Args.end(); it != ie; ++it) + (*it)->render(Args, OriginalArgs); + + SmallString<256> Flags; + const char *Exec = getToolChain().getDriver().getClangProgramPath(); + Flags += Exec; + for (unsigned i = 0, e = OriginalArgs.size(); i != e; ++i) { + Flags += " "; + Flags += OriginalArgs[i]; + } + CmdArgs.push_back("-dwarf-debug-flags"); + CmdArgs.push_back(Args.MakeArgString(Flags.str())); + } + + // FIXME: Add -static support, once we have it. + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + Args.AddAllArgs(CmdArgs, options::OPT_mllvm); + + assert(Output.isFilename() && "Unexpected lipo output."); + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + assert(Input.isFilename() && "Invalid input."); + CmdArgs.push_back(Input.getFilename()); + + const char *Exec = getToolChain().getDriver().getClangProgramPath(); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + for (ArgList::const_iterator + it = Args.begin(), ie = Args.end(); it != ie; ++it) { + Arg *A = *it; + if (A->getOption().hasForwardToGCC()) { + // Don't forward any -g arguments to assembly steps. + if (isa<AssembleJobAction>(JA) && + A->getOption().matches(options::OPT_g_Group)) + continue; + + // It is unfortunate that we have to claim here, as this means + // we will basically never report anything interesting for + // platforms using a generic gcc, even if we are just using gcc + // to get to the assembler. + A->claim(); + A->render(Args, CmdArgs); + } + } + + RenderExtraToolArgs(JA, CmdArgs); + + // If using a driver driver, force the arch. + const std::string &Arch = getToolChain().getArchName(); + if (getToolChain().getTriple().isOSDarwin()) { + CmdArgs.push_back("-arch"); + + // FIXME: Remove these special cases. + if (Arch == "powerpc") + CmdArgs.push_back("ppc"); + else if (Arch == "powerpc64") + CmdArgs.push_back("ppc64"); + else + CmdArgs.push_back(Args.MakeArgString(Arch)); + } + + // Try to force gcc to match the tool chain we want, if we recognize + // the arch. + // + // FIXME: The triple class should directly provide the information we want + // here. + if (Arch == "i386" || Arch == "powerpc") + CmdArgs.push_back("-m32"); + else if (Arch == "x86_64" || Arch == "powerpc64") + CmdArgs.push_back("-m64"); + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Unexpected output"); + CmdArgs.push_back("-fsyntax-only"); + } + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + // Only pass -x if gcc will understand it; otherwise hope gcc + // understands the suffix correctly. The main use case this would go + // wrong in is for linker inputs if they happened to have an odd + // suffix; really the only way to get this to happen is a command + // like '-x foobar a.c' which will treat a.c like a linker input. + // + // FIXME: For the linker case specifically, can we safely convert + // inputs into '-Wl,' options? + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + + // Don't try to pass LLVM or AST inputs to a generic gcc. + if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR || + II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC) + D.Diag(diag::err_drv_no_linker_llvm_support) + << getToolChain().getTripleString(); + else if (II.getType() == types::TY_AST) + D.Diag(diag::err_drv_no_ast_support) + << getToolChain().getTripleString(); + + if (types::canTypeBeUserSpecified(II.getType())) { + CmdArgs.push_back("-x"); + CmdArgs.push_back(types::getTypeName(II.getType())); + } + + if (II.isFilename()) + CmdArgs.push_back(II.getFilename()); + else { + const Arg &A = II.getInputArg(); + + // Reverse translate some rewritten options. + if (A.getOption().matches(options::OPT_Z_reserved_lib_stdcxx)) { + CmdArgs.push_back("-lstdc++"); + continue; + } + + // Don't render as input, we need gcc to do the translations. + A.render(Args, CmdArgs); + } + } + + const std::string customGCCName = D.getCCCGenericGCCName(); + const char *GCCName; + if (!customGCCName.empty()) + GCCName = customGCCName.c_str(); + else if (D.CCCIsCXX) { + GCCName = "g++"; + } else + GCCName = "gcc"; + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath(GCCName)); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void gcc::Preprocess::RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const { + CmdArgs.push_back("-E"); +} + +void gcc::Precompile::RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const { + // The type is good enough. +} + +void gcc::Compile::RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const { + const Driver &D = getToolChain().getDriver(); + + // If -flto, etc. are present then make sure not to force assembly output. + if (JA.getType() == types::TY_LLVM_IR || JA.getType() == types::TY_LTO_IR || + JA.getType() == types::TY_LLVM_BC || JA.getType() == types::TY_LTO_BC) + CmdArgs.push_back("-c"); + else { + if (JA.getType() != types::TY_PP_Asm) + D.Diag(diag::err_drv_invalid_gcc_output_type) + << getTypeName(JA.getType()); + + CmdArgs.push_back("-S"); + } +} + +void gcc::Assemble::RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const { + CmdArgs.push_back("-c"); +} + +void gcc::Link::RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const { + // The types are (hopefully) good enough. +} + +// Hexagon tools start. +void hexagon::Assemble::RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const { + +} +void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + std::string MarchString = "-march="; + MarchString += getHexagonTargetCPU(Args); + CmdArgs.push_back(Args.MakeArgString(MarchString)); + + RenderExtraToolArgs(JA, CmdArgs); + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Unexpected output"); + CmdArgs.push_back("-fsyntax-only"); + } + + + // Only pass -x if gcc will understand it; otherwise hope gcc + // understands the suffix correctly. The main use case this would go + // wrong in is for linker inputs if they happened to have an odd + // suffix; really the only way to get this to happen is a command + // like '-x foobar a.c' which will treat a.c like a linker input. + // + // FIXME: For the linker case specifically, can we safely convert + // inputs into '-Wl,' options? + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + + // Don't try to pass LLVM or AST inputs to a generic gcc. + if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR || + II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC) + D.Diag(clang::diag::err_drv_no_linker_llvm_support) + << getToolChain().getTripleString(); + else if (II.getType() == types::TY_AST) + D.Diag(clang::diag::err_drv_no_ast_support) + << getToolChain().getTripleString(); + + if (II.isFilename()) + CmdArgs.push_back(II.getFilename()); + else + // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ? + II.getInputArg().render(Args, CmdArgs); + } + + const char *GCCName = "hexagon-as"; + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath(GCCName)); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); + +} +void hexagon::Link::RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const { + // The types are (hopefully) good enough. +} + +void hexagon::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + for (ArgList::const_iterator + it = Args.begin(), ie = Args.end(); it != ie; ++it) { + Arg *A = *it; + if (A->getOption().hasForwardToGCC()) { + // Don't forward any -g arguments to assembly steps. + if (isa<AssembleJobAction>(JA) && + A->getOption().matches(options::OPT_g_Group)) + continue; + + // It is unfortunate that we have to claim here, as this means + // we will basically never report anything interesting for + // platforms using a generic gcc, even if we are just using gcc + // to get to the assembler. + A->claim(); + A->render(Args, CmdArgs); + } + } + + RenderExtraToolArgs(JA, CmdArgs); + + // Add Arch Information + Arg *A; + if ((A = getLastHexagonArchArg(Args))) { + if (A->getOption().matches(options::OPT_m_Joined)) + A->render(Args, CmdArgs); + else + CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args))); + } + else { + CmdArgs.push_back (Args.MakeArgString("-m" + getHexagonTargetCPU(Args))); + } + + CmdArgs.push_back("-mqdsp6-compat"); + + const char *GCCName; + if (C.getDriver().CCCIsCXX) + GCCName = "hexagon-g++"; + else + GCCName = "hexagon-gcc"; + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath(GCCName)); + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + + // Don't try to pass LLVM or AST inputs to a generic gcc. + if (II.getType() == types::TY_LLVM_IR || II.getType() == types::TY_LTO_IR || + II.getType() == types::TY_LLVM_BC || II.getType() == types::TY_LTO_BC) + D.Diag(clang::diag::err_drv_no_linker_llvm_support) + << getToolChain().getTripleString(); + else if (II.getType() == types::TY_AST) + D.Diag(clang::diag::err_drv_no_ast_support) + << getToolChain().getTripleString(); + + if (II.isFilename()) + CmdArgs.push_back(II.getFilename()); + else + // Don't render as input, we need gcc to do the translations. FIXME: Pranav: What is this ? + II.getInputArg().render(Args, CmdArgs); + } + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); + +} +// Hexagon tools end. + + +const char *darwin::CC1::getCC1Name(types::ID Type) const { + switch (Type) { + default: + llvm_unreachable("Unexpected type for Darwin CC1 tool."); + case types::TY_Asm: + case types::TY_C: case types::TY_CHeader: + case types::TY_PP_C: case types::TY_PP_CHeader: + return "cc1"; + case types::TY_ObjC: case types::TY_ObjCHeader: + case types::TY_PP_ObjC: case types::TY_PP_ObjC_Alias: + case types::TY_PP_ObjCHeader: + return "cc1obj"; + case types::TY_CXX: case types::TY_CXXHeader: + case types::TY_PP_CXX: case types::TY_PP_CXXHeader: + return "cc1plus"; + case types::TY_ObjCXX: case types::TY_ObjCXXHeader: + case types::TY_PP_ObjCXX: case types::TY_PP_ObjCXX_Alias: + case types::TY_PP_ObjCXXHeader: + return "cc1objplus"; + } +} + +void darwin::CC1::anchor() {} + +const char *darwin::CC1::getBaseInputName(const ArgList &Args, + const InputInfoList &Inputs) { + return Args.MakeArgString( + llvm::sys::path::filename(Inputs[0].getBaseInput())); +} + +const char *darwin::CC1::getBaseInputStem(const ArgList &Args, + const InputInfoList &Inputs) { + const char *Str = getBaseInputName(Args, Inputs); + + if (const char *End = strrchr(Str, '.')) + return Args.MakeArgString(std::string(Str, End)); + + return Str; +} + +const char * +darwin::CC1::getDependencyFileName(const ArgList &Args, + const InputInfoList &Inputs) { + // FIXME: Think about this more. + std::string Res; + + if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { + std::string Str(OutputOpt->getValue(Args)); + Res = Str.substr(0, Str.rfind('.')); + } else { + Res = darwin::CC1::getBaseInputStem(Args, Inputs); + } + return Args.MakeArgString(Res + ".d"); +} + +void darwin::CC1::RemoveCC1UnsupportedArgs(ArgStringList &CmdArgs) const { + for (ArgStringList::iterator it = CmdArgs.begin(), ie = CmdArgs.end(); + it != ie;) { + + StringRef Option = *it; + bool RemoveOption = false; + + // Erase both -fmodule-cache-path and its argument. + if (Option.equals("-fmodule-cache-path") && it+2 != ie) { + it = CmdArgs.erase(it, it+2); + ie = CmdArgs.end(); + continue; + } + + // Remove unsupported -f options. + if (Option.startswith("-f")) { + // Remove -f/-fno- to reduce the number of cases. + if (Option.startswith("-fno-")) + Option = Option.substr(5); + else + Option = Option.substr(2); + RemoveOption = llvm::StringSwitch<bool>(Option) + .Case("altivec", true) + .Case("modules", true) + .Case("diagnostics-show-note-include-stack", true) + .Default(false); + } + + // Handle machine specific options. + if (Option.startswith("-m")) { + RemoveOption = llvm::StringSwitch<bool>(Option) + .Case("-mthumb", true) + .Case("-mno-thumb", true) + .Case("-mno-fused-madd", true) + .Case("-mlong-branch", true) + .Case("-mlongcall", true) + .Case("-mcpu=G4", true) + .Case("-mcpu=G5", true) + .Default(false); + } + + // Handle warning options. + if (Option.startswith("-W")) { + // Remove -W/-Wno- to reduce the number of cases. + if (Option.startswith("-Wno-")) + Option = Option.substr(5); + else + Option = Option.substr(2); + + RemoveOption = llvm::StringSwitch<bool>(Option) + .Case("address-of-temporary", true) + .Case("ambiguous-member-template", true) + .Case("analyzer-incompatible-plugin", true) + .Case("array-bounds", true) + .Case("array-bounds-pointer-arithmetic", true) + .Case("bind-to-temporary-copy", true) + .Case("bitwise-op-parentheses", true) + .Case("bool-conversions", true) + .Case("builtin-macro-redefined", true) + .Case("c++-hex-floats", true) + .Case("c++0x-compat", true) + .Case("c++0x-extensions", true) + .Case("c++0x-narrowing", true) + .Case("c++11-compat", true) + .Case("c++11-extensions", true) + .Case("c++11-narrowing", true) + .Case("conditional-uninitialized", true) + .Case("constant-conversion", true) + .Case("conversion-null", true) + .Case("CFString-literal", true) + .Case("constant-logical-operand", true) + .Case("custom-atomic-properties", true) + .Case("default-arg-special-member", true) + .Case("delegating-ctor-cycles", true) + .Case("delete-non-virtual-dtor", true) + .Case("deprecated-implementations", true) + .Case("deprecated-writable-strings", true) + .Case("distributed-object-modifiers", true) + .Case("duplicate-method-arg", true) + .Case("dynamic-class-memaccess", true) + .Case("enum-compare", true) + .Case("exit-time-destructors", true) + .Case("gnu", true) + .Case("gnu-designator", true) + .Case("header-hygiene", true) + .Case("idiomatic-parentheses", true) + .Case("ignored-qualifiers", true) + .Case("implicit-atomic-properties", true) + .Case("incompatible-pointer-types", true) + .Case("incomplete-implementation", true) + .Case("initializer-overrides", true) + .Case("invalid-noreturn", true) + .Case("invalid-token-paste", true) + .Case("language-extension-token", true) + .Case("literal-conversion", true) + .Case("literal-range", true) + .Case("local-type-template-args", true) + .Case("logical-op-parentheses", true) + .Case("method-signatures", true) + .Case("microsoft", true) + .Case("mismatched-tags", true) + .Case("missing-method-return-type", true) + .Case("non-pod-varargs", true) + .Case("nonfragile-abi2", true) + .Case("null-arithmetic", true) + .Case("null-dereference", true) + .Case("out-of-line-declaration", true) + .Case("overriding-method-mismatch", true) + .Case("readonly-setter-attrs", true) + .Case("return-stack-address", true) + .Case("self-assign", true) + .Case("semicolon-before-method-body", true) + .Case("sentinel", true) + .Case("shift-overflow", true) + .Case("shift-sign-overflow", true) + .Case("sign-conversion", true) + .Case("sizeof-array-argument", true) + .Case("sizeof-pointer-memaccess", true) + .Case("string-compare", true) + .Case("super-class-method-mismatch", true) + .Case("tautological-compare", true) + .Case("typedef-redefinition", true) + .Case("typename-missing", true) + .Case("undefined-reinterpret-cast", true) + .Case("unknown-warning-option", true) + .Case("unnamed-type-template-args", true) + .Case("unneeded-internal-declaration", true) + .Case("unneeded-member-function", true) + .Case("unused-comparison", true) + .Case("unused-exception-parameter", true) + .Case("unused-member-function", true) + .Case("unused-result", true) + .Case("vector-conversions", true) + .Case("vla", true) + .Case("used-but-marked-unused", true) + .Case("weak-vtables", true) + .Default(false); + } // if (Option.startswith("-W")) + if (RemoveOption) { + it = CmdArgs.erase(it); + ie = CmdArgs.end(); + } else { + ++it; + } + } +} + +void darwin::CC1::AddCC1Args(const ArgList &Args, + ArgStringList &CmdArgs) const { + const Driver &D = getToolChain().getDriver(); + + CheckCodeGenerationOptions(D, Args); + + // Derived from cc1 spec. + if (!Args.hasArg(options::OPT_mkernel) && !Args.hasArg(options::OPT_static) && + !Args.hasArg(options::OPT_mdynamic_no_pic)) + CmdArgs.push_back("-fPIC"); + + if (getToolChain().getTriple().getArch() == llvm::Triple::arm || + getToolChain().getTriple().getArch() == llvm::Triple::thumb) { + if (!Args.hasArg(options::OPT_fbuiltin_strcat)) + CmdArgs.push_back("-fno-builtin-strcat"); + if (!Args.hasArg(options::OPT_fbuiltin_strcpy)) + CmdArgs.push_back("-fno-builtin-strcpy"); + } + + if (Args.hasArg(options::OPT_g_Flag) && + !Args.hasArg(options::OPT_fno_eliminate_unused_debug_symbols)) + CmdArgs.push_back("-feliminate-unused-debug-symbols"); +} + +void darwin::CC1::AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, + const InputInfoList &Inputs, + const ArgStringList &OutputArgs) const { + const Driver &D = getToolChain().getDriver(); + + // Derived from cc1_options spec. + if (Args.hasArg(options::OPT_fast) || + Args.hasArg(options::OPT_fastf) || + Args.hasArg(options::OPT_fastcp)) + CmdArgs.push_back("-O3"); + + if (Arg *A = Args.getLastArg(options::OPT_pg)) + if (Args.hasArg(options::OPT_fomit_frame_pointer)) + D.Diag(diag::err_drv_argument_not_allowed_with) + << A->getAsString(Args) << "-fomit-frame-pointer"; + + AddCC1Args(Args, CmdArgs); + + if (!Args.hasArg(options::OPT_Q)) + CmdArgs.push_back("-quiet"); + + CmdArgs.push_back("-dumpbase"); + CmdArgs.push_back(darwin::CC1::getBaseInputName(Args, Inputs)); + + Args.AddAllArgs(CmdArgs, options::OPT_d_Group); + + Args.AddAllArgs(CmdArgs, options::OPT_m_Group); + Args.AddAllArgs(CmdArgs, options::OPT_a_Group); + + // FIXME: The goal is to use the user provided -o if that is our + // final output, otherwise to drive from the original input + // name. Find a clean way to go about this. + if ((Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) && + Args.hasArg(options::OPT_o)) { + Arg *OutputOpt = Args.getLastArg(options::OPT_o); + CmdArgs.push_back("-auxbase-strip"); + CmdArgs.push_back(OutputOpt->getValue(Args)); + } else { + CmdArgs.push_back("-auxbase"); + CmdArgs.push_back(darwin::CC1::getBaseInputStem(Args, Inputs)); + } + + Args.AddAllArgs(CmdArgs, options::OPT_g_Group); + + Args.AddAllArgs(CmdArgs, options::OPT_O); + // FIXME: -Wall is getting some special treatment. Investigate. + Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group); + Args.AddLastArg(CmdArgs, options::OPT_w); + Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi, + options::OPT_trigraphs); + if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) { + // Honor -std-default. + Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, + "-std=", /*Joined=*/true); + } + + if (Args.hasArg(options::OPT_v)) + CmdArgs.push_back("-version"); + if (Args.hasArg(options::OPT_pg) && + getToolChain().SupportsProfiling()) + CmdArgs.push_back("-p"); + Args.AddLastArg(CmdArgs, options::OPT_p); + + // The driver treats -fsyntax-only specially. + if (getToolChain().getTriple().getArch() == llvm::Triple::arm || + getToolChain().getTriple().getArch() == llvm::Triple::thumb) { + // Removes -fbuiltin-str{cat,cpy}; these aren't recognized by cc1 but are + // used to inhibit the default -fno-builtin-str{cat,cpy}. + // + // FIXME: Should we grow a better way to deal with "removing" args? + for (arg_iterator it = Args.filtered_begin(options::OPT_f_Group, + options::OPT_fsyntax_only), + ie = Args.filtered_end(); it != ie; ++it) { + if (!(*it)->getOption().matches(options::OPT_fbuiltin_strcat) && + !(*it)->getOption().matches(options::OPT_fbuiltin_strcpy)) { + (*it)->claim(); + (*it)->render(Args, CmdArgs); + } + } + } else + Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only); + + // Claim Clang only -f options, they aren't worth warning about. + Args.ClaimAllArgs(options::OPT_f_clang_Group); + + Args.AddAllArgs(CmdArgs, options::OPT_undef); + if (Args.hasArg(options::OPT_Qn)) + CmdArgs.push_back("-fno-ident"); + + // FIXME: This isn't correct. + //Args.AddLastArg(CmdArgs, options::OPT__help) + //Args.AddLastArg(CmdArgs, options::OPT__targetHelp) + + CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); + + // FIXME: Still don't get what is happening here. Investigate. + Args.AddAllArgs(CmdArgs, options::OPT__param); + + if (Args.hasArg(options::OPT_fmudflap) || + Args.hasArg(options::OPT_fmudflapth)) { + CmdArgs.push_back("-fno-builtin"); + CmdArgs.push_back("-fno-merge-constants"); + } + + if (Args.hasArg(options::OPT_coverage)) { + CmdArgs.push_back("-fprofile-arcs"); + CmdArgs.push_back("-ftest-coverage"); + } + + if (types::isCXX(Inputs[0].getType())) + CmdArgs.push_back("-D__private_extern__=extern"); +} + +void darwin::CC1::AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, + const InputInfoList &Inputs, + const ArgStringList &OutputArgs) const { + // Derived from cpp_options + AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs); + + CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); + + AddCC1Args(Args, CmdArgs); + + // NOTE: The code below has some commonality with cpp_options, but + // in classic gcc style ends up sending things in different + // orders. This may be a good merge candidate once we drop pedantic + // compatibility. + + Args.AddAllArgs(CmdArgs, options::OPT_m_Group); + Args.AddAllArgs(CmdArgs, options::OPT_std_EQ, options::OPT_ansi, + options::OPT_trigraphs); + if (!Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) { + // Honor -std-default. + Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, + "-std=", /*Joined=*/true); + } + Args.AddAllArgs(CmdArgs, options::OPT_W_Group, options::OPT_pedantic_Group); + Args.AddLastArg(CmdArgs, options::OPT_w); + + // The driver treats -fsyntax-only specially. + Args.AddAllArgs(CmdArgs, options::OPT_f_Group, options::OPT_fsyntax_only); + + // Claim Clang only -f options, they aren't worth warning about. + Args.ClaimAllArgs(options::OPT_f_clang_Group); + + if (Args.hasArg(options::OPT_g_Group) && !Args.hasArg(options::OPT_g0) && + !Args.hasArg(options::OPT_fno_working_directory)) + CmdArgs.push_back("-fworking-directory"); + + Args.AddAllArgs(CmdArgs, options::OPT_O); + Args.AddAllArgs(CmdArgs, options::OPT_undef); + if (Args.hasArg(options::OPT_save_temps)) + CmdArgs.push_back("-fpch-preprocess"); +} + +void darwin::CC1::AddCPPUniqueOptionsArgs(const ArgList &Args, + ArgStringList &CmdArgs, + const InputInfoList &Inputs) const { + const Driver &D = getToolChain().getDriver(); + + CheckPreprocessingOptions(D, Args); + + // Derived from cpp_unique_options. + // -{C,CC} only with -E is checked in CheckPreprocessingOptions(). + Args.AddLastArg(CmdArgs, options::OPT_C); + Args.AddLastArg(CmdArgs, options::OPT_CC); + if (!Args.hasArg(options::OPT_Q)) + CmdArgs.push_back("-quiet"); + Args.AddAllArgs(CmdArgs, options::OPT_nostdinc); + Args.AddAllArgs(CmdArgs, options::OPT_nostdincxx); + Args.AddLastArg(CmdArgs, options::OPT_v); + Args.AddAllArgs(CmdArgs, options::OPT_I_Group, options::OPT_F); + Args.AddLastArg(CmdArgs, options::OPT_P); + + // FIXME: Handle %I properly. + if (getToolChain().getArchName() == "x86_64") { + CmdArgs.push_back("-imultilib"); + CmdArgs.push_back("x86_64"); + } + + if (Args.hasArg(options::OPT_MD)) { + CmdArgs.push_back("-MD"); + CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs)); + } + + if (Args.hasArg(options::OPT_MMD)) { + CmdArgs.push_back("-MMD"); + CmdArgs.push_back(darwin::CC1::getDependencyFileName(Args, Inputs)); + } + + Args.AddLastArg(CmdArgs, options::OPT_M); + Args.AddLastArg(CmdArgs, options::OPT_MM); + Args.AddAllArgs(CmdArgs, options::OPT_MF); + Args.AddLastArg(CmdArgs, options::OPT_MG); + Args.AddLastArg(CmdArgs, options::OPT_MP); + Args.AddAllArgs(CmdArgs, options::OPT_MQ); + Args.AddAllArgs(CmdArgs, options::OPT_MT); + if (!Args.hasArg(options::OPT_M) && !Args.hasArg(options::OPT_MM) && + (Args.hasArg(options::OPT_MD) || Args.hasArg(options::OPT_MMD))) { + if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) { + CmdArgs.push_back("-MQ"); + CmdArgs.push_back(OutputOpt->getValue(Args)); + } + } + + Args.AddLastArg(CmdArgs, options::OPT_remap); + if (Args.hasArg(options::OPT_g3)) + CmdArgs.push_back("-dD"); + Args.AddLastArg(CmdArgs, options::OPT_H); + + AddCPPArgs(Args, CmdArgs); + + Args.AddAllArgs(CmdArgs, options::OPT_D, options::OPT_U, options::OPT_A); + Args.AddAllArgs(CmdArgs, options::OPT_i_Group); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + + CmdArgs.push_back(II.getFilename()); + } + + Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA, + options::OPT_Xpreprocessor); + + if (Args.hasArg(options::OPT_fmudflap)) { + CmdArgs.push_back("-D_MUDFLAP"); + CmdArgs.push_back("-include"); + CmdArgs.push_back("mf-runtime.h"); + } + + if (Args.hasArg(options::OPT_fmudflapth)) { + CmdArgs.push_back("-D_MUDFLAP"); + CmdArgs.push_back("-D_MUDFLAPTH"); + CmdArgs.push_back("-include"); + CmdArgs.push_back("mf-runtime.h"); + } +} + +void darwin::CC1::AddCPPArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + // Derived from cpp spec. + + if (Args.hasArg(options::OPT_static)) { + // The gcc spec is broken here, it refers to dynamic but + // that has been translated. Start by being bug compatible. + + // if (!Args.hasArg(arglist.parser.dynamicOption)) + CmdArgs.push_back("-D__STATIC__"); + } else + CmdArgs.push_back("-D__DYNAMIC__"); + + if (Args.hasArg(options::OPT_pthread)) + CmdArgs.push_back("-D_REENTRANT"); +} + +void darwin::Preprocess::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + assert(Inputs.size() == 1 && "Unexpected number of inputs!"); + + CmdArgs.push_back("-E"); + + if (Args.hasArg(options::OPT_traditional) || + Args.hasArg(options::OPT_traditional_cpp)) + CmdArgs.push_back("-traditional-cpp"); + + ArgStringList OutputArgs; + assert(Output.isFilename() && "Unexpected CC1 output."); + OutputArgs.push_back("-o"); + OutputArgs.push_back(Output.getFilename()); + + if (Args.hasArg(options::OPT_E) || getToolChain().getDriver().CCCIsCPP) { + AddCPPOptionsArgs(Args, CmdArgs, Inputs, OutputArgs); + } else { + AddCPPOptionsArgs(Args, CmdArgs, Inputs, ArgStringList()); + CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); + } + + Args.AddAllArgs(CmdArgs, options::OPT_d_Group); + + RemoveCC1UnsupportedArgs(CmdArgs); + + const char *CC1Name = getCC1Name(Inputs[0].getType()); + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath(CC1Name)); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void darwin::Compile::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + assert(Inputs.size() == 1 && "Unexpected number of inputs!"); + + // Silence warning about unused --serialize-diagnostics + Args.ClaimAllArgs(options::OPT__serialize_diags); + + types::ID InputType = Inputs[0].getType(); + if (const Arg *A = Args.getLastArg(options::OPT_traditional)) + D.Diag(diag::err_drv_argument_only_allowed_with) + << A->getAsString(Args) << "-E"; + + if (JA.getType() == types::TY_LLVM_IR || + JA.getType() == types::TY_LTO_IR) + CmdArgs.push_back("-emit-llvm"); + else if (JA.getType() == types::TY_LLVM_BC || + JA.getType() == types::TY_LTO_BC) + CmdArgs.push_back("-emit-llvm-bc"); + else if (Output.getType() == types::TY_AST) + D.Diag(diag::err_drv_no_ast_support) + << getToolChain().getTripleString(); + else if (JA.getType() != types::TY_PP_Asm && + JA.getType() != types::TY_PCH) + D.Diag(diag::err_drv_invalid_gcc_output_type) + << getTypeName(JA.getType()); + + ArgStringList OutputArgs; + if (Output.getType() != types::TY_PCH) { + OutputArgs.push_back("-o"); + if (Output.isNothing()) + OutputArgs.push_back("/dev/null"); + else + OutputArgs.push_back(Output.getFilename()); + } + + // There is no need for this level of compatibility, but it makes + // diffing easier. + bool OutputArgsEarly = (Args.hasArg(options::OPT_fsyntax_only) || + Args.hasArg(options::OPT_S)); + + if (types::getPreprocessedType(InputType) != types::TY_INVALID) { + AddCPPUniqueOptionsArgs(Args, CmdArgs, Inputs); + if (OutputArgsEarly) { + AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs); + } else { + AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList()); + CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); + } + } else { + CmdArgs.push_back("-fpreprocessed"); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + + // Reject AST inputs. + if (II.getType() == types::TY_AST) { + D.Diag(diag::err_drv_no_ast_support) + << getToolChain().getTripleString(); + return; + } + + CmdArgs.push_back(II.getFilename()); + } + + if (OutputArgsEarly) { + AddCC1OptionsArgs(Args, CmdArgs, Inputs, OutputArgs); + } else { + AddCC1OptionsArgs(Args, CmdArgs, Inputs, ArgStringList()); + CmdArgs.append(OutputArgs.begin(), OutputArgs.end()); + } + } + + if (Output.getType() == types::TY_PCH) { + assert(Output.isFilename() && "Invalid PCH output."); + + CmdArgs.push_back("-o"); + // NOTE: gcc uses a temp .s file for this, but there doesn't seem + // to be a good reason. + const char *TmpPath = C.getArgs().MakeArgString( + D.GetTemporaryPath("cc", "s")); + C.addTempFile(TmpPath); + CmdArgs.push_back(TmpPath); + + // If we're emitting a pch file with the last 4 characters of ".pth" + // and falling back to llvm-gcc we want to use ".gch" instead. + std::string OutputFile(Output.getFilename()); + size_t loc = OutputFile.rfind(".pth"); + if (loc != std::string::npos) + OutputFile.replace(loc, 4, ".gch"); + const char *Tmp = C.getArgs().MakeArgString("--output-pch="+OutputFile); + CmdArgs.push_back(Tmp); + } + + RemoveCC1UnsupportedArgs(CmdArgs); + + const char *CC1Name = getCC1Name(Inputs[0].getType()); + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath(CC1Name)); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void darwin::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + assert(Inputs.size() == 1 && "Unexpected number of inputs."); + const InputInfo &Input = Inputs[0]; + + // Determine the original source input. + const Action *SourceAction = &JA; + while (SourceAction->getKind() != Action::InputClass) { + assert(!SourceAction->getInputs().empty() && "unexpected root action!"); + SourceAction = SourceAction->getInputs()[0]; + } + + // Forward -g, assuming we are dealing with an actual assembly file. + if (SourceAction->getType() == types::TY_Asm || + SourceAction->getType() == types::TY_PP_Asm) { + if (Args.hasArg(options::OPT_gstabs)) + CmdArgs.push_back("--gstabs"); + else if (Args.hasArg(options::OPT_g_Group)) + CmdArgs.push_back("-g"); + } + + // Derived from asm spec. + AddDarwinArch(Args, CmdArgs); + + // Use -force_cpusubtype_ALL on x86 by default. + if (getToolChain().getTriple().getArch() == llvm::Triple::x86 || + getToolChain().getTriple().getArch() == llvm::Triple::x86_64 || + Args.hasArg(options::OPT_force__cpusubtype__ALL)) + CmdArgs.push_back("-force_cpusubtype_ALL"); + + if (getToolChain().getTriple().getArch() != llvm::Triple::x86_64 && + (Args.hasArg(options::OPT_mkernel) || + Args.hasArg(options::OPT_static) || + Args.hasArg(options::OPT_fapple_kext))) + CmdArgs.push_back("-static"); + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + assert(Output.isFilename() && "Unexpected lipo output."); + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + assert(Input.isFilename() && "Invalid input."); + CmdArgs.push_back(Input.getFilename()); + + // asm_final spec is empty. + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("as")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void darwin::DarwinTool::anchor() {} + +void darwin::DarwinTool::AddDarwinArch(const ArgList &Args, + ArgStringList &CmdArgs) const { + StringRef ArchName = getDarwinToolChain().getDarwinArchName(Args); + + // Derived from darwin_arch spec. + CmdArgs.push_back("-arch"); + CmdArgs.push_back(Args.MakeArgString(ArchName)); + + // FIXME: Is this needed anymore? + if (ArchName == "arm") + CmdArgs.push_back("-force_cpusubtype_ALL"); +} + +void darwin::Link::AddLinkArgs(Compilation &C, + const ArgList &Args, + ArgStringList &CmdArgs) const { + const Driver &D = getToolChain().getDriver(); + const toolchains::Darwin &DarwinTC = getDarwinToolChain(); + + unsigned Version[3] = { 0, 0, 0 }; + if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) { + bool HadExtra; + if (!Driver::GetReleaseVersion(A->getValue(Args), Version[0], + Version[1], Version[2], HadExtra) || + HadExtra) + D.Diag(diag::err_drv_invalid_version_number) + << A->getAsString(Args); + } + + // Newer linkers support -demangle, pass it if supported and not disabled by + // the user. + if (Version[0] >= 100 && !Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) { + // Don't pass -demangle to ld_classic. + // + // FIXME: This is a temporary workaround, ld should be handling this. + bool UsesLdClassic = (getToolChain().getArch() == llvm::Triple::x86 && + Args.hasArg(options::OPT_static)); + if (getToolChain().getArch() == llvm::Triple::x86) { + for (arg_iterator it = Args.filtered_begin(options::OPT_Xlinker, + options::OPT_Wl_COMMA), + ie = Args.filtered_end(); it != ie; ++it) { + const Arg *A = *it; + for (unsigned i = 0, e = A->getNumValues(); i != e; ++i) + if (StringRef(A->getValue(Args, i)) == "-kext") + UsesLdClassic = true; + } + } + if (!UsesLdClassic) + CmdArgs.push_back("-demangle"); + } + + // If we are using LTO, then automatically create a temporary file path for + // the linker to use, so that it's lifetime will extend past a possible + // dsymutil step. + if (Version[0] >= 116 && D.IsUsingLTO(Args)) { + const char *TmpPath = C.getArgs().MakeArgString( + D.GetTemporaryPath("cc", types::getTypeTempSuffix(types::TY_Object))); + C.addTempFile(TmpPath); + CmdArgs.push_back("-object_path_lto"); + CmdArgs.push_back(TmpPath); + } + + // Derived from the "link" spec. + Args.AddAllArgs(CmdArgs, options::OPT_static); + if (!Args.hasArg(options::OPT_static)) + CmdArgs.push_back("-dynamic"); + if (Args.hasArg(options::OPT_fgnu_runtime)) { + // FIXME: gcc replaces -lobjc in forward args with -lobjc-gnu + // here. How do we wish to handle such things? + } + + if (!Args.hasArg(options::OPT_dynamiclib)) { + AddDarwinArch(Args, CmdArgs); + // FIXME: Why do this only on this path? + Args.AddLastArg(CmdArgs, options::OPT_force__cpusubtype__ALL); + + Args.AddLastArg(CmdArgs, options::OPT_bundle); + Args.AddAllArgs(CmdArgs, options::OPT_bundle__loader); + Args.AddAllArgs(CmdArgs, options::OPT_client__name); + + Arg *A; + if ((A = Args.getLastArg(options::OPT_compatibility__version)) || + (A = Args.getLastArg(options::OPT_current__version)) || + (A = Args.getLastArg(options::OPT_install__name))) + D.Diag(diag::err_drv_argument_only_allowed_with) + << A->getAsString(Args) << "-dynamiclib"; + + Args.AddLastArg(CmdArgs, options::OPT_force__flat__namespace); + Args.AddLastArg(CmdArgs, options::OPT_keep__private__externs); + Args.AddLastArg(CmdArgs, options::OPT_private__bundle); + } else { + CmdArgs.push_back("-dylib"); + + Arg *A; + if ((A = Args.getLastArg(options::OPT_bundle)) || + (A = Args.getLastArg(options::OPT_bundle__loader)) || + (A = Args.getLastArg(options::OPT_client__name)) || + (A = Args.getLastArg(options::OPT_force__flat__namespace)) || + (A = Args.getLastArg(options::OPT_keep__private__externs)) || + (A = Args.getLastArg(options::OPT_private__bundle))) + D.Diag(diag::err_drv_argument_not_allowed_with) + << A->getAsString(Args) << "-dynamiclib"; + + Args.AddAllArgsTranslated(CmdArgs, options::OPT_compatibility__version, + "-dylib_compatibility_version"); + Args.AddAllArgsTranslated(CmdArgs, options::OPT_current__version, + "-dylib_current_version"); + + AddDarwinArch(Args, CmdArgs); + + Args.AddAllArgsTranslated(CmdArgs, options::OPT_install__name, + "-dylib_install_name"); + } + + Args.AddLastArg(CmdArgs, options::OPT_all__load); + Args.AddAllArgs(CmdArgs, options::OPT_allowable__client); + Args.AddLastArg(CmdArgs, options::OPT_bind__at__load); + if (DarwinTC.isTargetIPhoneOS()) + Args.AddLastArg(CmdArgs, options::OPT_arch__errors__fatal); + Args.AddLastArg(CmdArgs, options::OPT_dead__strip); + Args.AddLastArg(CmdArgs, options::OPT_no__dead__strip__inits__and__terms); + Args.AddAllArgs(CmdArgs, options::OPT_dylib__file); + Args.AddLastArg(CmdArgs, options::OPT_dynamic); + Args.AddAllArgs(CmdArgs, options::OPT_exported__symbols__list); + Args.AddLastArg(CmdArgs, options::OPT_flat__namespace); + Args.AddAllArgs(CmdArgs, options::OPT_force__load); + Args.AddAllArgs(CmdArgs, options::OPT_headerpad__max__install__names); + Args.AddAllArgs(CmdArgs, options::OPT_image__base); + Args.AddAllArgs(CmdArgs, options::OPT_init); + + // Add the deployment target. + VersionTuple TargetVersion = DarwinTC.getTargetVersion(); + + // If we had an explicit -mios-simulator-version-min argument, honor that, + // otherwise use the traditional deployment targets. We can't just check the + // is-sim attribute because existing code follows this path, and the linker + // may not handle the argument. + // + // FIXME: We may be able to remove this, once we can verify no one depends on + // it. + if (Args.hasArg(options::OPT_mios_simulator_version_min_EQ)) + CmdArgs.push_back("-ios_simulator_version_min"); + else if (DarwinTC.isTargetIPhoneOS()) + CmdArgs.push_back("-iphoneos_version_min"); + else + CmdArgs.push_back("-macosx_version_min"); + CmdArgs.push_back(Args.MakeArgString(TargetVersion.getAsString())); + + Args.AddLastArg(CmdArgs, options::OPT_nomultidefs); + Args.AddLastArg(CmdArgs, options::OPT_multi__module); + Args.AddLastArg(CmdArgs, options::OPT_single__module); + Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined); + Args.AddAllArgs(CmdArgs, options::OPT_multiply__defined__unused); + + if (const Arg *A = Args.getLastArg(options::OPT_fpie, options::OPT_fPIE, + options::OPT_fno_pie, + options::OPT_fno_PIE)) { + if (A->getOption().matches(options::OPT_fpie) || + A->getOption().matches(options::OPT_fPIE)) + CmdArgs.push_back("-pie"); + else + CmdArgs.push_back("-no_pie"); + } + + Args.AddLastArg(CmdArgs, options::OPT_prebind); + Args.AddLastArg(CmdArgs, options::OPT_noprebind); + Args.AddLastArg(CmdArgs, options::OPT_nofixprebinding); + Args.AddLastArg(CmdArgs, options::OPT_prebind__all__twolevel__modules); + Args.AddLastArg(CmdArgs, options::OPT_read__only__relocs); + Args.AddAllArgs(CmdArgs, options::OPT_sectcreate); + Args.AddAllArgs(CmdArgs, options::OPT_sectorder); + Args.AddAllArgs(CmdArgs, options::OPT_seg1addr); + Args.AddAllArgs(CmdArgs, options::OPT_segprot); + Args.AddAllArgs(CmdArgs, options::OPT_segaddr); + Args.AddAllArgs(CmdArgs, options::OPT_segs__read__only__addr); + Args.AddAllArgs(CmdArgs, options::OPT_segs__read__write__addr); + Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table); + Args.AddAllArgs(CmdArgs, options::OPT_seg__addr__table__filename); + Args.AddAllArgs(CmdArgs, options::OPT_sub__library); + Args.AddAllArgs(CmdArgs, options::OPT_sub__umbrella); + + // Give --sysroot= preference, over the Apple specific behavior to also use + // --isysroot as the syslibroot. + StringRef sysroot = C.getSysRoot(); + if (sysroot != "") { + CmdArgs.push_back("-syslibroot"); + CmdArgs.push_back(C.getArgs().MakeArgString(sysroot)); + } else if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { + CmdArgs.push_back("-syslibroot"); + CmdArgs.push_back(A->getValue(Args)); + } else if (getDarwinToolChain().isTargetIPhoneOS()) { + CmdArgs.push_back("-syslibroot"); + CmdArgs.push_back("/Developer/SDKs/Extra"); + } + + Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace); + Args.AddLastArg(CmdArgs, options::OPT_twolevel__namespace__hints); + Args.AddAllArgs(CmdArgs, options::OPT_umbrella); + Args.AddAllArgs(CmdArgs, options::OPT_undefined); + Args.AddAllArgs(CmdArgs, options::OPT_unexported__symbols__list); + Args.AddAllArgs(CmdArgs, options::OPT_weak__reference__mismatches); + Args.AddLastArg(CmdArgs, options::OPT_X_Flag); + Args.AddAllArgs(CmdArgs, options::OPT_y); + Args.AddLastArg(CmdArgs, options::OPT_w); + Args.AddAllArgs(CmdArgs, options::OPT_pagezero__size); + Args.AddAllArgs(CmdArgs, options::OPT_segs__read__); + Args.AddLastArg(CmdArgs, options::OPT_seglinkedit); + Args.AddLastArg(CmdArgs, options::OPT_noseglinkedit); + Args.AddAllArgs(CmdArgs, options::OPT_sectalign); + Args.AddAllArgs(CmdArgs, options::OPT_sectobjectsymbols); + Args.AddAllArgs(CmdArgs, options::OPT_segcreate); + Args.AddLastArg(CmdArgs, options::OPT_whyload); + Args.AddLastArg(CmdArgs, options::OPT_whatsloaded); + Args.AddAllArgs(CmdArgs, options::OPT_dylinker__install__name); + Args.AddLastArg(CmdArgs, options::OPT_dylinker); + Args.AddLastArg(CmdArgs, options::OPT_Mach); +} + +void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + assert(Output.getType() == types::TY_Image && "Invalid linker output type."); + + // The logic here is derived from gcc's behavior; most of which + // comes from specs (starting with link_command). Consult gcc for + // more information. + ArgStringList CmdArgs; + + /// Hack(tm) to ignore linking errors when we are doing ARC migration. + if (Args.hasArg(options::OPT_ccc_arcmt_check, + options::OPT_ccc_arcmt_migrate)) { + for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I) + (*I)->claim(); + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("touch")); + CmdArgs.push_back(Output.getFilename()); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); + return; + } + + // I'm not sure why this particular decomposition exists in gcc, but + // we follow suite for ease of comparison. + AddLinkArgs(C, Args, CmdArgs); + + Args.AddAllArgs(CmdArgs, options::OPT_d_Flag); + Args.AddAllArgs(CmdArgs, options::OPT_s); + Args.AddAllArgs(CmdArgs, options::OPT_t); + Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag); + Args.AddAllArgs(CmdArgs, options::OPT_u_Group); + Args.AddAllArgs(CmdArgs, options::OPT_A); + Args.AddLastArg(CmdArgs, options::OPT_e); + Args.AddAllArgs(CmdArgs, options::OPT_m_Separate); + Args.AddAllArgs(CmdArgs, options::OPT_r); + + // Forward -ObjC when either -ObjC or -ObjC++ is used, to force loading + // members of static archive libraries which implement Objective-C classes or + // categories. + if (Args.hasArg(options::OPT_ObjC) || Args.hasArg(options::OPT_ObjCXX)) + CmdArgs.push_back("-ObjC"); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + if (!Args.hasArg(options::OPT_A) && + !Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + // Derived from startfile spec. + if (Args.hasArg(options::OPT_dynamiclib)) { + // Derived from darwin_dylib1 spec. + if (getDarwinToolChain().isTargetIOSSimulator()) { + // The simulator doesn't have a versioned crt1 file. + CmdArgs.push_back("-ldylib1.o"); + } else if (getDarwinToolChain().isTargetIPhoneOS()) { + if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1)) + CmdArgs.push_back("-ldylib1.o"); + } else { + if (getDarwinToolChain().isMacosxVersionLT(10, 5)) + CmdArgs.push_back("-ldylib1.o"); + else if (getDarwinToolChain().isMacosxVersionLT(10, 6)) + CmdArgs.push_back("-ldylib1.10.5.o"); + } + } else { + if (Args.hasArg(options::OPT_bundle)) { + if (!Args.hasArg(options::OPT_static)) { + // Derived from darwin_bundle1 spec. + if (getDarwinToolChain().isTargetIOSSimulator()) { + // The simulator doesn't have a versioned crt1 file. + CmdArgs.push_back("-lbundle1.o"); + } else if (getDarwinToolChain().isTargetIPhoneOS()) { + if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1)) + CmdArgs.push_back("-lbundle1.o"); + } else { + if (getDarwinToolChain().isMacosxVersionLT(10, 6)) + CmdArgs.push_back("-lbundle1.o"); + } + } + } else { + if (Args.hasArg(options::OPT_pg) && + getToolChain().SupportsProfiling()) { + if (Args.hasArg(options::OPT_static) || + Args.hasArg(options::OPT_object) || + Args.hasArg(options::OPT_preload)) { + CmdArgs.push_back("-lgcrt0.o"); + } else { + CmdArgs.push_back("-lgcrt1.o"); + + // darwin_crt2 spec is empty. + } + } else { + if (Args.hasArg(options::OPT_static) || + Args.hasArg(options::OPT_object) || + Args.hasArg(options::OPT_preload)) { + CmdArgs.push_back("-lcrt0.o"); + } else { + // Derived from darwin_crt1 spec. + if (getDarwinToolChain().isTargetIOSSimulator()) { + // The simulator doesn't have a versioned crt1 file. + CmdArgs.push_back("-lcrt1.o"); + } else if (getDarwinToolChain().isTargetIPhoneOS()) { + if (getDarwinToolChain().isIPhoneOSVersionLT(3, 1)) + CmdArgs.push_back("-lcrt1.o"); + else + CmdArgs.push_back("-lcrt1.3.1.o"); + } else { + if (getDarwinToolChain().isMacosxVersionLT(10, 5)) + CmdArgs.push_back("-lcrt1.o"); + else if (getDarwinToolChain().isMacosxVersionLT(10, 6)) + CmdArgs.push_back("-lcrt1.10.5.o"); + else if (getDarwinToolChain().isMacosxVersionLT(10, 8)) + CmdArgs.push_back("-lcrt1.10.6.o"); + + // darwin_crt2 spec is empty. + } + } + } + } + } + + if (!getDarwinToolChain().isTargetIPhoneOS() && + Args.hasArg(options::OPT_shared_libgcc) && + getDarwinToolChain().isMacosxVersionLT(10, 5)) { + const char *Str = + Args.MakeArgString(getToolChain().GetFilePath("crt3.o")); + CmdArgs.push_back(Str); + } + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + + // If we're building a dynamic lib with -faddress-sanitizer, unresolved + // symbols may appear. Mark all of them as dynamic_lookup. + // Linking executables is handled in lib/Driver/ToolChains.cpp. + if (Args.hasFlag(options::OPT_faddress_sanitizer, + options::OPT_fno_address_sanitizer, false)) { + if (Args.hasArg(options::OPT_dynamiclib) || + Args.hasArg(options::OPT_bundle)) { + CmdArgs.push_back("-undefined"); + CmdArgs.push_back("dynamic_lookup"); + } + } + + if (Args.hasArg(options::OPT_fopenmp)) + // This is more complicated in gcc... + CmdArgs.push_back("-lgomp"); + + getDarwinToolChain().AddLinkSearchPathArgs(Args, CmdArgs); + + if (isObjCRuntimeLinked(Args)) { + // Avoid linking compatibility stubs on i386 mac. + if (!getDarwinToolChain().isTargetMacOS() || + getDarwinToolChain().getArchName() != "i386") { + // If we don't have ARC or subscripting runtime support, link in the + // runtime stubs. We have to do this *before* adding any of the normal + // linker inputs so that its initializer gets run first. + ObjCRuntime runtime; + getDarwinToolChain().configureObjCRuntime(runtime); + // We use arclite library for both ARC and subscripting support. + if ((!runtime.HasARC && isObjCAutoRefCount(Args)) || + !runtime.HasSubscripting) + getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs); + CmdArgs.push_back("-framework"); + CmdArgs.push_back("Foundation"); + } + // Link libobj. + CmdArgs.push_back("-lobjc"); + } + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (LinkingOutput) { + CmdArgs.push_back("-arch_multiple"); + CmdArgs.push_back("-final_output"); + CmdArgs.push_back(LinkingOutput); + } + + if (Args.hasArg(options::OPT_fnested_functions)) + CmdArgs.push_back("-allow_stack_execute"); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (getToolChain().getDriver().CCCIsCXX) + getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); + + // link_ssp spec is empty. + + // Let the tool chain choose which runtime library to link. + getDarwinToolChain().AddLinkRuntimeLibArgs(Args, CmdArgs); + } + + if (!Args.hasArg(options::OPT_A) && + !Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + // endfile_spec is empty. + } + + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_F); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void darwin::Lipo::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + CmdArgs.push_back("-create"); + assert(Output.isFilename() && "Unexpected lipo output."); + + CmdArgs.push_back("-output"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + assert(II.isFilename() && "Unexpected lipo input."); + CmdArgs.push_back(II.getFilename()); + } + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("lipo")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void darwin::Dsymutil::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + assert(Inputs.size() == 1 && "Unable to handle multiple inputs."); + const InputInfo &Input = Inputs[0]; + assert(Input.isFilename() && "Unexpected dsymutil input."); + CmdArgs.push_back(Input.getFilename()); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("dsymutil")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void darwin::VerifyDebug::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + CmdArgs.push_back("--verify"); + CmdArgs.push_back("--debug-info"); + CmdArgs.push_back("--eh-frame"); + CmdArgs.push_back("--quiet"); + + assert(Inputs.size() == 1 && "Unable to handle multiple inputs."); + const InputInfo &Input = Inputs[0]; + assert(Input.isFilename() && "Unexpected verify input"); + + // Grabbing the output of the earlier dsymutil run. + CmdArgs.push_back(Input.getFilename()); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("dwarfdump")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void solaris::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("as")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + + +void solaris::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + // FIXME: Find a real GCC, don't hard-code versions here + std::string GCCLibPath = "/usr/gcc/4.5/lib/gcc/"; + const llvm::Triple &T = getToolChain().getTriple(); + std::string LibPath = "/usr/lib/"; + llvm::Triple::ArchType Arch = T.getArch(); + switch (Arch) { + case llvm::Triple::x86: + GCCLibPath += ("i386-" + T.getVendorName() + "-" + + T.getOSName()).str() + "/4.5.2/"; + break; + case llvm::Triple::x86_64: + GCCLibPath += ("i386-" + T.getVendorName() + "-" + + T.getOSName()).str(); + GCCLibPath += "/4.5.2/amd64/"; + LibPath += "amd64/"; + break; + default: + assert(0 && "Unsupported architecture"); + } + + ArgStringList CmdArgs; + + // Demangle C++ names in errors + CmdArgs.push_back("-C"); + + if ((!Args.hasArg(options::OPT_nostdlib)) && + (!Args.hasArg(options::OPT_shared))) { + CmdArgs.push_back("-e"); + CmdArgs.push_back("_start"); + } + + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-Bstatic"); + CmdArgs.push_back("-dn"); + } else { + CmdArgs.push_back("-Bdynamic"); + if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-shared"); + } else { + CmdArgs.push_back("--dynamic-linker"); + CmdArgs.push_back(Args.MakeArgString(LibPath + "ld.so.1")); + } + } + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back(Args.MakeArgString(LibPath + "crt1.o")); + CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o")); + CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o")); + CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o")); + } else { + CmdArgs.push_back(Args.MakeArgString(LibPath + "crti.o")); + CmdArgs.push_back(Args.MakeArgString(LibPath + "values-Xa.o")); + CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtbegin.o")); + } + if (getToolChain().getDriver().CCCIsCXX) + CmdArgs.push_back(Args.MakeArgString(LibPath + "cxa_finalize.o")); + } + + CmdArgs.push_back(Args.MakeArgString("-L" + GCCLibPath)); + + Args.AddAllArgs(CmdArgs, options::OPT_L); + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_e); + Args.AddAllArgs(CmdArgs, options::OPT_r); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (getToolChain().getDriver().CCCIsCXX) + getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("-lgcc_s"); + if (!Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-lgcc"); + CmdArgs.push_back("-lc"); + CmdArgs.push_back("-lm"); + } + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + CmdArgs.push_back(Args.MakeArgString(GCCLibPath + "crtend.o")); + } + CmdArgs.push_back(Args.MakeArgString(LibPath + "crtn.o")); + + addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple()); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void auroraux::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("gas")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void auroraux::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + if ((!Args.hasArg(options::OPT_nostdlib)) && + (!Args.hasArg(options::OPT_shared))) { + CmdArgs.push_back("-e"); + CmdArgs.push_back("_start"); + } + + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-Bstatic"); + CmdArgs.push_back("-dn"); + } else { +// CmdArgs.push_back("--eh-frame-hdr"); + CmdArgs.push_back("-Bdynamic"); + if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-shared"); + } else { + CmdArgs.push_back("--dynamic-linker"); + CmdArgs.push_back("/lib/ld.so.1"); // 64Bit Path /lib/amd64/ld.so.1 + } + } + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crt1.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtbegin.o"))); + } else { + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crti.o"))); + } + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtn.o"))); + } + + CmdArgs.push_back(Args.MakeArgString("-L/opt/gcc4/lib/gcc/" + + getToolChain().getTripleString() + + "/4.2.4")); + + Args.AddAllArgs(CmdArgs, options::OPT_L); + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_e); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + // FIXME: For some reason GCC passes -lgcc before adding + // the default system libraries. Just mimic this for now. + CmdArgs.push_back("-lgcc"); + + if (Args.hasArg(options::OPT_pthread)) + CmdArgs.push_back("-pthread"); + if (!Args.hasArg(options::OPT_shared)) + CmdArgs.push_back("-lc"); + CmdArgs.push_back("-lgcc"); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtend.o"))); + } + + addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple()); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void openbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("as")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void openbsd::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + if ((!Args.hasArg(options::OPT_nostdlib)) && + (!Args.hasArg(options::OPT_shared))) { + CmdArgs.push_back("-e"); + CmdArgs.push_back("__start"); + } + + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-Bstatic"); + } else { + if (Args.hasArg(options::OPT_rdynamic)) + CmdArgs.push_back("-export-dynamic"); + CmdArgs.push_back("--eh-frame-hdr"); + CmdArgs.push_back("-Bdynamic"); + if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-shared"); + } else { + CmdArgs.push_back("-dynamic-linker"); + CmdArgs.push_back("/usr/libexec/ld.so"); + } + } + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) { + if (Args.hasArg(options::OPT_pg)) + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("gcrt0.o"))); + else + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crt0.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtbegin.o"))); + } else { + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtbeginS.o"))); + } + } + + std::string Triple = getToolChain().getTripleString(); + if (Triple.substr(0, 6) == "x86_64") + Triple.replace(0, 6, "amd64"); + CmdArgs.push_back(Args.MakeArgString("-L/usr/lib/gcc-lib/" + Triple + + "/4.2.1")); + + Args.AddAllArgs(CmdArgs, options::OPT_L); + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_e); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (D.CCCIsCXX) { + getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); + if (Args.hasArg(options::OPT_pg)) + CmdArgs.push_back("-lm_p"); + else + CmdArgs.push_back("-lm"); + } + + // FIXME: For some reason GCC passes -lgcc before adding + // the default system libraries. Just mimic this for now. + CmdArgs.push_back("-lgcc"); + + if (Args.hasArg(options::OPT_pthread)) + CmdArgs.push_back("-lpthread"); + if (!Args.hasArg(options::OPT_shared)) { + if (Args.hasArg(options::OPT_pg)) + CmdArgs.push_back("-lc_p"); + else + CmdArgs.push_back("-lc"); + } + CmdArgs.push_back("-lgcc"); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtend.o"))); + else + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtendS.o"))); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void freebsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + // When building 32-bit code on FreeBSD/amd64, we have to explicitly + // instruct as in the base system to assemble 32-bit code. + if (getToolChain().getArchName() == "i386") + CmdArgs.push_back("--32"); + + if (getToolChain().getArchName() == "powerpc") + CmdArgs.push_back("-a32"); + + // Set byte order explicitly + if (getToolChain().getArchName() == "mips") + CmdArgs.push_back("-EB"); + else if (getToolChain().getArchName() == "mipsel") + CmdArgs.push_back("-EL"); + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("as")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void freebsd::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + if (!D.SysRoot.empty()) + CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); + + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-Bstatic"); + } else { + if (Args.hasArg(options::OPT_rdynamic)) + CmdArgs.push_back("-export-dynamic"); + CmdArgs.push_back("--eh-frame-hdr"); + if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-Bshareable"); + } else { + CmdArgs.push_back("-dynamic-linker"); + CmdArgs.push_back("/libexec/ld-elf.so.1"); + } + } + + // When building 32-bit code on FreeBSD/amd64, we have to explicitly + // instruct ld in the base system to link 32-bit code. + if (getToolChain().getArchName() == "i386") { + CmdArgs.push_back("-m"); + CmdArgs.push_back("elf_i386_fbsd"); + } + + if (getToolChain().getArchName() == "powerpc") { + CmdArgs.push_back("-m"); + CmdArgs.push_back("elf32ppc_fbsd"); + } + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) { + if (Args.hasArg(options::OPT_pg)) + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("gcrt1.o"))); + else { + const char *crt = Args.hasArg(options::OPT_pie) ? "Scrt1.o" : "crt1.o"; + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath(crt))); + } + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtbegin.o"))); + } else { + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtbeginS.o"))); + } + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + const ToolChain::path_list Paths = getToolChain().getFilePaths(); + for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end(); + i != e; ++i) + CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i)); + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_e); + Args.AddAllArgs(CmdArgs, options::OPT_s); + Args.AddAllArgs(CmdArgs, options::OPT_t); + Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag); + Args.AddAllArgs(CmdArgs, options::OPT_r); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (D.CCCIsCXX) { + getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); + if (Args.hasArg(options::OPT_pg)) + CmdArgs.push_back("-lm_p"); + else + CmdArgs.push_back("-lm"); + } + // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding + // the default system libraries. Just mimic this for now. + if (Args.hasArg(options::OPT_pg)) + CmdArgs.push_back("-lgcc_p"); + else + CmdArgs.push_back("-lgcc"); + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-lgcc_eh"); + } else if (Args.hasArg(options::OPT_pg)) { + CmdArgs.push_back("-lgcc_eh_p"); + } else { + CmdArgs.push_back("--as-needed"); + CmdArgs.push_back("-lgcc_s"); + CmdArgs.push_back("--no-as-needed"); + } + + if (Args.hasArg(options::OPT_pthread)) { + if (Args.hasArg(options::OPT_pg)) + CmdArgs.push_back("-lpthread_p"); + else + CmdArgs.push_back("-lpthread"); + } + + if (Args.hasArg(options::OPT_pg)) { + if (Args.hasArg(options::OPT_shared)) + CmdArgs.push_back("-lc"); + else + CmdArgs.push_back("-lc_p"); + CmdArgs.push_back("-lgcc_p"); + } else { + CmdArgs.push_back("-lc"); + CmdArgs.push_back("-lgcc"); + } + + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-lgcc_eh"); + } else if (Args.hasArg(options::OPT_pg)) { + CmdArgs.push_back("-lgcc_eh_p"); + } else { + CmdArgs.push_back("--as-needed"); + CmdArgs.push_back("-lgcc_s"); + CmdArgs.push_back("--no-as-needed"); + } + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath( + "crtend.o"))); + else + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath( + "crtendS.o"))); + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath( + "crtn.o"))); + } + + addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple()); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void netbsd::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + // When building 32-bit code on NetBSD/amd64, we have to explicitly + // instruct as in the base system to assemble 32-bit code. + if (getToolChain().getArch() == llvm::Triple::x86) + CmdArgs.push_back("--32"); + + // Set byte order explicitly + if (getToolChain().getArchName() == "mips") + CmdArgs.push_back("-EB"); + else if (getToolChain().getArchName() == "mipsel") + CmdArgs.push_back("-EL"); + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = Args.MakeArgString((getToolChain().GetProgramPath("as"))); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void netbsd::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + if (!D.SysRoot.empty()) + CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); + + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-Bstatic"); + } else { + if (Args.hasArg(options::OPT_rdynamic)) + CmdArgs.push_back("-export-dynamic"); + CmdArgs.push_back("--eh-frame-hdr"); + if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-Bshareable"); + } else { + CmdArgs.push_back("-dynamic-linker"); + CmdArgs.push_back("/libexec/ld.elf_so"); + } + } + + // When building 32-bit code on NetBSD/amd64, we have to explicitly + // instruct ld in the base system to link 32-bit code. + if (getToolChain().getArch() == llvm::Triple::x86) { + CmdArgs.push_back("-m"); + CmdArgs.push_back("elf_i386"); + } + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crt0.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtbegin.o"))); + } else { + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtbeginS.o"))); + } + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_e); + Args.AddAllArgs(CmdArgs, options::OPT_s); + Args.AddAllArgs(CmdArgs, options::OPT_t); + Args.AddAllArgs(CmdArgs, options::OPT_Z_Flag); + Args.AddAllArgs(CmdArgs, options::OPT_r); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (D.CCCIsCXX) { + getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("-lm"); + } + // FIXME: For some reason GCC passes -lgcc and -lgcc_s before adding + // the default system libraries. Just mimic this for now. + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-lgcc_eh"); + } else { + CmdArgs.push_back("--as-needed"); + CmdArgs.push_back("-lgcc_s"); + CmdArgs.push_back("--no-as-needed"); + } + CmdArgs.push_back("-lgcc"); + + if (Args.hasArg(options::OPT_pthread)) + CmdArgs.push_back("-lpthread"); + CmdArgs.push_back("-lc"); + + CmdArgs.push_back("-lgcc"); + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-lgcc_eh"); + } else { + CmdArgs.push_back("--as-needed"); + CmdArgs.push_back("-lgcc_s"); + CmdArgs.push_back("--no-as-needed"); + } + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath( + "crtend.o"))); + else + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath( + "crtendS.o"))); + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath( + "crtn.o"))); + } + + addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple()); + + const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void linuxtools::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + // Add --32/--64 to make sure we get the format we want. + // This is incomplete + if (getToolChain().getArch() == llvm::Triple::x86) { + CmdArgs.push_back("--32"); + } else if (getToolChain().getArch() == llvm::Triple::x86_64) { + CmdArgs.push_back("--64"); + } else if (getToolChain().getArch() == llvm::Triple::ppc) { + CmdArgs.push_back("-a32"); + CmdArgs.push_back("-mppc"); + CmdArgs.push_back("-many"); + } else if (getToolChain().getArch() == llvm::Triple::ppc64) { + CmdArgs.push_back("-a64"); + CmdArgs.push_back("-mppc64"); + CmdArgs.push_back("-many"); + } else if (getToolChain().getArch() == llvm::Triple::arm) { + StringRef MArch = getToolChain().getArchName(); + if (MArch == "armv7" || MArch == "armv7a" || MArch == "armv7-a") + CmdArgs.push_back("-mfpu=neon"); + } else if (getToolChain().getArch() == llvm::Triple::mips || + getToolChain().getArch() == llvm::Triple::mipsel || + getToolChain().getArch() == llvm::Triple::mips64 || + getToolChain().getArch() == llvm::Triple::mips64el) { + StringRef CPUName; + StringRef ABIName; + getMipsCPUAndABI(Args, getToolChain(), CPUName, ABIName); + + CmdArgs.push_back("-march"); + CmdArgs.push_back(CPUName.data()); + + // Convert ABI name to the GNU tools acceptable variant. + if (ABIName == "o32") + ABIName = "32"; + else if (ABIName == "n64") + ABIName = "64"; + + CmdArgs.push_back("-mabi"); + CmdArgs.push_back(ABIName.data()); + + if (getToolChain().getArch() == llvm::Triple::mips || + getToolChain().getArch() == llvm::Triple::mips64) + CmdArgs.push_back("-EB"); + else + CmdArgs.push_back("-EL"); + } + + Args.AddLastArg(CmdArgs, options::OPT_march_EQ); + Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ); + Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ); + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("as")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +static void AddLibgcc(const Driver &D, ArgStringList &CmdArgs, + const ArgList &Args) { + bool StaticLibgcc = Args.hasArg(options::OPT_static) || + Args.hasArg(options::OPT_static_libgcc); + if (!D.CCCIsCXX) + CmdArgs.push_back("-lgcc"); + + if (StaticLibgcc) { + if (D.CCCIsCXX) + CmdArgs.push_back("-lgcc"); + } else { + if (!D.CCCIsCXX) + CmdArgs.push_back("--as-needed"); + CmdArgs.push_back("-lgcc_s"); + if (!D.CCCIsCXX) + CmdArgs.push_back("--no-as-needed"); + } + + if (StaticLibgcc) + CmdArgs.push_back("-lgcc_eh"); + else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX) + CmdArgs.push_back("-lgcc"); +} + +void linuxtools::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const toolchains::Linux& ToolChain = + static_cast<const toolchains::Linux&>(getToolChain()); + const Driver &D = ToolChain.getDriver(); + ArgStringList CmdArgs; + + // Silence warning for "clang -g foo.o -o foo" + Args.ClaimAllArgs(options::OPT_g_Group); + // and "clang -emit-llvm foo.o -o foo" + Args.ClaimAllArgs(options::OPT_emit_llvm); + // and for "clang -g foo.o -o foo". Other warning options are already + // handled somewhere else. + Args.ClaimAllArgs(options::OPT_w); + + if (!D.SysRoot.empty()) + CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); + + if (Args.hasArg(options::OPT_pie)) + CmdArgs.push_back("-pie"); + + if (Args.hasArg(options::OPT_rdynamic)) + CmdArgs.push_back("-export-dynamic"); + + if (Args.hasArg(options::OPT_s)) + CmdArgs.push_back("-s"); + + for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(), + e = ToolChain.ExtraOpts.end(); + i != e; ++i) + CmdArgs.push_back(i->c_str()); + + if (!Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("--eh-frame-hdr"); + } + + CmdArgs.push_back("-m"); + if (ToolChain.getArch() == llvm::Triple::x86) + CmdArgs.push_back("elf_i386"); + else if (ToolChain.getArch() == llvm::Triple::arm + || ToolChain.getArch() == llvm::Triple::thumb) + CmdArgs.push_back("armelf_linux_eabi"); + else if (ToolChain.getArch() == llvm::Triple::ppc) + CmdArgs.push_back("elf32ppclinux"); + else if (ToolChain.getArch() == llvm::Triple::ppc64) + CmdArgs.push_back("elf64ppc"); + else if (ToolChain.getArch() == llvm::Triple::mips) + CmdArgs.push_back("elf32btsmip"); + else if (ToolChain.getArch() == llvm::Triple::mipsel) + CmdArgs.push_back("elf32ltsmip"); + else if (ToolChain.getArch() == llvm::Triple::mips64) + CmdArgs.push_back("elf64btsmip"); + else if (ToolChain.getArch() == llvm::Triple::mips64el) + CmdArgs.push_back("elf64ltsmip"); + else + CmdArgs.push_back("elf_x86_64"); + + if (Args.hasArg(options::OPT_static)) { + if (ToolChain.getArch() == llvm::Triple::arm + || ToolChain.getArch() == llvm::Triple::thumb) + CmdArgs.push_back("-Bstatic"); + else + CmdArgs.push_back("-static"); + } else if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-shared"); + } + + if (ToolChain.getArch() == llvm::Triple::arm || + ToolChain.getArch() == llvm::Triple::thumb || + (!Args.hasArg(options::OPT_static) && + !Args.hasArg(options::OPT_shared))) { + CmdArgs.push_back("-dynamic-linker"); + if (ToolChain.getArch() == llvm::Triple::x86) + CmdArgs.push_back("/lib/ld-linux.so.2"); + else if (ToolChain.getArch() == llvm::Triple::arm || + ToolChain.getArch() == llvm::Triple::thumb) + CmdArgs.push_back("/lib/ld-linux.so.3"); + else if (ToolChain.getArch() == llvm::Triple::mips || + ToolChain.getArch() == llvm::Triple::mipsel) + CmdArgs.push_back("/lib/ld.so.1"); + else if (ToolChain.getArch() == llvm::Triple::mips64 || + ToolChain.getArch() == llvm::Triple::mips64el) + CmdArgs.push_back("/lib64/ld.so.1"); + else if (ToolChain.getArch() == llvm::Triple::ppc) + CmdArgs.push_back("/lib/ld.so.1"); + else if (ToolChain.getArch() == llvm::Triple::ppc64) + CmdArgs.push_back("/lib64/ld64.so.1"); + else + CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2"); + } + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + const char *crt1 = NULL; + if (!Args.hasArg(options::OPT_shared)){ + if (Args.hasArg(options::OPT_pie)) + crt1 = "Scrt1.o"; + else + crt1 = "crt1.o"; + } + if (crt1) + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crt1))); + + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crti.o"))); + + const char *crtbegin; + if (Args.hasArg(options::OPT_static)) + crtbegin = "crtbeginT.o"; + else if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) + crtbegin = "crtbeginS.o"; + else + crtbegin = "crtbegin.o"; + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin))); + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + + const ToolChain::path_list Paths = ToolChain.getFilePaths(); + + for (ToolChain::path_list::const_iterator i = Paths.begin(), e = Paths.end(); + i != e; ++i) + CmdArgs.push_back(Args.MakeArgString(StringRef("-L") + *i)); + + // Tell the linker to load the plugin. This has to come before AddLinkerInputs + // as gold requires -plugin to come before any -plugin-opt that -Wl might + // forward. + if (D.IsUsingLTO(Args) || Args.hasArg(options::OPT_use_gold_plugin)) { + CmdArgs.push_back("-plugin"); + std::string Plugin = ToolChain.getDriver().Dir + "/../lib/LLVMgold.so"; + CmdArgs.push_back(Args.MakeArgString(Plugin)); + } + + AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs); + + if (D.CCCIsCXX && !Args.hasArg(options::OPT_nostdlib)) { + bool OnlyLibstdcxxStatic = Args.hasArg(options::OPT_static_libstdcxx) && + !Args.hasArg(options::OPT_static); + if (OnlyLibstdcxxStatic) + CmdArgs.push_back("-Bstatic"); + ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); + if (OnlyLibstdcxxStatic) + CmdArgs.push_back("-Bdynamic"); + CmdArgs.push_back("-lm"); + } + + // Call this before we add the C run-time. + addAsanRTLinux(getToolChain(), Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib)) { + if (Args.hasArg(options::OPT_static)) + CmdArgs.push_back("--start-group"); + + AddLibgcc(D, CmdArgs, Args); + + if (Args.hasArg(options::OPT_pthread) || + Args.hasArg(options::OPT_pthreads)) + CmdArgs.push_back("-lpthread"); + + CmdArgs.push_back("-lc"); + + if (Args.hasArg(options::OPT_static)) + CmdArgs.push_back("--end-group"); + else + AddLibgcc(D, CmdArgs, Args); + + + if (!Args.hasArg(options::OPT_nostartfiles)) { + const char *crtend; + if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie)) + crtend = "crtendS.o"; + else + crtend = "crtend.o"; + + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend))); + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o"))); + } + } + + addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple()); + + C.addCommand(new Command(JA, *this, ToolChain.Linker.c_str(), CmdArgs)); +} + +void minix::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("as")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void minix::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crt1.o"))); + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o"))); + CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crtn.o"))); + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_e); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple()); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (D.CCCIsCXX) { + getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("-lm"); + } + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (Args.hasArg(options::OPT_pthread)) + CmdArgs.push_back("-lpthread"); + CmdArgs.push_back("-lc"); + CmdArgs.push_back("-lCompilerRT-Generic"); + CmdArgs.push_back("-L/usr/pkg/compiler-rt/lib"); + CmdArgs.push_back( + Args.MakeArgString(getToolChain().GetFilePath("crtend.o"))); + } + + const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +/// DragonFly Tools + +// For now, DragonFly Assemble does just about the same as for +// FreeBSD, but this may change soon. +void dragonfly::Assemble::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + // When building 32-bit code on DragonFly/pc64, we have to explicitly + // instruct as in the base system to assemble 32-bit code. + if (getToolChain().getArchName() == "i386") + CmdArgs.push_back("--32"); + + Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, + options::OPT_Xassembler); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + const InputInfo &II = *it; + CmdArgs.push_back(II.getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("as")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + const Driver &D = getToolChain().getDriver(); + ArgStringList CmdArgs; + + if (!D.SysRoot.empty()) + CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot)); + + if (Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-Bstatic"); + } else { + if (Args.hasArg(options::OPT_shared)) + CmdArgs.push_back("-Bshareable"); + else { + CmdArgs.push_back("-dynamic-linker"); + CmdArgs.push_back("/usr/libexec/ld-elf.so.2"); + } + } + + // When building 32-bit code on DragonFly/pc64, we have to explicitly + // instruct ld in the base system to link 32-bit code. + if (getToolChain().getArchName() == "i386") { + CmdArgs.push_back("-m"); + CmdArgs.push_back("elf_i386"); + } + + if (Output.isFilename()) { + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back( + Args.MakeArgString(getToolChain().GetFilePath("crt1.o"))); + CmdArgs.push_back( + Args.MakeArgString(getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back( + Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o"))); + } else { + CmdArgs.push_back( + Args.MakeArgString(getToolChain().GetFilePath("crti.o"))); + CmdArgs.push_back( + Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o"))); + } + } + + Args.AddAllArgs(CmdArgs, options::OPT_L); + Args.AddAllArgs(CmdArgs, options::OPT_T_Group); + Args.AddAllArgs(CmdArgs, options::OPT_e); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + // FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of + // rpaths + CmdArgs.push_back("-L/usr/lib/gcc41"); + + if (!Args.hasArg(options::OPT_static)) { + CmdArgs.push_back("-rpath"); + CmdArgs.push_back("/usr/lib/gcc41"); + + CmdArgs.push_back("-rpath-link"); + CmdArgs.push_back("/usr/lib/gcc41"); + + CmdArgs.push_back("-rpath"); + CmdArgs.push_back("/usr/lib"); + + CmdArgs.push_back("-rpath-link"); + CmdArgs.push_back("/usr/lib"); + } + + if (D.CCCIsCXX) { + getToolChain().AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("-lm"); + } + + if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-lgcc_pic"); + } else { + CmdArgs.push_back("-lgcc"); + } + + + if (Args.hasArg(options::OPT_pthread)) + CmdArgs.push_back("-lpthread"); + + if (!Args.hasArg(options::OPT_nolibc)) { + CmdArgs.push_back("-lc"); + } + + if (Args.hasArg(options::OPT_shared)) { + CmdArgs.push_back("-lgcc_pic"); + } else { + CmdArgs.push_back("-lgcc"); + } + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + if (!Args.hasArg(options::OPT_shared)) + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtend.o"))); + else + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtendS.o"))); + CmdArgs.push_back(Args.MakeArgString( + getToolChain().GetFilePath("crtn.o"))); + } + + addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple()); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("ld")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} + +void visualstudio::Link::ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &Args, + const char *LinkingOutput) const { + ArgStringList CmdArgs; + + if (Output.isFilename()) { + CmdArgs.push_back(Args.MakeArgString(std::string("-out:") + + Output.getFilename())); + } else { + assert(Output.isNothing() && "Invalid output."); + } + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nostartfiles)) { + CmdArgs.push_back("-defaultlib:libcmt"); + } + + CmdArgs.push_back("-nologo"); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("link.exe")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} diff --git a/clang/lib/Driver/Tools.h b/clang/lib/Driver/Tools.h new file mode 100644 index 0000000..651a8f2 --- /dev/null +++ b/clang/lib/Driver/Tools.h @@ -0,0 +1,605 @@ +//===--- Tools.h - Tool Implementations -------------------------*- C++ -*-===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#ifndef CLANG_LIB_DRIVER_TOOLS_H_ +#define CLANG_LIB_DRIVER_TOOLS_H_ + +#include "clang/Driver/Tool.h" +#include "clang/Driver/Types.h" +#include "clang/Driver/Util.h" + +#include "llvm/ADT/Triple.h" +#include "llvm/Support/Compiler.h" + +namespace clang { +namespace driver { + class Driver; + +namespace toolchains { + class Darwin; +} + +namespace tools { + + /// \brief Clang compiler tool. + class LLVM_LIBRARY_VISIBILITY Clang : public Tool { + void AddPreprocessingOptions(Compilation &C, + const Driver &D, + const ArgList &Args, + ArgStringList &CmdArgs, + const InputInfo &Output, + const InputInfoList &Inputs) const; + + void AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs, + bool KernelOrKext) const; + void AddMIPSTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const; + void AddSparcTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const; + void AddX86TargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const; + void AddHexagonTargetArgs (const ArgList &Args, ArgStringList &CmdArgs) const; + + public: + Clang(const ToolChain &TC) : Tool("clang", "clang frontend", TC) {} + + virtual bool hasGoodDiagnostics() const { return true; } + virtual bool hasIntegratedAssembler() const { return true; } + virtual bool hasIntegratedCPP() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + /// \brief Clang integrated assembler tool. + class LLVM_LIBRARY_VISIBILITY ClangAs : public Tool { + void AddARMTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const; + public: + ClangAs(const ToolChain &TC) : Tool("clang::as", + "clang integrated assembler", TC) {} + + virtual bool hasGoodDiagnostics() const { return true; } + virtual bool hasIntegratedAssembler() const { return false; } + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + /// gcc - Generic GCC tool implementations. +namespace gcc { + class LLVM_LIBRARY_VISIBILITY Common : public Tool { + public: + Common(const char *Name, const char *ShortName, + const ToolChain &TC) : Tool(Name, ShortName, TC) {} + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + + /// RenderExtraToolArgs - Render any arguments necessary to force + /// the particular tool mode. + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const = 0; + }; + + + class LLVM_LIBRARY_VISIBILITY Preprocess : public Common { + public: + Preprocess(const ToolChain &TC) : Common("gcc::Preprocess", + "gcc preprocessor", TC) {} + + virtual bool hasGoodDiagnostics() const { return true; } + virtual bool hasIntegratedCPP() const { return false; } + + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const; + }; + + class LLVM_LIBRARY_VISIBILITY Precompile : public Common { + public: + Precompile(const ToolChain &TC) : Common("gcc::Precompile", + "gcc precompile", TC) {} + + virtual bool hasGoodDiagnostics() const { return true; } + virtual bool hasIntegratedCPP() const { return true; } + + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const; + }; + + class LLVM_LIBRARY_VISIBILITY Compile : public Common { + public: + Compile(const ToolChain &TC) : Common("gcc::Compile", + "gcc frontend", TC) {} + + virtual bool hasGoodDiagnostics() const { return true; } + virtual bool hasIntegratedCPP() const { return true; } + + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const; + }; + + class LLVM_LIBRARY_VISIBILITY Assemble : public Common { + public: + Assemble(const ToolChain &TC) : Common("gcc::Assemble", + "assembler (via gcc)", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const; + }; + + class LLVM_LIBRARY_VISIBILITY Link : public Common { + public: + Link(const ToolChain &TC) : Common("gcc::Link", + "linker (via gcc)", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const; + }; +} // end namespace gcc + +namespace hexagon { + // For Hexagon, we do not need to instantiate tools for PreProcess, PreCompile and Compile. + // We simply use "clang -cc1" for those actions. + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("hexagon::Assemble", + "hexagon-as", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const; + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("hexagon::Link", + "hexagon-ld", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void RenderExtraToolArgs(const JobAction &JA, + ArgStringList &CmdArgs) const; + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace hexagon. + + +namespace darwin { + class LLVM_LIBRARY_VISIBILITY DarwinTool : public Tool { + virtual void anchor(); + protected: + void AddDarwinArch(const ArgList &Args, ArgStringList &CmdArgs) const; + + const toolchains::Darwin &getDarwinToolChain() const { + return reinterpret_cast<const toolchains::Darwin&>(getToolChain()); + } + + public: + DarwinTool(const char *Name, const char *ShortName, + const ToolChain &TC) : Tool(Name, ShortName, TC) {} + }; + + class LLVM_LIBRARY_VISIBILITY CC1 : public DarwinTool { + virtual void anchor(); + public: + static const char *getBaseInputName(const ArgList &Args, + const InputInfoList &Input); + static const char *getBaseInputStem(const ArgList &Args, + const InputInfoList &Input); + static const char *getDependencyFileName(const ArgList &Args, + const InputInfoList &Inputs); + + protected: + const char *getCC1Name(types::ID Type) const; + + void AddCC1Args(const ArgList &Args, ArgStringList &CmdArgs) const; + void RemoveCC1UnsupportedArgs(ArgStringList &CmdArgs) const; + void AddCC1OptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, + const InputInfoList &Inputs, + const ArgStringList &OutputArgs) const; + void AddCPPOptionsArgs(const ArgList &Args, ArgStringList &CmdArgs, + const InputInfoList &Inputs, + const ArgStringList &OutputArgs) const; + void AddCPPUniqueOptionsArgs(const ArgList &Args, + ArgStringList &CmdArgs, + const InputInfoList &Inputs) const; + void AddCPPArgs(const ArgList &Args, ArgStringList &CmdArgs) const; + + public: + CC1(const char *Name, const char *ShortName, + const ToolChain &TC) : DarwinTool(Name, ShortName, TC) {} + + virtual bool hasGoodDiagnostics() const { return true; } + virtual bool hasIntegratedCPP() const { return true; } + }; + + class LLVM_LIBRARY_VISIBILITY Preprocess : public CC1 { + public: + Preprocess(const ToolChain &TC) : CC1("darwin::Preprocess", + "gcc preprocessor", TC) {} + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + class LLVM_LIBRARY_VISIBILITY Compile : public CC1 { + public: + Compile(const ToolChain &TC) : CC1("darwin::Compile", "gcc frontend", TC) {} + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + class LLVM_LIBRARY_VISIBILITY Assemble : public DarwinTool { + public: + Assemble(const ToolChain &TC) : DarwinTool("darwin::Assemble", + "assembler", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + class LLVM_LIBRARY_VISIBILITY Link : public DarwinTool { + void AddLinkArgs(Compilation &C, const ArgList &Args, + ArgStringList &CmdArgs) const; + + public: + Link(const ToolChain &TC) : DarwinTool("darwin::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + class LLVM_LIBRARY_VISIBILITY Lipo : public DarwinTool { + public: + Lipo(const ToolChain &TC) : DarwinTool("darwin::Lipo", "lipo", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + class LLVM_LIBRARY_VISIBILITY Dsymutil : public DarwinTool { + public: + Dsymutil(const ToolChain &TC) : DarwinTool("darwin::Dsymutil", + "dsymutil", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + + class LLVM_LIBRARY_VISIBILITY VerifyDebug : public DarwinTool { + public: + VerifyDebug(const ToolChain &TC) : DarwinTool("darwin::VerifyDebug", + "dwarfdump", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + +} + + /// openbsd -- Directly call GNU Binutils assembler and linker +namespace openbsd { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("openbsd::Assemble", "assembler", + TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("openbsd::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace openbsd + + /// freebsd -- Directly call GNU Binutils assembler and linker +namespace freebsd { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("freebsd::Assemble", "assembler", + TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("freebsd::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace freebsd + + /// netbsd -- Directly call GNU Binutils assembler and linker +namespace netbsd { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + + public: + Assemble(const ToolChain &TC) + : Tool("netbsd::Assemble", "assembler", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + + public: + Link(const ToolChain &TC) + : Tool("netbsd::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace netbsd + + /// linux -- Directly call GNU Binutils assembler and linker +namespace linuxtools { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("linux::Assemble", "assembler", + TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("linux::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} + /// minix -- Directly call GNU Binutils assembler and linker +namespace minix { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("minix::Assemble", "assembler", + TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("minix::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace minix + + /// solaris -- Directly call Solaris assembler and linker +namespace solaris { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("solaris::Assemble", "assembler", + TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("solaris::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace solaris + + /// auroraux -- Directly call GNU Binutils assembler and linker +namespace auroraux { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("auroraux::Assemble", "assembler", + TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("auroraux::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace auroraux + + /// dragonfly -- Directly call GNU Binutils assembler and linker +namespace dragonfly { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("dragonfly::Assemble", "assembler", + TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("dragonfly::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace dragonfly + + /// Visual studio tools. +namespace visualstudio { + class LLVM_LIBRARY_VISIBILITY Link : public Tool { + public: + Link(const ToolChain &TC) : Tool("visualstudio::Link", "linker", TC) {} + + virtual bool hasIntegratedCPP() const { return false; } + virtual bool isLinkJob() const { return true; } + + virtual void ConstructJob(Compilation &C, const JobAction &JA, + const InputInfo &Output, + const InputInfoList &Inputs, + const ArgList &TCArgs, + const char *LinkingOutput) const; + }; +} // end namespace visualstudio + +} // end namespace toolchains +} // end namespace driver +} // end namespace clang + +#endif // CLANG_LIB_DRIVER_TOOLS_H_ diff --git a/clang/lib/Driver/Types.cpp b/clang/lib/Driver/Types.cpp new file mode 100644 index 0000000..50742fe --- /dev/null +++ b/clang/lib/Driver/Types.cpp @@ -0,0 +1,254 @@ +//===--- Types.cpp - Driver input & temporary type information ------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "clang/Driver/Types.h" + +#include "llvm/ADT/StringSwitch.h" +#include <string.h> +#include <cassert> + +using namespace clang::driver; +using namespace clang::driver::types; + +struct TypeInfo { + const char *Name; + const char *Flags; + const char *TempSuffix; + ID PreprocessedType; +}; + +static const TypeInfo TypeInfos[] = { +#define TYPE(NAME, ID, PP_TYPE, TEMP_SUFFIX, FLAGS) \ + { NAME, FLAGS, TEMP_SUFFIX, TY_##PP_TYPE, }, +#include "clang/Driver/Types.def" +#undef TYPE +}; +static const unsigned numTypes = sizeof(TypeInfos) / sizeof(TypeInfos[0]); + +static const TypeInfo &getInfo(unsigned id) { + assert(id > 0 && id - 1 < numTypes && "Invalid Type ID."); + return TypeInfos[id - 1]; +} + +const char *types::getTypeName(ID Id) { + return getInfo(Id).Name; +} + +types::ID types::getPreprocessedType(ID Id) { + return getInfo(Id).PreprocessedType; +} + +const char *types::getTypeTempSuffix(ID Id) { + return getInfo(Id).TempSuffix; +} + +bool types::onlyAssembleType(ID Id) { + return strchr(getInfo(Id).Flags, 'a'); +} + +bool types::onlyPrecompileType(ID Id) { + return strchr(getInfo(Id).Flags, 'p'); +} + +bool types::canTypeBeUserSpecified(ID Id) { + return strchr(getInfo(Id).Flags, 'u'); +} + +bool types::appendSuffixForType(ID Id) { + return strchr(getInfo(Id).Flags, 'A'); +} + +bool types::canLipoType(ID Id) { + return (Id == TY_Nothing || + Id == TY_Image || + Id == TY_Object); +} + +bool types::isAcceptedByClang(ID Id) { + switch (Id) { + default: + return false; + + case TY_Asm: + case TY_C: case TY_PP_C: + case TY_CL: + case TY_CUDA: + case TY_ObjC: case TY_PP_ObjC: case TY_PP_ObjC_Alias: + case TY_CXX: case TY_PP_CXX: + case TY_ObjCXX: case TY_PP_ObjCXX: case TY_PP_ObjCXX_Alias: + case TY_CHeader: case TY_PP_CHeader: + case TY_CLHeader: + case TY_ObjCHeader: case TY_PP_ObjCHeader: + case TY_CXXHeader: case TY_PP_CXXHeader: + case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader: + case TY_AST: + case TY_LLVM_IR: case TY_LLVM_BC: + return true; + } +} + +bool types::isOnlyAcceptedByClang(ID Id) { + switch (Id) { + default: + return false; + + case TY_AST: + case TY_LLVM_IR: + case TY_LLVM_BC: + case TY_RewrittenObjC: + case TY_RewrittenLegacyObjC: + return true; + } +} + +bool types::isObjC(ID Id) { + switch (Id) { + default: + return false; + + case TY_ObjC: case TY_PP_ObjC: case TY_PP_ObjC_Alias: + case TY_ObjCXX: case TY_PP_ObjCXX: + case TY_ObjCHeader: case TY_PP_ObjCHeader: + case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader: case TY_PP_ObjCXX_Alias: + return true; + } +} + +bool types::isCXX(ID Id) { + switch (Id) { + default: + return false; + + case TY_CXX: case TY_PP_CXX: + case TY_ObjCXX: case TY_PP_ObjCXX: + case TY_CXXHeader: case TY_PP_CXXHeader: + case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader: + return true; + } +} + +types::ID types::lookupTypeForExtension(const char *Ext) { + return llvm::StringSwitch<types::ID>(Ext) + .Case("c", TY_C) + .Case("i", TY_PP_C) + .Case("m", TY_ObjC) + .Case("M", TY_ObjCXX) + .Case("h", TY_CHeader) + .Case("C", TY_CXX) + .Case("H", TY_CXXHeader) + .Case("f", TY_PP_Fortran) + .Case("F", TY_Fortran) + .Case("s", TY_PP_Asm) + .Case("S", TY_Asm) + .Case("o", TY_Object) + .Case("ii", TY_PP_CXX) + .Case("mi", TY_PP_ObjC) + .Case("mm", TY_ObjCXX) + .Case("bc", TY_LLVM_BC) + .Case("cc", TY_CXX) + .Case("CC", TY_CXX) + .Case("cl", TY_CL) + .Case("cp", TY_CXX) + .Case("cu", TY_CUDA) + .Case("hh", TY_CXXHeader) + .Case("ll", TY_LLVM_IR) + .Case("hpp", TY_CXXHeader) + .Case("ads", TY_Ada) + .Case("adb", TY_Ada) + .Case("ast", TY_AST) + .Case("c++", TY_CXX) + .Case("C++", TY_CXX) + .Case("cxx", TY_CXX) + .Case("cpp", TY_CXX) + .Case("CPP", TY_CXX) + .Case("CXX", TY_CXX) + .Case("for", TY_PP_Fortran) + .Case("FOR", TY_PP_Fortran) + .Case("fpp", TY_Fortran) + .Case("FPP", TY_Fortran) + .Case("f90", TY_PP_Fortran) + .Case("f95", TY_PP_Fortran) + .Case("F90", TY_Fortran) + .Case("F95", TY_Fortran) + .Case("mii", TY_PP_ObjCXX) + .Default(TY_INVALID); +} + +types::ID types::lookupTypeForTypeSpecifier(const char *Name) { + unsigned N = strlen(Name); + + for (unsigned i=0; i<numTypes; ++i) { + types::ID Id = (types::ID) (i + 1); + if (canTypeBeUserSpecified(Id) && + memcmp(Name, getInfo(Id).Name, N + 1) == 0) + return Id; + } + + return TY_INVALID; +} + +// FIXME: Why don't we just put this list in the defs file, eh. + +unsigned types::getNumCompilationPhases(ID Id) { + if (Id == TY_Object) + return 1; + + unsigned N = 0; + if (getPreprocessedType(Id) != TY_INVALID) + N += 1; + + if (onlyAssembleType(Id)) + return N + 2; // assemble, link + if (onlyPrecompileType(Id)) + return N + 1; // precompile + + return N + 3; // compile, assemble, link +} + +phases::ID types::getCompilationPhase(ID Id, unsigned N) { + assert(N < getNumCompilationPhases(Id) && "Invalid index."); + + if (Id == TY_Object) + return phases::Link; + + if (getPreprocessedType(Id) != TY_INVALID) { + if (N == 0) + return phases::Preprocess; + --N; + } + + if (onlyAssembleType(Id)) + return N == 0 ? phases::Assemble : phases::Link; + + if (onlyPrecompileType(Id)) + return phases::Precompile; + + if (N == 0) + return phases::Compile; + if (N == 1) + return phases::Assemble; + + return phases::Link; +} + +ID types::lookupCXXTypeForCType(ID Id) { + switch (Id) { + default: + return Id; + + case types::TY_C: + return types::TY_CXX; + case types::TY_PP_C: + return types::TY_PP_CXX; + case types::TY_CHeader: + return types::TY_CXXHeader; + case types::TY_PP_CHeader: + return types::TY_PP_CXXHeader; + } +} diff --git a/clang/lib/Driver/WindowsToolChain.cpp b/clang/lib/Driver/WindowsToolChain.cpp new file mode 100644 index 0000000..6827034 --- /dev/null +++ b/clang/lib/Driver/WindowsToolChain.cpp @@ -0,0 +1,368 @@ +//===--- ToolChains.cpp - ToolChain Implementations -----------------------===// +// +// The LLVM Compiler Infrastructure +// +// This file is distributed under the University of Illinois Open Source +// License. See LICENSE.TXT for details. +// +//===----------------------------------------------------------------------===// + +#include "ToolChains.h" + +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Compilation.h" +#include "clang/Driver/Driver.h" +#include "clang/Driver/Options.h" +#include "clang/Basic/Version.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/Path.h" + +// Include the necessary headers to interface with the Windows registry and +// environment. +#ifdef _MSC_VER + #define WIN32_LEAN_AND_MEAN + #define NOGDI + #define NOMINMAX + #include <Windows.h> +#endif + +using namespace clang::driver; +using namespace clang::driver::toolchains; +using namespace clang; + +Windows::Windows(const Driver &D, const llvm::Triple& Triple) + : ToolChain(D, Triple) { +} + +Tool &Windows::SelectTool(const Compilation &C, const JobAction &JA, + const ActionList &Inputs) const { + Action::ActionClass Key; + if (getDriver().ShouldUseClangCompiler(C, JA, getTriple())) + Key = Action::AnalyzeJobClass; + else + Key = JA.getKind(); + + bool UseIntegratedAs = C.getArgs().hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIntegratedAssemblerDefault()); + + Tool *&T = Tools[Key]; + if (!T) { + switch (Key) { + case Action::InputClass: + case Action::BindArchClass: + case Action::LipoJobClass: + case Action::DsymutilJobClass: + case Action::VerifyJobClass: + llvm_unreachable("Invalid tool kind."); + case Action::PreprocessJobClass: + case Action::PrecompileJobClass: + case Action::AnalyzeJobClass: + case Action::MigrateJobClass: + case Action::CompileJobClass: + T = new tools::Clang(*this); break; + case Action::AssembleJobClass: + if (!UseIntegratedAs && getTriple().getEnvironment() == llvm::Triple::MachO) + T = new tools::darwin::Assemble(*this); + else + T = new tools::ClangAs(*this); + break; + case Action::LinkJobClass: + T = new tools::visualstudio::Link(*this); break; + } + } + + return *T; +} + +bool Windows::IsIntegratedAssemblerDefault() const { + return true; +} + +bool Windows::IsUnwindTablesDefault() const { + // FIXME: Gross; we should probably have some separate target + // definition, possibly even reusing the one in clang. + return getArchName() == "x86_64"; +} + +const char *Windows::GetDefaultRelocationModel() const { + return "static"; +} + +const char *Windows::GetForcedPicModel() const { + if (getArchName() == "x86_64") + return "pic"; + return 0; +} + +// FIXME: This probably should goto to some platform utils place. +#ifdef _MSC_VER + +/// \brief Read registry string. +/// This also supports a means to look for high-versioned keys by use +/// of a $VERSION placeholder in the key path. +/// $VERSION in the key path is a placeholder for the version number, +/// causing the highest value path to be searched for and used. +/// I.e. "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION". +/// There can be additional characters in the component. Only the numberic +/// characters are compared. +static bool getSystemRegistryString(const char *keyPath, const char *valueName, + char *value, size_t maxLength) { + HKEY hRootKey = NULL; + HKEY hKey = NULL; + const char* subKey = NULL; + DWORD valueType; + DWORD valueSize = maxLength - 1; + long lResult; + bool returnValue = false; + + if (strncmp(keyPath, "HKEY_CLASSES_ROOT\\", 18) == 0) { + hRootKey = HKEY_CLASSES_ROOT; + subKey = keyPath + 18; + } else if (strncmp(keyPath, "HKEY_USERS\\", 11) == 0) { + hRootKey = HKEY_USERS; + subKey = keyPath + 11; + } else if (strncmp(keyPath, "HKEY_LOCAL_MACHINE\\", 19) == 0) { + hRootKey = HKEY_LOCAL_MACHINE; + subKey = keyPath + 19; + } else if (strncmp(keyPath, "HKEY_CURRENT_USER\\", 18) == 0) { + hRootKey = HKEY_CURRENT_USER; + subKey = keyPath + 18; + } else { + return false; + } + + const char *placeHolder = strstr(subKey, "$VERSION"); + char bestName[256]; + bestName[0] = '\0'; + // If we have a $VERSION placeholder, do the highest-version search. + if (placeHolder) { + const char *keyEnd = placeHolder - 1; + const char *nextKey = placeHolder; + // Find end of previous key. + while ((keyEnd > subKey) && (*keyEnd != '\\')) + keyEnd--; + // Find end of key containing $VERSION. + while (*nextKey && (*nextKey != '\\')) + nextKey++; + size_t partialKeyLength = keyEnd - subKey; + char partialKey[256]; + if (partialKeyLength > sizeof(partialKey)) + partialKeyLength = sizeof(partialKey); + strncpy(partialKey, subKey, partialKeyLength); + partialKey[partialKeyLength] = '\0'; + HKEY hTopKey = NULL; + lResult = RegOpenKeyEx(hRootKey, partialKey, 0, KEY_READ, &hTopKey); + if (lResult == ERROR_SUCCESS) { + char keyName[256]; + int bestIndex = -1; + double bestValue = 0.0; + DWORD index, size = sizeof(keyName) - 1; + for (index = 0; RegEnumKeyEx(hTopKey, index, keyName, &size, NULL, + NULL, NULL, NULL) == ERROR_SUCCESS; index++) { + const char *sp = keyName; + while (*sp && !isdigit(*sp)) + sp++; + if (!*sp) + continue; + const char *ep = sp + 1; + while (*ep && (isdigit(*ep) || (*ep == '.'))) + ep++; + char numBuf[32]; + strncpy(numBuf, sp, sizeof(numBuf) - 1); + numBuf[sizeof(numBuf) - 1] = '\0'; + double value = strtod(numBuf, NULL); + if (value > bestValue) { + bestIndex = (int)index; + bestValue = value; + strcpy(bestName, keyName); + } + size = sizeof(keyName) - 1; + } + // If we found the highest versioned key, open the key and get the value. + if (bestIndex != -1) { + // Append rest of key. + strncat(bestName, nextKey, sizeof(bestName) - 1); + bestName[sizeof(bestName) - 1] = '\0'; + // Open the chosen key path remainder. + lResult = RegOpenKeyEx(hTopKey, bestName, 0, KEY_READ, &hKey); + if (lResult == ERROR_SUCCESS) { + lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, + (LPBYTE)value, &valueSize); + if (lResult == ERROR_SUCCESS) + returnValue = true; + RegCloseKey(hKey); + } + } + RegCloseKey(hTopKey); + } + } else { + lResult = RegOpenKeyEx(hRootKey, subKey, 0, KEY_READ, &hKey); + if (lResult == ERROR_SUCCESS) { + lResult = RegQueryValueEx(hKey, valueName, NULL, &valueType, + (LPBYTE)value, &valueSize); + if (lResult == ERROR_SUCCESS) + returnValue = true; + RegCloseKey(hKey); + } + } + return returnValue; +} + +/// \brief Get Windows SDK installation directory. +static bool getWindowsSDKDir(std::string &path) { + char windowsSDKInstallDir[256]; + // Try the Windows registry. + bool hasSDKDir = getSystemRegistryString( + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\$VERSION", + "InstallationFolder", + windowsSDKInstallDir, + sizeof(windowsSDKInstallDir) - 1); + // If we have both vc80 and vc90, pick version we were compiled with. + if (hasSDKDir && windowsSDKInstallDir[0]) { + path = windowsSDKInstallDir; + return true; + } + return false; +} + + // Get Visual Studio installation directory. +static bool getVisualStudioDir(std::string &path) { + // First check the environment variables that vsvars32.bat sets. + const char* vcinstalldir = getenv("VCINSTALLDIR"); + if (vcinstalldir) { + char *p = const_cast<char *>(strstr(vcinstalldir, "\\VC")); + if (p) + *p = '\0'; + path = vcinstalldir; + return true; + } + + char vsIDEInstallDir[256]; + char vsExpressIDEInstallDir[256]; + // Then try the windows registry. + bool hasVCDir = getSystemRegistryString( + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\$VERSION", + "InstallDir", vsIDEInstallDir, sizeof(vsIDEInstallDir) - 1); + bool hasVCExpressDir = getSystemRegistryString( + "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VCExpress\\$VERSION", + "InstallDir", vsExpressIDEInstallDir, sizeof(vsExpressIDEInstallDir) - 1); + // If we have both vc80 and vc90, pick version we were compiled with. + if (hasVCDir && vsIDEInstallDir[0]) { + char *p = (char*)strstr(vsIDEInstallDir, "\\Common7\\IDE"); + if (p) + *p = '\0'; + path = vsIDEInstallDir; + return true; + } + + if (hasVCExpressDir && vsExpressIDEInstallDir[0]) { + char *p = (char*)strstr(vsExpressIDEInstallDir, "\\Common7\\IDE"); + if (p) + *p = '\0'; + path = vsExpressIDEInstallDir; + return true; + } + + // Try the environment. + const char *vs100comntools = getenv("VS100COMNTOOLS"); + const char *vs90comntools = getenv("VS90COMNTOOLS"); + const char *vs80comntools = getenv("VS80COMNTOOLS"); + const char *vscomntools = NULL; + + // Try to find the version that we were compiled with + if(false) {} + #if (_MSC_VER >= 1600) // VC100 + else if(vs100comntools) { + vscomntools = vs100comntools; + } + #elif (_MSC_VER == 1500) // VC80 + else if(vs90comntools) { + vscomntools = vs90comntools; + } + #elif (_MSC_VER == 1400) // VC80 + else if(vs80comntools) { + vscomntools = vs80comntools; + } + #endif + // Otherwise find any version we can + else if (vs100comntools) + vscomntools = vs100comntools; + else if (vs90comntools) + vscomntools = vs90comntools; + else if (vs80comntools) + vscomntools = vs80comntools; + + if (vscomntools && *vscomntools) { + const char *p = strstr(vscomntools, "\\Common7\\Tools"); + path = p ? std::string(vscomntools, p) : vscomntools; + return true; + } + return false; +} + +#endif // _MSC_VER + +void Windows::AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + if (DriverArgs.hasArg(options::OPT_nostdinc)) + return; + + if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) { + llvm::sys::Path P(getDriver().ResourceDir); + P.appendComponent("include"); + addSystemInclude(DriverArgs, CC1Args, P.str()); + } + + if (DriverArgs.hasArg(options::OPT_nostdlibinc)) + return; + +#ifdef _MSC_VER + // Honor %INCLUDE%. It should know essential search paths with vcvarsall.bat. + if (const char *cl_include_dir = getenv("INCLUDE")) { + SmallVector<StringRef, 8> Dirs; + StringRef(cl_include_dir).split(Dirs, ";"); + int n = 0; + for (SmallVectorImpl<StringRef>::iterator I = Dirs.begin(), E = Dirs.end(); + I != E; ++I) { + StringRef d = *I; + if (d.size() == 0) + continue; + ++n; + addSystemInclude(DriverArgs, CC1Args, d); + } + if (n) return; + } + + std::string VSDir; + std::string WindowsSDKDir; + + // When built with access to the proper Windows APIs, try to actually find + // the correct include paths first. + if (getVisualStudioDir(VSDir)) { + addSystemInclude(DriverArgs, CC1Args, VSDir + "\\VC\\include"); + if (getWindowsSDKDir(WindowsSDKDir)) + addSystemInclude(DriverArgs, CC1Args, WindowsSDKDir + "\\include"); + else + addSystemInclude(DriverArgs, CC1Args, + VSDir + "\\VC\\PlatformSDK\\Include"); + return; + } +#endif // _MSC_VER + + // As a fallback, select default install paths. + const StringRef Paths[] = { + "C:/Program Files/Microsoft Visual Studio 10.0/VC/include", + "C:/Program Files/Microsoft Visual Studio 9.0/VC/include", + "C:/Program Files/Microsoft Visual Studio 9.0/VC/PlatformSDK/Include", + "C:/Program Files/Microsoft Visual Studio 8/VC/include", + "C:/Program Files/Microsoft Visual Studio 8/VC/PlatformSDK/Include" + }; + addSystemIncludes(DriverArgs, CC1Args, Paths); +} + +void Windows::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + // FIXME: There should probably be logic here to find libc++ on Windows. +} |