12 #include "clang/Driver/Options.h"
13 #include "clang/Frontend/CompilerInvocation.h"
14 #include "clang/Tooling/ArgumentsAdjusters.h"
15 #include "llvm/Option/Option.h"
16 #include "llvm/Support/Allocator.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/Program.h"
30 llvm::Optional<std::string> queryXcrun(llvm::ArrayRef<llvm::StringRef> Argv) {
31 auto Xcrun = llvm::sys::findProgramByName(
"xcrun");
33 log(
"Couldn't find xcrun. Hopefully you have a non-apple toolchain...");
36 llvm::SmallString<64> OutFile;
37 llvm::sys::fs::createTemporaryFile(
"clangd-xcrun",
"", OutFile);
38 llvm::FileRemover OutRemover(OutFile);
39 llvm::Optional<llvm::StringRef> Redirects[3] = {
40 {
""}, {OutFile}, {
""}};
41 vlog(
"Invoking {0} to find clang installation", *Xcrun);
42 int Ret = llvm::sys::ExecuteAndWait(*Xcrun, Argv,
46 log(
"xcrun exists but failed with code {0}. "
47 "If you have a non-apple toolchain, this is OK. "
48 "Otherwise, try xcode-select --install.",
53 auto Buf = llvm::MemoryBuffer::getFile(OutFile);
55 log(
"Can't read xcrun output: {0}", Buf.getError().message());
58 StringRef
Path = Buf->get()->getBuffer().trim();
60 log(
"xcrun produced no output");
67 std::string resolve(std::string
Path) {
68 llvm::SmallString<128> Resolved;
69 if (llvm::sys::fs::real_path(
Path, Resolved)) {
70 log(
"Failed to resolve possible symlink {0}",
Path);
73 return std::string(Resolved.str());
79 std::string detectClangPath() {
91 if (
auto MacClang = queryXcrun({
"xcrun",
"--find",
"clang"}))
92 return resolve(std::move(*MacClang));
95 for (
const char *
Name : {
"clang",
"gcc",
"cc"})
96 if (
auto PathCC = llvm::sys::findProgramByName(
Name))
97 return resolve(std::move(*PathCC));
100 std::string ClangdExecutable =
101 llvm::sys::fs::getMainExecutable(
"clangd", (
void *)&Dummy);
102 SmallString<128> ClangPath;
103 ClangPath = llvm::sys::path::parent_path(ClangdExecutable);
104 llvm::sys::path::append(ClangPath,
"clang");
105 return std::string(ClangPath.str());
110 const llvm::Optional<std::string> detectSysroot() {
116 if (::getenv(
"SDKROOT"))
118 return queryXcrun({
"xcrun",
"--show-sdk-path"});
122 std::string detectStandardResourceDir() {
124 return CompilerInvocation::GetResourcesPath(
"clangd", (
void *)&Dummy);
132 static std::string resolveDriver(llvm::StringRef Driver,
bool FollowSymlink,
133 llvm::Optional<std::string> ClangPath) {
134 auto SiblingOf = [&](llvm::StringRef AbsPath) {
135 llvm::SmallString<128> Result = llvm::sys::path::parent_path(AbsPath);
136 llvm::sys::path::append(Result, llvm::sys::path::filename(Driver));
137 return Result.str().str();
142 if (!llvm::sys::path::is_absolute(Driver)) {
146 if (llvm::any_of(Driver,
147 [](
char C) {
return llvm::sys::path::is_separator(C); }))
151 (Driver ==
"clang" || Driver ==
"clang++" || Driver ==
"gcc" ||
152 Driver ==
"g++" || Driver ==
"cc" || Driver ==
"c++")) {
153 return SiblingOf(*ClangPath);
156 auto Absolute = llvm::sys::findProgramByName(Driver);
157 if (Absolute && llvm::sys::path::is_absolute(*Absolute))
158 Driver = Storage = std::move(*Absolute);
160 return SiblingOf(*ClangPath);
166 assert(llvm::sys::path::is_absolute(Driver));
168 llvm::SmallString<256> Resolved;
169 if (!llvm::sys::fs::real_path(Driver, Resolved))
170 return SiblingOf(Resolved);
179 Result.ClangPath = detectClangPath();
180 Result.ResourceDir = detectStandardResourceDir();
181 Result.Sysroot = detectSysroot();
194 auto Has = [&](llvm::StringRef Flag) {
195 for (llvm::StringRef Arg : Cmd) {
196 if (Arg.consume_front(Flag) && (Arg.empty() || Arg[0] ==
'='))
204 Cmd = tooling::getClangStripDependencyFileAdjuster()(Cmd,
"");
208 Cmd = tooling::getStripPluginsAdjuster()(Cmd,
"");
209 Cmd = tooling::getClangSyntaxOnlyAdjuster()(Cmd,
"");
216 if (
Sysroot && !Has(
"-isysroot") && !Has(
"--sysroot")) {
217 Cmd.push_back(
"-isysroot");
222 bool FollowSymlink = !Has(
"-no-canonical-prefixes");
224 (FollowSymlink ? ResolvedDrivers : ResolvedDriversNoFollow)
225 .get(Cmd.front(), [&,
this] {
226 return resolveDriver(Cmd.front(), FollowSymlink,
ClangPath);
231 CommandMangler::operator clang::tooling::ArgumentsAdjuster() && {
233 return [Mangler = std::make_shared<CommandMangler>(std::move(*
this))](
234 const std::vector<std::string> &Args, llvm::StringRef File) {
236 Mangler->adjust(Result);
246 std::pair<unsigned, unsigned> getArgCount(
const llvm::opt::Option &Opt) {
247 constexpr
static unsigned Rest = 10000;
249 using llvm::opt::Option;
250 switch (Opt.getKind()) {
251 case Option::FlagClass:
253 case Option::JoinedClass:
254 case Option::CommaJoinedClass:
256 case Option::GroupClass:
257 case Option::InputClass:
258 case Option::UnknownClass:
259 case Option::ValuesClass:
261 case Option::JoinedAndSeparateClass:
263 case Option::SeparateClass:
265 case Option::MultiArgClass:
266 return {1 + Opt.getNumArgs(), 0};
267 case Option::JoinedOrSeparateClass:
269 case Option::RemainingArgsClass:
271 case Option::RemainingArgsJoinedClass:
286 DriverMode getDriverMode(
const std::vector<std::string> &Args) {
287 DriverMode Mode = DM_GCC;
288 llvm::StringRef
Argv0 = Args.front();
289 if (
Argv0.endswith_lower(
".exe"))
291 if (
Argv0.endswith_lower(
"cl"))
293 for (
const llvm::StringRef Arg : Args) {
294 if (Arg ==
"--driver-mode=cl") {
307 unsigned char getModes(
const llvm::opt::Option &Opt) {
310 unsigned char Result = DM_None;
311 if (Opt.hasFlag(driver::options::CC1Option))
313 if (!Opt.hasFlag(driver::options::NoDriverOption)) {
314 if (Opt.hasFlag(driver::options::CLOption)) {
318 if (Opt.hasFlag(driver::options::CoreOption)) {
328 llvm::ArrayRef<ArgStripper::Rule> ArgStripper::rulesFor(llvm::StringRef Arg) {
333 llvm::StringMap<llvm::SmallVector<Rule, 4>, llvm::BumpPtrAllocator>;
334 static TableTy *Table = [] {
335 auto &DriverTable = driver::getDriverOptTable();
336 using DriverID = clang::driver::options::ID;
341 DriverID PrevAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
342 DriverID NextAlias[DriverID::LastOption] = {DriverID::OPT_INVALID};
343 auto AddAlias = [&](DriverID Self, DriverID T) {
345 PrevAlias[NextAlias[T]] = Self;
346 NextAlias[Self] = NextAlias[T];
352 const char *
const *Prefixes[DriverID::LastOption] = {
nullptr};
353 #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
354 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
355 HELP, METAVAR, VALUES) \
356 if (DriverID::OPT_##ALIAS != DriverID::OPT_INVALID && ALIASARGS == nullptr) \
357 AddAlias(DriverID::OPT_##ID, DriverID::OPT_##ALIAS); \
358 Prefixes[DriverID::OPT_##ID] = PREFIX;
359 #include "clang/Driver/Options.inc"
363 auto Result = std::make_unique<TableTy>();
366 for (
unsigned ID = 1 ; ID < DriverID::LastOption; ++ID) {
367 if (PrevAlias[ID] || ID == DriverID::OPT_Xclang)
369 llvm::SmallVector<Rule, 8> Rules;
371 for (
unsigned A = ID; A != DriverID::OPT_INVALID; A = NextAlias[A]) {
372 if (Prefixes[A] ==
nullptr)
374 auto Opt = DriverTable.getOption(A);
376 if (Opt.getName().empty())
378 auto Modes = getModes(Opt);
379 std::pair<unsigned, unsigned> ArgCount = getArgCount(Opt);
381 for (
auto *Prefix = Prefixes[A]; *Prefix !=
nullptr; ++Prefix) {
382 llvm::SmallString<64> Buf(*Prefix);
383 Buf.append(Opt.getName());
384 llvm::StringRef Spelling = Result->try_emplace(Buf).first->getKey();
385 Rules.emplace_back();
386 Rule &R = Rules.back();
389 R.ExactArgs = ArgCount.first;
390 R.PrefixArgs = ArgCount.second;
393 assert(ID < std::numeric_limits<decltype(R.Priority)>::max() &&
394 "Rules::Priority overflowed by options table");
399 for (
const auto &R : Rules)
400 Result->find(R.Text)->second.append(Rules.begin(), Rules.end());
404 unsigned RuleCount = 0;
405 dlog(
"ArgStripper Option spelling table");
406 for (
const auto &
Entry : *Result) {
408 RuleCount +=
Entry.second.size();
409 for (
const auto &R :
Entry.second)
410 dlog(
" {0} #={1} *={2} Mode={3}", R.Text, R.ExactArgs, R.PrefixArgs,
413 dlog(
"Table spellings={0} rules={1} string-bytes={2}", Result->size(),
414 RuleCount, Result->getAllocator().getBytesAllocated());
417 return Result.release();
420 auto It = Table->find(Arg);
421 return (It == Table->end()) ? llvm::ArrayRef<Rule>() : It->second;
425 auto OptionRules = rulesFor(Arg);
426 if (OptionRules.empty()) {
428 Storage.emplace_back(Arg);
429 Rules.emplace_back();
430 Rules.back().Text = Storage.back();
431 Rules.back().ExactArgs = 1;
432 if (Rules.back().Text.consume_back(
"*"))
433 Rules.back().PrefixArgs = 1;
434 Rules.back().Modes = DM_All;
435 Rules.back().Priority = -1;
437 Rules.append(OptionRules.begin(), OptionRules.end());
441 const ArgStripper::Rule *ArgStripper::matchingRule(llvm::StringRef Arg,
443 unsigned &ArgCount)
const {
444 const ArgStripper::Rule *BestRule =
nullptr;
445 for (
const Rule &R : Rules) {
447 if (!(R.Modes & Mode))
449 if (BestRule && BestRule->Priority < R.Priority)
451 if (!Arg.startswith(R.Text))
453 bool PrefixMatch = Arg.size() > R.Text.size();
455 if (
unsigned Count = PrefixMatch ? R.PrefixArgs : R.ExactArgs) {
470 DriverMode MainMode = getDriverMode(Args);
471 DriverMode CurrentMode = MainMode;
475 bool WasXclang =
false;
476 while (
Read < Args.size()) {
477 unsigned ArgCount = 0;
478 if (
const Rule *R = matchingRule(Args[
Read], CurrentMode, ArgCount)) {
483 CurrentMode = MainMode;
487 for (
unsigned I = 1;
Read < Args.size() && I < ArgCount; ++I) {
489 if (
Read < Args.size() && Args[
Read] ==
"-Xclang")
494 WasXclang = Args[
Read] ==
"-Xclang";
495 CurrentMode = WasXclang ? DM_CC1 : MainMode;