diff options
Diffstat (limited to 'contrib/llvm/tools/clang/lib/Driver')
21 files changed, 14834 insertions, 0 deletions
diff --git a/contrib/llvm/tools/clang/lib/Driver/Action.cpp b/contrib/llvm/tools/clang/lib/Driver/Action.cpp new file mode 100644 index 0000000..2b5bbee --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Action.cpp @@ -0,0 +1,121 @@ +//===--- 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/contrib/llvm/tools/clang/lib/Driver/Arg.cpp b/contrib/llvm/tools/clang/lib/Driver/Arg.cpp new file mode 100644 index 0000000..93d70a9 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Arg.cpp @@ -0,0 +1,123 @@ +//===--- 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/Basic/LLVM.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; +using clang::StringRef; + +Arg::Arg(const Option _Opt, StringRef S, unsigned _Index, const Arg *_BaseArg) + : Opt(_Opt), BaseArg(_BaseArg), Spelling(S), Index(_Index), + Claimed(false), OwnsValues(false) { +} + +Arg::Arg(const Option _Opt, StringRef S, unsigned _Index, + const char *Value0, const Arg *_BaseArg) + : Opt(_Opt), BaseArg(_BaseArg), Spelling(S), Index(_Index), + Claimed(false), OwnsValues(false) { + Values.push_back(Value0); +} + +Arg::Arg(const Option _Opt, StringRef S, unsigned _Index, + const char *Value0, const char *Value1, const Arg *_BaseArg) + : Opt(_Opt), BaseArg(_BaseArg), Spelling(S), 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(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(i)); + break; + + case Option::RenderCommaJoinedStyle: { + SmallString<256> Res; + llvm::raw_svector_ostream OS(Res); + OS << getSpelling(); + for (unsigned i = 0, e = getNumValues(); i != e; ++i) { + if (i) OS << ','; + OS << getValue(i); + } + Output.push_back(Args.MakeArgString(OS.str())); + break; + } + + case Option::RenderJoinedStyle: + Output.push_back(Args.GetOrMakeJoinedArgString( + getIndex(), getSpelling(), getValue(0))); + for (unsigned i = 1, e = getNumValues(); i != e; ++i) + Output.push_back(getValue(i)); + break; + + case Option::RenderSeparateStyle: + Output.push_back(Args.MakeArgString(getSpelling())); + for (unsigned i = 0, e = getNumValues(); i != e; ++i) + Output.push_back(getValue(i)); + break; + } +} diff --git a/contrib/llvm/tools/clang/lib/Driver/ArgList.cpp b/contrib/llvm/tools/clang/lib/Driver/ArgList.cpp new file mode 100644 index 0000000..6c57b62 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/ArgList.cpp @@ -0,0 +1,408 @@ +//===--- 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; +} + +Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1, + OptSpecifier Id2, OptSpecifier Id3, + OptSpecifier Id4, OptSpecifier Id5) 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) || + (*it)->getOption().matches(Id5)) { + Res = *it; + Res->claim(); + } + } + + return Res; +} + +Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1, + OptSpecifier Id2, OptSpecifier Id3, + OptSpecifier Id4, OptSpecifier Id5, + OptSpecifier Id6) 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) || + (*it)->getOption().matches(Id5) || + (*it)->getOption().matches(Id6)) { + Res = *it; + Res->claim(); + } + } + + return Res; +} + +Arg *ArgList::getLastArg(OptSpecifier Id0, OptSpecifier Id1, + OptSpecifier Id2, OptSpecifier Id3, + OptSpecifier Id4, OptSpecifier Id5, + OptSpecifier Id6, OptSpecifier Id7) 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) || + (*it)->getOption().matches(Id5) || + (*it)->getOption().matches(Id6) || + (*it)->getOption().matches(Id7)) { + 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(); + 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()).getAsInteger(10, Res)) { + if (Diags) + Diags->Report(diag::err_drv_invalid_int_value) + << A->getAsString(*this) << A->getValue(); + } + } + + 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(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(0))); + } else { + Output.push_back(Translation); + Output.push_back((*it)->getValue(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); +} + +void ArgList::dump() { + llvm::errs() << "ArgList:"; + for (iterator it = begin(), ie = end(); it != ie; ++it) { + llvm::errs() << " " << (*it)->getSpelling(); + } + llvm::errs() << "\n"; +} + +// + +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, ArgList::MakeArgString(Twine(Opt.getPrefix()) + + Twine(Opt.getName())), + 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, ArgList::MakeArgString(Twine(Opt.getPrefix()) + + Twine(Opt.getName())), + 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, ArgList::MakeArgString(Twine(Opt.getPrefix()) + + Twine(Opt.getName())), + 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, ArgList::MakeArgString(Twine(Opt.getPrefix()) + + Twine(Opt.getName())), Index, + BaseArgs.getArgString(Index) + Opt.getName().size(), + BaseArg); + SynthesizedArgs.push_back(A); + return A; +} diff --git a/contrib/llvm/tools/clang/lib/Driver/CC1AsOptions.cpp b/contrib/llvm/tools/clang/lib/Driver/CC1AsOptions.cpp new file mode 100644 index 0000000..9048043 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/CC1AsOptions.cpp @@ -0,0 +1,47 @@ +//===--- 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/OptTable.h" +#include "clang/Driver/Option.h" +using namespace clang; +using namespace clang::driver; +using namespace clang::driver::options; +using namespace clang::driver::cc1asoptions; + +#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; +#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ + HELPTEXT, METAVAR) +#include "clang/Driver/CC1AsOptions.inc" +#undef OPTION +#undef PREFIX + +static const OptTable::Info CC1AsInfoTable[] = { +#define PREFIX(NAME, VALUE) +#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ + HELPTEXT, METAVAR) \ + { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, 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/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp b/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp new file mode 100644 index 0000000..1bff4a3 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Compilation.cpp @@ -0,0 +1,380 @@ +//===--- 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/ADT/StringSwitch.h" +#include "llvm/Support/Program.h" +#include "llvm/Support/raw_ostream.h" +#include <errno.h> +#include <sys/stat.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); + } +} + +static bool skipArg(const char *Flag, bool &SkipNextArg) { + StringRef FlagRef(Flag); + + // Assume we're going to see -Flag <Arg>. + SkipNextArg = true; + + // These flags are all of the form -Flag <Arg> and are treated as two + // arguments. Therefore, we need to skip the flag and the next argument. + bool Res = llvm::StringSwitch<bool>(Flag) + .Cases("-I", "-MF", "-MT", "-MQ", true) + .Cases("-o", "-coverage-file", "-dependency-file", true) + .Cases("-fdebug-compilation-dir", "-idirafter", true) + .Cases("-include", "-include-pch", "-internal-isystem", true) + .Cases("-internal-externc-isystem", "-iprefix", "-iwithprefix", true) + .Cases("-iwithprefixbefore", "-isysroot", "-isystem", "-iquote", true) + .Cases("-resource-dir", "-serialize-diagnostic-file", true) + .Case("-dwarf-debug-flags", true) + .Default(false); + + // Match found. + if (Res) + return Res; + + // The remaining flags are treated as a single argument. + SkipNextArg = false; + + // These flags are all of the form -Flag and have no second argument. + Res = llvm::StringSwitch<bool>(Flag) + .Cases("-M", "-MM", "-MG", "-MP", "-MD", true) + .Case("-MMD", true) + .Default(false); + + // Match found. + if (Res) + return Res; + + // These flags are treated as a single argument (e.g., -F<Dir>). + if (FlagRef.startswith("-F") || FlagRef.startswith("-I")) + return true; + + return false; +} + +static bool quoteNextArg(const char *flag) { + return llvm::StringSwitch<bool>(flag) + .Case("-D", true) + .Default(false); +} + +void Compilation::PrintDiagnosticJob(raw_ostream &OS, const Job &J) const { + if (const Command *C = dyn_cast<Command>(&J)) { + OS << C->getExecutable(); + unsigned QuoteNextArg = 0; + for (ArgStringList::const_iterator it = C->getArguments().begin(), + ie = C->getArguments().end(); it != ie; ++it) { + + bool SkipNext; + if (skipArg(*it, SkipNext)) { + if (SkipNext) ++it; + continue; + } + + if (!QuoteNextArg) + QuoteNextArg = quoteNextArg(*it) ? 2 : 0; + + OS << ' '; + + if (QuoteNextArg == 1) + OS << '"'; + + if (!std::strpbrk(*it, " \"\\$")) { + OS << *it; + } else { + // 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 << '"'; + } + + if (QuoteNextArg) { + if (QuoteNextArg == 1) + OS << '"'; + --QuoteNextArg; + } + } + OS << '\n'; + } else { + const JobList *Jobs = cast<JobList>(&J); + for (JobList::const_iterator + it = Jobs->begin(), ie = Jobs->end(); it != ie; ++it) + PrintDiagnosticJob(OS, **it); + } +} + +bool Compilation::CleanupFile(const char *File, bool IssueErrors) const { + llvm::sys::Path P(File); + std::string Error; + + // Don't try to remove files which we don't have write access to (but may be + // able to remove), or non-regular files. Underlying tools may have + // intentionally not overwritten them. + if (!P.canWrite() || !P.isRegularFile()) + return true; + + 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; + return false; + } + } + return true; +} + +bool Compilation::CleanupFileList(const ArgStringList &Files, + bool IssueErrors) const { + bool Success = true; + for (ArgStringList::const_iterator + it = Files.begin(), ie = Files.end(); it != ie; ++it) + Success &= CleanupFile(*it, IssueErrors); + return Success; +} + +bool Compilation::CleanupFileMap(const ArgStringMap &Files, + const JobAction *JA, + bool IssueErrors) const { + bool Success = true; + for (ArgStringMap::const_iterator + it = Files.begin(), ie = Files.end(); it != ie; ++it) { + + // If specified, only delete the files associated with the JobAction. + // Otherwise, delete all files in the map. + if (JA && it->first != JA) + continue; + Success &= CleanupFile(it->second, IssueErrors); + } + return Success; +} + +int Compilation::ExecuteCommand(const Command &C, + const Command *&FailingCommand) const { + 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; + bool ExecutionFailed; + int Res = + llvm::sys::Program::ExecuteAndWait(Prog, Argv, + /*env*/0, Redirects, + /*secondsToWait*/0, /*memoryLimit*/0, + &Error, &ExecutionFailed); + if (!Error.empty()) { + assert(Res && "Error string set with 0 result code!"); + getDriver().Diag(clang::diag::err_drv_command_failure) << Error; + } + + if (Res) + FailingCommand = &C; + + delete[] Argv; + return ExecutionFailed ? 1 : Res; +} + +typedef SmallVectorImpl< std::pair<int, const Command *> > FailingCommandList; + +static bool ActionFailed(const Action *A, + const FailingCommandList &FailingCommands) { + + if (FailingCommands.empty()) + return false; + + for (FailingCommandList::const_iterator CI = FailingCommands.begin(), + CE = FailingCommands.end(); CI != CE; ++CI) + if (A == &(CI->second->getSource())) + return true; + + for (Action::const_iterator AI = A->begin(), AE = A->end(); AI != AE; ++AI) + if (ActionFailed(*AI, FailingCommands)) + return true; + + return false; +} + +static bool InputsOk(const Command &C, + const FailingCommandList &FailingCommands) { + return !ActionFailed(&C.getSource(), FailingCommands); +} + +void Compilation::ExecuteJob(const Job &J, + FailingCommandList &FailingCommands) const { + if (const Command *C = dyn_cast<Command>(&J)) { + if (!InputsOk(*C, FailingCommands)) + return; + const Command *FailingCommand = 0; + if (int Res = ExecuteCommand(*C, FailingCommand)) + FailingCommands.push_back(std::make_pair(Res, FailingCommand)); + } else { + const JobList *Jobs = cast<JobList>(&J); + for (JobList::const_iterator it = Jobs->begin(), ie = Jobs->end(); + it != ie; ++it) + ExecuteJob(**it, FailingCommands); + } +} + +void Compilation::initCompilationForDiagnostics() { + // Free actions and jobs. + DeleteContainerPointers(Actions); + Jobs.clear(); + + // Clear temporary/results file lists. + TempFiles.clear(); + ResultFiles.clear(); + FailureResultFiles.clear(); + + // Remove any user specified output. Claim any unclaimed arguments, so as + // to avoid emitting warnings about unused args. + OptSpecifier OutputOpts[] = { options::OPT_o, options::OPT_MD, + options::OPT_MMD }; + for (unsigned i = 0, e = llvm::array_lengthof(OutputOpts); i != e; ++i) { + if (TranslatedArgs->hasArg(OutputOpts[i])) + TranslatedArgs->eraseArg(OutputOpts[i]); + } + TranslatedArgs->ClaimAllArgs(); + + // Redirect stdout/stderr to /dev/null. + Redirects = new const llvm::sys::Path*[3](); + Redirects[1] = new const llvm::sys::Path(); + Redirects[2] = new const llvm::sys::Path(); +} + +StringRef Compilation::getSysRoot() const { + return getDriver().SysRoot; +} diff --git a/contrib/llvm/tools/clang/lib/Driver/Driver.cpp b/contrib/llvm/tools/clang/lib/Driver/Driver.cpp new file mode 100644 index 0000000..6af03bd --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Driver.cpp @@ -0,0 +1,1819 @@ +//===--- 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 "InputInfo.h" +#include "ToolChains.h" +#include "clang/Basic/Version.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 "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/OwningPtr.h" +#include "llvm/ADT/StringSet.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/PrettyStackTrace.h" +#include "llvm/Support/Program.h" +#include "llvm/Support/raw_ostream.h" +#include <map> + +// FIXME: It would prevent us from including llvm-config.h +// if config.h were included before system_error.h. +#include "clang/Config/config.h" + +using namespace clang::driver; +using namespace clang; + +Driver::Driver(StringRef ClangExecutable, + StringRef DefaultTargetTriple, + StringRef DefaultImageName, + DiagnosticsEngine &Diags) + : Opts(createDriverOptTable()), Diags(Diags), + ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT), + UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple), + DefaultImageName(DefaultImageName), + DriverTitle("clang LLVM compiler"), + 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), + CCCUsePCH(true), SuppressMissingInputWarning(false) { + + 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().hasFlag(options::Unsupported)) { + 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_module_file_info)) || + (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(i)) != "--no-demangle") + DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), + A->getValue(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->getValue(0) == StringRef("-MD") || + A->getValue(0) == StringRef("-MMD"))) { + // Rewrite to -MD/-MMD along with -MF. + if (A->getValue(0) == StringRef("-MD")) + DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD)); + else + DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD)); + if (A->getNumValues() == 2) + DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF), + A->getValue(1)); + continue; + } + + // Rewrite reserved library names. + if (A->getOption().matches(options::OPT_l)) { + StringRef Value = A->getValue(); + + // 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(llvm::sys::PathSeparator); + 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, CCCPrintActions; + + 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(); + CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch, + options::OPT_ccc_pch_is_pth); + // 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(); + if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir)) + Dir = InstalledDir = A->getValue(); + 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(0)); + } + if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ)) + SysRoot = A->getValue(); + if (Args->hasArg(options::OPT_nostdlib)) + UseStdLib = false; + + if (const Arg *A = Args->getLastArg(options::OPT_resource_dir)) + ResourceDir = A->getValue(); + + // 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 or dsymutil jobs. + if (FailingCommand && (FailingCommand->getCreator().isLinkJob() || + FailingCommand->getCreator().isDsymutilJob())) + return; + + // Print the version of the compiler. + PrintVersion(C, llvm::errs()); + + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the " + "crash backtrace, preprocessed source, and associated run script."; + + // Suppress driver output and emit preprocessor output to temp file. + CCCIsCPP = true; + CCGenDiagnostics = true; + C.getArgs().AddFlagArg(0, Opts->getOption(options::OPT_frewrite_includes)); + + // Save the original job command(s). + std::string Cmd; + llvm::raw_string_ostream OS(Cmd); + if (FailingCommand) + C.PrintDiagnosticJob(OS, *FailingCommand); + else + // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an + // associated FailingCommand, so just pass all jobs. + C.PrintDiagnosticJob(OS, C.getJobs()); + OS.flush(); + + // Keep track of whether we produce any errors while trying to produce + // preprocessed sources. + DiagnosticErrorTrap Trap(Diags); + + // Suppress tool output. + C.initCompilationForDiagnostics(); + + // 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(), "-")) { + 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; + } + } + + if (Inputs.empty()) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating preprocessed source(s) - no preprocessable inputs."; + return; + } + + // 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(); + 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; + } + + // 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 (Trap.hasErrorOccurred()) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "Error generating preprocessed source(s)."; + return; + } + + // Generate preprocessed output. + SmallVector<std::pair<int, const Command *>, 4> FailingCommands; + C.ExecuteJob(C.getJobs(), FailingCommands); + + // If the command succeeded, we are done. + if (FailingCommands.empty()) { + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "\n********************\n\n" + "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n" + "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 { + // Append the new filename with correct preprocessed suffix. + size_t I, E; + I = Cmd.find("-main-file-name "); + assert (I != std::string::npos && "Expected to find -main-file-name"); + I += 16; + E = Cmd.find(" ", I); + assert (E != std::string::npos && "-main-file-name missing argument?"); + StringRef OldFilename = StringRef(Cmd).slice(I, E); + StringRef NewFilename = llvm::sys::path::filename(*it); + I = StringRef(Cmd).rfind(OldFilename); + E = I + OldFilename.size(); + I = Cmd.rfind(" ", I) + 1; + Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size()); + ScriptOS << Cmd; + Diag(clang::diag::note_drv_command_failed_diag_msg) << Script; + } + } + Diag(clang::diag::note_drv_command_failed_diag_msg) + << "\n\n********************"; + } 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, + SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) 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; + + C.ExecuteJob(C.getJobs(), FailingCommands); + + // Remove temp files. + C.CleanupFileList(C.getTempFiles()); + + // If the command succeeded, we are done. + if (FailingCommands.empty()) + return 0; + + // Otherwise, remove result files and print extra information about abnormal + // failures. + for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it = + FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) { + int Res = it->first; + const Command *FailingCommand = it->second; + + // Remove result files if we're not saving temps. + if (!C.getArgs().hasArg(options::OPT_save_temps)) { + const JobAction *JA = cast<JobAction>(&FailingCommand->getSource()); + C.CleanupFileMap(C.getResultFiles(), JA, true); + + // Failure result files are valid unless we crashed. + if (Res < 0) + C.CleanupFileMap(C.getFailureResultFiles(), JA, true); + } + + // 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 0; +} + +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().getPrefixedName() << "\", " + << "Values: {"; + for (unsigned j = 0; j < A->getNumValues(); ++j) { + if (j) + llvm::errs() << ", "; + llvm::errs() << '"' << A->getValue(j) << '"'; + } + llvm::errs() << "}\n"; + } +} + +void Driver::PrintHelp(bool ShowHidden) const { + getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(), + /*Include*/0, + /*Exclude*/options::NoDriverOption | + (ShowHidden ? 0 : options::HelpHidden)); +} + +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(), TC) << "\n"; + return false; + } + + if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) { + llvm::outs() << GetProgramPath(A->getValue(), 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() << "." << "\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() << "\""; + } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) { + os << '"' << BIA->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 = + tools::darwin::getArchTypeForDarwinArchName(A->getValue()); + if (Arch == llvm::Triple::UnknownArch) { + Diag(clang::diag::err_drv_invalid_arch_name) + << A->getAsString(Args); + continue; + } + + A->claim(); + if (ArchNames.insert(A->getValue())) + Archs.push_back(A->getValue()); + } + } + + // 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(Args.MakeArgString(TC.getDefaultUniversalArchName())); + + // 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 + // 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 (A->getOption().getKind() == Option::InputClass) { + const char *Value = A->getValue(); + 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)) { + if (!llvm::sys::path::is_absolute(Path.str())) { + SmallString<64> Directory(WorkDir->getValue()); + 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().hasFlag(options::LinkerInput)) { + // 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()); + 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(); + 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; + ActionList SplitInputs; + llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL; + for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { + types::ID InputType = Inputs[i].first; + const Arg *InputArg = Inputs[i].second; + + PL.clear(); + types::getCompilationPhases(InputType, PL); + + // 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 = PL[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 when final phase determined by binary name, rather than + // by a command-line argument with a corresponding Arg. + if (CCCIsCPP) + Diag(clang::diag::warn_drv_input_file_unused_by_cpp) + << InputArg->getAsString(Args) + << getPhaseName(InitialPhase); + // Special case '-E' warning on a previously preprocessed file to make + // more sense. + else 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 + << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""; + else + Diag(clang::diag::warn_drv_input_file_unused) + << InputArg->getAsString(Args) + << getPhaseName(InitialPhase) + << !!FinalPhaseArg + << FinalPhaseArg ? FinalPhaseArg->getOption().getName() : ""; + continue; + } + + // Build the pipeline for this file. + OwningPtr<Action> Current(new InputAction(*InputArg, InputType)); + for (llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases>::iterator + i = PL.begin(), e = PL.end(); i != e; ++i) { + phases::ID Phase = *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) == e && "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 && PL.size() == 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 = Input->getType(); + if (!Args.hasFlag(options::OPT_frewrite_includes, + options::OPT_fno_rewrite_includes, false)) + OutputTy = types::getPreprocessedType(OutputTy); + assert(OutputTy != types::TY_INVALID && + "Cannot preprocess this input type!"); + } + return new PreprocessJobAction(Input, OutputTy); + } + case phases::Precompile: { + types::ID OutputTy = types::TY_PCH; + if (Args.hasArg(options::OPT_fsyntax_only)) { + // Syntax checks should not emit a PCH file + OutputTy = types::TY_Nothing; + } + return new PrecompileJobAction(Input, OutputTy); + } + 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 (Args.hasArg(options::OPT_module_file_info)) { + return new CompileJobAction(Input, types::TY_ModuleFile); + } 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(); + 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().hasFlag(options::NoArgumentUnused)) + 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 (Opt.getKind() == Option::FlagClass) { + 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 (TC->useIntegratedAs() && + !C.getArgs().hasArg(options::OPT_save_temps) && + isa<AssembleJobAction>(JA) && + Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) { + const Tool *Compiler = + TC->SelectTool(cast<JobAction>(**Inputs->begin())); + if (!Compiler) + return NULL; + if (Compiler->hasIntegratedAssembler()) { + Inputs = &(*Inputs)[0]->getInputs(); + ToolForJob = Compiler; + } + } + + // Otherwise use the tool for the current job. + if (!ToolForJob) + ToolForJob = TC->SelectTool(*JA); + + // 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) && + !C.getArgs().hasArg(options::OPT_rewrite_objc) && + 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(); + Result = InputInfo(Name, A->getType(), Name); + } else + Result = InputInfo(&Input, A->getType(), ""); + return; + } + + if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) { + const ToolChain *TC; + const char *ArchName = BAA->getArchName(); + + if (ArchName) + TC = &getToolChain(C.getArgs(), ArchName); + else + TC = &C.getDefaultToolChain(); + + 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); + if (!T) + return; + + // 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 and verify 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) || 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(), &JA); + } + + // Default to writing to stdout? + if (AtTopLevel && !CCGenDiagnostics && + (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile)) + 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 file conflicts with the input file, + // then avoid overwriting input file. + if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) && + NamedOutput == BaseName) { + + bool SameFile = false; + SmallString<256> Result; + llvm::sys::fs::current_path(Result); + llvm::sys::path::append(Result, BaseName); + llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile); + // Must share the same path to conflict. + if (SameFile) { + 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()), &JA); + } else { + return C.addResultFile(NamedOutput, &JA); + } +} + +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 looking for file 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; +} + +std::string Driver::GetProgramPath(const char *Name, + const ToolChain &TC) 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 looking for program paths. + for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(), + ie = PrefixDirs.end(); it != ie; ++it) { + bool IsDirectory; + if (!llvm::sys::fs::is_directory(*it, IsDirectory) && IsDirectory) { + llvm::sys::Path P(*it); + P.appendComponent(TargetSpecificExecutable); + if (P.canExecute()) return P.str(); + P.eraseComponent(); + P.appendComponent(Name); + if (P.canExecute()) return P.str(); + } else { + llvm::sys::Path P(*it + Name); + if (P.canExecute()) 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 (P.canExecute()) return P.str(); + P.eraseComponent(); + P.appendComponent(Name); + if (P.canExecute()) 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_unable_to_make_temp) << Error; + return ""; + } + + // FIXME: Grumble, makeUnique sometimes leaves the file around!? PR3837. + P.eraseFromDisk(false, 0); + + if (Suffix) + 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(); + + 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( + tools::darwin::getArchTypeForDarwinArchName(DarwinArchName)); + return Target; + } + + // Handle the Darwin '-arch' flag. + if (Arg *A = Args.getLastArg(options::OPT_arch)) { + llvm::Triple::ArchType DarwinArch + = tools::darwin::getArchTypeForDarwinArchName(A->getValue()); + if (DarwinArch != llvm::Triple::UnknownArch) + Target.setArch(DarwinArch); + } + } + + // Handle pseudo-target flags '-EL' and '-EB'. + if (Arg *A = Args.getLastArg(options::OPT_EL, options::OPT_EB)) { + if (A->getOption().matches(options::OPT_EL)) { + if (Target.getArch() == llvm::Triple::mips) + Target.setArch(llvm::Triple::mipsel); + else if (Target.getArch() == llvm::Triple::mips64) + Target.setArch(llvm::Triple::mips64el); + } else { + if (Target.getArch() == llvm::Triple::mipsel) + Target.setArch(llvm::Triple::mips); + else if (Target.getArch() == llvm::Triple::mips64el) + Target.setArch(llvm::Triple::mips64); + } + } + + // 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, Args); + 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::Bitrig: + TC = new toolchains::Bitrig(*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, Args); + 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, Args); + 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, Args); + break; + } + // If Hexagon is configured as an OSless target + if (Target.getArch() == llvm::Triple::hexagon) { + TC = new toolchains::Hexagon_TC(*this, Target, Args); + break; + } + TC = new toolchains::Generic_GCC(*this, Target, Args); + break; + } + } + return *TC; +} + +bool Driver::ShouldUseClangCompiler(const JobAction &JA) const { + // Check if user requested no clang, or clang doesn't understand this type (we + // only handle single inputs for now). + if (JA.size() != 1 || + !types::isAcceptedByClang((*JA.begin())->getType())) + return false; + + // Otherwise make sure this is an action clang understands. + if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) && + !isa<CompileJobAction>(JA)) + 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/contrib/llvm/tools/clang/lib/Driver/DriverOptions.cpp b/contrib/llvm/tools/clang/lib/Driver/DriverOptions.cpp new file mode 100644 index 0000000..3925b8a --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/DriverOptions.cpp @@ -0,0 +1,45 @@ +//===--- 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; + +#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; +#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ + HELPTEXT, METAVAR) +#include "clang/Driver/Options.inc" +#undef OPTION +#undef PREFIX + +static const OptTable::Info InfoTable[] = { +#define PREFIX(NAME, VALUE) +#define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, FLAGS, PARAM, \ + HELPTEXT, METAVAR) \ + { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, 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/contrib/llvm/tools/clang/lib/Driver/InputInfo.h b/contrib/llvm/tools/clang/lib/Driver/InputInfo.h new file mode 100644 index 0000000..a243d32 --- /dev/null +++ b/contrib/llvm/tools/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/Arg.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/contrib/llvm/tools/clang/lib/Driver/Job.cpp b/contrib/llvm/tools/clang/lib/Driver/Job.cpp new file mode 100644 index 0000000..8c46705 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Job.cpp @@ -0,0 +1,40 @@ +//===--- 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/contrib/llvm/tools/clang/lib/Driver/OptTable.cpp b/contrib/llvm/tools/clang/lib/Driver/OptTable.cpp new file mode 100644 index 0000000..20214a6 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/OptTable.cpp @@ -0,0 +1,388 @@ +//===--- 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 "clang/Driver/Options.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.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; + + for (const char * const *APre = A.Prefixes, + * const *BPre = B.Prefixes; + *APre != 0 && *BPre != 0; ++APre, ++BPre) { + if (int N = StrCmpOptionName(*APre, *BPre)) + 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), + TheInputOptionID(0), + TheUnknownOptionID(0), + FirstSearchableIndex(0) +{ + // Explicitly zero initialize the error to work around a bug in array + // value-initialization on MinGW with gcc 4.3.5. + + // 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(!TheInputOptionID && "Cannot have multiple input options!"); + TheInputOptionID = getInfo(i + 1).ID; + } else if (Kind == Option::UnknownClass) { + assert(!TheUnknownOptionID && "Cannot have multiple unknown options!"); + TheUnknownOptionID = getInfo(i + 1).ID; + } 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 + + // Build prefixes. + for (unsigned i = FirstSearchableIndex+1, e = getNumOptions(); i != e; ++i) { + if (const char *const *P = getInfo(i).Prefixes) { + for (; *P != 0; ++P) { + PrefixesUnion.insert(*P); + } + } + } + + // Build prefix chars. + for (llvm::StringSet<>::const_iterator I = PrefixesUnion.begin(), + E = PrefixesUnion.end(); I != E; ++I) { + StringRef Prefix = I->getKey(); + for (StringRef::const_iterator C = Prefix.begin(), CE = Prefix.end(); + C != CE; ++C) + if (std::find(PrefixChars.begin(), PrefixChars.end(), *C) + == PrefixChars.end()) + PrefixChars.push_back(*C); + } +} + +OptTable::~OptTable() { +} + +const Option OptTable::getOption(OptSpecifier Opt) const { + unsigned id = Opt.getID(); + if (id == 0) + return Option(0, 0); + assert((unsigned) (id - 1) < getNumOptions() && "Invalid ID."); + return Option(&getInfo(id), this); +} + +static bool isInput(const llvm::StringSet<> &Prefixes, StringRef Arg) { + if (Arg == "-") + return true; + for (llvm::StringSet<>::const_iterator I = Prefixes.begin(), + E = Prefixes.end(); I != E; ++I) + if (Arg.startswith(I->getKey())) + return false; + return true; +} + +/// \returns Matched size. 0 means no match. +static unsigned matchOption(const OptTable::Info *I, StringRef Str) { + for (const char * const *Pre = I->Prefixes; *Pre != 0; ++Pre) { + StringRef Prefix(*Pre); + if (Str.startswith(Prefix) && Str.substr(Prefix.size()).startswith(I->Name)) + return Prefix.size() + StringRef(I->Name).size(); + } + return 0; +} + +Arg *OptTable::ParseOneArg(const ArgList &Args, unsigned &Index) const { + unsigned Prev = Index; + const char *Str = Args.getArgString(Index); + + // Anything that doesn't start with PrefixesUnion is an input, as is '-' + // itself. + if (isInput(PrefixesUnion, Str)) + return new Arg(getOption(TheInputOptionID), Str, Index++, Str); + + const Info *Start = OptionInfos + FirstSearchableIndex; + const Info *End = OptionInfos + getNumOptions(); + StringRef Name = StringRef(Str).ltrim(PrefixChars); + + // Search for the first next option which could be a prefix. + Start = std::lower_bound(Start, End, Name.data()); + + // 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) { + unsigned ArgSize = 0; + // Scan for first option which is a proper prefix. + for (; Start != End; ++Start) + if ((ArgSize = matchOption(Start, Str))) + break; + if (Start == End) + break; + + // See if this option matches. + if (Arg *A = Option(Start, this).accept(Args, Index, ArgSize)) + return A; + + // Otherwise, see if this argument was missing values. + if (Prev != Index) + return 0; + } + + return new Arg(getOption(TheUnknownOptionID), Str, 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) { + const Option O = Opts.getOption(Id); + std::string Name = O.getPrefixedName(); + + // Add metavar, if used. + switch (O.getKind()) { + 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, unsigned short FlagsToInclude, + unsigned short FlagsToExclude) 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 ((FlagsToInclude && !(getInfo(Id).Flags & FlagsToInclude)) || + getInfo(Id).Flags & FlagsToExclude) + 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/contrib/llvm/tools/clang/lib/Driver/Option.cpp b/contrib/llvm/tools/clang/lib/Driver/Option.cpp new file mode 100644 index 0000000..dbc61ea --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Option.cpp @@ -0,0 +1,200 @@ +//===--- 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/ADT/Twine.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/raw_ostream.h" +#include <algorithm> +#include <cassert> +using namespace clang::driver; + +Option::Option(const OptTable::Info *info, const OptTable *owner) + : Info(info), Owner(owner) { + + // Multi-level aliases are not supported, and alias options cannot + // have groups. This just simplifies option tracking, it is not an + // inherent limitation. + assert((!Info || !getAlias().isValid() || (!getAlias().getAlias().isValid() && + !getGroup().isValid())) && + "Multi-level aliases and aliases with groups are unsupported."); +} + +Option::~Option() { +} + +void Option::dump() const { + llvm::errs() << "<"; + switch (getKind()) { +#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() << " Prefixes:["; + for (const char * const *Pre = Info->Prefixes; *Pre != 0; ++Pre) { + llvm::errs() << '"' << *Pre << (*(Pre + 1) == 0 ? "\"" : "\", "); + } + llvm::errs() << ']'; + + llvm::errs() << " Name:\"" << getName() << '"'; + + const Option Group = getGroup(); + if (Group.isValid()) { + llvm::errs() << " Group:"; + Group.dump(); + } + + const Option Alias = getAlias(); + if (Alias.isValid()) { + llvm::errs() << " Alias:"; + Alias.dump(); + } + + if (getKind() == MultiArgClass) + llvm::errs() << " NumArgs:" << getNumArgs(); + + llvm::errs() << ">\n"; +} + +bool Option::matches(OptSpecifier Opt) const { + // Aliases are never considered in matching, look through them. + const Option Alias = getAlias(); + if (Alias.isValid()) + return Alias.matches(Opt); + + // Check exact match. + if (getID() == Opt.getID()) + return true; + + const Option Group = getGroup(); + if (Group.isValid()) + return Group.matches(Opt); + return false; +} + +Arg *Option::accept(const ArgList &Args, + unsigned &Index, + unsigned ArgSize) const { + const Option &UnaliasedOption = getUnaliasedOption(); + StringRef Spelling; + // If the option was an alias, get the spelling from the unaliased one. + if (getID() == UnaliasedOption.getID()) { + Spelling = StringRef(Args.getArgString(Index), ArgSize); + } else { + Spelling = Args.MakeArgString(Twine(UnaliasedOption.getPrefix()) + + Twine(UnaliasedOption.getName())); + } + + switch (getKind()) { + case FlagClass: + if (ArgSize != strlen(Args.getArgString(Index))) + return 0; + + return new Arg(UnaliasedOption, Spelling, Index++); + case JoinedClass: { + const char *Value = Args.getArgString(Index) + ArgSize; + return new Arg(UnaliasedOption, Spelling, Index++, Value); + } + case CommaJoinedClass: { + // Always matches. + const char *Str = Args.getArgString(Index) + ArgSize; + Arg *A = new Arg(UnaliasedOption, Spelling, 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; + } + case SeparateClass: + // Matches iff this is an exact match. + // FIXME: Avoid strlen. + if (ArgSize != strlen(Args.getArgString(Index))) + return 0; + + Index += 2; + if (Index > Args.getNumInputArgStrings()) + return 0; + + return new Arg(UnaliasedOption, Spelling, + Index - 2, Args.getArgString(Index - 1)); + case MultiArgClass: { + // Matches iff this is an exact match. + // FIXME: Avoid strlen. + if (ArgSize != strlen(Args.getArgString(Index))) + return 0; + + Index += 1 + getNumArgs(); + if (Index > Args.getNumInputArgStrings()) + return 0; + + Arg *A = new Arg(UnaliasedOption, Spelling, Index - 1 - getNumArgs(), + Args.getArgString(Index - getNumArgs())); + for (unsigned i = 1; i != getNumArgs(); ++i) + A->getValues().push_back(Args.getArgString(Index - getNumArgs() + i)); + return A; + } + case JoinedOrSeparateClass: { + // If this is not an exact match, it is a joined arg. + // FIXME: Avoid strlen. + if (ArgSize != strlen(Args.getArgString(Index))) { + const char *Value = Args.getArgString(Index) + ArgSize; + return new Arg(*this, Spelling, Index++, Value); + } + + // Otherwise it must be separate. + Index += 2; + if (Index > Args.getNumInputArgStrings()) + return 0; + + return new Arg(UnaliasedOption, Spelling, + Index - 2, Args.getArgString(Index - 1)); + } + case JoinedAndSeparateClass: + // Always matches. + Index += 2; + if (Index > Args.getNumInputArgStrings()) + return 0; + + return new Arg(UnaliasedOption, Spelling, Index - 2, + Args.getArgString(Index - 2) + ArgSize, + Args.getArgString(Index - 1)); + default: + llvm_unreachable("Invalid option kind!"); + } +} diff --git a/contrib/llvm/tools/clang/lib/Driver/Phases.cpp b/contrib/llvm/tools/clang/lib/Driver/Phases.cpp new file mode 100644 index 0000000..155e53b --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Phases.cpp @@ -0,0 +1,26 @@ +//===--- 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/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.h b/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.h new file mode 100644 index 0000000..e61f15a --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/SanitizerArgs.h @@ -0,0 +1,216 @@ +//===--- SanitizerArgs.h - Arguments for sanitizer tools -------*- 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_SANITIZERARGS_H_ +#define CLANG_LIB_DRIVER_SANITIZERARGS_H_ + +#include "clang/Driver/Arg.h" +#include "clang/Driver/ArgList.h" +#include "clang/Driver/Driver.h" +#include "clang/Driver/DriverDiagnostic.h" +#include "clang/Driver/Options.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/Support/Path.h" + +namespace clang { +namespace driver { + +class SanitizerArgs { + /// Assign ordinals to sanitizer flags. We'll use the ordinal values as + /// bit positions within \c Kind. + enum SanitizeOrdinal { +#define SANITIZER(NAME, ID) SO_##ID, +#include "clang/Basic/Sanitizers.def" + SO_Count + }; + + /// Bugs to catch at runtime. + enum SanitizeKind { +#define SANITIZER(NAME, ID) ID = 1 << SO_##ID, +#define SANITIZER_GROUP(NAME, ID, ALIAS) ID = ALIAS, +#include "clang/Basic/Sanitizers.def" + NeedsAsanRt = Address, + NeedsTsanRt = Thread, + NeedsMsanRt = Memory, + NeedsUbsanRt = Undefined | Integer, + NotAllowedWithTrap = Vptr + }; + unsigned Kind; + std::string BlacklistFile; + bool MsanTrackOrigins; + bool AsanZeroBaseShadow; + bool UbsanTrapOnError; + + public: + SanitizerArgs() : Kind(0), BlacklistFile(""), MsanTrackOrigins(false), + AsanZeroBaseShadow(false), UbsanTrapOnError(false) {} + /// Parses the sanitizer arguments from an argument list. + SanitizerArgs(const Driver &D, const ArgList &Args); + + bool needsAsanRt() const { return Kind & NeedsAsanRt; } + bool needsTsanRt() const { return Kind & NeedsTsanRt; } + bool needsMsanRt() const { return Kind & NeedsMsanRt; } + bool needsUbsanRt() const { + if (UbsanTrapOnError) + return false; + return Kind & NeedsUbsanRt; + } + + bool sanitizesVptr() const { return Kind & Vptr; } + bool notAllowedWithTrap() const { return Kind & NotAllowedWithTrap; } + + void addArgs(const ArgList &Args, ArgStringList &CmdArgs) const { + if (!Kind) + return; + SmallString<256> SanitizeOpt("-fsanitize="); +#define SANITIZER(NAME, ID) \ + if (Kind & ID) \ + SanitizeOpt += NAME ","; +#include "clang/Basic/Sanitizers.def" + SanitizeOpt.pop_back(); + CmdArgs.push_back(Args.MakeArgString(SanitizeOpt)); + if (!BlacklistFile.empty()) { + SmallString<64> BlacklistOpt("-fsanitize-blacklist="); + BlacklistOpt += BlacklistFile; + CmdArgs.push_back(Args.MakeArgString(BlacklistOpt)); + } + + if (MsanTrackOrigins) + CmdArgs.push_back(Args.MakeArgString("-fsanitize-memory-track-origins")); + + if (AsanZeroBaseShadow) + CmdArgs.push_back(Args.MakeArgString( + "-fsanitize-address-zero-base-shadow")); + } + + private: + /// Parse a single value from a -fsanitize= or -fno-sanitize= value list. + /// Returns OR of members of the \c SanitizeKind enumeration, or \c 0 + /// if \p Value is not known. + static unsigned parse(const char *Value) { + unsigned ParsedKind = llvm::StringSwitch<SanitizeKind>(Value) +#define SANITIZER(NAME, ID) .Case(NAME, ID) +#define SANITIZER_GROUP(NAME, ID, ALIAS) .Case(NAME, ID) +#include "clang/Basic/Sanitizers.def" + .Default(SanitizeKind()); + // Assume -fsanitize=address implies -fsanitize=init-order. + // FIXME: This should be either specified in Sanitizers.def, or go away when + // we get rid of "-fsanitize=init-order" flag at all. + if (ParsedKind & Address) + ParsedKind |= InitOrder; + return ParsedKind; + } + + /// Parse a -fsanitize= or -fno-sanitize= argument's values, diagnosing any + /// invalid components. + static unsigned parse(const Driver &D, const Arg *A, bool DiagnoseErrors) { + unsigned Kind = 0; + for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) { + if (unsigned K = parse(A->getValue(I))) + Kind |= K; + else if (DiagnoseErrors) + D.Diag(diag::err_drv_unsupported_option_argument) + << A->getOption().getName() << A->getValue(I); + } + return Kind; + } + + /// Parse a single flag of the form -f[no]sanitize=, or + /// -f*-sanitizer. Sets the masks defining required change of Kind value. + /// Returns true if the flag was parsed successfully. + static bool parse(const Driver &D, const ArgList &Args, const Arg *A, + unsigned &Add, unsigned &Remove, bool DiagnoseErrors) { + Add = 0; + Remove = 0; + const char *DeprecatedReplacement = 0; + if (A->getOption().matches(options::OPT_faddress_sanitizer)) { + Add = Address; + DeprecatedReplacement = "-fsanitize=address"; + } else if (A->getOption().matches(options::OPT_fno_address_sanitizer)) { + Remove = Address; + DeprecatedReplacement = "-fno-sanitize=address"; + } else if (A->getOption().matches(options::OPT_fthread_sanitizer)) { + Add = Thread; + DeprecatedReplacement = "-fsanitize=thread"; + } else if (A->getOption().matches(options::OPT_fno_thread_sanitizer)) { + Remove = Thread; + DeprecatedReplacement = "-fno-sanitize=thread"; + } else if (A->getOption().matches(options::OPT_fcatch_undefined_behavior)) { + Add = UndefinedTrap; + DeprecatedReplacement = + "-fsanitize=undefined-trap -fsanitize-undefined-trap-on-error"; + } else if (A->getOption().matches(options::OPT_fbounds_checking) || + A->getOption().matches(options::OPT_fbounds_checking_EQ)) { + Add = Bounds; + DeprecatedReplacement = "-fsanitize=bounds"; + } else if (A->getOption().matches(options::OPT_fsanitize_EQ)) { + Add = parse(D, A, DiagnoseErrors); + } else if (A->getOption().matches(options::OPT_fno_sanitize_EQ)) { + Remove = parse(D, A, DiagnoseErrors); + } else { + // Flag is not relevant to sanitizers. + return false; + } + // If this is a deprecated synonym, produce a warning directing users + // towards the new spelling. + if (DeprecatedReplacement && DiagnoseErrors) + D.Diag(diag::warn_drv_deprecated_arg) + << A->getAsString(Args) << DeprecatedReplacement; + return true; + } + + /// Produce an argument string from ArgList \p Args, which shows how it + /// provides a sanitizer kind in \p Mask. For example, the argument list + /// "-fsanitize=thread,vptr -faddress-sanitizer" with mask \c NeedsUbsanRt + /// would produce "-fsanitize=vptr". + static std::string lastArgumentForKind(const Driver &D, const ArgList &Args, + unsigned Kind) { + for (ArgList::const_reverse_iterator I = Args.rbegin(), E = Args.rend(); + I != E; ++I) { + unsigned Add, Remove; + if (parse(D, Args, *I, Add, Remove, false) && + (Add & Kind)) + return describeSanitizeArg(Args, *I, Kind); + Kind &= ~Remove; + } + llvm_unreachable("arg list didn't provide expected value"); + } + + /// Produce an argument string from argument \p A, which shows how it provides + /// a value in \p Mask. For instance, the argument + /// "-fsanitize=address,alignment" with mask \c NeedsUbsanRt would produce + /// "-fsanitize=alignment". + static std::string describeSanitizeArg(const ArgList &Args, const Arg *A, + unsigned Mask) { + if (!A->getOption().matches(options::OPT_fsanitize_EQ)) + return A->getAsString(Args); + + for (unsigned I = 0, N = A->getNumValues(); I != N; ++I) + if (parse(A->getValue(I)) & Mask) + return std::string("-fsanitize=") + A->getValue(I); + + llvm_unreachable("arg didn't provide expected value"); + } + + static bool getDefaultBlacklistForKind(const Driver &D, unsigned Kind, + std::string &BLPath) { + // For now, specify the default blacklist location for ASan only. + if (Kind & NeedsAsanRt) { + SmallString<64> Path(D.ResourceDir); + llvm::sys::path::append(Path, "asan_blacklist.txt"); + BLPath = Path.str(); + return true; + } + return false; + } +}; + +} // namespace driver +} // namespace clang + +#endif // CLANG_LIB_DRIVER_SANITIZERARGS_H_ diff --git a/contrib/llvm/tools/clang/lib/Driver/Tool.cpp b/contrib/llvm/tools/clang/lib/Driver/Tool.cpp new file mode 100644 index 0000000..b93864f --- /dev/null +++ b/contrib/llvm/tools/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/contrib/llvm/tools/clang/lib/Driver/ToolChain.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChain.cpp new file mode 100644 index 0000000..19270b2 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChain.cpp @@ -0,0 +1,400 @@ +//===--- 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 "Tools.h" +#include "clang/Driver/ToolChain.h" +#include "clang/Basic/ObjCRuntime.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/Option.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, + const ArgList &A) + : D(D), Triple(T), Args(A) { +} + +ToolChain::~ToolChain() { +} + +const Driver &ToolChain::getDriver() const { + return D; +} + +bool ToolChain::useIntegratedAs() const { + return Args.hasFlag(options::OPT_integrated_as, + options::OPT_no_integrated_as, + IsIntegratedAssemblerDefault()); +} + +std::string ToolChain::getDefaultUniversalArchName() const { + // In universal driver terms, the arch name accepted by -arch isn't exactly + // the same as the ones that appear in the triple. Roughly speaking, this is + // an inverse of the darwin::getArchTypeForDarwinArchName() function, but the + // only interesting special case is powerpc. + switch (Triple.getArch()) { + case llvm::Triple::ppc: + return "ppc"; + case llvm::Triple::ppc64: + return "ppc64"; + default: + return Triple.getArchName(); + } +} + +bool ToolChain::IsUnwindTablesDefault() const { + return false; +} + +Tool *ToolChain::getClang() const { + if (!Clang) + Clang.reset(new tools::Clang(*this)); + return Clang.get(); +} + +Tool *ToolChain::buildAssembler() const { + return new tools::ClangAs(*this); +} + +Tool *ToolChain::buildLinker() const { + llvm_unreachable("Linking is not supported by this toolchain"); +} + +Tool *ToolChain::getAssemble() const { + if (!Assemble) + Assemble.reset(buildAssembler()); + return Assemble.get(); +} + +Tool *ToolChain::getClangAs() const { + if (!Assemble) + Assemble.reset(new tools::ClangAs(*this)); + return Assemble.get(); +} + +Tool *ToolChain::getLink() const { + if (!Link) + Link.reset(buildLinker()); + return Link.get(); +} + +Tool *ToolChain::getTool(Action::ActionClass AC) const { + switch (AC) { + case Action::AssembleJobClass: + return getAssemble(); + + case Action::LinkJobClass: + return getLink(); + + case Action::InputClass: + case Action::BindArchClass: + case Action::LipoJobClass: + case Action::DsymutilJobClass: + case Action::VerifyJobClass: + llvm_unreachable("Invalid tool kind."); + + case Action::CompileJobClass: + case Action::PrecompileJobClass: + case Action::PreprocessJobClass: + case Action::AnalyzeJobClass: + case Action::MigrateJobClass: + return getClang(); + } + + llvm_unreachable("Invalid tool kind."); +} + +Tool *ToolChain::SelectTool(const JobAction &JA) const { + if (getDriver().ShouldUseClangCompiler(JA)) + return getClang(); + Action::ActionClass AC = JA.getKind(); + if (AC == Action::AssembleJobClass && useIntegratedAs()) + return getClangAs(); + return getTool(AC); +} + +std::string ToolChain::GetFilePath(const char *Name) const { + return D.GetFilePath(Name, *this); + +} + +std::string ToolChain::GetProgramPath(const char *Name) const { + return D.GetProgramPath(Name, *this); +} + +types::ID ToolChain::LookupTypeForExtension(const char *Ext) const { + return types::lookupTypeForExtension(Ext); +} + +bool ToolChain::HasNativeLLVMSupport() const { + return false; +} + +ObjCRuntime ToolChain::getDefaultObjCRuntime(bool isNonFragile) const { + return ObjCRuntime(isNonFragile ? ObjCRuntime::GNUstep : ObjCRuntime::GCC, + VersionTuple()); +} + +/// 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(); + } + + 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(); + } 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("armv6m", "armv6-m", "cortex-m0") + .Cases("armv7", "armv7a", "armv7-a", "cortex-a8") + .Cases("armv7l", "armv7-l", "cortex-a8") + .Cases("armv7f", "armv7-f", "cortex-a9-mp") + .Cases("armv7s", "armv7-s", "swift") + .Cases("armv7r", "armv7-r", "cortex-r4") + .Cases("armv7m", "armv7-m", "cortex-m3") + .Cases("armv7em", "armv7e-m", "cortex-m4") + .Case("ep9312", "ep9312") + .Case("iwmmxt", "iwmmxt") + .Case("xscale", "xscale") + // 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-a5", "cortex-a7", "cortex-a8", "v7") + .Cases("cortex-a9", "cortex-a15", "v7") + .Case("cortex-r5", "v7r") + .Case("cortex-m0", "v6m") + .Case("cortex-m3", "v7m") + .Case("cortex-m4", "v7em") + .Case("cortex-a9-mp", "v7f") + .Case("swift", "v7s") + .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.startswith("v6m") || + (Suffix.startswith("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. +} + +void ToolChain::addClangTargetOptions(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { +} + +ToolChain::RuntimeLibType ToolChain::GetRuntimeLibType( + const ArgList &Args) const +{ + if (Arg *A = Args.getLastArg(options::OPT_rtlib_EQ)) { + StringRef Value = A->getValue(); + 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(); + 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"); +} + +bool ToolChain::AddFastMathRuntimeIfAvailable(const ArgList &Args, + ArgStringList &CmdArgs) const { + // Check if -ffast-math or -funsafe-math is enabled. + Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_fno_fast_math, + options::OPT_funsafe_math_optimizations, + options::OPT_fno_unsafe_math_optimizations); + + if (!A || A->getOption().getID() == options::OPT_fno_fast_math || + A->getOption().getID() == options::OPT_fno_unsafe_math_optimizations) + return false; + + // If crtfastmath.o exists add it to the arguments. + std::string Path = GetFilePath("crtfastmath.o"); + if (Path == "crtfastmath.o") // Not found. + return false; + + CmdArgs.push_back(Args.MakeArgString(Path)); + return true; +} diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp b/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp new file mode 100644 index 0000000..bcfe51e --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains.cpp @@ -0,0 +1,2446 @@ +//===--- 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 "SanitizerArgs.h" +#include "clang/Basic/ObjCRuntime.h" +#include "clang/Basic/Version.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/OptTable.h" +#include "clang/Driver/Option.h" +#include "clang/Driver/Options.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/ADT/StringExtras.h" +#include "llvm/ADT/StringSwitch.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/Support/Path.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Support/system_error.h" + +// FIXME: This needs to be listed last until we fix the broken include guards +// in these files and the LLVM config.h files. +#include "clang/Config/config.h" // for GCC_INSTALL_PREFIX + +#include <cstdlib> // ::getenv + +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, const ArgList &Args) + : ToolChain(D, Triple, Args), TargetInitialized(false) +{ + // 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; + + // Compute the initial iOS version from the triple + Triple.getiOSVersion(Major, Minor, Micro); + llvm::raw_string_ostream(iOSVersionMin) + << Major << '.' << Minor << '.' << Micro; +} + +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; +} + +/// Darwin provides an ARC runtime starting in MacOS X 10.7 and iOS 5.0. +ObjCRuntime Darwin::getDefaultObjCRuntime(bool isNonFragile) const { + if (isTargetIPhoneOS()) + return ObjCRuntime(ObjCRuntime::iOS, TargetVersion); + if (isNonFragile) + return ObjCRuntime(ObjCRuntime::MacOSX, TargetVersion); + return ObjCRuntime(ObjCRuntime::FragileMacOSX, TargetVersion); +} + +/// 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("armv6m", "armv6m") + .Case("armv5tej", "armv5") + .Case("xscale", "xscale") + .Case("armv4t", "armv4t") + .Case("armv7", "armv7") + .Cases("armv7a", "armv7-a", "armv7") + .Cases("armv7r", "armv7-r", "armv7") + .Cases("armv7em", "armv7e-m", "armv7em") + .Cases("armv7f", "armv7-f", "armv7f") + .Cases("armv7k", "armv7-k", "armv7k") + .Cases("armv7m", "armv7-m", "armv7m") + .Cases("armv7s", "armv7-s", "armv7s") + .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", "armv6") + .Case("cortex-m0", "armv6m") + .Cases("cortex-a8", "cortex-r4", "cortex-a9", "cortex-a15", "armv7") + .Case("cortex-a9-mp", "armv7f") + .Case("cortex-m3", "armv7m") + .Case("cortex-m4", "armv7em") + .Case("swift", "armv7s") + .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())) + return Arch; + + if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) + if (const char *Arch = GetArmArchForMCpu(A->getValue())) + return Arch; + + return "arm"; + } + } +} + +Darwin::~Darwin() { +} + +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::getTool(Action::ActionClass AC) const { + switch (AC) { + case Action::LipoJobClass: + if (!Lipo) + Lipo.reset(new tools::darwin::Lipo(*this)); + return Lipo.get(); + case Action::DsymutilJobClass: + if (!Dsymutil) + Dsymutil.reset(new tools::darwin::Dsymutil(*this)); + return Dsymutil.get(); + case Action::VerifyJobClass: + if (!VerifyDebug) + VerifyDebug.reset(new tools::darwin::VerifyDebug(*this)); + return VerifyDebug.get(); + default: + return ToolChain::getTool(AC); + } +} + +Tool *Darwin::buildLinker() const { + return new tools::darwin::Link(*this); +} + +Tool *Darwin::buildAssembler() const { + return new tools::darwin::Assemble(*this); +} + +DarwinClang::DarwinClang(const Driver &D, const llvm::Triple& Triple, + const ArgList &Args) + : Darwin(D, Triple, Args) +{ + 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); +} + +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"; + else + s += "macosx"; + s += ".a"; + + CmdArgs.push_back(Args.MakeArgString(s)); +} + +void DarwinClang::AddLinkRuntimeLib(const ArgList &Args, + ArgStringList &CmdArgs, + const char *DarwinStaticLib, + bool AlwaysLink) 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 (unless + // we explicitly force linking with this library). + bool Exists; + if (AlwaysLink || (!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() << "darwin"; + return; + } + + // Darwin doesn't support real static executables, don't link any runtime + // libraries with -static. + if (Args.hasArg(options::OPT_static) || + Args.hasArg(options::OPT_fapple_kext) || + Args.hasArg(options::OPT_mkernel)) + 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"); + } + } + + SanitizerArgs Sanitize(getDriver(), Args); + + // Add Ubsan runtime library, if required. + if (Sanitize.needsUbsanRt()) { + if (isTargetIPhoneOS()) { + getDriver().Diag(diag::err_drv_clang_unsupported_per_platform) + << "-fsanitize=undefined"; + } else { + AddLinkRuntimeLib(Args, CmdArgs, "libclang_rt.ubsan_osx.a", true); + + // The Ubsan runtime library requires C++. + AddCXXStdlibLibArgs(Args, CmdArgs); + } + } + + // Add ASAN runtime library, if required. Dynamic libraries and bundles + // should not be linked with the runtime library. + if (Sanitize.needsAsanRt()) { + if (isTargetIPhoneOS() && !isTargetIOSSimulator()) { + getDriver().Diag(diag::err_drv_clang_unsupported_per_platform) + << "-fsanitize=address"; + } else { + if (Args.hasArg(options::OPT_dynamiclib) || + Args.hasArg(options::OPT_bundle)) { + // Assume the binary will provide the ASan runtime. + } else { + AddLinkRuntimeLib(Args, CmdArgs, + "libclang_rt.asan_osx_dynamic.dylib", true); + // The ASAN runtime library requires C++. + AddCXXStdlibLibArgs(Args, CmdArgs); + } + } + } + + // 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"); + } + } +} + +void Darwin::AddDeploymentTarget(DerivedArgList &Args) const { + const OptTable &Opts = getDriver().getOpts(); + + // Support allowing the SDKROOT environment variable used by xcrun and other + // Xcode tools to define the default sysroot, by making it the default for + // isysroot. + if (const Arg *A = Args.getLastArg(options::OPT_isysroot)) { + // Warn if the path does not exist. + bool Exists; + if (llvm::sys::fs::exists(A->getValue(), Exists) || !Exists) + getDriver().Diag(clang::diag::warn_missing_sysroot) << A->getValue(); + } else { + if (char *env = ::getenv("SDKROOT")) { + // We only use this value as the default if it is an absolute path, + // exists, and it is not the root path. + if (llvm::sys::path::is_absolute(env) && llvm::sys::fs::exists(env) && + StringRef(env) != "/") { + Args.append(Args.MakeSeparateArg( + 0, Opts.getOption(options::OPT_isysroot), env)); + } + } + } + + 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); + + 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(); + 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() && + (getDarwinArchName(Args) == "armv7" || + getDarwinArchName(Args) == "armv7s")) + iOSTarget = iOSVersionMin; + + // 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(), 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(), 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()); + 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"); + + // Use the newer cc_kext for iOS ARM after 6.0. + if (!isTargetIPhoneOS() || isTargetIOSSimulator() || + !isIPhoneOSVersionLT(6, 0)) { + P.appendComponent("libclang_rt.cc_kext.a"); + } else { + P.appendComponent("libclang_rt.cc_kext_ios5.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. + llvm::Triple::ArchType XarchArch = + tools::darwin::getArchTypeForDarwinArchName(A->getValue(0)); + if (!(XarchArch == getArch() || + (BoundArch && XarchArch == + tools::darwin::getArchTypeForDarwinArchName(BoundArch)))) + continue; + + Arg *OriginalArg = A; + unsigned Index = Args.getBaseArgs().MakeIndex(A->getValue(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().hasFlag(options::DriverOption)) { + 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().hasFlag(options::LinkerInput)) { + // 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(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()); + 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 == "armv6m") + DAL->AddJoinedArg(0, MArch, "armv6m"); + else if (Name == "armv7") + DAL->AddJoinedArg(0, MArch, "armv7a"); + else if (Name == "armv7em") + DAL->AddJoinedArg(0, MArch, "armv7em"); + else if (Name == "armv7f") + DAL->AddJoinedArg(0, MArch, "armv7f"); + else if (Name == "armv7k") + DAL->AddJoinedArg(0, MArch, "armv7k"); + else if (Name == "armv7m") + DAL->AddJoinedArg(0, MArch, "armv7m"); + else if (Name == "armv7s") + DAL->AddJoinedArg(0, MArch, "armv7s"); + + 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. + if (BoundArch) + AddDeploymentTarget(*DAL); + + // For iOS 6, undo the translation to add -static for -mkernel/-fapple-kext. + // FIXME: It would be far better to avoid inserting those -static arguments, + // but we can't check the deployment target in the translation code until + // it is set here. + if (isTargetIPhoneOS() && !isIPhoneOSVersionLT(6, 0)) { + for (ArgList::iterator it = DAL->begin(), ie = DAL->end(); it != ie; ) { + Arg *A = *it; + ++it; + if (A->getOption().getID() != options::OPT_mkernel && + A->getOption().getID() != options::OPT_fapple_kext) + continue; + assert(it != ie && "unexpected argument translation"); + A = *it; + assert(A->getOption().getID() == options::OPT_static && + "missing expected -static argument"); + it = DAL->getArgs().erase(it); + } + } + + // Validate the C++ standard library choice. + CXXStdlibType Type = GetCXXStdlibType(*DAL); + if (Type == ToolChain::CST_Libcxx) { + // Check whether the target provides libc++. + StringRef where; + + // Complain about targetting iOS < 5.0 in any way. + if (isTargetIPhoneOS() && isIPhoneOSVersionLT(5, 0)) + where = "iOS 5.0"; + + if (where != StringRef()) { + getDriver().Diag(clang::diag::err_drv_invalid_libcxx_deployment) + << where; + } + } + + return DAL; +} + +bool Darwin::IsUnwindTablesDefault() const { + return getArch() == llvm::Triple::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); +} + +bool Darwin::isPICDefault() const { + return true; +} + +bool Darwin::isPICDefaultForced() const { + return getArch() == llvm::Triple::x86_64; +} + +bool Darwin::SupportsProfiling() const { + // Profiling instrumentation is only supported on x86. + return getArch() == llvm::Triple::x86 || getArch() == llvm::Triple::x86_64; +} + +bool Darwin::SupportsObjCGC() const { + // Garbage collection is supported everywhere except on iPhone OS. + return !isTargetIPhoneOS(); +} + +void Darwin::CheckObjCARC() const { + if (isTargetIPhoneOS() || !isMacosxVersionLT(10, 6)) + return; + getDriver().Diag(diag::err_arc_unsupported_on_toolchain); +} + +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 (size_t 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 Major < RHS.Major; + if (Minor != RHS.Minor) + return Minor < RHS.Minor; + if (Patch != RHS.Patch) { + // Note that versions without a specified patch sort higher than those with + // a patch. + if (RHS.Patch == -1) + return true; + if (Patch == -1) + return false; + + // Otherwise just sort on the patch itself. + return Patch < RHS.Patch; + } + if (PatchSuffix != RHS.PatchSuffix) { + // Sort empty suffixes higher. + if (RHS.PatchSuffix.empty()) + return true; + if (PatchSuffix.empty()) + return false; + + // Provide a lexicographic sort to make this a total ordering. + return PatchSuffix < RHS.PatchSuffix; + } + + // The versions are equal. + return false; +} + +static StringRef getGCCToolchainDir(const ArgList &Args) { + const Arg *A = Args.getLastArg(options::OPT_gcc_toolchain); + if (A) + return A->getValue(); + 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, Args, 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, Args, 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 AArch64LibDirs[] = { "/lib" }; + static const char *const AArch64Triples[] = { + "aarch64-none-linux-gnu", + "aarch64-linux-gnu" + }; + + static const char *const ARMLibDirs[] = { "/lib" }; + static const char *const ARMTriples[] = { + "arm-linux-gnueabi", + "arm-linux-androideabi" + }; + static const char *const ARMHFTriples[] = { + "arm-linux-gnueabihf", + }; + + 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", + "i386-redhat-linux6E", + "i686-redhat-linux", + "i586-redhat-linux", + "i386-redhat-linux", + "i586-suse-linux", + "i486-slackware-linux", + "i686-montavista-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", + "mipsel-linux-android" + }; + + static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" }; + static const char *const MIPS64Triples[] = { "mips64-linux-gnu" }; + static const char *const MIPS64ELLibDirs[] = { "/lib64", "/lib" }; + static const char *const MIPS64ELTriples[] = { "mips64el-linux-gnu" }; + + static const char *const PPCLibDirs[] = { "/lib32", "/lib" }; + static const char *const PPCTriples[] = { + "powerpc-linux-gnu", + "powerpc-unknown-linux-gnu", + "powerpc-linux-gnuspe", + "powerpc-suse-linux", + "powerpc-montavista-linuxspe" + }; + 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::aarch64: + LibDirs.append(AArch64LibDirs, AArch64LibDirs + + llvm::array_lengthof(AArch64LibDirs)); + TripleAliases.append( + AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples)); + MultiarchLibDirs.append( + AArch64LibDirs, AArch64LibDirs + llvm::array_lengthof(AArch64LibDirs)); + MultiarchTripleAliases.append( + AArch64Triples, AArch64Triples + llvm::array_lengthof(AArch64Triples)); + break; + case llvm::Triple::arm: + case llvm::Triple::thumb: + LibDirs.append(ARMLibDirs, ARMLibDirs + llvm::array_lengthof(ARMLibDirs)); + if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) { + TripleAliases.append( + ARMHFTriples, ARMHFTriples + llvm::array_lengthof(ARMHFTriples)); + } else { + 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)); + MultiarchLibDirs.append( + MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs)); + MultiarchTripleAliases.append( + MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples)); + break; + case llvm::Triple::mipsel: + LibDirs.append( + MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs)); + TripleAliases.append( + MIPSELTriples, MIPSELTriples + llvm::array_lengthof(MIPSELTriples)); + MultiarchLibDirs.append( + MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs)); + MultiarchTripleAliases.append( + MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples)); + break; + case llvm::Triple::mips64: + LibDirs.append( + MIPS64LibDirs, MIPS64LibDirs + llvm::array_lengthof(MIPS64LibDirs)); + TripleAliases.append( + MIPS64Triples, MIPS64Triples + llvm::array_lengthof(MIPS64Triples)); + MultiarchLibDirs.append( + MIPSLibDirs, MIPSLibDirs + llvm::array_lengthof(MIPSLibDirs)); + MultiarchTripleAliases.append( + MIPSTriples, MIPSTriples + llvm::array_lengthof(MIPSTriples)); + break; + case llvm::Triple::mips64el: + LibDirs.append( + MIPS64ELLibDirs, MIPS64ELLibDirs + llvm::array_lengthof(MIPS64ELLibDirs)); + TripleAliases.append( + MIPS64ELTriples, MIPS64ELTriples + llvm::array_lengthof(MIPS64ELTriples)); + MultiarchLibDirs.append( + MIPSELLibDirs, MIPSELLibDirs + llvm::array_lengthof(MIPSELLibDirs)); + MultiarchTripleAliases.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()); +} + +// FIXME: There is the same routine in the Tools.cpp. +static bool hasMipsN32ABIArg(const ArgList &Args) { + Arg *A = Args.getLastArg(options::OPT_mabi_EQ); + return A && (A->getValue() == StringRef("n32")); +} + +static StringRef getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch, + const ArgList &Args) { + if (TargetArch == llvm::Triple::x86_64 || + TargetArch == llvm::Triple::ppc64) + return "/64"; + + if (TargetArch == llvm::Triple::mips64 || + TargetArch == llvm::Triple::mips64el) { + if (hasMipsN32ABIArg(Args)) + return "/n32"; + else + return "/64"; + } + + return "/32"; +} + +void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple( + llvm::Triple::ArchType TargetArch, const ArgList &Args, + 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(), + + // The Freescale PPC SDK has the gcc libraries in + // <sysroot>/usr/lib/<triple>/x.y.z so have a look there as well. + "/" + 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 = getTargetMultiarchSuffix(TargetArch, Args); + 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, Args), GCCInstallation(getDriver(), Triple, Args) { + getProgramPaths().push_back(getDriver().getInstalledDir()); + if (getDriver().getInstalledDir() != getDriver().Dir) + getProgramPaths().push_back(getDriver().Dir); +} + +Generic_GCC::~Generic_GCC() { +} + +Tool *Generic_GCC::getTool(Action::ActionClass AC) const { + switch (AC) { + case Action::PreprocessJobClass: + if (!Preprocess) + Preprocess.reset(new tools::gcc::Preprocess(*this)); + return Preprocess.get(); + case Action::PrecompileJobClass: + if (!Precompile) + Precompile.reset(new tools::gcc::Precompile(*this)); + return Precompile.get(); + case Action::CompileJobClass: + if (!Compile) + Compile.reset(new tools::gcc::Compile(*this)); + return Compile.get(); + default: + return ToolChain::getTool(AC); + } +} + +Tool *Generic_GCC::buildAssembler() const { + return new tools::gcc::Assemble(*this); +} + +Tool *Generic_GCC::buildLinker() const { + return new tools::gcc::Link(*this); +} + +bool Generic_GCC::IsUnwindTablesDefault() const { + return getArch() == llvm::Triple::x86_64; +} + +bool Generic_GCC::isPICDefault() const { + return false; +} + +bool Generic_GCC::isPICDefaultForced() const { + return false; +} + +/// Hexagon Toolchain + +std::string Hexagon_TC::GetGnuDir(const std::string &InstalledDir) { + + // Locate the rest of the toolchain ... + if (strlen(GCC_INSTALL_PREFIX)) + return std::string(GCC_INSTALL_PREFIX); + + std::string InstallRelDir = InstalledDir + "/../../gnu"; + if (llvm::sys::fs::exists(InstallRelDir)) + return InstallRelDir; + + std::string PrefixRelDir = std::string(LLVM_PREFIX) + "/../gnu"; + if (llvm::sys::fs::exists(PrefixRelDir)) + return PrefixRelDir; + + return InstallRelDir; +} + +static void GetHexagonLibraryPaths( + const ArgList &Args, + const std::string Ver, + const std::string MarchString, + const std::string &InstalledDir, + ToolChain::path_list *LibPaths) +{ + bool buildingLib = Args.hasArg(options::OPT_shared); + + //---------------------------------------------------------------------------- + // -L Args + //---------------------------------------------------------------------------- + for (arg_iterator + it = Args.filtered_begin(options::OPT_L), + ie = Args.filtered_end(); + it != ie; + ++it) { + for (unsigned i = 0, e = (*it)->getNumValues(); i != e; ++i) + LibPaths->push_back((*it)->getValue(i)); + } + + //---------------------------------------------------------------------------- + // Other standard paths + //---------------------------------------------------------------------------- + const std::string MarchSuffix = "/" + MarchString; + const std::string G0Suffix = "/G0"; + const std::string MarchG0Suffix = MarchSuffix + G0Suffix; + const std::string RootDir = Hexagon_TC::GetGnuDir(InstalledDir) + "/"; + + // lib/gcc/hexagon/... + std::string LibGCCHexagonDir = RootDir + "lib/gcc/hexagon/"; + if (buildingLib) { + LibPaths->push_back(LibGCCHexagonDir + Ver + MarchG0Suffix); + LibPaths->push_back(LibGCCHexagonDir + Ver + G0Suffix); + } + LibPaths->push_back(LibGCCHexagonDir + Ver + MarchSuffix); + LibPaths->push_back(LibGCCHexagonDir + Ver); + + // lib/gcc/... + LibPaths->push_back(RootDir + "lib/gcc"); + + // hexagon/lib/... + std::string HexagonLibDir = RootDir + "hexagon/lib"; + if (buildingLib) { + LibPaths->push_back(HexagonLibDir + MarchG0Suffix); + LibPaths->push_back(HexagonLibDir + G0Suffix); + } + LibPaths->push_back(HexagonLibDir + MarchSuffix); + LibPaths->push_back(HexagonLibDir); +} + +Hexagon_TC::Hexagon_TC(const Driver &D, const llvm::Triple &Triple, + const ArgList &Args) + : Linux(D, Triple, Args) { + const std::string InstalledDir(getDriver().getInstalledDir()); + const std::string GnuDir = Hexagon_TC::GetGnuDir(InstalledDir); + + // Note: Generic_GCC::Generic_GCC adds InstalledDir and getDriver().Dir to + // program paths + const std::string BinDir(GnuDir + "/bin"); + if (llvm::sys::fs::exists(BinDir)) + getProgramPaths().push_back(BinDir); + + // Determine version of GCC libraries and headers to use. + const std::string HexagonDir(GnuDir + "/lib/gcc/hexagon"); + llvm::error_code ec; + GCCVersion MaxVersion= GCCVersion::Parse("0.0.0"); + for (llvm::sys::fs::directory_iterator di(HexagonDir, ec), de; + !ec && di != de; di = di.increment(ec)) { + GCCVersion cv = GCCVersion::Parse(llvm::sys::path::filename(di->path())); + if (MaxVersion < cv) + MaxVersion = cv; + } + GCCLibAndIncVersion = MaxVersion; + + ToolChain::path_list *LibPaths= &getFilePaths(); + + // Remove paths added by Linux toolchain. Currently Hexagon_TC really targets + // 'elf' OS type, so the Linux paths are not appropriate. When we actually + // support 'linux' we'll need to fix this up + LibPaths->clear(); + + GetHexagonLibraryPaths( + Args, + GetGCCLibAndIncVersion(), + GetTargetCPU(Args), + InstalledDir, + LibPaths); +} + +Hexagon_TC::~Hexagon_TC() { +} + +Tool *Hexagon_TC::buildAssembler() const { + return new tools::hexagon::Assemble(*this); +} + +Tool *Hexagon_TC::buildLinker() const { + return new tools::hexagon::Link(*this); +} + +void Hexagon_TC::AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + const Driver &D = getDriver(); + + if (DriverArgs.hasArg(options::OPT_nostdinc) || + DriverArgs.hasArg(options::OPT_nostdlibinc)) + return; + + llvm::sys::Path InstallDir(D.InstalledDir); + std::string Ver(GetGCCLibAndIncVersion()); + std::string GnuDir = Hexagon_TC::GetGnuDir(D.InstalledDir); + std::string HexagonDir(GnuDir + "/lib/gcc/hexagon/" + Ver); + addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include"); + addExternCSystemInclude(DriverArgs, CC1Args, HexagonDir + "/include-fixed"); + addExternCSystemInclude(DriverArgs, CC1Args, GnuDir + "/hexagon/include"); +} + +void Hexagon_TC::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + + if (DriverArgs.hasArg(options::OPT_nostdlibinc) || + DriverArgs.hasArg(options::OPT_nostdincxx)) + return; + + const Driver &D = getDriver(); + std::string Ver(GetGCCLibAndIncVersion()); + llvm::sys::Path IncludeDir(Hexagon_TC::GetGnuDir(D.InstalledDir)); + + IncludeDir.appendComponent("hexagon/include/c++/"); + IncludeDir.appendComponent(Ver); + addSystemInclude(DriverArgs, CC1Args, IncludeDir.str()); +} + +ToolChain::CXXStdlibType +Hexagon_TC::GetCXXStdlibType(const ArgList &Args) const { + Arg *A = Args.getLastArg(options::OPT_stdlib_EQ); + if (!A) + return ToolChain::CST_Libstdcxx; + + StringRef Value = A->getValue(); + if (Value != "libstdc++") { + getDriver().Diag(diag::err_drv_invalid_stdlib_name) + << A->getAsString(Args); + } + + return ToolChain::CST_Libstdcxx; +} + +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(0); + if (Value.startswith("v")) { + A = *it; + A->claim(); + } + } + } + return A; +} + +StringRef Hexagon_TC::GetTargetCPU(const ArgList &Args) +{ + // Select the default CPU (v4) if none was given or detection failed. + Arg *A = GetLastHexagonArchArg (Args); + if (A) { + StringRef WhichHexagon = A->getValue(); + if (WhichHexagon.startswith("hexagon")) + return WhichHexagon.substr(sizeof("hexagon") - 1); + if (WhichHexagon != "") + return WhichHexagon; + } + + return "v4"; +} +// 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, + const ArgList &Args) + : ToolChain(D, Triple, Args) { + // Path mangling to find libexec + std::string Path(getDriver().Dir); + + Path += "/../libexec"; + getProgramPaths().push_back(Path); +} + +TCEToolChain::~TCEToolChain() { +} + +bool TCEToolChain::IsMathErrnoDefault() const { + return true; +} + +bool TCEToolChain::isPICDefault() const { + return false; +} + +bool TCEToolChain::isPICDefaultForced() const { + return false; +} + +/// 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::buildAssembler() const { + return new tools::openbsd::Assemble(*this); +} + +Tool *OpenBSD::buildLinker() const { + return new tools::openbsd::Link(*this); +} + +/// Bitrig - Bitrig tool chain which can call as(1) and ld(1) directly. + +Bitrig::Bitrig(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 *Bitrig::buildAssembler() const { + return new tools::bitrig::Assemble(*this); +} + +Tool *Bitrig::buildLinker() const { + return new tools::bitrig::Link(*this); +} + +void Bitrig::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + if (DriverArgs.hasArg(options::OPT_nostdlibinc) || + DriverArgs.hasArg(options::OPT_nostdincxx)) + return; + + switch (GetCXXStdlibType(DriverArgs)) { + case ToolChain::CST_Libcxx: + addSystemInclude(DriverArgs, CC1Args, + getDriver().SysRoot + "/usr/include/c++/"); + break; + case ToolChain::CST_Libstdcxx: + addSystemInclude(DriverArgs, CC1Args, + getDriver().SysRoot + "/usr/include/c++/stdc++"); + addSystemInclude(DriverArgs, CC1Args, + getDriver().SysRoot + "/usr/include/c++/stdc++/backward"); + + StringRef Triple = getTriple().str(); + if (Triple.startswith("amd64")) + addSystemInclude(DriverArgs, CC1Args, + getDriver().SysRoot + "/usr/include/c++/stdc++/x86_64" + + Triple.substr(5)); + else + addSystemInclude(DriverArgs, CC1Args, + getDriver().SysRoot + "/usr/include/c++/stdc++/" + + Triple); + break; + } +} + +void Bitrig::AddCXXStdlibLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + switch (GetCXXStdlibType(Args)) { + case ToolChain::CST_Libcxx: + CmdArgs.push_back("-lc++"); + CmdArgs.push_back("-lcxxrt"); + // Include supc++ to provide Unwind until provided by libcxx. + CmdArgs.push_back("-lgcc"); + break; + case ToolChain::CST_Libstdcxx: + CmdArgs.push_back("-lstdc++"); + break; + } +} + +/// 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::buildAssembler() const { + return new tools::freebsd::Assemble(*this); +} + +Tool *FreeBSD::buildLinker() const { + return new tools::freebsd::Link(*this); +} + +bool FreeBSD::UseSjLjExceptions() const { + // FreeBSD uses SjLj exceptions on ARM oabi. + switch (getTriple().getEnvironment()) { + case llvm::Triple::GNUEABI: + case llvm::Triple::EABI: + return false; + + default: + return (getTriple().getArch() == llvm::Triple::arm || + getTriple().getArch() == llvm::Triple::thumb); + } +} + +/// 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::buildAssembler() const { + return new tools::netbsd::Assemble(*this); +} + +Tool *NetBSD::buildLinker() const { + return new tools::netbsd::Link(*this); +} + +/// 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::buildAssembler() const { + return new tools::minix::Assemble(*this); +} + +Tool *Minix::buildLinker() const { + return new tools::minix::Link(*this); +} + +/// 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::buildAssembler() const { + return new tools::auroraux::Assemble(*this); +} + +Tool *AuroraUX::buildLinker() const { + return new tools::auroraux::Link(*this); +} + +/// 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::buildAssembler() const { + return new tools::solaris::Assemble(*this); +} + +Tool *Solaris::buildLinker() const { + return new tools::solaris::Link(*this); +} + +/// Distribution (very bare-bones at the moment). + +enum Distro { + ArchLinux, + DebianLenny, + DebianSqueeze, + DebianWheezy, + DebianJessie, + 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, + UbuntuQuantal, + UbuntuRaring, + UnknownDistro +}; + +static bool IsRedhat(enum Distro Distro) { + return (Distro >= Fedora13 && Distro <= FedoraRawhide) || + (Distro >= RHEL4 && Distro <= RHEL6); +} + +static bool IsOpenSuse(enum Distro Distro) { + return Distro >= OpenSuse11_3 && Distro <= OpenSuse12_2; +} + +static bool IsDebian(enum Distro Distro) { + return Distro >= DebianLenny && Distro <= DebianJessie; +} + +static bool IsUbuntu(enum Distro Distro) { + return Distro >= UbuntuHardy && Distro <= UbuntuRaring; +} + +static Distro DetectDistro(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"); + Distro Version = UnknownDistro; + for (unsigned i = 0, s = Lines.size(); i != s; ++i) + if (Version == UnknownDistro && Lines[i].startswith("DISTRIB_CODENAME=")) + Version = llvm::StringSwitch<Distro>(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) + .Case("quantal", UbuntuQuantal) + .Case("raring", UbuntuRaring) + .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; + else if (Data.startswith("jessie/sid") || Data[0] == '8') + return DebianJessie; + return UnknownDistro; + } + + if (!llvm::MemoryBuffer::getFile("/etc/SuSE-release", File)) + return llvm::StringSwitch<Distro>(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::arm: + case llvm::Triple::thumb: + if (TargetTriple.getEnvironment() == llvm::Triple::GNUEABIHF) { + if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabihf")) + return "arm-linux-gnueabihf"; + } else { + if (llvm::sys::fs::exists(SysRoot + "/lib/arm-linux-gnueabi")) + return "arm-linux-gnueabi"; + } + return TargetTriple.str(); + 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::aarch64: + if (llvm::sys::fs::exists(SysRoot + "/lib/aarch64-linux-gnu")) + return "aarch64-linux-gnu"; + 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-gnuspe")) + return "powerpc-linux-gnuspe"; + 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()); +} + +static bool isMipsArch(llvm::Triple::ArchType Arch) { + return Arch == llvm::Triple::mips || + Arch == llvm::Triple::mipsel || + Arch == llvm::Triple::mips64 || + Arch == llvm::Triple::mips64el; +} + +static bool isMipsR2Arch(llvm::Triple::ArchType Arch, + const ArgList &Args) { + if (Arch != llvm::Triple::mips && + Arch != llvm::Triple::mipsel) + return false; + + Arg *A = Args.getLastArg(options::OPT_march_EQ, + options::OPT_mcpu_EQ, + options::OPT_mips_CPUs_Group); + + if (!A) + return false; + + if (A->getOption().matches(options::OPT_mips_CPUs_Group)) + return A->getOption().matches(options::OPT_mips32r2); + + return A->getValue() == StringRef("mips32r2"); +} + +static StringRef getMultilibDir(const llvm::Triple &Triple, + const ArgList &Args) { + if (!isMipsArch(Triple.getArch())) + return Triple.isArch32Bit() ? "lib32" : "lib64"; + + // lib32 directory has a special meaning on MIPS targets. + // It contains N32 ABI binaries. Use this folder if produce + // code for N32 ABI only. + if (hasMipsN32ABIArg(Args)) + return "lib32"; + + return Triple.isArch32Bit() ? "lib" : "lib64"; +} + +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"); + + Distro Distro = DetectDistro(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 IsAndroid = Triple.getEnvironment() == llvm::Triple::Android; + + // 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 (!isMipsArch(Arch) && !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 || + Distro == DebianJessie || 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 = getMultilibDir(Triple, Args); + 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(); + + if (IsAndroid && isMipsR2Arch(Triple.getArch(), Args)) + addPathIfExists(GCCInstallation.getInstallPath() + + GCCInstallation.getMultiarchSuffix() + + "/mips-r2", + Paths); + else + 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); + } + // On Android, libraries in the parent prefix of the GCC installation are + // preferred to the ones under sysroot. + if (IsAndroid) { + addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", 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::buildLinker() const { + return new tools::gnutools::Link(*this); +} + +Tool *Linux::buildAssembler() const { + return new tools::gnutools::Assemble(*this); +} + +void Linux::addClangTargetOptions(const ArgList &DriverArgs, + ArgStringList &CC1Args) const { + const Generic_GCC::GCCVersion &V = GCCInstallation.getVersion(); + bool UseInitArrayDefault + = V >= Generic_GCC::GCCVersion::Parse("4.7.0") || + getTriple().getArch() == llvm::Triple::aarch64 || + getTriple().getEnvironment() == llvm::Triple::Android; + if (DriverArgs.hasFlag(options::OPT_fuse_init_array, + options::OPT_fno_use_init_array, + UseInitArrayDefault)) + CC1Args.push_back("-fuse-init-array"); +} + +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 AArch64MultiarchIncludeDirs[] = { + "/usr/include/aarch64-linux-gnu" + }; + const StringRef ARMMultiarchIncludeDirs[] = { + "/usr/include/arm-linux-gnueabi" + }; + const StringRef ARMHFMultiarchIncludeDirs[] = { + "/usr/include/arm-linux-gnueabihf" + }; + 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::aarch64) { + MultiarchIncludeDirs = AArch64MultiarchIncludeDirs; + } else if (getTriple().getArch() == llvm::Triple::arm) { + if (getTriple().getEnvironment() == llvm::Triple::GNUEABIHF) + MultiarchIncludeDirs = ARMHFMultiarchIncludeDirs; + else + 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 three 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; +} + +/// \brief Helper to add an extra variant path for an (Ubuntu) multilib +/// libstdc++ installation. +/*static*/ bool Linux::addLibStdCXXIncludePaths(Twine Base, Twine Suffix, + Twine TargetArchDir, + Twine MultiLibSuffix, + const ArgList &DriverArgs, + ArgStringList &CC1Args) { + if (!addLibStdCXXIncludePaths(Base+Suffix, TargetArchDir + MultiLibSuffix, + DriverArgs, CC1Args)) + return false; + + addSystemInclude(DriverArgs, CC1Args, Base + "/" + TargetArchDir + Suffix + + MultiLibSuffix); + 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().Text; + StringRef TripleStr = GCCInstallation.getTriple().str(); + + if (addLibStdCXXIncludePaths(LibDir.str() + "/../include", + "/c++/" + Version.str(), + TripleStr, + GCCInstallation.getMultiarchSuffix(), + DriverArgs, CC1Args)) + return; + + const std::string IncludePathCandidates[] = { + // Gentoo is weird and places its headers inside the GCC install, so if the + // first attempt to find the headers fails, try this pattern. + InstallDir.str() + "/include/g++-v4", + // Android standalone toolchain has C++ headers in yet another place. + LibDir.str() + "/../" + TripleStr.str() + "/include/c++/" + Version.str(), + // Freescale SDK C++ headers are directly in <sysroot>/usr/include/c++, + // without a subdirectory corresponding to the gcc version. + LibDir.str() + "/../include/c++", + }; + + for (unsigned i = 0; i < llvm::array_lengthof(IncludePathCandidates); ++i) { + if (addLibStdCXXIncludePaths(IncludePathCandidates[i], (TripleStr + + GCCInstallation.getMultiarchSuffix()), + DriverArgs, CC1Args)) + break; + } +} + +/// 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::buildAssembler() const { + return new tools::dragonfly::Assemble(*this); +} + +Tool *DragonFly::buildLinker() const { + return new tools::dragonfly::Link(*this); +} diff --git a/contrib/llvm/tools/clang/lib/Driver/ToolChains.h b/contrib/llvm/tools/clang/lib/Driver/ToolChains.h new file mode 100644 index 0000000..3421c53 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/ToolChains.h @@ -0,0 +1,590 @@ +//===--- 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 "Tools.h" +#include "clang/Basic/VersionTuple.h" +#include "clang/Driver/Action.h" +#include "clang/Driver/ToolChain.h" +#include "llvm/ADT/DenseMap.h" +#include "llvm/Support/Compiler.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. + const GCCVersion &getVersion() const { return Version; } + + 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 ArgList &Args, + const std::string &LibDir, + StringRef CandidateTriple, + bool NeedsMultiarchSuffix = false); + }; + + GCCInstallationDetector GCCInstallation; + +public: + Generic_GCC(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + ~Generic_GCC(); + + virtual bool IsUnwindTablesDefault() const; + virtual bool isPICDefault() const; + virtual bool isPICDefaultForced() const; + +protected: + virtual Tool *getTool(Action::ActionClass AC) const; + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; + + /// \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(); } + + /// @} + +private: + mutable OwningPtr<tools::gcc::Preprocess> Preprocess; + mutable OwningPtr<tools::gcc::Precompile> Precompile; + mutable OwningPtr<tools::gcc::Compile> Compile; +}; + + /// Darwin - The base Darwin tool chain. +class LLVM_LIBRARY_VISIBILITY Darwin : public ToolChain { +public: + /// The host version. + unsigned DarwinVersion[3]; + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; + virtual Tool *getTool(Action::ActionClass AC) const; + +private: + mutable OwningPtr<tools::darwin::Lipo> Lipo; + mutable OwningPtr<tools::darwin::Dsymutil> Dsymutil; + mutable OwningPtr<tools::darwin::VerifyDebug> VerifyDebug; + + /// 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; + + /// 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; + +private: + /// The default macosx-version-min of this tool chain; empty until + /// initialized. + std::string MacosxVersionMin; + + /// The default ios-version-min of this tool chain; empty until + /// initialized. + std::string iOSVersionMin; + +private: + void AddDeploymentTarget(DerivedArgList &Args) const; + +public: + Darwin(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + ~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(); + } + + 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); + } + + /// 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 ObjCRuntime getDefaultObjCRuntime(bool isNonFragile) const; + virtual bool hasBlocksRuntime() const; + + virtual DerivedArgList *TranslateArgs(const DerivedArgList &Args, + const char *BoundArch) 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 IsMathErrnoDefault() const { + return false; + } + + virtual bool IsEncodeExtendedBlockSignatureDefault() const { + return true; + } + + virtual bool IsObjCNonFragileABIDefault() const { + // Non-fragile ABI is default for everything but i386. + return getTriple().getArch() != llvm::Triple::x86; + } + + 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 bool isPICDefault() const; + virtual bool isPICDefaultForced() const; + + virtual bool SupportsProfiling() const; + + virtual bool SupportsObjCGC() const; + + virtual void CheckObjCARC() const; + + virtual bool UseDwarfDebugFlags() const; + + virtual bool UseSjLjExceptions() const; + + /// } +}; + +/// DarwinClang - The Darwin toolchain used by Clang. +class LLVM_LIBRARY_VISIBILITY DarwinClang : public Darwin { +public: + DarwinClang(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + /// @name Darwin ToolChain Implementation + /// { + + virtual void AddLinkRuntimeLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const; + void AddLinkRuntimeLib(const ArgList &Args, ArgStringList &CmdArgs, + const char *DarwinStaticLib, + bool AlwaysLink = false) 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 bool isPICDefault() const { return false; } +}; + +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::aarch64 || + 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); + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; +}; + +class LLVM_LIBRARY_VISIBILITY Solaris : public Generic_GCC { +public: + Solaris(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsIntegratedAssemblerDefault() const { return true; } +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; + +}; + + +class LLVM_LIBRARY_VISIBILITY OpenBSD : public Generic_ELF { +public: + OpenBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsMathErrnoDefault() const { return false; } + virtual bool IsObjCNonFragileABIDefault() const { return true; } + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; +}; + +class LLVM_LIBRARY_VISIBILITY Bitrig : public Generic_ELF { +public: + Bitrig(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsMathErrnoDefault() const { return false; } + virtual bool IsObjCNonFragileABIDefault() const { return true; } + virtual bool IsObjCLegacyDispatchDefault() const { return false; } + + virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual void AddCXXStdlibLibArgs(const ArgList &Args, + ArgStringList &CmdArgs) const; + virtual unsigned GetDefaultStackProtectorLevel(bool KernelOrKext) const { + return 1; + } + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; +}; + +class LLVM_LIBRARY_VISIBILITY FreeBSD : public Generic_ELF { +public: + FreeBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsMathErrnoDefault() const { return false; } + virtual bool IsObjCNonFragileABIDefault() const { return true; } + + virtual bool UseSjLjExceptions() const; +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; +}; + +class LLVM_LIBRARY_VISIBILITY NetBSD : public Generic_ELF { +public: + NetBSD(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsMathErrnoDefault() const { return false; } + virtual bool IsObjCNonFragileABIDefault() const { return true; } + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; +}; + +class LLVM_LIBRARY_VISIBILITY Minix : public Generic_ELF { +public: + Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; +}; + +class LLVM_LIBRARY_VISIBILITY DragonFly : public Generic_ELF { +public: + DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsMathErrnoDefault() const { return false; } + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() 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 void AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual void addClangTargetOptions(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + + std::string Linker; + std::vector<std::string> ExtraOpts; + +protected: + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; + +private: + static bool addLibStdCXXIncludePaths(Twine Base, Twine Suffix, + Twine TargetArchDir, + Twine MultiLibSuffix, + const ArgList &DriverArgs, + ArgStringList &CC1Args); + static bool addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir, + const ArgList &DriverArgs, + ArgStringList &CC1Args); +}; + +class LLVM_LIBRARY_VISIBILITY Hexagon_TC : public Linux { +protected: + GCCVersion GCCLibAndIncVersion; + virtual Tool *buildAssembler() const; + virtual Tool *buildLinker() const; + +public: + Hexagon_TC(const Driver &D, const llvm::Triple &Triple, + const ArgList &Args); + ~Hexagon_TC(); + + virtual void AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual CXXStdlibType GetCXXStdlibType(const ArgList &Args) const; + + StringRef GetGCCLibAndIncVersion() const { return GCCLibAndIncVersion.Text; } + + static std::string GetGnuDir(const std::string &InstalledDir); + + static StringRef GetTargetCPU(const ArgList &Args); +}; + +/// 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, + const ArgList &Args); + ~TCEToolChain(); + + bool IsMathErrnoDefault() const; + bool isPICDefault() const; + bool isPICDefaultForced() const; +}; + +class LLVM_LIBRARY_VISIBILITY Windows : public ToolChain { +public: + Windows(const Driver &D, const llvm::Triple& Triple, const ArgList &Args); + + virtual bool IsIntegratedAssemblerDefault() const; + virtual bool IsUnwindTablesDefault() const; + virtual bool isPICDefault() const; + virtual bool isPICDefaultForced() const; + + virtual void AddClangSystemIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; + virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs, + ArgStringList &CC1Args) const; +protected: + virtual Tool *buildLinker() const; + virtual Tool *buildAssembler() const; +}; + +} // end namespace toolchains +} // end namespace driver +} // end namespace clang + +#endif diff --git a/contrib/llvm/tools/clang/lib/Driver/Tools.cpp b/contrib/llvm/tools/clang/lib/Driver/Tools.cpp new file mode 100644 index 0000000..294b791 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Tools.cpp @@ -0,0 +1,6318 @@ +//===--- 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 "InputInfo.h" +#include "SanitizerArgs.h" +#include "ToolChains.h" +#include "clang/Basic/ObjCRuntime.h" +#include "clang/Basic/Version.h" +#include "clang/Driver/Action.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/Job.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/ErrorHandling.h" +#include "llvm/Support/FileSystem.h" +#include "llvm/Support/Format.h" +#include "llvm/Support/Host.h" +#include "llvm/Support/Process.h" +#include "llvm/Support/raw_ostream.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); + bool CombinedArg = false; + + if (!DirList) + return; // Nothing to do. + + StringRef Name(ArgName); + if (Name.equals("-I") || Name.equals("-L")) + CombinedArg = true; + + 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. + if (CombinedArg) { + CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); + } else { + CmdArgs.push_back(ArgName); + CmdArgs.push_back("."); + } + } else { + if (CombinedArg) { + CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs.substr(0, Delim))); + } else { + CmdArgs.push_back(ArgName); + CmdArgs.push_back(Args.MakeArgString(Dirs.substr(0, Delim))); + } + } + Dirs = Dirs.substr(Delim + 1); + } + + if (Dirs.empty()) { // Trailing colon. + if (CombinedArg) { + CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + ".")); + } else { + CmdArgs.push_back(ArgName); + CmdArgs.push_back("."); + } + } else { // Add the last path. + if (CombinedArg) { + CmdArgs.push_back(Args.MakeArgString(std::string(ArgName) + Dirs)); + } else { + 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)) { + Args.ClaimAllArgs(options::OPT_fobjc_link_runtime); + 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)); +} + +static bool forwardToGCC(const Option &O) { + return !O.hasFlag(options::NoForward) && + !O.hasFlag(options::DriverOption) && + !O.hasFlag(options::LinkerInput); +} + +void Clang::AddPreprocessingOptions(Compilation &C, + const JobAction &JA, + 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 (Arg *MF = Args.getLastArg(options::OPT_MF)) { + DepFile = MF->getValue(); + C.addFailureResultFile(DepFile, &JA); + } else if (Output.getType() == types::TY_Dependencies) { + DepFile = Output.getFilename(); + } else if (A->getOption().matches(options::OPT_M) || + A->getOption().matches(options::OPT_MM)) { + DepFile = "-"; + } else { + DepFile = getDependencyFileName(Args, Inputs); + C.addFailureResultFile(DepFile, &JA); + } + 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(); + } 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(), 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()); + 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)); + } + } + + // 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); +} + +/// 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-a5", "cortex-a7", "cortex-a8", "v7") + .Cases("cortex-a9", "cortex-a15", "v7") + .Case("cortex-r5", "v7r") + .Case("cortex-m0", "v6m") + .Case("cortex-m3", "v7m") + .Case("cortex-m4", "v7em") + .Case("cortex-a9-mp", "v7f") + .Case("swift", "v7s") + .Default(""); +} + +/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting. +// +// FIXME: tblgen this. +static std::string 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)) { + StringRef MCPU = A->getValue(); + // Handle -mcpu=native. + if (MCPU == "native") + return llvm::sys::getHostCPUName(); + else + return MCPU; + } + + 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(); + } else { + // Otherwise, use the Arch from the triple. + MArch = Triple.getArchName(); + } + + // Handle -march=native. + std::string NativeMArch; + if (MArch == "native") { + std::string CPU = llvm::sys::getHostCPUName(); + if (CPU != "generic") { + // Translate the native cpu into the architecture. The switch below will + // then chose the minimum cpu for that arch. + NativeMArch = std::string("arm") + getLLVMArchSuffixForARM(CPU); + MArch = NativeMArch; + } + } + + 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", "arm1022e") + .Case("armv5tej", "arm926ej-s") + .Cases("armv6", "armv6k", "arm1136jf-s") + .Case("armv6j", "arm1136j-s") + .Cases("armv6z", "armv6zk", "arm1176jzf-s") + .Case("armv6t2", "arm1156t2-s") + .Cases("armv6m", "armv6-m", "cortex-m0") + .Cases("armv7", "armv7a", "armv7-a", "cortex-a8") + .Cases("armv7em", "armv7e-m", "cortex-m4") + .Cases("armv7f", "armv7-f", "cortex-a9-mp") + .Cases("armv7s", "armv7-s", "swift") + .Cases("armv7r", "armv7-r", "cortex-r4") + .Cases("armv7m", "armv7-m", "cortex-m3") + .Case("ep9312", "ep9312") + .Case("iwmmxt", "iwmmxt") + .Case("xscale", "xscale") + // If all else failed, return the most base CPU LLVM supports. + .Default("arm7tdmi"); +} + +// FIXME: Move to target hook. +static bool isSignedCharDefault(const llvm::Triple &Triple) { + switch (Triple.getArch()) { + default: + return true; + + case llvm::Triple::aarch64: + 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(); + + // 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(); + + // Set the target features based on the FPMath. + if (FPMath == "neon") { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("+neonfp"); + + if (CPU != "cortex-a5" && CPU != "cortex-a7" && + CPU != "cortex-a8" && CPU != "cortex-a9" && + CPU != "cortex-a9-mp" && CPU != "cortex-a15") + 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(); + 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. + std::string ArchName = + getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple)); + if (StringRef(ArchName).startswith("v6") || + StringRef(ArchName).startswith("v7")) + FloatABI = "softfp"; + else + FloatABI = "soft"; + break; + } + + case llvm::Triple::FreeBSD: + // FreeBSD defaults to soft float + FloatABI = "soft"; + break; + + default: + switch(Triple.getEnvironment()) { + case llvm::Triple::GNUEABIHF: + FloatABI = "hard"; + break; + 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::Android: { + std::string ArchName = + getLLVMArchSuffixForARM(getARMTargetCPU(Args, Triple)); + if (StringRef(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(); + // Get the effective triple, which takes into account the deployment target. + std::string TripleStr = getToolChain().ComputeEffectiveClangTriple(Args); + llvm::Triple Triple(TripleStr); + std::string CPUName = getARMTargetCPU(Args, Triple); + + // Select the ABI to use. + // + // FIXME: Support -meabi. + const char *ABIName = 0; + if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) { + ABIName = A->getValue(); + } else if (Triple.isOSDarwin()) { + // The backend is hardwired to assume AAPCS for M-class processors, ensure + // the frontend matches that. + if (StringRef(CPUName).startswith("cortex-m")) { + ABIName = "aapcs"; + } else { + ABIName = "apcs-gnu"; + } + } else { + // Select the default based on the platform. + switch(Triple.getEnvironment()) { + case llvm::Triple::Android: + case llvm::Triple::GNUEABI: + case llvm::Triple::GNUEABIHF: + 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(Args.MakeArgString(CPUName)); + + // 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) { + if (Triple.getOS() != llvm::Triple::IOS || Triple.isOSVersionLT(6)) { + 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"); + } + + if (Args.hasArg(options::OPT_mno_implicit_float)) + CmdArgs.push_back("-no-implicit-float"); +} + +// Translate MIPS CPU name alias option to CPU name. +static StringRef getMipsCPUFromAlias(const Arg &A) { + if (A.getOption().matches(options::OPT_mips32)) + return "mips32"; + if (A.getOption().matches(options::OPT_mips32r2)) + return "mips32r2"; + if (A.getOption().matches(options::OPT_mips64)) + return "mips64"; + if (A.getOption().matches(options::OPT_mips64r2)) + return "mips64r2"; + llvm_unreachable("Unexpected option"); + return ""; +} + +// 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) { + const char *DefMips32CPU = "mips32"; + const char *DefMips64CPU = "mips64"; + + if (Arg *A = Args.getLastArg(options::OPT_march_EQ, + options::OPT_mcpu_EQ, + options::OPT_mips_CPUs_Group)) { + if (A->getOption().matches(options::OPT_mips_CPUs_Group)) + CPUName = getMipsCPUFromAlias(*A); + else + CPUName = A->getValue(); + } + + if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) + ABIName = A->getValue(); + + // Setup default CPU and ABI names. + if (CPUName.empty() && ABIName.empty()) { + switch (TC.getTriple().getArch()) { + default: + llvm_unreachable("Unexpected triple arch name"); + case llvm::Triple::mips: + case llvm::Triple::mipsel: + CPUName = DefMips32CPU; + break; + case llvm::Triple::mips64: + case llvm::Triple::mips64el: + CPUName = DefMips64CPU; + break; + } + } + + if (!ABIName.empty()) { + // Deduce CPU name from ABI name. + CPUName = llvm::StringSwitch<const char *>(ABIName) + .Cases("32", "o32", "eabi", DefMips32CPU) + .Cases("n32", "n64", "64", DefMips64CPU) + .Default(""); + } + else if (!CPUName.empty()) { + // Deduce ABI name from CPU name. + ABIName = llvm::StringSwitch<const char *>(CPUName) + .Cases("mips32", "mips32r2", "o32") + .Cases("mips64", "mips64r2", "n64") + .Default(""); + } + + // FIXME: Warn on inconsistent cpu and abi usage. +} + +// Convert ABI name to the GNU tools acceptable variant. +static StringRef getGnuCompatibleMipsABIName(StringRef ABI) { + return llvm::StringSwitch<llvm::StringRef>(ABI) + .Case("o32", "32") + .Case("n64", "64") + .Default(ABI); +} + +// Select the MIPS float ABI as determined by -msoft-float, -mhard-float, +// and -mfloat-abi=. +static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) { + // 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(); + 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"; + } + + return FloatABI; +} + +static void AddTargetFeature(const ArgList &Args, + ArgStringList &CmdArgs, + OptSpecifier OnOpt, + OptSpecifier OffOpt, + StringRef FeatureName) { + if (Arg *A = Args.getLastArg(OnOpt, OffOpt)) { + CmdArgs.push_back("-target-feature"); + if (A->getOption().matches(OnOpt)) + CmdArgs.push_back(Args.MakeArgString("+" + FeatureName)); + else + CmdArgs.push_back(Args.MakeArgString("-" + FeatureName)); + } +} + +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()); + + StringRef FloatABI = getMipsFloatABI(D, Args); + + bool IsMips16 = Args.getLastArg(options::OPT_mips16) != NULL; + + if (FloatABI == "soft" || (FloatABI == "hard" && IsMips16)) { + // 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"); + + if (FloatABI == "hard" && IsMips16) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-mips16-hard-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"); + } + + AddTargetFeature(Args, CmdArgs, + options::OPT_mips16, options::OPT_mno_mips16, + "mips16"); + AddTargetFeature(Args, CmdArgs, + options::OPT_mdsp, options::OPT_mno_dsp, + "dsp"); + AddTargetFeature(Args, CmdArgs, + options::OPT_mdspr2, options::OPT_mno_dspr2, + "dspr2"); + + if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) { + if (A->getOption().matches(options::OPT_mxgot)) { + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back("-mxgot"); + } + } + + if (Arg *A = Args.getLastArg(options::OPT_G)) { + StringRef v = A->getValue(); + CmdArgs.push_back("-mllvm"); + CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v)); + A->claim(); + } +} + +/// getPPCTargetCPU - Get the (LLVM) name of the PowerPC cpu we are targeting. +static std::string getPPCTargetCPU(const ArgList &Args) { + if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { + StringRef CPUName = A->getValue(); + + if (CPUName == "native") { + std::string CPU = llvm::sys::getHostCPUName(); + if (!CPU.empty() && CPU != "generic") + return CPU; + else + return ""; + } + + return llvm::StringSwitch<const char *>(CPUName) + .Case("common", "generic") + .Case("440", "440") + .Case("440fp", "440") + .Case("450", "450") + .Case("601", "601") + .Case("602", "602") + .Case("603", "603") + .Case("603e", "603e") + .Case("603ev", "603ev") + .Case("604", "604") + .Case("604e", "604e") + .Case("620", "620") + .Case("630", "pwr3") + .Case("G3", "g3") + .Case("7400", "7400") + .Case("G4", "g4") + .Case("7450", "7450") + .Case("G4+", "g4+") + .Case("750", "750") + .Case("970", "970") + .Case("G5", "g5") + .Case("a2", "a2") + .Case("a2q", "a2q") + .Case("e500mc", "e500mc") + .Case("e5500", "e5500") + .Case("power3", "pwr3") + .Case("power4", "pwr4") + .Case("power5", "pwr5") + .Case("power5x", "pwr5x") + .Case("power6", "pwr6") + .Case("power6x", "pwr6x") + .Case("power7", "pwr7") + .Case("pwr3", "pwr3") + .Case("pwr4", "pwr4") + .Case("pwr5", "pwr5") + .Case("pwr5x", "pwr5x") + .Case("pwr6", "pwr6") + .Case("pwr6x", "pwr6x") + .Case("pwr7", "pwr7") + .Case("powerpc", "ppc") + .Case("powerpc64", "ppc64") + .Default(""); + } + + return ""; +} + +void Clang::AddPPCTargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + std::string TargetCPUName = getPPCTargetCPU(Args); + + // LLVM may default to generating code for the native CPU, + // but, like gcc, we default to a more generic option for + // each architecture. (except on Darwin) + llvm::Triple Triple = getToolChain().getTriple(); + if (TargetCPUName.empty() && !Triple.isOSDarwin()) { + if (Triple.getArch() == llvm::Triple::ppc64) + TargetCPUName = "ppc64"; + else + TargetCPUName = "ppc"; + } + + if (!TargetCPUName.empty()) { + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(Args.MakeArgString(TargetCPUName.c_str())); + } + + // Allow override of the Altivec feature. + AddTargetFeature(Args, CmdArgs, + options::OPT_faltivec, options::OPT_fno_altivec, + "altivec"); + + AddTargetFeature(Args, CmdArgs, + options::OPT_mfprnd, options::OPT_mno_fprnd, + "fprnd"); + + // Note that gcc calls this mfcrf and LLVM calls this mfocrf. + AddTargetFeature(Args, CmdArgs, + options::OPT_mmfcrf, options::OPT_mno_mfcrf, + "mfocrf"); + + AddTargetFeature(Args, CmdArgs, + options::OPT_mpopcntd, options::OPT_mno_popcntd, + "popcntd"); + + // It is really only possible to turn qpx off because turning qpx on is tied + // to using the a2q CPU. + if (Args.hasFlag(options::OPT_mno_qpx, options::OPT_mqpx, false)) { + CmdArgs.push_back("-target-feature"); + CmdArgs.push_back("-qpx"); + } +} + +/// Get the (LLVM) name of the R600 gpu we are targeting. +static std::string getR600TargetGPU(const ArgList &Args) { + if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) { + std::string GPUName = A->getValue(); + return llvm::StringSwitch<const char *>(GPUName) + .Cases("rv610", "rv620", "rv630", "r600") + .Cases("rv635", "rs780", "rs880", "r600") + .Case("rv740", "rv770") + .Case("palm", "cedar") + .Cases("sumo", "sumo2", "redwood") + .Case("hemlock", "cypress") + .Case("aruba", "cayman") + .Default(GPUName.c_str()); + } + return ""; +} + +void Clang::AddR600TargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + std::string TargetGPUName = getR600TargetGPU(Args); + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(Args.MakeArgString(TargetGPUName.c_str())); +} + +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()); + } + + // 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"); + } +} + +static const char *getX86TargetCPU(const ArgList &Args, + const llvm::Triple &Triple) { + if (const Arg *A = Args.getLastArg(options::OPT_march_EQ)) { + if (StringRef(A->getValue()) != "native") + return A->getValue(); + + // 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() && CPU != "generic") + return Args.MakeArgString(CPU); + } + + // Select the default CPU if none was given (or detection failed). + + if (Triple.getArch() != llvm::Triple::x86_64 && + Triple.getArch() != llvm::Triple::x86) + return 0; // This routine is only handling x86 targets. + + bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64; + + // FIXME: Need target hooks. + if (Triple.isOSDarwin()) + return Is64Bit ? "core2" : "yonah"; + + // Everything else goes to x86-64 in 64-bit mode. + if (Is64Bit) + return "x86-64"; + + if (Triple.getOSName().startswith("haiku")) + return "i586"; + if (Triple.getOSName().startswith("openbsd")) + return "i486"; + if (Triple.getOSName().startswith("bitrig")) + return "i686"; + if (Triple.getOSName().startswith("freebsd")) + return "i486"; + if (Triple.getOSName().startswith("netbsd")) + return "i486"; + // All x86 devices running Android have core2 as their common + // denominator. This makes a better choice than pentium4. + if (Triple.getEnvironment() == llvm::Triple::Android) + return "core2"; + + // Fallback to p4. + return "pentium4"; +} + +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"); + + // Default to avoid implicit floating-point for kernel/kext code, but allow + // that to be overridden with -mno-soft-float. + bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) || + Args.hasArg(options::OPT_fapple_kext)); + if (Arg *A = Args.getLastArg(options::OPT_msoft_float, + options::OPT_mno_soft_float, + options::OPT_mno_implicit_float)) { + const Option &O = A->getOption(); + NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) || + O.matches(options::OPT_msoft_float)); + } + if (NoImplicitFloat) + CmdArgs.push_back("-no-implicit-float"); + + if (const char *CPUName = getX86TargetCPU(Args, getToolChain().getTriple())) { + 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(1); + + 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 inline bool HasPICArg(const ArgList &Args) { + return Args.hasArg(options::OPT_fPIC) + || Args.hasArg(options::OPT_fpic); +} + +static Arg *GetLastSmallDataThresholdArg(const ArgList &Args) { + return Args.getLastArg(options::OPT_G, + options::OPT_G_EQ, + options::OPT_msmall_data_threshold_EQ); +} + +static std::string GetHexagonSmallDataThresholdValue(const ArgList &Args) { + std::string value; + if (HasPICArg(Args)) + value = "0"; + else if (Arg *A = GetLastSmallDataThresholdArg(Args)) { + value = A->getValue(); + A->claim(); + } + return value; +} + +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" + + toolchains::Hexagon_TC::GetTargetCPU(Args))); + CmdArgs.push_back("-fno-signed-char"); + CmdArgs.push_back("-mqdsp6-compat"); + CmdArgs.push_back("-Wreturn-type"); + + std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args); + if (!SmallDataThreshold.empty()) { + CmdArgs.push_back ("-mllvm"); + CmdArgs.push_back(Args.MakeArgString( + "-hexagon-small-data-threshold=" + SmallDataThreshold)); + } + + if (!Args.hasArg(options::OPT_fno_short_enums)) + CmdArgs.push_back("-fshort-enums"); + if (Args.getLastArg(options::OPT_mieee_rnd_near)) { + CmdArgs.push_back ("-mllvm"); + CmdArgs.push_back ("-enable-hexagon-ieee-rnd-near"); + } + CmdArgs.push_back ("-mllvm"); + CmdArgs.push_back ("-machine-sink-split=0"); +} + +static bool +shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime, + 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 (runtime.isNonFragile()) + 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, + const ObjCRuntime &objcRuntime, + 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(objcRuntime, 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 = TC.useIntegratedAs(); + } + 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 UseDwarfDirectory = Args.hasFlag(options::OPT_fdwarf_directory_asm, + options::OPT_fno_dwarf_directory_asm, + TC.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); +} + +SanitizerArgs::SanitizerArgs(const Driver &D, const ArgList &Args) + : Kind(0), BlacklistFile(""), MsanTrackOrigins(false), + AsanZeroBaseShadow(false) { + unsigned AllKinds = 0; // All kinds of sanitizers that were turned on + // at least once (possibly, disabled further). + for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I) { + unsigned Add, Remove; + if (!parse(D, Args, *I, Add, Remove, true)) + continue; + (*I)->claim(); + Kind |= Add; + Kind &= ~Remove; + AllKinds |= Add; + } + + UbsanTrapOnError = + Args.hasArg(options::OPT_fcatch_undefined_behavior) || + Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error, + options::OPT_fno_sanitize_undefined_trap_on_error, false); + + if (Args.hasArg(options::OPT_fcatch_undefined_behavior) && + !Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error, + options::OPT_fno_sanitize_undefined_trap_on_error, true)) { + D.Diag(diag::err_drv_argument_not_allowed_with) + << "-fcatch-undefined-behavior" + << "-fno-sanitize-undefined-trap-on-error"; + } + + // Warn about undefined sanitizer options that require runtime support. + if (UbsanTrapOnError && notAllowedWithTrap()) { + if (Args.hasArg(options::OPT_fcatch_undefined_behavior)) + D.Diag(diag::err_drv_argument_not_allowed_with) + << lastArgumentForKind(D, Args, NotAllowedWithTrap) + << "-fcatch-undefined-behavior"; + else if (Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error, + options::OPT_fno_sanitize_undefined_trap_on_error, + false)) + D.Diag(diag::err_drv_argument_not_allowed_with) + << lastArgumentForKind(D, Args, NotAllowedWithTrap) + << "-fsanitize-undefined-trap-on-error"; + } + + // Only one runtime library can be used at once. + bool NeedsAsan = needsAsanRt(); + bool NeedsTsan = needsTsanRt(); + bool NeedsMsan = needsMsanRt(); + if (NeedsAsan && NeedsTsan) + D.Diag(diag::err_drv_argument_not_allowed_with) + << lastArgumentForKind(D, Args, NeedsAsanRt) + << lastArgumentForKind(D, Args, NeedsTsanRt); + if (NeedsAsan && NeedsMsan) + D.Diag(diag::err_drv_argument_not_allowed_with) + << lastArgumentForKind(D, Args, NeedsAsanRt) + << lastArgumentForKind(D, Args, NeedsMsanRt); + if (NeedsTsan && NeedsMsan) + D.Diag(diag::err_drv_argument_not_allowed_with) + << lastArgumentForKind(D, Args, NeedsTsanRt) + << lastArgumentForKind(D, Args, NeedsMsanRt); + + // If -fsanitize contains extra features of ASan, it should also + // explicitly contain -fsanitize=address (probably, turned off later in the + // command line). + if ((Kind & AddressFull) != 0 && (AllKinds & Address) == 0) + D.Diag(diag::warn_drv_unused_sanitizer) + << lastArgumentForKind(D, Args, AddressFull) + << "-fsanitize=address"; + + // Parse -f(no-)sanitize-blacklist options. + if (Arg *BLArg = Args.getLastArg(options::OPT_fsanitize_blacklist, + options::OPT_fno_sanitize_blacklist)) { + if (BLArg->getOption().matches(options::OPT_fsanitize_blacklist)) { + std::string BLPath = BLArg->getValue(); + bool BLExists = false; + if (!llvm::sys::fs::exists(BLPath, BLExists) && BLExists) + BlacklistFile = BLPath; + else + D.Diag(diag::err_drv_no_such_file) << BLPath; + } + } else { + // If no -fsanitize-blacklist option is specified, try to look up for + // blacklist in the resource directory. + std::string BLPath; + bool BLExists = false; + if (getDefaultBlacklistForKind(D, Kind, BLPath) && + !llvm::sys::fs::exists(BLPath, BLExists) && BLExists) + BlacklistFile = BLPath; + } + + // Parse -f(no-)sanitize-memory-track-origins options. + if (NeedsMsan) + MsanTrackOrigins = + Args.hasFlag(options::OPT_fsanitize_memory_track_origins, + options::OPT_fno_sanitize_memory_track_origins, + /* Default */false); + + // Parse -f(no-)sanitize-address-zero-base-shadow options. + if (NeedsAsan) + AsanZeroBaseShadow = + Args.hasFlag(options::OPT_fsanitize_address_zero_base_shadow, + options::OPT_fno_sanitize_address_zero_base_shadow, + /* Default */false); +} + +static void addSanitizerRTLinkFlagsLinux( + const ToolChain &TC, const ArgList &Args, ArgStringList &CmdArgs, + const StringRef Sanitizer, bool BeforeLibStdCXX, + bool ExportSymbols = true) { + // Sanitizer runtime is located in the Linux library directory and + // has name "libclang_rt.<Sanitizer>-<ArchName>.a". + SmallString<128> LibSanitizer(TC.getDriver().ResourceDir); + llvm::sys::path::append( + LibSanitizer, "lib", "linux", + (Twine("libclang_rt.") + Sanitizer + "-" + TC.getArchName() + ".a")); + + // Sanitizer runtime may need to come before -lstdc++ (or -lc++, libstdc++.a, + // etc.) so that the linker picks custom versions of the global 'operator + // new' and 'operator delete' symbols. We take the extreme (but simple) + // strategy of inserting it at the front of the link command. It also + // needs to be forced to end up in the executable, so wrap it in + // whole-archive. + SmallVector<const char *, 3> LibSanitizerArgs; + LibSanitizerArgs.push_back("-whole-archive"); + LibSanitizerArgs.push_back(Args.MakeArgString(LibSanitizer)); + LibSanitizerArgs.push_back("-no-whole-archive"); + + CmdArgs.insert(BeforeLibStdCXX ? CmdArgs.begin() : CmdArgs.end(), + LibSanitizerArgs.begin(), LibSanitizerArgs.end()); + + CmdArgs.push_back("-lpthread"); + CmdArgs.push_back("-ldl"); + + // If possible, use a dynamic symbols file to export the symbols from the + // runtime library. If we can't do so, use -export-dynamic instead to export + // all symbols from the binary. + if (ExportSymbols) { + if (llvm::sys::fs::exists(LibSanitizer + ".syms")) + CmdArgs.push_back( + Args.MakeArgString("--dynamic-list=" + LibSanitizer + ".syms")); + else + CmdArgs.push_back("-export-dynamic"); + } +} + +/// 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) { + if(TC.getTriple().getEnvironment() == llvm::Triple::Android) { + if (!Args.hasArg(options::OPT_shared)) { + if (!Args.hasArg(options::OPT_pie)) + TC.getDriver().Diag(diag::err_drv_asan_android_requires_pie); + } + + SmallString<128> LibAsan(TC.getDriver().ResourceDir); + llvm::sys::path::append(LibAsan, "lib", "linux", + (Twine("libclang_rt.asan-") + + TC.getArchName() + "-android.so")); + CmdArgs.insert(CmdArgs.begin(), Args.MakeArgString(LibAsan)); + } else { + if (!Args.hasArg(options::OPT_shared)) { + bool ZeroBaseShadow = Args.hasFlag( + options::OPT_fsanitize_address_zero_base_shadow, + options::OPT_fno_sanitize_address_zero_base_shadow, false); + if (ZeroBaseShadow && !Args.hasArg(options::OPT_pie)) { + TC.getDriver().Diag(diag::err_drv_argument_only_allowed_with) << + "-fsanitize-address-zero-base-shadow" << "-pie"; + } + addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "asan", true); + } + } +} + +/// If ThreadSanitizer is enabled, add appropriate linker flags (Linux). +/// This needs to be called before we add the C run-time (malloc, etc). +static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args, + ArgStringList &CmdArgs) { + if (!Args.hasArg(options::OPT_shared)) { + if (!Args.hasArg(options::OPT_pie)) + TC.getDriver().Diag(diag::err_drv_argument_only_allowed_with) << + "-fsanitize=thread" << "-pie"; + addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "tsan", true); + } +} + +/// If MemorySanitizer is enabled, add appropriate linker flags (Linux). +/// This needs to be called before we add the C run-time (malloc, etc). +static void addMsanRTLinux(const ToolChain &TC, const ArgList &Args, + ArgStringList &CmdArgs) { + if (!Args.hasArg(options::OPT_shared)) { + if (!Args.hasArg(options::OPT_pie)) + TC.getDriver().Diag(diag::err_drv_argument_only_allowed_with) << + "-fsanitize=memory" << "-pie"; + addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "msan", true); + } +} + +/// If UndefinedBehaviorSanitizer is enabled, add appropriate linker flags +/// (Linux). +static void addUbsanRTLinux(const ToolChain &TC, const ArgList &Args, + ArgStringList &CmdArgs, bool IsCXX, + bool HasOtherSanitizerRt) { + if (Args.hasArg(options::OPT_shared)) + return; + + // Need a copy of sanitizer_common. This could come from another sanitizer + // runtime; if we're not including one, include our own copy. + if (!HasOtherSanitizerRt) + addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "san", true, false); + + addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan", false); + + // Only include the bits of the runtime which need a C++ ABI library if + // we're linking in C++ mode. + if (IsCXX) + addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "ubsan_cxx", false); +} + +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; +} + +static bool shouldUseLeafFramePointer(const ArgList &Args, + const llvm::Triple &Triple) { + if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer, + options::OPT_momit_leaf_frame_pointer)) + return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer); + + // Don't use a leaf 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; +} + +/// If the PWD environment variable is set, add a CC1 option to specify the +/// debug compilation directory. +static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) { + 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)); + } + } +} + +static const char *SplitDebugName(const ArgList &Args, + const InputInfoList &Inputs) { + Arg *FinalOutput = Args.getLastArg(options::OPT_o); + if (FinalOutput && Args.hasArg(options::OPT_c)) { + SmallString<128> T(FinalOutput->getValue()); + llvm::sys::path::replace_extension(T, "dwo"); + return Args.MakeArgString(T); + } else { + // Use the compilation dir. + SmallString<128> T(Args.getLastArgValue(options::OPT_fdebug_compilation_dir)); + SmallString<128> F(llvm::sys::path::stem(Inputs[0].getBaseInput())); + llvm::sys::path::replace_extension(F, "dwo"); + T += F; + return Args.MakeArgString(F); + } +} + +static void SplitDebugInfo(const ToolChain &TC, Compilation &C, + const Tool &T, const JobAction &JA, + const ArgList &Args, const InputInfo &Output, + const char *OutFile) { + ArgStringList ExtractArgs; + ExtractArgs.push_back("--extract-dwo"); + + ArgStringList StripArgs; + StripArgs.push_back("--strip-dwo"); + + // Grabbing the output of the earlier compile step. + StripArgs.push_back(Output.getFilename()); + ExtractArgs.push_back(Output.getFilename()); + ExtractArgs.push_back(OutFile); + + const char *Exec = + Args.MakeArgString(TC.GetProgramPath("objcopy")); + + // First extract the dwo sections. + C.addCommand(new Command(JA, T, Exec, ExtractArgs)); + + // Then remove them from the original .o file. + C.addCommand(new Command(JA, T, Exec, StripArgs)); +} + +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. + RewriteKind rewriteKind = RK_None; + + 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"); + if (Args.hasArg(options::OPT_rewrite_objc) && + !Args.hasArg(options::OPT_g_Group)) + CmdArgs.push_back("-P"); + } + } 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(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 (JA.getType() == types::TY_Nothing) + CmdArgs.push_back("-fsyntax-only"); + else 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_ModuleFile) { + CmdArgs.push_back("-module-file-info"); + } else if (JA.getType() == types::TY_RewrittenObjC) { + CmdArgs.push_back("-rewrite-objc"); + rewriteKind = RK_NonFragile; + } else if (JA.getType() == types::TY_RewrittenLegacyObjC) { + CmdArgs.push_back("-rewrite-objc"); + rewriteKind = RK_Fragile; + } 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(getBaseInputName(Args, Inputs)); + + // Some flags which affect the language (via preprocessor + // defines). + 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"); + + // 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()); + 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); + + // For the PIC and PIE flag options, this logic is different from the legacy + // logic in very old versions of GCC, as that logic was just a bug no one had + // ever fixed. This logic is both more rational and consistent with GCC's new + // logic now that the bugs are fixed. The last argument relating to either + // PIC or PIE wins, and no other argument is used. If the last argument is + // any flavor of the '-fno-...' arguments, both PIC and PIE are disabled. Any + // PIE option implicitly enables PIC at the same level. + bool PIE = false; + bool PIC = getToolChain().isPICDefault(); + bool IsPICLevelTwo = PIC; + if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, + options::OPT_fpic, options::OPT_fno_pic, + options::OPT_fPIE, options::OPT_fno_PIE, + options::OPT_fpie, options::OPT_fno_pie)) { + Option O = A->getOption(); + if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) || + O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) { + PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie); + PIC = PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic); + IsPICLevelTwo = O.matches(options::OPT_fPIE) || + O.matches(options::OPT_fPIC); + } else { + PIE = PIC = false; + } + } + // Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness + // is forced, then neither PIC nor PIE flags will have no effect. + if (getToolChain().isPICDefaultForced()) { + PIE = false; + PIC = getToolChain().isPICDefault(); + IsPICLevelTwo = PIC; + } + + // Inroduce a Darwin-specific hack. If the default is PIC but the flags + // specified while enabling PIC enabled level 1 PIC, just force it back to + // level 2 PIC instead. This matches the behavior of Darwin GCC (based on my + // informal testing). + if (PIC && getToolChain().getTriple().isOSDarwin()) + IsPICLevelTwo |= getToolChain().isPICDefault(); + + // 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. + llvm::Triple Triple(TripleStr); + if (KernelOrKext && + (Triple.getOS() != llvm::Triple::IOS || + Triple.isOSVersionLT(6))) + PIC = PIE = false; + if (Args.hasArg(options::OPT_static)) + PIC = PIE = false; + + if (Arg *A = Args.getLastArg(options::OPT_mdynamic_no_pic)) { + // This is a very special mode. It trumps the other modes, almost no one + // uses it, and it isn't even valid on any OS but Darwin. + if (!getToolChain().getTriple().isOSDarwin()) + D.Diag(diag::err_drv_unsupported_opt_for_target) + << A->getSpelling() << getToolChain().getTriple().str(); + + // FIXME: Warn when this flag trumps some other PIC or PIE flag. + + CmdArgs.push_back("-mrelocation-model"); + CmdArgs.push_back("dynamic-no-pic"); + + // Only a forced PIC mode can cause the actual compile to have PIC defines + // etc., no flags are sufficient. This behavior was selected to closely + // match that of llvm-gcc and Apple GCC before that. + if (getToolChain().isPICDefault() && getToolChain().isPICDefaultForced()) { + CmdArgs.push_back("-pic-level"); + CmdArgs.push_back("2"); + } + } else { + // Currently, LLVM only knows about PIC vs. static; the PIE differences are + // handled in Clang's IRGen by the -pie-level flag. + CmdArgs.push_back("-mrelocation-model"); + CmdArgs.push_back(PIC ? "pic" : "static"); + + if (PIC) { + CmdArgs.push_back("-pic-level"); + CmdArgs.push_back(IsPICLevelTwo ? "2" : "1"); + if (PIE) { + CmdArgs.push_back("-pie-level"); + CmdArgs.push_back(IsPICLevelTwo ? "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()); + } + + 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.hasArg(options::OPT_fstruct_path_tbaa)) + CmdArgs.push_back("-struct-path-tbaa"); + 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 segmented stacks. + if (Args.hasArg(options::OPT_fsplit_stack)) + CmdArgs.push_back("-split-stacks"); + + // 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_fno_fast_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_fast_math && + 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_fno_fast_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_fast_math && + A->getOption().getID() != options::OPT_fno_finite_math_only && + A->getOption().getID() != options::OPT_fhonor_nans) + CmdArgs.push_back("-menable-no-nans"); + + // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes. + bool MathErrno = getToolChain().IsMathErrnoDefault(); + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_fno_fast_math, + options::OPT_fmath_errno, + options::OPT_fno_math_errno)) + MathErrno = A->getOption().getID() == options::OPT_fmath_errno; + if (MathErrno) + CmdArgs.push_back("-fmath-errno"); + + // 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_fno_fast_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_fast_math && + 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_fno_fast_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_fast_math && + 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_fno_fast_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_fast_math && + 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_fno_fast_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_fast_math && + 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"); + + + // Validate and pass through -fp-contract option. + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, + options::OPT_fno_fast_math, + options::OPT_ffp_contract)) { + if (A->getOption().getID() == options::OPT_ffp_contract) { + StringRef Val = A->getValue(); + if (Val == "fast" || Val == "on" || Val == "off") { + CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + Val)); + } else { + D.Diag(diag::err_drv_unsupported_option_argument) + << A->getOption().getName() << Val; + } + } else if (A->getOption().getID() == options::OPT_ffast_math) { + // If fast-math is set then set the fp-contract mode to fast. + CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast")); + } + } + + // We separately look for the '-ffast-math' and '-ffinite-math-only' flags, + // and if we find them, tell the frontend to provide the appropriate + // preprocessor macros. This is distinct from enabling any optimizations as + // these options induce language changes which must survive serialization + // and deserialization, etc. + if (Arg *A = Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math)) + if (A->getOption().matches(options::OPT_ffast_math)) + CmdArgs.push_back("-ffast-math"); + if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only, options::OPT_fno_fast_math)) + if (A->getOption().matches(options::OPT_ffinite_math_only)) + CmdArgs.push_back("-ffinite-math-only"); + + // 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"); + + getToolChain().addClangTargetOptions(Args, CmdArgs); + + if (Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) { + CmdArgs.push_back("-mlimit-float-precision"); + CmdArgs.push_back(A->getValue()); + } + + // 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()); + } + + // 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::ppc: + case llvm::Triple::ppc64: + AddPPCTargetArgs(Args, CmdArgs); + break; + + case llvm::Triple::r600: + AddR600TargetArgs(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()); + } + + if (!shouldUseLeafFramePointer(Args, getToolChain().getTriple())) + 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 : "-"); + } + + // Use the last option from "-g" group. "-gline-tables-only" + // is preserved, all other debug options are substituted with "-g". + Args.ClaimAllArgs(options::OPT_g_Group); + if (Arg *A = Args.getLastArg(options::OPT_g_Group)) { + if (A->getOption().matches(options::OPT_gline_tables_only)) + CmdArgs.push_back("-gline-tables-only"); + else if (!A->getOption().matches(options::OPT_g0) && + !A->getOption().matches(options::OPT_ggdb0)) + CmdArgs.push_back("-g"); + } + + // We ignore flags -gstrict-dwarf and -grecord-gcc-switches for now. + Args.ClaimAllArgs(options::OPT_g_flags_Group); + if (Args.hasArg(options::OPT_gcolumn_info)) + CmdArgs.push_back("-dwarf-column-info"); + + // -gsplit-dwarf should turn on -g and enable the backend dwarf + // splitting and extraction. + // FIXME: Currently only works on Linux. + if (getToolChain().getTriple().getOS() == llvm::Triple::Linux && + Args.hasArg(options::OPT_gsplit_dwarf)) { + CmdArgs.push_back("-g"); + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-split-dwarf=Enable"); + } + + 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"); + SmallString<128> CoverageFilename(Output.getFilename()); + if (llvm::sys::path::is_relative(CoverageFilename.str())) { + if (const char *pwd = ::getenv("PWD")) { + if (llvm::sys::path::is_absolute(pwd)) { + SmallString<128> Pwd(pwd); + llvm::sys::path::append(Pwd, CoverageFilename.str()); + CoverageFilename.swap(Pwd); + } + } + } + CmdArgs.push_back(Args.MakeArgString(CoverageFilename)); + } + } + + // 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.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()); + + 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, JA, 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()[0] == '\0') + CmdArgs.push_back("-O2"); + else + A->render(Args, CmdArgs); + } + + // Don't warn about unused -flto. This can happen when we're preprocessing or + // precompiling. + Args.ClaimAllArgs(options::OPT_flto); + + Args.AddAllArgs(CmdArgs, options::OPT_W_Group); + if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false)) + CmdArgs.push_back("-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); + else if (getToolChain().getTriple().getOS() == llvm::Triple::Win32) + CmdArgs.push_back("-std=c++11"); + + 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"); + + // Add in -fdebug-compilation-dir if necessary. + addDebugCompDirArg(Args, CmdArgs); + + if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_, + options::OPT_ftemplate_depth_EQ)) { + CmdArgs.push_back("-ftemplate-depth"); + CmdArgs.push_back(A->getValue()); + } + + if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) { + CmdArgs.push_back("-fconstexpr-depth"); + CmdArgs.push_back(A->getValue()); + } + + if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) { + CmdArgs.push_back("-fbracket-depth"); + CmdArgs.push_back(A->getValue()); + } + + if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ, + options::OPT_Wlarge_by_value_copy_def)) { + if (A->getNumValues()) { + StringRef bytes = A->getValue(); + CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes)); + } else + CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value + } + + + 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()); + } + + if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) { + CmdArgs.push_back("-ftabstop"); + CmdArgs.push_back(A->getValue()); + } + + CmdArgs.push_back("-ferror-limit"); + if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ)) + CmdArgs.push_back(A->getValue()); + 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()); + } + + if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) { + CmdArgs.push_back("-ftemplate-backtrace-limit"); + CmdArgs.push_back(A->getValue()); + } + + if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) { + CmdArgs.push_back("-fconstexpr-backtrace-limit"); + CmdArgs.push_back(A->getValue()); + } + + // Pass -fmessage-length=. + CmdArgs.push_back("-fmessage-length"); + if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) { + CmdArgs.push_back(A->getValue()); + } 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))); + } + + // -fvisibility= and -fvisibility-ms-compat are of a piece. + if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ, + options::OPT_fvisibility_ms_compat)) { + if (A->getOption().matches(options::OPT_fvisibility_EQ)) { + CmdArgs.push_back("-fvisibility"); + CmdArgs.push_back(A->getValue()); + } else { + assert(A->getOption().matches(options::OPT_fvisibility_ms_compat)); + CmdArgs.push_back("-fvisibility"); + CmdArgs.push_back("hidden"); + CmdArgs.push_back("-ftype-visibility"); + CmdArgs.push_back("default"); + } + } + + Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden); + + Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ); + + // -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_femit_all_decls); + Args.AddLastArg(CmdArgs, options::OPT_fformat_extensions); + 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); + Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree); + Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type); + + SanitizerArgs Sanitize(D, Args); + Sanitize.addArgs(Args, CmdArgs); + + if (!Args.hasFlag(options::OPT_fsanitize_recover, + options::OPT_fno_sanitize_recover, + true)) + CmdArgs.push_back("-fno-sanitize-recover"); + + if (Args.hasArg(options::OPT_fcatch_undefined_behavior) || + Args.hasFlag(options::OPT_fsanitize_undefined_trap_on_error, + options::OPT_fno_sanitize_undefined_trap_on_error, false)) + CmdArgs.push_back("-fsanitize-undefined-trap-on-error"); + + // Report an error for -faltivec on anything other than 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); + + // -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"); + + if (Args.hasFlag(options::OPT_frewrite_includes, + options::OPT_fno_rewrite_includes, false)) + CmdArgs.push_back("-frewrite-includes"); + + 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.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))); + } + + // --param ssp-buffer-size= + for (arg_iterator it = Args.filtered_begin(options::OPT__param), + ie = Args.filtered_end(); it != ie; ++it) { + StringRef Str((*it)->getValue()); + if (Str.startswith("ssp-buffer-size=")) { + if (StackProtectorLevel) { + CmdArgs.push_back("-stack-protector-buffer-size"); + // FIXME: Verify the argument is a valid integer. + CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16))); + } + (*it)->claim(); + } + } + + // 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)); + } + // -mkernel implies -mstrict-align; don't add the redundant option. + if (Args.hasArg(options::OPT_mstrict_align) && !KernelOrKext) { + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-arm-strict-align"); + } + + // 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. + bool HaveModules = false; + 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"); + HaveModules = true; + } + } + + // If a module path was provided, pass it along. Otherwise, use a temporary + // directory. + if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path)) { + A->claim(); + if (HaveModules) { + A->render(Args, CmdArgs); + } + } else if (HaveModules) { + SmallString<128> DefaultModuleCache; + llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, + DefaultModuleCache); + llvm::sys::path::append(DefaultModuleCache, "org.llvm.clang"); + llvm::sys::path::append(DefaultModuleCache, "ModuleCache"); + const char Arg[] = "-fmodules-cache-path="; + DefaultModuleCache.insert(DefaultModuleCache.begin(), + Arg, Arg + strlen(Arg)); + CmdArgs.push_back(Args.MakeArgString(DefaultModuleCache)); + } + + // Pass through all -fmodules-ignore-macro arguments. + Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro); + Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval); + Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after); + + // -fmodules-autolink (on by default when modules is enabled) automatically + // links against libraries for imported modules. This requires the + // integrated assembler. + if (HaveModules && getToolChain().useIntegratedAs() && + Args.hasFlag(options::OPT_fmodules_autolink, + options::OPT_fno_modules_autolink, + true)) { + CmdArgs.push_back("-fmodules-autolink"); + } + + // -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"); + + // -fno-rtti cannot usefully be combined with -fsanitize=vptr. + if (Sanitize.sanitizesVptr()) { + std::string NoRttiArg = + Args.getLastArg(options::OPT_mkernel, + options::OPT_fapple_kext, + options::OPT_fno_rtti)->getAsString(Args); + D.Diag(diag::err_drv_argument_not_allowed_with) + << "-fsanitize=vptr" << NoRttiArg; + } + } + + // -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)); + } + + + // -fno-borland-extensions 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"); + + ObjCRuntime objcRuntime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind); + + // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and + // legacy is the default. + if (objcRuntime.isNonFragile()) { + if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch, + options::OPT_fno_objc_legacy_dispatch, + objcRuntime.isLegacyDispatchDefaultForArch( + getToolChain().getTriple().getArch()))) { + 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"); + } + + // -fencode-extended-block-signature=1 is default. + if (getToolChain().IsEncodeExtendedBlockSignatureDefault()) { + CmdArgs.push_back("-fencode-extended-block-signature"); + } + + // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc. + // NOTE: This logic is duplicated in ToolChains.cpp. + bool ARC = isObjCAutoRefCount(Args); + if (ARC) { + getToolChain().CheckObjCARC(); + + 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 (rewriteKind != RK_None) + 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, objcRuntime, 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)) { + std::string PackStructStr = "-fpack-struct="; + PackStructStr += A->getValue(); + CmdArgs.push_back(Args.MakeArgString(PackStructStr)); + } else if (Args.hasFlag(options::OPT_fpack_struct, + options::OPT_fno_pack_struct, false)) { + CmdArgs.push_back("-fpack-struct=1"); + } + + if (KernelOrKext) { + 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()); + } + + if (const Arg *A = + Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) { + CmdArgs.push_back("-fdiagnostics-format"); + CmdArgs.push_back(A->getValue()); + } + + 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"); + + + // -fno-asm-blocks is default. + if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks, + false)) + CmdArgs.push_back("-fasm-blocks"); + + // -fvectorize is default. + if (Args.hasFlag(options::OPT_fvectorize, + options::OPT_fno_vectorize, true)) { + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-vectorize-loops"); + } + + // -fno-slp-vectorize is default. + if (Args.hasFlag(options::OPT_fslp_vectorize, + options::OPT_fno_slp_vectorize, false)) { + CmdArgs.push_back("-backend-option"); + CmdArgs.push_back("-vectorize"); + } + + 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())); + } + + if (Args.hasArg(options::OPT_fretain_comments_from_system_headers)) + CmdArgs.push_back("-fretain-comments-from-system-headers"); + + // Forward -fcomment-block-commands to -cc1. + Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands); + + // 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(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"); + if (Args.hasArg(options::OPT_rewrite_objc)) + CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX)); + else + 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())); + } + + // Add the split debug info name to the command lines here so we + // can propagate it to the backend. + bool SplitDwarf = Args.hasArg(options::OPT_gsplit_dwarf) && + (getToolChain().getTriple().getOS() == llvm::Triple::Linux) && + (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA)); + const char *SplitDwarfOut; + if (SplitDwarf) { + CmdArgs.push_back("-split-dwarf-file"); + SplitDwarfOut = SplitDebugName(Args, Inputs); + CmdArgs.push_back(SplitDwarfOut); + } + + // Finally add the compile command to the compilation. + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); + + // Handle the debug info splitting at object creation time if we're + // creating an object. + // TODO: Currently only works on linux with newer objcopy. + if (SplitDwarf && !isa<CompileJobAction>(JA)) + SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output, SplitDwarfOut); + + 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(Args.MakeArgString(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::AddX86TargetArgs(const ArgList &Args, + ArgStringList &CmdArgs) const { + // Set the CPU based on -march=. + if (const char *CPUName = getX86TargetCPU(Args, getToolChain().getTriple())) { + CmdArgs.push_back("-target-cpu"); + CmdArgs.push_back(CPUName); + } +} + +/// Add options related to the Objective-C runtime/ABI. +/// +/// Returns true if the runtime is non-fragile. +ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args, + ArgStringList &cmdArgs, + RewriteKind rewriteKind) const { + // Look for the controlling runtime option. + Arg *runtimeArg = args.getLastArg(options::OPT_fnext_runtime, + options::OPT_fgnu_runtime, + options::OPT_fobjc_runtime_EQ); + + // Just forward -fobjc-runtime= to the frontend. This supercedes + // options about fragility. + if (runtimeArg && + runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) { + ObjCRuntime runtime; + StringRef value = runtimeArg->getValue(); + if (runtime.tryParse(value)) { + getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime) + << value; + } + + runtimeArg->render(args, cmdArgs); + return runtime; + } + + // Otherwise, we'll need the ABI "version". Version numbers are + // slightly confusing for historical reasons: + // 1 - Traditional "fragile" ABI + // 2 - Non-fragile ABI, version 1 + // 3 - Non-fragile ABI, version 2 + unsigned objcABIVersion = 1; + // If -fobjc-abi-version= is present, use that to set the version. + if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) { + StringRef value = abiArg->getValue(); + if (value == "1") + objcABIVersion = 1; + else if (value == "2") + objcABIVersion = 2; + else if (value == "3") + objcABIVersion = 3; + else + getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) + << value; + } else { + // Otherwise, determine if we are using the non-fragile ABI. + bool nonFragileABIIsDefault = + (rewriteKind == RK_NonFragile || + (rewriteKind == RK_None && + 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 *abiArg = args.getLastArg( + options::OPT_fobjc_nonfragile_abi_version_EQ)) { + StringRef value = abiArg->getValue(); + if (value == "1") + nonFragileABIVersion = 1; + else if (value == "2") + nonFragileABIVersion = 2; + else + getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) + << value; + } + + objcABIVersion = 1 + nonFragileABIVersion; + } else { + objcABIVersion = 1; + } + } + + // We don't actually care about the ABI version other than whether + // it's non-fragile. + bool isNonFragile = objcABIVersion != 1; + + // If we have no runtime argument, ask the toolchain for its default runtime. + // However, the rewriter only really supports the Mac runtime, so assume that. + ObjCRuntime runtime; + if (!runtimeArg) { + switch (rewriteKind) { + case RK_None: + runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); + break; + case RK_Fragile: + runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple()); + break; + case RK_NonFragile: + runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); + break; + } + + // -fnext-runtime + } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) { + // On Darwin, make this use the default behavior for the toolchain. + if (getToolChain().getTriple().isOSDarwin()) { + runtime = getToolChain().getDefaultObjCRuntime(isNonFragile); + + // Otherwise, build for a generic macosx port. + } else { + runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple()); + } + + // -fgnu-runtime + } else { + assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime)); + // Legacy behaviour is to target the gnustep runtime if we are i + // non-fragile mode or the GCC runtime in fragile mode. + if (isNonFragile) + runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(1,6)); + else + runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple()); + } + + cmdArgs.push_back(args.MakeArgString( + "-fobjc-runtime=" + runtime.getAsString())); + return runtime; +} + +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"); + + // Set the main file name, so that debug info works even with + // -save-temps or preprocessed assembly. + CmdArgs.push_back("-main-file-name"); + CmdArgs.push_back(Clang::getBaseInputName(Args, Inputs)); + + 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; + + case llvm::Triple::x86: + case llvm::Triple::x86_64: + AddX86TargetArgs(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 and handle debug info related flags, 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"); + + // Add the -fdebug-compilation-dir flag if needed. + addDebugCompDirArg(Args, CmdArgs); + + // Set the AT_producer to the clang version when using the integrated + // assembler on assembly source files. + CmdArgs.push_back("-dwarf-debug-producer"); + CmdArgs.push_back(Args.MakeArgString(getClangFullVersion())); + } + + // 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 (forwardToGCC(A->getOption())) { + // 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. + llvm::Triple::ArchType Arch = getToolChain().getArch(); + if (getToolChain().getTriple().isOSDarwin()) { + CmdArgs.push_back("-arch"); + + // FIXME: Remove these special cases. + if (Arch == llvm::Triple::ppc) + CmdArgs.push_back("ppc"); + else if (Arch == llvm::Triple::ppc64) + CmdArgs.push_back("ppc64"); + else + CmdArgs.push_back(Args.MakeArgString(getToolChain().getArchName())); + } + + // 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 == llvm::Triple::x86 || Arch == llvm::Triple::ppc) + CmdArgs.push_back("-m32"); + else if (Arch == llvm::Triple::x86_64 || Arch == llvm::Triple::ppc64) + 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(); + else if (II.getType() == types::TY_ModuleFile) + D.Diag(diag::err_drv_no_module_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 += toolchains::Hexagon_TC::GetTargetCPU(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"); + } + + std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args); + if (!SmallDataThreshold.empty()) + CmdArgs.push_back( + Args.MakeArgString(std::string("-G") + SmallDataThreshold)); + + Args.AddAllArgs(CmdArgs, options::OPT_g_Group); + 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(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(); + else if (II.getType() == types::TY_ModuleFile) + D.Diag(diag::err_drv_no_module_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 toolchains::Hexagon_TC& ToolChain = + static_cast<const toolchains::Hexagon_TC&>(getToolChain()); + const Driver &D = ToolChain.getDriver(); + + ArgStringList CmdArgs; + + //---------------------------------------------------------------------------- + // + //---------------------------------------------------------------------------- + bool hasStaticArg = Args.hasArg(options::OPT_static); + bool buildingLib = Args.hasArg(options::OPT_shared); + bool buildPIE = Args.hasArg(options::OPT_pie); + bool incStdLib = !Args.hasArg(options::OPT_nostdlib); + bool incStartFiles = !Args.hasArg(options::OPT_nostartfiles); + bool incDefLibs = !Args.hasArg(options::OPT_nodefaultlibs); + bool useShared = buildingLib && !hasStaticArg; + + //---------------------------------------------------------------------------- + // Silence warnings for various options + //---------------------------------------------------------------------------- + + Args.ClaimAllArgs(options::OPT_g_Group); + Args.ClaimAllArgs(options::OPT_emit_llvm); + Args.ClaimAllArgs(options::OPT_w); // Other warning options are already + // handled somewhere else. + Args.ClaimAllArgs(options::OPT_static_libgcc); + + //---------------------------------------------------------------------------- + // + //---------------------------------------------------------------------------- + for (std::vector<std::string>::const_iterator i = ToolChain.ExtraOpts.begin(), + e = ToolChain.ExtraOpts.end(); + i != e; ++i) + CmdArgs.push_back(i->c_str()); + + std::string MarchString = toolchains::Hexagon_TC::GetTargetCPU(Args); + CmdArgs.push_back(Args.MakeArgString("-m" + MarchString)); + + if (buildingLib) { + CmdArgs.push_back("-shared"); + CmdArgs.push_back("-call_shared"); // should be the default, but doing as + // hexagon-gcc does + } + + if (hasStaticArg) + CmdArgs.push_back("-static"); + + if (buildPIE && !buildingLib) + CmdArgs.push_back("-pie"); + + std::string SmallDataThreshold = GetHexagonSmallDataThresholdValue(Args); + if (!SmallDataThreshold.empty()) { + CmdArgs.push_back( + Args.MakeArgString(std::string("-G") + SmallDataThreshold)); + } + + //---------------------------------------------------------------------------- + // + //---------------------------------------------------------------------------- + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + const std::string MarchSuffix = "/" + MarchString; + const std::string G0Suffix = "/G0"; + const std::string MarchG0Suffix = MarchSuffix + G0Suffix; + const std::string RootDir = toolchains::Hexagon_TC::GetGnuDir(D.InstalledDir) + + "/"; + const std::string StartFilesDir = RootDir + + "hexagon/lib" + + (buildingLib + ? MarchG0Suffix : MarchSuffix); + + //---------------------------------------------------------------------------- + // moslib + //---------------------------------------------------------------------------- + std::vector<std::string> oslibs; + bool hasStandalone= false; + + for (arg_iterator it = Args.filtered_begin(options::OPT_moslib_EQ), + ie = Args.filtered_end(); it != ie; ++it) { + (*it)->claim(); + oslibs.push_back((*it)->getValue()); + hasStandalone = hasStandalone || (oslibs.back() == "standalone"); + } + if (oslibs.empty()) { + oslibs.push_back("standalone"); + hasStandalone = true; + } + + //---------------------------------------------------------------------------- + // Start Files + //---------------------------------------------------------------------------- + if (incStdLib && incStartFiles) { + + if (!buildingLib) { + if (hasStandalone) { + CmdArgs.push_back( + Args.MakeArgString(StartFilesDir + "/crt0_standalone.o")); + } + CmdArgs.push_back(Args.MakeArgString(StartFilesDir + "/crt0.o")); + } + std::string initObj = useShared ? "/initS.o" : "/init.o"; + CmdArgs.push_back(Args.MakeArgString(StartFilesDir + initObj)); + } + + //---------------------------------------------------------------------------- + // Library Search Paths + //---------------------------------------------------------------------------- + const ToolChain::path_list &LibPaths = ToolChain.getFilePaths(); + for (ToolChain::path_list::const_iterator + i = LibPaths.begin(), + e = LibPaths.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_u_Group); + + AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs); + + //---------------------------------------------------------------------------- + // Libraries + //---------------------------------------------------------------------------- + if (incStdLib && incDefLibs) { + if (D.CCCIsCXX) { + ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); + CmdArgs.push_back("-lm"); + } + + CmdArgs.push_back("--start-group"); + + if (!buildingLib) { + for(std::vector<std::string>::iterator i = oslibs.begin(), + e = oslibs.end(); i != e; ++i) + CmdArgs.push_back(Args.MakeArgString("-l" + *i)); + CmdArgs.push_back("-lc"); + } + CmdArgs.push_back("-lgcc"); + + CmdArgs.push_back("--end-group"); + } + + //---------------------------------------------------------------------------- + // End files + //---------------------------------------------------------------------------- + if (incStdLib && incStartFiles) { + std::string finiObj = useShared ? "/finiS.o" : "/fini.o"; + CmdArgs.push_back(Args.MakeArgString(StartFilesDir + finiObj)); + } + + std::string Linker = ToolChain.GetProgramPath("hexagon-ld"); + C.addCommand( + new Command( + JA, *this, + Args.MakeArgString(Linker), CmdArgs)); +} +// Hexagon tools end. + +llvm::Triple::ArchType darwin::getArchTypeForDarwinArchName(StringRef Str) { + // See arch(3) and llvm-gcc's driver-driver.c. We don't implement support for + // archs which Darwin doesn't use. + + // The matching this routine does is fairly pointless, since it is neither the + // complete architecture list, nor a reasonable subset. The problem is that + // historically the driver driver accepts this and also ties its -march= + // handling to the architecture name, so we need to be careful before removing + // support for it. + + // This code must be kept in sync with Clang's Darwin specific argument + // translation. + + return llvm::StringSwitch<llvm::Triple::ArchType>(Str) + .Cases("ppc", "ppc601", "ppc603", "ppc604", "ppc604e", llvm::Triple::ppc) + .Cases("ppc750", "ppc7400", "ppc7450", "ppc970", llvm::Triple::ppc) + .Case("ppc64", llvm::Triple::ppc64) + .Cases("i386", "i486", "i486SX", "i586", "i686", llvm::Triple::x86) + .Cases("pentium", "pentpro", "pentIIm3", "pentIIm5", "pentium4", + llvm::Triple::x86) + .Case("x86_64", llvm::Triple::x86_64) + // This is derived from the driver driver. + .Cases("arm", "armv4t", "armv5", "armv6", "armv6m", llvm::Triple::arm) + .Cases("armv7", "armv7em", "armv7f", "armv7k", "armv7m", llvm::Triple::arm) + .Cases("armv7s", "xscale", llvm::Triple::arm) + .Case("r600", llvm::Triple::r600) + .Case("nvptx", llvm::Triple::nvptx) + .Case("nvptx64", llvm::Triple::nvptx64) + .Case("amdil", llvm::Triple::amdil) + .Case("spir", llvm::Triple::spir) + .Default(llvm::Triple::UnknownArch); +} + +const char *Clang::getBaseInputName(const ArgList &Args, + const InputInfoList &Inputs) { + return Args.MakeArgString( + llvm::sys::path::filename(Inputs[0].getBaseInput())); +} + +const char *Clang::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 *Clang::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()); + Res = Str.substr(0, Str.rfind('.')); + } else { + Res = getBaseInputStem(Args, Inputs); + } + return Args.MakeArgString(Res + ".d"); +} + +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_fapple_kext)) && + (!getDarwinToolChain().isTargetIPhoneOS() || + getDarwinToolChain().isIPhoneOSVersionLT(6, 0))) || + Args.hasArg(options::OPT_static))) + 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"); +} + +bool darwin::Link::NeedsTempPath(const InputInfoList &Inputs) const { + // We only need to generate a temp path for LTO if we aren't compiling object + // files. When compiling source files, we run 'dsymutil' after linking. We + // don't run 'dsymutil' when compiling object files. + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) + if (it->getType() != types::TY_Object) + return true; + + return false; +} + +void darwin::Link::AddLinkArgs(Compilation &C, + const ArgList &Args, + ArgStringList &CmdArgs, + const InputInfoList &Inputs) 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(), 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(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) && NeedsTempPath(Inputs)) { + 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.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, Inputs); + + 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.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"); + + if (Args.hasArg(options::OPT_rdynamic)) + CmdArgs.push_back("-export_dynamic"); + + CmdArgs.push_back("-o"); + CmdArgs.push_back(Output.getFilename()); + + if (!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. + } + // By default on OS X 10.8 and later, we don't link with a crt1.o + // file and the linker knows to use _main as the entry point. But, + // when compiling with -pg, we need to link with the gcrt1.o file, + // so pass the -no_new_main option to tell the linker to use the + // "start" symbol as the entry point. + if (getDarwinToolChain().isTargetMacOS() && + !getDarwinToolChain().isMacosxVersionLT(10, 8)) + CmdArgs.push_back("-no_new_main"); + } 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 if (getDarwinToolChain().isIPhoneOSVersionLT(6, 0)) + 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); + + SanitizerArgs Sanitize(getToolChain().getDriver(), Args); + // If we're building a dynamic lib with -fsanitize=address, + // unresolved symbols may appear. Mark all + // of them as dynamic_lookup. Linking executables is handled in + // lib/Driver/ToolChains.cpp. + if (Sanitize.needsAsanRt()) { + 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"); + + AddLinkerInputs(getToolChain(), Inputs, Args, CmdArgs); + + if (isObjCRuntimeLinked(Args) && + !Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + // Avoid linking compatibility stubs on i386 mac. + if (!getDarwinToolChain().isTargetMacOS() || + getDarwinToolChain().getArch() != llvm::Triple::x86) { + // 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().getDefaultObjCRuntime(/*nonfragile*/ true); + // We use arclite library for both ARC and subscripting support. + if ((!runtime.hasNativeARC() && isObjCAutoRefCount(Args)) || + !runtime.hasSubscripting()) + getDarwinToolChain().AddLinkARCArgs(Args, CmdArgs); + } + CmdArgs.push_back("-framework"); + CmdArgs.push_back("Foundation"); + // Link libobj. + CmdArgs.push_back("-lobjc"); + } + + 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_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; + + // 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 -w foo.o -o foo". Other warning options are already + // handled somewhere else. + Args.ClaimAllArgs(options::OPT_w); + + 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); + 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 before adding + // the default system libraries. Just mimic this for now. + CmdArgs.push_back("-lgcc"); + + if (Args.hasArg(options::OPT_pthread)) { + if (!Args.hasArg(options::OPT_shared) && + Args.hasArg(options::OPT_pg)) + CmdArgs.push_back("-lpthread_p"); + else + 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 bitrig::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 bitrig::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"))); + } + } + + 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"); + } + + if (Args.hasArg(options::OPT_pthread)) { + if (!Args.hasArg(options::OPT_shared) && + Args.hasArg(options::OPT_pg)) + CmdArgs.push_back("-lpthread_p"); + else + 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"); + } + + std::string myarch = "-lclang_rt."; + const llvm::Triple &T = getToolChain().getTriple(); + llvm::Triple::ArchType Arch = T.getArch(); + switch (Arch) { + case llvm::Triple::arm: + myarch += ("arm"); + break; + case llvm::Triple::x86: + myarch += ("i386"); + break; + case llvm::Triple::x86_64: + myarch += ("amd64"); + break; + default: + assert(0 && "Unsupported architecture"); + } + CmdArgs.push_back(Args.MakeArgString(myarch)); + } + + 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().getArch() == llvm::Triple::x86) + CmdArgs.push_back("--32"); + else if (getToolChain().getArch() == llvm::Triple::ppc) + CmdArgs.push_back("-a32"); + 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()); + + CmdArgs.push_back("-mabi"); + CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data()); + + if (getToolChain().getArch() == llvm::Triple::mips || + getToolChain().getArch() == llvm::Triple::mips64) + CmdArgs.push_back("-EB"); + else + CmdArgs.push_back("-EL"); + + Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, + options::OPT_fpic, options::OPT_fno_pic, + options::OPT_fPIE, options::OPT_fno_PIE, + options::OPT_fpie, options::OPT_fno_pie); + if (LastPICArg && + (LastPICArg->getOption().matches(options::OPT_fPIC) || + LastPICArg->getOption().matches(options::OPT_fpic) || + LastPICArg->getOption().matches(options::OPT_fPIE) || + LastPICArg->getOption().matches(options::OPT_fpie))) { + CmdArgs.push_back("-KPIC"); + } + } else if (getToolChain().getArch() == llvm::Triple::arm || + getToolChain().getArch() == llvm::Triple::thumb) { + CmdArgs.push_back("-mfpu=softvfp"); + switch(getToolChain().getTriple().getEnvironment()) { + case llvm::Triple::GNUEABI: + case llvm::Triple::EABI: + CmdArgs.push_back("-meabi=5"); + break; + + default: + CmdArgs.push_back("-matpcs"); + } + } + + 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 toolchains::FreeBSD& ToolChain = + static_cast<const toolchains::FreeBSD&>(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 -w 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_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"); + } + if (ToolChain.getTriple().getOSMajorVersion() >= 9) { + llvm::Triple::ArchType Arch = ToolChain.getArch(); + if (Arch == llvm::Triple::arm || Arch == llvm::Triple::sparc || + Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) { + CmdArgs.push_back("--hash-style=both"); + } + } + CmdArgs.push_back("--enable-new-dtags"); + } + + // When building 32-bit code on FreeBSD/amd64, we have to explicitly + // instruct ld in the base system to link 32-bit code. + if (ToolChain.getArch() == llvm::Triple::x86) { + CmdArgs.push_back("-m"); + CmdArgs.push_back("elf_i386_fbsd"); + } + + if (ToolChain.getArch() == llvm::Triple::ppc) { + 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)) { + const char *crt1 = NULL; + if (!Args.hasArg(options::OPT_shared)) { + if (Args.hasArg(options::OPT_pg)) + crt1 = "gcrt1.o"; + else 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 = NULL; + 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)); + 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(ToolChain, Inputs, Args, CmdArgs); + + if (!Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + if (D.CCCIsCXX) { + ToolChain.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) || Args.hasArg(options::OPT_pie)) + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtendS.o"))); + else + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtend.o"))); + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath("crtn.o"))); + } + + addProfileRT(ToolChain, Args, CmdArgs, ToolChain.getTriple()); + + const char *Exec = + Args.MakeArgString(ToolChain.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().getArch() == llvm::Triple::mips) + CmdArgs.push_back("-EB"); + else if (getToolChain().getArch() == llvm::Triple::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 gnutools::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"); + + StringRef ARMFloatABI = getARMFloatABI(getToolChain().getDriver(), Args, + getToolChain().getTriple()); + CmdArgs.push_back(Args.MakeArgString("-mfloat-abi=" + ARMFloatABI)); + + Args.AddLastArg(CmdArgs, options::OPT_march_EQ); + Args.AddLastArg(CmdArgs, options::OPT_mcpu_EQ); + Args.AddLastArg(CmdArgs, options::OPT_mfpu_EQ); + } 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()); + + CmdArgs.push_back("-mabi"); + CmdArgs.push_back(getGnuCompatibleMipsABIName(ABIName).data()); + + if (getToolChain().getArch() == llvm::Triple::mips || + getToolChain().getArch() == llvm::Triple::mips64) + CmdArgs.push_back("-EB"); + else + CmdArgs.push_back("-EL"); + + Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC, + options::OPT_fpic, options::OPT_fno_pic, + options::OPT_fPIE, options::OPT_fno_PIE, + options::OPT_fpie, options::OPT_fno_pie); + if (LastPICArg && + (LastPICArg->getOption().matches(options::OPT_fPIC) || + LastPICArg->getOption().matches(options::OPT_fpic) || + LastPICArg->getOption().matches(options::OPT_fPIE) || + LastPICArg->getOption().matches(options::OPT_fpie))) { + CmdArgs.push_back("-KPIC"); + } + } + + 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(llvm::Triple Triple, const Driver &D, + ArgStringList &CmdArgs, const ArgList &Args) { + bool isAndroid = Triple.getEnvironment() == llvm::Triple::Android; + bool StaticLibgcc = Args.hasArg(options::OPT_static_libgcc) || + Args.hasArg(options::OPT_static); + if (!D.CCCIsCXX) + CmdArgs.push_back("-lgcc"); + + if (StaticLibgcc || isAndroid) { + 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 && !isAndroid) + CmdArgs.push_back("-lgcc_eh"); + else if (!Args.hasArg(options::OPT_shared) && D.CCCIsCXX) + CmdArgs.push_back("-lgcc"); + + // According to Android ABI, we have to link with libdl if we are + // linking with non-static libgcc. + // + // NOTE: This fixes a link error on Android MIPS as well. The non-static + // libgcc for MIPS relies on _Unwind_Find_FDE and dl_iterate_phdr from libdl. + if (isAndroid && !StaticLibgcc) + CmdArgs.push_back("-ldl"); +} + +static bool hasMipsN32ABIArg(const ArgList &Args) { + Arg *A = Args.getLastArg(options::OPT_mabi_EQ); + return A && (A->getValue() == StringRef("n32")); +} + +void gnutools::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(); + const bool isAndroid = + ToolChain.getTriple().getEnvironment() == llvm::Triple::Android; + + 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 -w 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) && !Args.hasArg(options::OPT_shared)) + 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::aarch64) + CmdArgs.push_back("aarch64linux"); + 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) { + if (hasMipsN32ABIArg(Args)) + CmdArgs.push_back("elf32btsmipn32"); + else + CmdArgs.push_back("elf64btsmip"); + } + else if (ToolChain.getArch() == llvm::Triple::mips64el) { + if (hasMipsN32ABIArg(Args)) + CmdArgs.push_back("elf32ltsmipn32"); + else + 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 (isAndroid) { + CmdArgs.push_back("-Bsymbolic"); + } + } + + 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 (isAndroid) + CmdArgs.push_back("/system/bin/linker"); + else if (ToolChain.getArch() == llvm::Triple::x86) + CmdArgs.push_back("/lib/ld-linux.so.2"); + else if (ToolChain.getArch() == llvm::Triple::aarch64) + CmdArgs.push_back("/lib/ld-linux-aarch64.so.1"); + else if (ToolChain.getArch() == llvm::Triple::arm || + ToolChain.getArch() == llvm::Triple::thumb) { + if (ToolChain.getTriple().getEnvironment() == llvm::Triple::GNUEABIHF) + CmdArgs.push_back("/lib/ld-linux-armhf.so.3"); + else + 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) { + if (hasMipsN32ABIArg(Args)) + CmdArgs.push_back("/lib32/ld.so.1"); + else + 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)) { + if (!isAndroid) { + 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 = isAndroid ? "crtbegin_static.o" : "crtbeginT.o"; + else if (Args.hasArg(options::OPT_shared)) + crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o"; + else if (Args.hasArg(options::OPT_pie)) + crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o"; + else + crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o"; + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtbegin))); + + // Add crtfastmath.o if available and fast math is enabled. + ToolChain.AddFastMathRuntimeIfAvailable(Args, CmdArgs); + } + + 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)); + + // Try to pass driver level flags relevant to LTO code generation down to + // the plugin. + + // Handle architecture-specific flags for selecting CPU variants. + if (ToolChain.getArch() == llvm::Triple::x86 || + ToolChain.getArch() == llvm::Triple::x86_64) + CmdArgs.push_back( + Args.MakeArgString(Twine("-plugin-opt=mcpu=") + + getX86TargetCPU(Args, ToolChain.getTriple()))); + else if (ToolChain.getArch() == llvm::Triple::arm || + ToolChain.getArch() == llvm::Triple::thumb) + CmdArgs.push_back( + Args.MakeArgString(Twine("-plugin-opt=mcpu=") + + getARMTargetCPU(Args, ToolChain.getTriple()))); + + // FIXME: Factor out logic for MIPS, PPC, and other targets to support this + // as well. + } + + + if (Args.hasArg(options::OPT_Z_Xlinker__no_demangle)) + CmdArgs.push_back("--no-demangle"); + + AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs); + + SanitizerArgs Sanitize(D, Args); + + // Call these before we add the C++ ABI library. + if (Sanitize.needsUbsanRt()) + addUbsanRTLinux(getToolChain(), Args, CmdArgs, D.CCCIsCXX, + Sanitize.needsAsanRt() || Sanitize.needsTsanRt() || + Sanitize.needsMsanRt()); + if (Sanitize.needsAsanRt()) + addAsanRTLinux(getToolChain(), Args, CmdArgs); + if (Sanitize.needsTsanRt()) + addTsanRTLinux(getToolChain(), Args, CmdArgs); + if (Sanitize.needsMsanRt()) + addMsanRTLinux(getToolChain(), Args, CmdArgs); + + if (D.CCCIsCXX && + !Args.hasArg(options::OPT_nostdlib) && + !Args.hasArg(options::OPT_nodefaultlibs)) { + 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"); + } + + if (!Args.hasArg(options::OPT_nostdlib)) { + if (!Args.hasArg(options::OPT_nodefaultlibs)) { + if (Args.hasArg(options::OPT_static)) + CmdArgs.push_back("--start-group"); + + bool OpenMP = Args.hasArg(options::OPT_fopenmp); + if (OpenMP) { + CmdArgs.push_back("-lgomp"); + + // FIXME: Exclude this for platforms whith libgomp that doesn't require + // librt. Most modern Linux platfroms require it, but some may not. + CmdArgs.push_back("-lrt"); + } + + AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args); + + if (Args.hasArg(options::OPT_pthread) || + Args.hasArg(options::OPT_pthreads) || OpenMP) + CmdArgs.push_back("-lpthread"); + + CmdArgs.push_back("-lc"); + + if (Args.hasArg(options::OPT_static)) + CmdArgs.push_back("--end-group"); + else + AddLibgcc(ToolChain.getTriple(), D, CmdArgs, Args); + } + + if (!Args.hasArg(options::OPT_nostartfiles)) { + const char *crtend; + if (Args.hasArg(options::OPT_shared)) + crtend = isAndroid ? "crtend_so.o" : "crtendS.o"; + else if (Args.hasArg(options::OPT_pie)) + crtend = isAndroid ? "crtend_android.o" : "crtendS.o"; + else + crtend = isAndroid ? "crtend_android.o" : "crtend.o"; + + CmdArgs.push_back(Args.MakeArgString(ToolChain.GetFilePath(crtend))); + if (!isAndroid) + 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().getArch() == llvm::Triple::x86) + 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().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("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"); + + Args.AddAllArgValues(CmdArgs, options::OPT_l); + + // Add filenames immediately. + for (InputInfoList::const_iterator + it = Inputs.begin(), ie = Inputs.end(); it != ie; ++it) { + if (it->isFilename()) + CmdArgs.push_back(it->getFilename()); + } + + const char *Exec = + Args.MakeArgString(getToolChain().GetProgramPath("link.exe")); + C.addCommand(new Command(JA, *this, Exec, CmdArgs)); +} diff --git a/contrib/llvm/tools/clang/lib/Driver/Tools.h b/contrib/llvm/tools/clang/lib/Driver/Tools.h new file mode 100644 index 0000000..d647171 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Tools.h @@ -0,0 +1,600 @@ +//===--- 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 { + class ObjCRuntime; + +namespace driver { + class Driver; + +namespace toolchains { + class Darwin; +} + +namespace tools { + + /// \brief Clang compiler tool. + class LLVM_LIBRARY_VISIBILITY Clang : public Tool { + public: + static const char *getBaseInputName(const ArgList &Args, + const InputInfoList &Inputs); + static const char *getBaseInputStem(const ArgList &Args, + const InputInfoList &Inputs); + static const char *getDependencyFileName(const ArgList &Args, + const InputInfoList &Inputs); + + private: + void AddPreprocessingOptions(Compilation &C, + const JobAction &JA, + 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 AddPPCTargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const; + void AddR600TargetArgs(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; + + enum RewriteKind { RK_None, RK_Fragile, RK_NonFragile }; + + ObjCRuntime AddObjCRuntimeArgs(const ArgList &args, ArgStringList &cmdArgs, + RewriteKind rewrite) 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; + void AddX86TargetArgs(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 { + llvm::Triple::ArchType getArchTypeForDarwinArchName(StringRef Str); + + 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 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 { + bool NeedsTempPath(const InputInfoList &Inputs) const; + void AddLinkArgs(Compilation &C, const ArgList &Args, + ArgStringList &CmdArgs, const InputInfoList &Inputs) 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 bool isDsymutilJob() 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 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 + + /// bitrig -- Directly call GNU Binutils assembler and linker +namespace bitrig { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("bitrig::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("bitrig::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 bitrig + + /// 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 + + /// Directly call GNU Binutils' assembler and linker. +namespace gnutools { + class LLVM_LIBRARY_VISIBILITY Assemble : public Tool { + public: + Assemble(const ToolChain &TC) : Tool("GNU::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("GNU::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/contrib/llvm/tools/clang/lib/Driver/Types.cpp b/contrib/llvm/tools/clang/lib/Driver/Types.cpp new file mode 100644 index 0000000..7d22596 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/Types.cpp @@ -0,0 +1,222 @@ +//===--- 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 <cassert> +#include <string.h> + +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 || + Id == TY_LTO_BC); +} + +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_ModuleFile: + case TY_LLVM_IR: case TY_LLVM_BC: + 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_PP_ObjCXX_Alias: + case TY_CXXHeader: case TY_PP_CXXHeader: + case TY_ObjCXXHeader: case TY_PP_ObjCXXHeader: + case TY_CUDA: + 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) + .Case("pcm", TY_ModuleFile) + .Default(TY_INVALID); +} + +types::ID types::lookupTypeForTypeSpecifier(const char *Name) { + for (unsigned i=0; i<numTypes; ++i) { + types::ID Id = (types::ID) (i + 1); + if (canTypeBeUserSpecified(Id) && + strcmp(Name, getInfo(Id).Name) == 0) + return Id; + } + + return TY_INVALID; +} + +// FIXME: Why don't we just put this list in the defs file, eh. +void types::getCompilationPhases( + ID Id, + llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> &P) { + if (Id != TY_Object) { + if (getPreprocessedType(Id) != TY_INVALID) { + P.push_back(phases::Preprocess); + } + + if (onlyPrecompileType(Id)) { + P.push_back(phases::Precompile); + } else { + if (!onlyAssembleType(Id)) { + P.push_back(phases::Compile); + } + P.push_back(phases::Assemble); + } + } + if (!onlyPrecompileType(Id)) { + P.push_back(phases::Link); + } + assert(0 < P.size() && "Not enough phases in list"); + assert(P.size() <= phases::MaxNumberOfPhases && "Too many phases in list"); + return; +} + +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/contrib/llvm/tools/clang/lib/Driver/WindowsToolChain.cpp b/contrib/llvm/tools/clang/lib/Driver/WindowsToolChain.cpp new file mode 100644 index 0000000..dac7e77 --- /dev/null +++ b/contrib/llvm/tools/clang/lib/Driver/WindowsToolChain.cpp @@ -0,0 +1,336 @@ +//===--- 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/Basic/CharInfo.h" +#include "clang/Basic/Version.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/Options.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, + const ArgList &Args) + : ToolChain(D, Triple, Args) { +} + +Tool *Windows::buildLinker() const { + return new tools::visualstudio::Link(*this); +} + +Tool *Windows::buildAssembler() const { + if (getTriple().getEnvironment() == llvm::Triple::MachO) + return new tools::darwin::Assemble(*this); + getDriver().Diag(clang::diag::err_no_external_windows_assembler); + return NULL; +} + +bool Windows::IsIntegratedAssemblerDefault() const { + return true; +} + +bool Windows::IsUnwindTablesDefault() const { + return getArch() == llvm::Triple::x86_64; +} + +bool Windows::isPICDefault() const { + return getArch() == llvm::Triple::x86_64; +} + +bool Windows::isPICDefaultForced() const { + return getArch() == llvm::Triple::x86_64; +} + +// 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. +} |